-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.py
More file actions
1806 lines (1516 loc) · 82.4 KB
/
app.py
File metadata and controls
1806 lines (1516 loc) · 82.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import datetime
import io
import os
import importlib
import re
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm, Inches
from pptx import Presentation
from pptx.util import Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor
import streamlit as st
# from openai import OpenAI
from langchain_openai import AzureChatOpenAI, OpenAI
import requests
import highlight as hlt
from highlight.utils import ApproachPoints, PydanticOutputParser, ImpactPoints
import highlight.prompts as prompts
def sanitize_filename(name):
"""Removes or replaces characters invalid for filenames."""
# Remove characters not alphanumeric, underscore, hyphen, or period
name = re.sub(r'[^\w\-\.]', '_', name)
# Replace multiple consecutive underscores
name = re.sub(r'_+', '_', name)
# Remove leading/trailing underscores/periods
name = name.strip('_.')
# Limit length (optional but good practice)
return name[:100] if len(name) > 100 else name
def get_placeholder(slide, name):
for shape in slide.placeholders:
# Check placeholder name (shape.name)
if shape.name == name:
return shape
# Fallback: Check shapes by name if not found in placeholders (might be less reliable)
for shape in slide.shapes:
if shape.name == name:
return shape
return None
if "reduce_document" not in st.session_state:
st.session_state.reduce_document = False
if "content_dict" not in st.session_state:
st.session_state.content_dict = {}
if "model" not in st.session_state:
st.session_state.model = "gpt-4o"
if "package" not in st.session_state:
st.session_state.package = "langchain_azure_openai"
if "access" not in st.session_state:
st.session_state.access = False
# parameters for word document
if "title_response" not in st.session_state:
st.session_state.title_response = None
if "subtitle_response" not in st.session_state:
st.session_state.subtitle_response = None
if "photo" not in st.session_state:
st.session_state.photo = None
if "photo_link" not in st.session_state:
st.session_state.photo_link = None
if "photo_site_name" not in st.session_state:
st.session_state.photo_site_name = None
if "image_caption" not in st.session_state:
st.session_state.image_caption = None
if "science_response" not in st.session_state:
st.session_state.science_response = None
if "impact_response" not in st.session_state:
st.session_state.impact_response = None
if "summary_response" not in st.session_state:
st.session_state.summary_response = None
if "funding" not in st.session_state:
st.session_state.funding = None
if "citation" not in st.session_state:
st.session_state.citation = None
if "base_export_filename" not in st.session_state:
st.session_state.base_export_filename = f"ber-highlight_{datetime.date.today().strftime('%d%b%Y').lower()}"
if "related_links" not in st.session_state:
st.session_state.related_links = None
# additional word doc content that is not in the template
if "figure_response" not in st.session_state:
st.session_state.figure_response = None
if "figure_caption" not in st.session_state:
st.session_state.figure_caption = None
if "figure_data" not in st.session_state:
# Stores dict like {'Figure 1': 'Description...'} extracted from the paper for PPT selection
st.session_state.figure_data = None
if "selected_figure_id" not in st.session_state:
# Stores the ID (e.g., 'Figure 1') selected from the paper for the PPT slide
st.session_state.selected_figure_id = None
if "caption_response" not in st.session_state:
st.session_state.caption_response = None
if "output_file" not in st.session_state:
st.session_state.output_file = None
# parameters for the ppt slide
if "objective_response" not in st.session_state:
st.session_state.objective_response = None
if "approach_response" not in st.session_state:
st.session_state.approach_response = None
if "ppt_impact_response" not in st.session_state:
st.session_state.ppt_impact_response = None
if "figure_recommendation" not in st.session_state:
st.session_state.figure_recommendation = None
if "search_phrase" not in st.session_state:
st.session_state.search_phrase = None
if "point_of_contact" not in st.session_state:
st.session_state.point_of_contact = None
if "project_info" not in st.session_state:
st.session_state.project_info = {
os.getenv("IM3_ACCESS", default=None): {
"key": os.getenv("IM3_AZURE_OPENAI_API_KEY", default=None),
"endpoint": os.getenv("IM3_AZURE_OPENAI_ENDPOINT", default=None),
"deployment": "gpt-4o",
"version": "2024-02-01",
"project": "IM3"
},
os.getenv("GCIMS_ACCESS", default=None): {
"key": os.getenv("IM3_AZURE_OPENAI_API_KEY", default=None),
"endpoint": os.getenv("IM3_AZURE_OPENAI_ENDPOINT", default=None),
"deployment": "gpt-4o",
"version": "2024-02-01",
"project": "GCIMS"
},
os.getenv("ICOM_ACCESS", default=None): {
"key": os.getenv("IM3_AZURE_OPENAI_API_KEY", default=None),
"endpoint": os.getenv("IM3_AZURE_OPENAI_ENDPOINT", default=None),
"deployment": "gpt-4o",
"version": "2024-02-01",
"project": "ICoM"
},
os.getenv("PUGET_ACCESS", default=None): {
"key": os.getenv("IM3_AZURE_OPENAI_API_KEY", default=None),
"endpoint": os.getenv("IM3_AZURE_OPENAI_ENDPOINT", default=None),
"deployment": "gpt-4o",
"version": "2024-02-01",
"project": "Puget Sound"
},
os.getenv("GLM_ACCESS", default=None): {
"key": os.getenv("IM3_AZURE_OPENAI_API_KEY", default=None),
"endpoint": os.getenv("IM3_AZURE_OPENAI_ENDPOINT", default=None),
"deployment": "gpt-4o",
"version": "2024-02-01",
"project": "COMPASS-GLM"
},
}
if "active_project" not in st.session_state:
st.session_state.active_project = "Other"
if "project_dict" not in st.session_state:
st.session_state.project_dict = {
"IM3": "Jennie Rice\nIM3 Principal Investigator\njennie.rice@pnnl.gov",
"GCIMS": "Marshall Wise\nGCIMS Principal Investigator\nmarshall.wise@pnnl.gov",
"COMPASS-GLM": "Robert Hetland\nCOMPASS-GLM Principal Investigator\nrobert.hetland@pnnl.gov",
"ICoM": "Ian Kraucunas\nICoM Principal Investigator\nian.kraucunas@pnnl.gov",
"Puget Sound": "Ning Sun\nPuget Sound Scoping and Pilot Study Principal Investigator\nning.sun@pnnl.gov",
"Other": "First and Last Name\nCorresponding Project Name with POC Credentials\nEmail Address",
}
# Figure selection state
if "figure_list" not in st.session_state:
st.session_state.figure_list = None # Will hold the list ['Figure 1', 'Fig 2', ...]
if "selected_figure" not in st.session_state:
st.session_state.selected_figure = None # Will hold the user's choice, e.g., 'Figure 1'
if "selected_figure_caption" not in st.session_state:
st.session_state.selected_figure_caption = "" # Will hold the generated caption for the selected figure
if "wikimedia_query" not in st.session_state:
st.session_state.wikimedia_query = ""
if "wikimedia_results" not in st.session_state:
st.session_state.wikimedia_results = None # List of image dicts
if "selected_wikimedia_image_info" not in st.session_state:
st.session_state.selected_wikimedia_image_info = None # Dict of selected image
if "wikimedia_limit" not in st.session_state:
st.session_state.wikimedia_limit = 5
# States related to the chosen photo for the Word doc
if "photo" not in st.session_state: st.session_state.photo = None # Will hold BytesIO
if "photo_link" not in st.session_state: st.session_state.photo_link = None
if "photo_site_name" not in st.session_state: st.session_state.photo_site_name = None
if "extracted_pdf_images" not in st.session_state:
# List of dicts like [{"index": 0, "page": 1, "xref": 123, "bytes": b'...'}, ...]
st.session_state.extracted_pdf_images = None
if "ppt_figure_image_bytes" not in st.session_state:
# Holds the raw bytes of the image chosen via "Assign Image" button
st.session_state.ppt_figure_image_bytes = None
if "suggested_search_strings" not in st.session_state:
st.session_state.suggested_search_strings = None
# ------------------------------------------------
# -- BEGIN INTERFACE -->
# ------------------------------------------------
# Force responsive layout for columns also on mobile
st.write(
"""<style>
[data-testid="column"] {
width: calc(50% - 1rem);
flex: 1 1 calc(50% - 1rem);
min-width: calc(50% - 1rem);
}
</style>""",
unsafe_allow_html=True,
)
# Display the logo in the top left corner
# Define the target URL for the hyperlink
target_url = "https://im3.pnnl.gov/"
# --- Load Image Bytes ---
logo_bytes = None
try:
logo_path = importlib.resources.files('highlight.data').joinpath('im3.png')
with logo_path.open("rb") as f:
logo_bytes = f.read()
except FileNotFoundError:
st.error("Logo file 'im3.png' not found in package 'highlight.data'.")
except Exception as e:
st.error(f"An error occurred loading the logo bytes: {e}")
# --- If bytes were loaded successfully, create the clickable image ---
if logo_bytes:
try:
# 1. Encode the image bytes as Base64
b64_logo = base64.b64encode(logo_bytes).decode()
# 2. Determine the image MIME type (assuming PNG based on filename)
# For more robustness, you could use a library like python-magic
# or check the format if loading with Pillow.
image_type = "image/png"
# 3. Construct the Base64 data URL
data_url = f"data:{image_type};base64,{b64_logo}"
# 4. Define the desired width (adjust as needed)
image_width = 59
# 5. Create the HTML string for the clickable image
# - <a> tag for the link (href=target_url)
# - target="_blank" opens the link in a new tab
# - <img> tag for the image (src=data_url)
# - Use inline style for width control
html_code = f'<a href="{target_url}" target="_blank"><img src="{data_url}" alt="IM3 Logo" style="width:{image_width}px;"></a>'
# 6. Display the HTML using st.markdown
# IMPORTANT: unsafe_allow_html=True is required to render HTML
st.markdown(html_code, unsafe_allow_html=True)
except Exception as e:
st.error(f"An error occurred creating the clickable image: {e}")
st.markdown(
"""<h1 style='text-align: center;'>
<span style='font-size:40px;'>📜</span> PAIGE <span style='font-size:40px;'>📜</span>
</h1>
<h3 style='text-align: center;'>The Pnnl AI assistant for GEnerating publication highlights</h3>
<h5 style='text-align: center;'>Go from publication to a first draft highlight <i>fast</i>!</h5>
""",
unsafe_allow_html=True
)
with st.expander("**How to Use PAIGE**", expanded=False):
st.markdown((
"Simply: \n" +
"1. Enter in your project password or OpenAI API key \n"
"2. Load the PDF document of your publication into the app \n" +
"3. Generate each part of your document in order \n" +
"4. Export the document to your local machine \n" +
"5. Repeat to generate the PowerPoint slide as well \n" +
"\n :memo: Note: Some parts of this process were left to be semi-automated. " +
"These include finding images that are free and open to use from a reliable " +
"source and choosing which figure from the paper to use in the PowerPoint slide. " +
"But don't worry, PAIGE offers helpers along the way."
))
if st.session_state.model in (["gpt-4o"]):
st.session_state.max_allowable_tokens = 150000
# validate project and access key
if st.session_state.access is False:
user_input = st.text_input(
"Enter your project password or API key:",
type="password",
)
if user_input:
if user_input in st.session_state.project_info.keys():
project_info = st.session_state.project_info[user_input]
st.session_state.active_project = project_info["project"]
if st.session_state.package == "langchain_azure_openai":
# setup environment locally
os.environ["OPENAI_API_TYPE"]="azure"
os.environ["OPENAI_API_VERSION"]=project_info["version"]
os.environ["OPENAI_API_BASE"]=project_info["endpoint"]
os.environ["OPENAI_API_KEY"]=project_info["key"]
os.environ["OPENAI_CHAT_MODEL"]=project_info["deployment"]
st.success(f"Hello {st.session_state.active_project} representative!", icon="✅")
st.session_state.access = True
st.session_state.client = AzureChatOpenAI(
deployment_name=project_info["deployment"],
azure_endpoint=project_info["endpoint"]
)
else:
st.error(f"Invalid key or password. Please provide a valid entry.", icon="🚨")
st.session_state.access = False
user_input = False
if st.session_state.access:
st.markdown("### Upload file to process:")
uploaded_file = st.file_uploader(
label="### Select PDF or text file to upload",
type=["pdf", "txt"],
help="Select PDF or text file to upload",
)
if uploaded_file is not None:
if uploaded_file.type == "text/plain":
content_dict = hlt.read_text(uploaded_file)
elif uploaded_file.type == "application/pdf":
content_dict = hlt.read_pdf(uploaded_file)
st.session_state.output_file = uploaded_file.name
st.code(f"""File specs:\n
- Number of pages: {content_dict['n_pages']}
- Number of characters: {content_dict['n_characters']}
- Number of words: {content_dict['n_words']}
- Number of tokens: {content_dict['n_tokens']}
""")
if content_dict['n_tokens'] > st.session_state.max_allowable_tokens:
msg = f"""
The number of tokens in your document exceeds the maximum allowable tokens.
This will cause your queries to fail.
The queries account for the number of tokens in a prompt + the number of tokens in your document.
Maximum allowable token count: {st.session_state.max_allowable_tokens}
Your documents token count: {content_dict['n_tokens']}
Token deficit: {content_dict['n_tokens'] - st.session_state.max_allowable_tokens}
"""
st.error(msg, icon="🚨")
st.session_state.reduce_document = st.radio(
"""Would you like me to attempt to reduce the size of
your document by keeping only relevant information?
If so, I will give you a file to download with the content
so you only have to do this once.
If you choose to go through with this, it may take a while
to process, usually on the order of 15 minutes for a 20K token
document.
Alternatively, you can copy and paste the contents that you
know are of interest into a text file and upload that
instead.
""",
("Yes", "No"),
)
# word document content
st.markdown("### Section 1: Content to fill in Word document template:")
# ------------------------------------------------
# -- DOC: START TITLE SECTION -->
# ------------------------------------------------
st.markdown("---")
# title section
title_container = st.container()
title_container.markdown("##### Generate title from text content")
# title criteria
title_container.markdown("""
The title should meet the following criteria:
- No colons are allowed in the output.
- Should pique the interest of the reader while still being somewhat descriptive.
- Be understandable to a general audience.
- Should be only once sentence.
- Should have a maximum length of 10 words.
""")
title_container.markdown("Set desired temperature:")
# title slider
title_temperature = title_container.slider(
"Title Temperature",
0.0,
1.0,
0.2,
label_visibility="collapsed"
)
# build container content
if title_container.button('Generate Title'):
st.session_state.title_response = hlt.generate_content(
client=st.session_state.client,
container=title_container,
content=content_dict["content"],
prompt_name="title",
result_title="Title Result:",
max_tokens=50,
temperature=title_temperature,
box_height=75,
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model
)
else:
if st.session_state.title_response is not None:
title_container.markdown("Title Result:")
title_container.text_area(
label="Title Result:",
value=st.session_state.title_response,
label_visibility="collapsed",
height=75
)
# ------------------------------------------------
# -- DOC: START SUBTITLE SECTION -->
# ------------------------------------------------
st.markdown("---")
# subtitle section
subtitle_container = st.container()
subtitle_container.markdown("##### Generate subtitle from text content")
# subtitle criteria
subtitle_container.markdown("""
The subtitle should meet the following criteria:
- Be an extension of and related to, but not directly quote, the title.
- Provide information that will make the audience want to find out more about the research.
- Do not use more than 155 characters including spaces.
""")
subtitle_container.markdown("Set desired temperature:")
# subtitle slider
subtitle_temperature = subtitle_container.slider(
"Subtitle Temperature",
0.0,
1.0,
0.5,
label_visibility="collapsed"
)
# build container content
if subtitle_container.button('Generate Subtitle'):
if st.session_state.title_response is None:
st.write("Please generate a Title first. Subtitle generation considers the title response.")
else:
st.session_state.subtitle_response = hlt.generate_content(
client=st.session_state.client,
container=subtitle_container,
content=content_dict["content"],
prompt_name="subtitle",
result_title="Subtitle Result:",
max_tokens=100,
temperature=subtitle_temperature,
box_height=75,
additional_content=st.session_state.title_response,
max_word_count=100,
min_word_count=75,
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model
)
else:
if st.session_state.subtitle_response is not None:
subtitle_container.markdown("Subtitle Result:")
subtitle_container.text_area(
label="Subtitle Result:",
value=st.session_state.subtitle_response,
label_visibility="collapsed",
height=75
)
# ------------------------------------------------
# -- DOC: START SCIENCE SUMMARY SECTION -->
# ------------------------------------------------
st.markdown("---")
# science section
science_container = st.container()
science_container.markdown("##### Generate science summary from text content")
# science criteria
science_container.markdown("""
**GOAL**: Describe the scientific results for a non-expert, non-scientist audience.
The description should meet the following criteria:
- Answer what the big challenge in this field of science is that the research addresses.
- State what the key finding is.
- Explain the science, not the process.
- Be understandable to a high school senior or college freshman.
- Use short sentences and succinct words.
- Avoid technical terms if possible. If technical terms are necessary, define them.
- Provide the necessary context so someone can have a very basic understanding of what you did.
- Start with topics that the reader already may know and move on to more complex ideas.
- Use present tense.
- In general, the description should speak about the research or researchers in first person.
- Use a minimum of 75 words and a maximum of 100 words.
""")
science_container.markdown("Set desired temperature:")
# slider
science_temperature = science_container.slider(
"Science Summary Temperature",
0.0,
1.0,
0.3,
label_visibility="collapsed"
)
# build container content
if science_container.button('Generate Science Summary'):
st.session_state.science_response = hlt.generate_content(
client=st.session_state.client,
container=science_container,
content=content_dict["content"],
prompt_name="science",
result_title="Science Summary Result:",
max_tokens=200,
temperature=science_temperature,
box_height=250,
max_word_count=100,
min_word_count=75,
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model
)
else:
if st.session_state.science_response is not None:
science_container.markdown("Science Summary Result:")
science_container.text_area(
label="Science Summary Result:",
value=st.session_state.science_response,
label_visibility="collapsed",
height=250
)
# ------------------------------------------------
# -- DOC: START IMPACT SUMMARY SECTION -->
# ------------------------------------------------
st.markdown("---")
# impact section
impact_container = st.container()
impact_container.markdown("##### Generate impact summary from text content")
impact_container.markdown("""
**GOAL**: Describe the impact of the research to a non-expert, non-scientist audience.
The description should meet the following criteria:
- Answer why the findings presented are important, i.e., what problem the research is trying to solve.
- Answer if the finding is the first of its kind.
- Answer what was innovative or distinct about the research.
- Answer what the research enables other scientists in your field to do next.
- Include other scientific fields potentially impacted.
- Be understandable to a high school senior or college freshman.
- Use short sentences and succinct words.
- Avoid technical terms if possible. If technical terms are necessary, define them.
- Use present tense.
- In general, the description should speak about the research or researchers in first person.
- Use a minimum of 75 words and a maximum of 100 words.
""")
impact_container.markdown("Set desired temperature:")
# slider
impact_temperature = impact_container.slider(
"Impact Summary Temperature",
0.0,
1.0,
0.0,
label_visibility="collapsed"
)
# build container content
if impact_container.button('Generate Impact Summary'):
st.session_state.impact_response = hlt.generate_content(
client=st.session_state.client,
container=impact_container,
content=content_dict["content"],
prompt_name="impact",
result_title="Impact Summary Result:",
max_tokens=700,
temperature=impact_temperature,
box_height=250,
max_word_count=100,
min_word_count=75,
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model
)
else:
if st.session_state.impact_response is not None:
impact_container.markdown("Impact Summary Result:")
impact_container.text_area(
label="Impact Summary Result:",
value=st.session_state.impact_response,
label_visibility="collapsed",
height=250
)
# ------------------------------------------------
# -- DOC: START GENERAL SUMMARY SECTION -->
# ------------------------------------------------
st.markdown("---")
# general summary section
summary_container = st.container()
summary_container.markdown("##### Generate general summary from text content")
summary_container.markdown("""
**GOAL**: Generate a general summary of the current research.
The summary should meet the following criteria:
- Should relay key findings and value.
- The summary should be still accessible to the non-specialist but may be more technical if necessary.
- Do not mention the names of institutions.
- If there is a United States Department of Energy Office of Science user facility involved, such as NERSC, you can mention the user facility.
- Should be 1 or 2 paragraphs detailing the research.
- Use present tense.
- In general, the description should speak about the research or researchers in first person.
- Use no more than 200 words.
""")
summary_container.markdown("Set desired temperature:")
# slider
summary_temperature = summary_container.slider(
"General Summary Temperature",
0.0,
1.0,
0.3,
label_visibility="collapsed"
)
# build container content
if summary_container.button('Generate General Summary'):
st.session_state.summary_response = hlt.generate_content(
client=st.session_state.client,
container=summary_container,
content=content_dict["content"],
prompt_name="summary",
result_title="General Summary Result:",
max_tokens=700,
temperature=summary_temperature,
box_height=400,
max_word_count=200,
min_word_count=100,
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model
)
else:
if st.session_state.summary_response is not None:
summary_container.markdown("General Summary Result:")
summary_container.text_area(
label="General Summary Result:",
value=st.session_state.summary_response,
label_visibility="collapsed",
height=400
)
# ------------------------------------------------
# -- DOC: START CITATION SELECTION -->
# ------------------------------------------------
st.markdown("---")
# citation recommendations section
citation_container = st.container()
citation_container.markdown("##### Citation for the paper in Chicago style")
citation_container.markdown("This will only use what is represented in the publication provided.")
if citation_container.button('Generate Citation'):
st.session_state.citation = hlt.generate_content(
client=st.session_state.client,
container=citation_container,
content=content_dict["content"],
prompt_name="citation",
result_title="",
max_tokens=300,
temperature=0.0,
box_height=200,
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model
).replace('"', "")
else:
if st.session_state.citation is not None:
citation_container.text_area(
label="Citation",
value=st.session_state.citation,
label_visibility="collapsed",
height=200
)
# ------------------------------------------------
# -- DOC: START PHOTO SELECTION -->
# ------------------------------------------------
st.markdown("---")
st.markdown("##### Find an Image for your Word Document")
st.markdown("**Note**: This is not an image from your paper. It is meant to be an editorial cover image.")
st.markdown(
"The following is a convenience service and uses Wikimedia Commons due to their images being fully open and reusable. " +
"That being stated, you may not always be able to find what you need in their database and may have to " +
"search another resource. Simply do not execute this block if you intend to find an image elsewhere."
)
# --- Main Container for this Section ---
img_search_container = st.container(border=True)
# Step 1 - Suggest Search Strings
img_search_container.markdown("##### 1. Generate Suggested Wikimedia Search Strings (Optional)")
img_search_container.caption(
"These are produced from the 'General Summary' generated earlier. " +
"Simple searches are more productive, so use these as general guidance. " +
"\n\n**For example**, simply searching for 'Groundwater irrigation' will work better than " +
"'Groundwater irrigation in the Snake River Basin'."
)
suggest_container = img_search_container.container() # Sub-container for this step
# Check if summary exists first
if st.session_state.summary_response:
if suggest_container.button("Suggest Search Strings", key="suggest_wiki_search"):
with st.spinner("Generating search string ideas..."):
# Call generate_content for suggestions
# Assuming 'figure' prompt takes summary and returns newline-separated strings
suggestions = hlt.generate_content(
client=st.session_state.client,
container=suggest_container, # Display result within this container
content=st.session_state.summary_response, # Input is the summary
prompt_name="figure", # Use the prompt for generating search strings
result_title="Suggested Strings:",
max_tokens=200, # Adjust as needed
temperature=0.5, # Moderate temperature for suggestions
box_height=150, # Text area height
# Assuming generate_content displays result in text_area, no max/min words needed here
max_allowable_tokens=st.session_state.max_allowable_tokens,
model=st.session_state.model,
package=st.session_state.package
)
# Store the raw response (might be newline separated string)
st.session_state.suggested_search_strings = suggestions
# Rerun not strictly necessary as generate_content handles display,
# but needed if default query logic below should immediately update
st.rerun()
# Display existing suggestions if already generated
elif st.session_state.suggested_search_strings:
suggest_container.markdown("**Suggested Strings:**")
suggest_container.text_area(
label="Suggested Strings", # Hidden label
value=st.session_state.suggested_search_strings.replace('"', ''),
height=150,
disabled=False,
label_visibility="collapsed"
)
else:
suggest_container.warning("Please generate the 'General Summary' in Section 1 first to enable suggestions.")
img_search_container.markdown("---") # Separator
# --- Step 2: Search and Select Image (Previously Step 1) ---
img_search_container.markdown("##### 2. Search Wikimedia Commons and Select Image")
# --- Determine Default Query ---
default_query = ""
# PRIORITIZE first suggested string if available
if st.session_state.suggested_search_strings:
first_suggestion = st.session_state.suggested_search_strings.split('\n')[0].strip()
if first_suggestion:
default_query = first_suggestion
# Fallback to title or summary
elif st.session_state.title_response:
default_query = st.session_state.title_response
elif st.session_state.summary_response:
default_query = " ".join(st.session_state.summary_response.split()[:15])
# --- Search Controls Row (No change needed here) ---
controls_cols = img_search_container.columns([3, 1, 1])
with controls_cols[0]: # Search Query Input
user_query = st.text_input(
"Image Search Query:",
value=st.session_state.get("wikimedia_query", default_query), # Use default logic
key="wikimedia_query_input"
)
st.session_state.wikimedia_query = user_query
with controls_cols[1]: # Number of Images Input
num_images = st.number_input(
"Max Results:", min_value=3, max_value=30,
value=st.session_state.wikimedia_limit, step=3,
key="wikimedia_limit_input", help="Number of images to retrieve (max 30)"
)
st.session_state.wikimedia_limit = int(num_images)
with controls_cols[2]: # Search Button
st.write("") # Placeholder for spacing
st.write("")
search_button = st.button("Search", key="wiki_search_btn", use_container_width=True)
# --- Clear Button ---
if st.session_state.wikimedia_results or st.session_state.selected_wikimedia_image_info:
if img_search_container.button("Clear Search / Reset Selection", key="wiki_clear_btn"):
st.session_state.wikimedia_results = None
st.session_state.selected_wikimedia_image_info = None
st.session_state.photo = None
st.session_state.photo_link = None
st.session_state.photo_site_name = None
st.rerun()
# --- Execute Search ---
if search_button and st.session_state.wikimedia_query:
with st.spinner("Searching Wikimedia Commons..."):
st.session_state.wikimedia_results = hlt.search_wikimedia_commons(
query=st.session_state.wikimedia_query,
limit=st.session_state.wikimedia_limit
)
st.session_state.selected_wikimedia_image_info = None # Reset previous selection
if not st.session_state.wikimedia_results:
img_search_container.info("No suitable images found for your query.")
# No rerun here, let results display immediately below
# st.rerun() # Removing rerun for smoother feel
# --- Display Results in Columns ---
if st.session_state.wikimedia_results:
if st.session_state.selected_wikimedia_image_info is None:
num_found = len(st.session_state.wikimedia_results)
# Title ABOVE the results box
img_search_container.markdown(f"**Found {num_found} image(s):** (Select one below)")
# --- Create a NEW sub-container specifically for the results grid ---
results_grid_container = st.container(border=True, height=500)
results_grid_container.write("##### 3. Select an image")
# --- Place columns and results INSIDE the new sub-container ---
with results_grid_container: # Use 'with' block for clarity
num_columns = 3 # Adjust as desired
cols = st.columns(num_columns) # Create columns inside the sub-container
for i, img_data in enumerate(st.session_state.wikimedia_results):
col_index = i % num_columns
with cols[col_index]: # Place content in the current column
if img_data.get("thumbnail_url"):
st.image(
img_data["thumbnail_url"],
caption=f"{img_data.get('title', 'N/A')} ({img_data.get('license', 'N/A')})",
width=180 # Adjust width
)
if img_data.get('page_url'):
st.caption(f"[View on Wikimedia]({img_data['page_url']})")
# Selection Button for each image
button_key = f"select_wiki_{img_data.get('id', i)}"
if st.button(f"Select This Image", key=button_key):
# --- Selection logic (remains the same) ---
st.session_state.selected_wikimedia_image_info = img_data
with st.spinner("Preparing selected image..."):
try:
headers = {'User-Agent': 'PAIGE/1.0 (Highlight Generator App)'}
img_response = requests.get(img_data['full_url'], stream=True, timeout=15, headers=headers)
img_response.raise_for_status()
img_bytes_io = io.BytesIO(img_response.content)
st.session_state.photo = img_bytes_io
st.session_state.photo_link = img_data.get('page_url', '')
st.session_state.photo_site_name = "Wikimedia Commons"
st.success(f"Image '{img_data.get('title', 'Selected')}' prepared for Word doc.")
st.rerun()
except Exception as e:
st.error(f"Failed to download/prepare selected image: {e}")
# Reset relevant states on failure
st.session_state.photo = None
st.session_state.photo_link = None
st.session_state.photo_site_name = None
st.session_state.selected_wikimedia_image_info = None
# --- End selection logic ---
# Add separator below button
st.markdown("---")
else:
st.caption(f"Thumbnail missing for '{img_data.get('title', 'N/A')}'")
st.markdown("---")
# --- Display Final Selection Info and Download Button ---
if st.session_state.selected_wikimedia_image_info:
# This section remains unchanged from the previous version
img_search_container.markdown("---")
img_search_container.markdown("##### 3. Selected Image:")
selected_info = st.session_state.selected_wikimedia_image_info
# Display image thumbnail and details
sel_col1, sel_col2 = img_search_container.columns([1, 2])
with sel_col1:
if selected_info.get("thumbnail_url"):
st.image(selected_info["thumbnail_url"], width=150)
with sel_col2:
st.markdown(f"**Title:** {selected_info.get('title', 'N/A')}")
st.markdown(f"**License:** {selected_info.get('license', 'N/A')}")
if selected_info.get('page_url'):
st.markdown(f"**Attribution/Source:** [{selected_info['page_url']}]({selected_info['page_url']})")
if selected_info.get('artist'):
st.caption(f"Artist Info: {selected_info['artist']}", unsafe_allow_html=True)
st.info("Selected image & attribution link will be used in Word doc export.")
# CAPTION GENERATION/EDIT SECTION
img_search_container.markdown("---") # Separator
img_search_container.markdown("##### 4. Generate a General Caption (based on paper summary)")
# Using a sub-container for layout clarity, optional
caption_editor_container = img_search_container.container()
# Define parameters for caption generation
caption_prompt_name = "figure_caption" # Assumes this prompt summarizes the paper
caption_temperature = 0.3 # Adjust temperature if needed
caption_max_tokens = 100 # Max tokens for the LLM response
caption_box_height = 100 # Height of the text area
caption_max_words = 30 # Target max words (adjust if needed)
caption_min_words = 10 # Target min words
# Button to generate a caption suggestion
if caption_editor_container.button("Suggest Caption", key="gen_wiki_caption"):
with st.spinner("Generating caption suggestion..."):
# We use generate_content which handles UI updates within the container
# Base the caption on the *paper's* content, not the image metadata
generated_caption = hlt.generate_content(
client=st.session_state.client,