Spaces:
Running
Running
File size: 66,608 Bytes
87c3140 e729f97 87c3140 93fd830 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 2e76bd4 87c3140 5ee1861 e729f97 87c3140 e729f97 87c3140 f2055e5 87c3140 f2055e5 87c3140 e729f97 87c3140 9f288f7 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 ff6cbfc 1f88809 7b8df6e 88f7b69 ff6cbfc 87c3140 e729f97 904c317 e729f97 904c317 e729f97 904c317 87c3140 e729f97 5b17165 e729f97 87c3140 e729f97 ab9dab7 e729f97 0bec306 82babfb aaf86cc 82babfb 26c9c07 2e76bd4 697083f 492b0f2 82babfb 644099c 6dbe10f 22e0bab 6dbe10f 026faf8 644099c 87c3140 e729f97 87c3140 e729f97 bb0313e e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 dedb651 e729f97 87c3140 e729f97 3b75f1a e729f97 cc75837 e729f97 e805b05 e729f97 e805b05 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 cc75837 5ee1861 e729f97 87c3140 cc75837 87c3140 cc9202c 87c3140 3b75f1a 08a14c4 5ee1861 3b75f1a 08a14c4 cc9202c 08a14c4 3b75f1a 08a14c4 cc9202c 08a14c4 cc9202c 08a14c4 3b75f1a ce5b499 cc75837 daf2e4b 87c3140 cc75837 daf2e4b 87c3140 cc75837 daf2e4b cc75837 6275f78 e729f97 6275f78 e729f97 cc75837 87c3140 cc75837 87c3140 cc75837 87c3140 e729f97 87c3140 3b75f1a 87c3140 ce5b499 87c3140 ce5b499 87c3140 3b75f1a 87c3140 d2fb9ea d9f8a09 d2fb9ea d9f8a09 d2fb9ea d9f8a09 ce5b499 d9f8a09 d2fb9ea d9f8a09 d2fb9ea d9f8a09 6275f78 3d2a012 87c3140 cc75837 87c3140 e729f97 dc252b5 87c3140 e729f97 87c3140 dc252b5 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 87c3140 eb18fda e729f97 eb18fda 87c3140 26c9c07 e729f97 26c9c07 87c3140 26c9c07 87c3140 9f288f7 87c3140 9f288f7 87c3140 93fd830 697083f 87c3140 6b7f4d9 0ee709f dc252b5 6b7f4d9 0ee709f dc252b5 87c3140 dc252b5 82babfb 87c3140 446471a e729f97 87c3140 e729f97 8d4eec7 87c3140 8d4eec7 0ee709f 87c3140 0ee709f 87c3140 e86548c 5b7117f e86548c 8d4eec7 ae3d41c 2e76bd4 ae3d41c 35f5e08 2e76bd4 35f5e08 87c3140 2e76bd4 8d4eec7 87c3140 e86548c a3d159a 87c3140 12ba60e e729f97 8d4eec7 ff6cbfc 7b8df6e ff6cbfc 5efd4b8 446471a 5efd4b8 ff6cbfc 49fb854 6a78dda 7b8df6e 5ee1861 1c57739 7b8df6e 49fb854 5efd4b8 c47fa5d 6bef370 94bb15c 88f7b69 c47fa5d c3e4ae3 e729f97 8d4eec7 7b8df6e 1f88809 5ee1861 32e89be 5ee1861 32e89be e729f97 87c3140 e9f4039 87c3140 0ee709f 87c3140 32f1ba8 87c3140 e729f97 87c3140 12ba60e 87c3140 e729f97 d88f98b 87c3140 e729f97 87c3140 e729f97 87c3140 e729f97 5b17165 e729f97 87c3140 5731488 945eeae e729f97 446471a 87c3140 e729f97 87c3140 e729f97 93fd830 e729f97 8d4eec7 e729f97 7b8df6e e729f97 cc9202c e729f97 ce5b499 e729f97 6275f78 e729f97 6275f78 e729f97 d2fb9ea e729f97 eb18fda 4571328 2e76bd4 b3c3533 ae3d41c 87c3140 e729f97 93fd830 87c3140 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 |
import streamlit as st
import yaml, os, json, random, time, shutil
import plotly.graph_objs as go
from itertools import chain
from PIL import Image
from io import BytesIO
from streamlit_extras.let_it_rain import rain
from vouchervision.LeafMachine2_Config_Builder import write_config_file
from vouchervision.VoucherVision_Config_Builder import build_VV_config , TestOptionsGPT, TestOptionsPalm, check_if_usable
from vouchervision.vouchervision_main import voucher_vision
from vouchervision.general_utils import summarize_expense_report, validate_dir
from vouchervision.utils import upload_to_drive, image_to_base64, setup_streamlit_config, save_uploaded_file, check_prompt_yaml_filename
########################################################################################################
### Constants ####
########################################################################################################
PROMPTS_THAT_NEED_DOMAIN_KNOWLEDGE = ["Version 1","Version 1 PaLM 2"]
# LLM_VERSIONS = ["GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5", "PaLM 2"]
COLORS_EXPENSE_REPORT = {
'GPT_4': '#8fff66', # Bright Green
'GPT_3_5': '#006400', # Dark Green
'PALM2': '#66a8ff' # blue
}
MAX_GALLERY_IMAGES = 50
GALLERY_IMAGE_SIZE = 128
N_OVERALL_STEPS = 6
########################################################################################################
### Progress bar ####
########################################################################################################
class ProgressReport:
def __init__(self, overall_bar, batch_bar, text_overall, text_batch):
self.overall_bar = overall_bar
self.batch_bar = batch_bar
self.text_overall = text_overall
self.text_batch = text_batch
self.current_overall_step = 0
self.total_overall_steps = 20 # number of major steps in machine function
self.current_batch = 0
self.total_batches = 20
def update_overall(self, step_name=""):
self.current_overall_step += 1
self.overall_bar.progress(self.current_overall_step / self.total_overall_steps)
self.text_overall.text(step_name)
def update_batch(self, step_name=""):
self.current_batch += 1
self.batch_bar.progress(self.current_batch / self.total_batches)
self.text_batch.text(step_name)
def set_n_batches(self, n_batches):
self.total_batches = n_batches
def set_n_overall(self, total_overall_steps):
self.current_overall_step = 0
self.overall_bar.progress(0)
self.total_overall_steps = total_overall_steps
def reset_batch(self, step_name):
self.current_batch = 0
self.batch_bar.progress(0)
self.text_batch.text(step_name)
def reset_overall(self, step_name):
self.current_overall_step = 0
self.overall_bar.progress(0)
self.text_overall.text(step_name)
def get_n_images(self):
return self.n_images
def get_n_overall(self):
return self.total_overall_steps
########################################################################################################
### Streamlit helper functions ####
########################################################################################################
def display_scrollable_results(JSON_results, test_results, OPT2, OPT3):
"""
Display the results from JSON_results in a scrollable container.
"""
# Initialize the container
con_results = st.empty()
with con_results.container():
# Start the custom container for all the results
results_html = """<div class='scrollable-results-container'>"""
for idx, (test_name, _) in enumerate(sorted(test_results.items())):
_, ind_opt1, ind_opt2, ind_opt3 = test_name.split('__')
opt2_readable = "Use LeafMachine2" if OPT2[int(ind_opt2.split('-')[1])] else "Don't use LeafMachine2"
opt3_readable = f"{OPT3[int(ind_opt3.split('-')[1])]}"
if JSON_results[idx] is None:
results_html += f"<p>None</p>"
else:
formatted_json = json.dumps(JSON_results[idx], indent=4, sort_keys=False)
results_html += f"<pre>[{opt2_readable}] + [{opt3_readable}]<br/>{formatted_json}</pre>"
# End the custom container
results_html += """</div>"""
# The CSS to make this container scrollable
css = """
<style>
.scrollable-results-container {
overflow-y: auto;
height: 600px;
width: 100%;
white-space: pre-wrap; # To wrap the content
font-family: monospace; # To give the JSON a code-like appearance
}
</style>
"""
# Apply the CSS and then the results
st.markdown(css, unsafe_allow_html=True)
st.markdown(results_html, unsafe_allow_html=True)
def display_test_results(test_results, JSON_results, llm_version):
if llm_version == 'gpt':
OPT1, OPT2, OPT3 = TestOptionsGPT.get_options()
elif llm_version == 'palm':
OPT1, OPT2, OPT3 = TestOptionsPalm.get_options()
else:
raise
widths = [1] * (len(OPT1) + 2) + [2]
columns = st.columns(widths)
with columns[0]:
st.write("LeafMachine2")
with columns[1]:
st.write("Prompt")
with columns[len(OPT1) + 2]:
st.write("Scroll to See Last Transcription in Each Test")
already_written = set()
for test_name, result in sorted(test_results.items()):
_, ind_opt1, _, _ = test_name.split('__')
option_value = OPT1[int(ind_opt1.split('-')[1])]
if option_value not in already_written:
with columns[int(ind_opt1.split('-')[1]) + 2]:
st.write(option_value)
already_written.add(option_value)
printed_options = set()
with columns[-1]:
display_scrollable_results(JSON_results, test_results, OPT2, OPT3)
# Close the custom container
st.write('</div>', unsafe_allow_html=True)
for idx, (test_name, result) in enumerate(sorted(test_results.items())):
_, ind_opt1, ind_opt2, ind_opt3 = test_name.split('__')
opt2_readable = "Use LeafMachine2" if OPT2[int(ind_opt2.split('-')[1])] else "Don't use LeafMachine2"
opt3_readable = f"{OPT3[int(ind_opt3.split('-')[1])]}"
if (opt2_readable, opt3_readable) not in printed_options:
with columns[0]:
st.info(f"{opt2_readable}")
st.write('---')
with columns[1]:
st.info(f"{opt3_readable}")
st.write('---')
printed_options.add((opt2_readable, opt3_readable))
with columns[int(ind_opt1.split('-')[1]) + 2]:
if result:
st.success(f"Test Passed")
else:
st.error(f"Test Failed")
st.write('---')
# success_count = sum(1 for result in test_results.values() if result)
# failure_count = len(test_results) - success_count
# proportional_rain("🥇", success_count, "💔", failure_count, font_size=72, falling_speed=5, animation_length="infinite")
rain_emojis(test_results)
def add_emoji_delay():
time.sleep(0.3)
def rain_emojis(test_results):
# test_results = {
# 'test1': True, # Test passed
# 'test2': True, # Test passed
# 'test3': True, # Test passed
# 'test4': False, # Test failed
# 'test5': False, # Test failed
# 'test6': False, # Test failed
# 'test7': False, # Test failed
# 'test8': False, # Test failed
# 'test9': False, # Test failed
# 'test10': False, # Test failed
# }
success_emojis = ["🥇", "🏆", "🍾", "🙌"]
failure_emojis = ["💔", "😭"]
success_count = sum(1 for result in test_results.values() if result)
failure_count = len(test_results) - success_count
chosen_emoji = random.choice(success_emojis)
for _ in range(success_count):
rain(
emoji=chosen_emoji,
font_size=72,
falling_speed=4,
animation_length=2,
)
add_emoji_delay()
chosen_emoji = random.choice(failure_emojis)
for _ in range(failure_count):
rain(
emoji=chosen_emoji,
font_size=72,
falling_speed=5,
animation_length=1,
)
add_emoji_delay()
def get_prompt_versions(LLM_version):
yaml_files = [f for f in os.listdir(os.path.join(st.session_state.dir_home, 'custom_prompts')) if f.endswith('.yaml')]
if LLM_version in ["GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5"]:
versions = ["Version 1", "Version 1 No Domain Knowledge", "Version 2"]
return (versions + yaml_files, "Version 2")
elif LLM_version in ["PaLM 2",]:
versions = ["Version 1 PaLM 2", "Version 1 PaLM 2 No Domain Knowledge", "Version 2 PaLM 2"]
return (versions + yaml_files, "Version 2 PaLM 2")
else:
# Handle other cases or raise an error
return (yaml_files, None)
def delete_directory(dir_path):
try:
shutil.rmtree(dir_path)
st.session_state['input_list'] = []
st.session_state['input_list_small'] = []
# st.success(f"Deleted previously uploaded images, making room for new images: {dir_path}")
except OSError as e:
st.error(f"Error: {dir_path} : {e.strerror}")
# Function to load a YAML file and update session_state
def load_prompt_yaml(filename):
st.session_state['user_clicked_load_prompt_yaml'] = filename
with open(filename, 'r') as file:
st.session_state['prompt_info'] = yaml.safe_load(file)
st.session_state['prompt_author'] = st.session_state['prompt_info'].get('prompt_author', st.session_state['default_prompt_author'])
st.session_state['prompt_author_institution'] = st.session_state['prompt_info'].get('prompt_author_institution', st.session_state['default_prompt_author_institution'])
st.session_state['prompt_description'] = st.session_state['prompt_info'].get('prompt_description', st.session_state['default_prompt_description'])
st.session_state['LLM'] = st.session_state['prompt_info'].get('LLM', 'gpt')
st.session_state['instructions'] = st.session_state['prompt_info'].get('instructions', st.session_state['default_instructions'])
st.session_state['json_formatting_instructions'] = st.session_state['prompt_info'].get('json_formatting_instructions', st.session_state['default_json_formatting_instructions'] )
st.session_state['rules'] = st.session_state['prompt_info'].get('rules', {})
st.session_state['mapping'] = st.session_state['prompt_info'].get('mapping', {})
st.session_state['prompt_info'] = {
'prompt_author': st.session_state['prompt_author'],
'prompt_author_institution': st.session_state['prompt_author_institution'],
'prompt_description': st.session_state['prompt_description'],
'LLM': st.session_state['LLM'],
'instructions': st.session_state['instructions'],
'json_formatting_instructions': st.session_state['json_formatting_instructions'],
'rules': st.session_state['rules'],
'mapping': st.session_state['mapping'],
}
# Placeholder:
st.session_state['assigned_columns'] = list(chain.from_iterable(st.session_state['mapping'].values()))
def save_prompt_yaml(filename, col_right_save):
yaml_content = {
'prompt_author': st.session_state['prompt_author'],
'prompt_author_institution': st.session_state['prompt_author_institution'],
'prompt_description': st.session_state['prompt_description'],
'LLM': st.session_state['LLM'],
'instructions': st.session_state['instructions'],
'json_formatting_instructions': st.session_state['json_formatting_instructions'],
'rules': st.session_state['rules'],
'mapping': st.session_state['mapping'],
}
dir_prompt = os.path.join(st.session_state.dir_home, 'custom_prompts')
filepath = os.path.join(dir_prompt, f"{filename}.yaml")
with open(filepath, 'w') as file:
yaml.safe_dump(dict(yaml_content), file, sort_keys=False)
st.success(f"Prompt saved as '{filename}.yaml'.")
upload_to_drive(filepath, filename)
with col_right_save:
create_download_button_yaml(filepath, filename)
def check_unique_mapping_assignments():
if len(st.session_state['assigned_columns']) != len(set(st.session_state['assigned_columns'])):
st.error("Each column name must be assigned to only one category.")
return False
else:
st.success("Mapping confirmed.")
return True
def create_download_button(zip_filepath):
with open(zip_filepath, 'rb') as f:
bytes_io = BytesIO(f.read())
st.download_button(
label=f"Download Results for{st.session_state['processing_add_on']}",type='primary',
data=bytes_io,
file_name=os.path.basename(zip_filepath),
mime='application/zip'
)
def btn_load_prompt(selected_yaml_file, dir_prompt):
if selected_yaml_file:
yaml_file_path = os.path.join(dir_prompt, selected_yaml_file)
load_prompt_yaml(yaml_file_path)
elif not selected_yaml_file:
# Directly assigning default values since no file is selected
st.session_state['prompt_info'] = {}
st.session_state['prompt_author'] = st.session_state['default_prompt_author']
st.session_state['prompt_author_institution'] = st.session_state['default_prompt_author_institution']
st.session_state['prompt_description'] = st.session_state['default_prompt_description']
st.session_state['instructions'] = st.session_state['default_instructions']
st.session_state['json_formatting_instructions'] = st.session_state['default_json_formatting_instructions']
st.session_state['rules'] = {}
st.session_state['LLM'] = 'gpt'
st.session_state['assigned_columns'] = []
st.session_state['prompt_info'] = {
'prompt_author': st.session_state['prompt_author'],
'prompt_author_institution': st.session_state['prompt_author_institution'],
'prompt_description': st.session_state['prompt_description'],
'LLM': st.session_state['LLM'],
'instructions': st.session_state['instructions'],
'json_formatting_instructions': st.session_state['json_formatting_instructions'],
'rules': st.session_state['rules'],
'mapping': st.session_state['mapping'],
}
def refresh():
st.write('')
def upload_local_prompt_to_server(dir_prompt):
uploaded_file = st.file_uploader("Upload a custom prompt file", type=['yaml'])
if uploaded_file is not None:
# Check the file extension
file_name = uploaded_file.name
if file_name.endswith('.yaml'):
file_path = os.path.join(dir_prompt, file_name)
# Save the file
with open(file_path, 'wb') as f:
f.write(uploaded_file.getbuffer())
st.success(f"Saved file {file_name} in {dir_prompt}")
else:
st.error("Please upload a .yaml file that you previously created using this Prompt Builder tool.")
def create_download_button_yaml(file_path, selected_yaml_file):
file_label = f"Download {selected_yaml_file}"
with open(file_path, 'rb') as f:
st.download_button(
label=file_label,
data=f,
file_name=os.path.basename(file_path),
mime='application/x-yaml'
)
def clear_image_gallery():
delete_directory(st.session_state['dir_uploaded_images'])
delete_directory(st.session_state['dir_uploaded_images_small'])
validate_dir(st.session_state['dir_uploaded_images'])
validate_dir(st.session_state['dir_uploaded_images_small'])
def use_test_image():
st.info(f"Processing images from {os.path.join(st.session_state.dir_home,'demo','demo_images')}")
st.session_state.config['leafmachine']['project']['dir_images_local'] = os.path.join(st.session_state.dir_home,'demo','demo_images')
n_images = len([f for f in os.listdir(st.session_state.config['leafmachine']['project']['dir_images_local']) if os.path.isfile(os.path.join(st.session_state.config['leafmachine']['project']['dir_images_local'], f))])
st.session_state['processing_add_on'] = f" {n_images} Images"
########################################################################################################
### Streamlit sections ####
########################################################################################################
def create_space_saver():
st.subheader("Space Saving Options")
col_ss_1, col_ss_2 = st.columns([2,2])
with col_ss_1:
st.write("Several folders are created and populated with data during the VoucherVision transcription process.")
st.write("Below are several options that will allow you to automatically delete temporary files that you may not need for everyday operations.")
st.write("VoucherVision creates the following folders. Folders marked with a :star: are required if you want to use VoucherVisionEditor for quality control.")
st.write("`../[Run Name]/Archival_Components`")
st.write("`../[Run Name]/Config_File`")
st.write("`../[Run Name]/Cropped_Images` :star:")
st.write("`../[Run Name]/Logs`")
st.write("`../[Run Name]/Original_Images` :star:")
st.write("`../[Run Name]/Transcription` :star:")
with col_ss_2:
st.session_state.config['leafmachine']['project']['delete_temps_keep_VVE'] = st.checkbox("Delete Temporary Files (KEEP files required for VoucherVisionEditor)", st.session_state.config['leafmachine']['project'].get('delete_temps_keep_VVE', False))
st.session_state.config['leafmachine']['project']['delete_all_temps'] = st.checkbox("Keep only the final transcription file", st.session_state.config['leafmachine']['project'].get('delete_all_temps', False),help="*WARNING:* This limits your ability to do quality assurance. This will delete all folders created by VoucherVision, leaving only the `transcription.xlsx` file.")
def show_available_APIs():
st.session_state['has_key_openai'] = (os.getenv('OPENAI_API_KEY') is not None) and (os.getenv('OPENAI_API_KEY') != '')
st.session_state['has_key_google_OCR'] = (os.getenv('GOOGLE_APPLICATION_CREDENTIALS') is not None) and (os.getenv('GOOGLE_APPLICATION_CREDENTIALS') != '')
st.session_state['has_key_palm2'] = (os.getenv('PALM_API_KEY') is not None) and (os.getenv('PALM_API_KEY') != '')
st.session_state['has_key_azure'] = (os.getenv('AZURE_API_KEY') is not None) and (os.getenv('AZURE_API_KEY') != '')
emoji_good = ":heavy_check_mark:"
emoji_bad = ":x:"
table = {
'Google Vision OCR API (required!)': emoji_good if st.session_state['has_key_google_OCR'] else emoji_bad,
'OpenAI API': emoji_good if st.session_state['has_key_openai'] else emoji_bad,
'PaLM 2 API': emoji_good if st.session_state['has_key_palm2'] else emoji_bad,
'OpenAI API (Azure)': emoji_good if st.session_state['has_key_azure'] else emoji_bad,
}
for api_name, status in table.items():
st.markdown(f"* {status} {api_name}")
def display_image_gallery():
# Initialize the container
con_image = st.empty()
# Start the div for the image grid
img_grid_html = """
<div style='display: flex; flex-wrap: wrap; align-items: flex-start; overflow-y: auto; max-height: 400px; gap: 10px;'>
"""
# Loop through each image in the input list
# with con_image.container():
for image_path in st.session_state['input_list']:
# Open the image and create a thumbnail
img = Image.open(image_path)
img.thumbnail((120, 120), Image.Resampling.LANCZOS)
# Convert the image to base64
base64_image = image_to_base64(img)
# Append the image to the grid HTML
# img_html = f"""
# <div style='display: flex; flex-wrap: wrap; overflow-y: auto; max-height: 400px;'>
# <img src='data:image/jpeg;base64,{base64_image}' alt='Image' style='max-width: 100%; height: auto;'>
# </div>
# """
img_html = f"""
<img src='data:image/jpeg;base64,{base64_image}' alt='Image' style='max-width: 100%; height: auto;'>
"""
img_grid_html += img_html
# st.markdown(img_html, unsafe_allow_html=True)
# Close the div for the image grid
img_grid_html += "</div>"
# Display the image grid in the container
with con_image.container():
st.markdown(img_grid_html, unsafe_allow_html=True)
# The CSS to make the images display inline and be responsive
css = """
<style>
.scrollable-image-container img {
max-width: 100%;
height: auto;
}
</style>
"""
# Apply the CSS
st.markdown(css, unsafe_allow_html=True)
def show_header_welcome():
st.session_state.logo_path = os.path.join(st.session_state.dir_home, 'img','logo.png')
st.session_state.logo = Image.open(st.session_state.logo_path)
st.image(st.session_state.logo, width=250)
########################################################################################################
### Sidebar for Expense Report ####
########################################################################################################
def render_expense_report_summary():
cost_labels = []
cost_values = []
total_images = 0
cost_per_image_dict = {}
st.header('Expense Report Summary')
if st.session_state.expense_summary:
st.metric(label="Total Cost", value=f"${round(st.session_state.expense_summary['total_cost_sum'], 4):,}")
col1, col2 = st.columns(2)
# Run count and total costs
with col1:
st.metric(label="Run Count", value=st.session_state.expense_summary['run_count'])
st.metric(label="Tokens In", value=f"{st.session_state.expense_summary['tokens_in_sum']:,}")
# Token information
with col2:
st.metric(label="Total Images", value=st.session_state.expense_summary['n_images_sum'])
st.metric(label="Tokens Out", value=f"{st.session_state.expense_summary['tokens_out_sum']:,}")
# Calculate cost proportion per image for each API version
st.subheader('Average Cost per Image by API Version')
# Iterate through the expense report to accumulate costs and image counts
for index, row in st.session_state.expense_report.iterrows():
api_version = row['api_version']
total_cost = row['total_cost']
n_images = row['n_images']
total_images += n_images # Keep track of total images processed
if api_version not in cost_per_image_dict:
cost_per_image_dict[api_version] = {'total_cost': 0, 'n_images': 0}
cost_per_image_dict[api_version]['total_cost'] += total_cost
cost_per_image_dict[api_version]['n_images'] += n_images
api_versions = list(cost_per_image_dict.keys())
colors = [COLORS_EXPENSE_REPORT[version] if version in COLORS_EXPENSE_REPORT else '#DDDDDD' for version in api_versions]
# Calculate the cost per image for each API version
for version, cost_data in cost_per_image_dict.items():
total_cost = cost_data['total_cost']
n_images = cost_data['n_images']
# Calculate the cost per image for this version
cost_per_image = total_cost / n_images if n_images > 0 else 0
cost_labels.append(version)
cost_values.append(cost_per_image)
# Generate the pie chart
cost_pie_chart = go.Figure(data=[go.Pie(labels=cost_labels, values=cost_values, hole=.3)])
# Update traces for custom text in hoverinfo, displaying cost with a dollar sign and two decimal places
cost_pie_chart.update_traces(
marker=dict(colors=colors),
text=[f"${value:.2f}" for value in cost_values],
textinfo='percent+label',
hoverinfo='label+percent+text'
)
st.plotly_chart(cost_pie_chart, use_container_width=True)
st.subheader('Proportion of Total Cost by API Version')
cost_labels = []
cost_proportions = []
total_cost_by_version = {}
# Sum the total cost for each API version
for index, row in st.session_state.expense_report.iterrows():
api_version = row['api_version']
total_cost = row['total_cost']
if api_version not in total_cost_by_version:
total_cost_by_version[api_version] = 0
total_cost_by_version[api_version] += total_cost
# Calculate the combined total cost for all versions
combined_total_cost = sum(total_cost_by_version.values())
# Calculate the proportion of total cost for each API version
for version, total_cost in total_cost_by_version.items():
proportion = (total_cost / combined_total_cost) * 100 if combined_total_cost > 0 else 0
cost_labels.append(version)
cost_proportions.append(proportion)
# Generate the pie chart
cost_pie_chart = go.Figure(data=[go.Pie(labels=cost_labels, values=cost_proportions, hole=.3)])
# Update traces for custom text in hoverinfo
cost_pie_chart.update_traces(
marker=dict(colors=colors),
text=[f"${cost:.2f}" for cost in total_cost_by_version.values()],
textinfo='percent+label',
hoverinfo='label+percent+text'
)
st.plotly_chart(cost_pie_chart, use_container_width=True)
# API version usage percentages pie chart
st.subheader('Runs by API Version')
api_versions = list(st.session_state.expense_summary['api_version_percentages'].keys())
percentages = [st.session_state.expense_summary['api_version_percentages'][version] for version in api_versions]
pie_chart = go.Figure(data=[go.Pie(labels=api_versions, values=percentages, hole=.3)])
pie_chart.update_layout(margin=dict(t=0, b=0, l=0, r=0))
pie_chart.update_traces(marker=dict(colors=colors),)
st.plotly_chart(pie_chart, use_container_width=True)
else:
st.error('No expense report data available.')
def sidebar_content():
if not os.path.exists(os.path.join(st.session_state.dir_home,'expense_report')):
validate_dir(os.path.join(st.session_state.dir_home,'expense_report'))
expense_report_path = os.path.join(st.session_state.dir_home, 'expense_report', 'expense_report.csv')
if os.path.exists(expense_report_path):
# File exists, proceed with summarization
st.session_state.expense_summary, st.session_state.expense_report = summarize_expense_report(expense_report_path)
render_expense_report_summary()
else:
st.session_state.expense_summary, st.session_state.expense_report = None, None
st.header('Expense Report Summary')
st.write('Available after first run...')
########################################################################################################
### Config Builder ####
########################################################################################################
def build_LLM_prompt_config():
st.session_state['assigned_columns'] = []
st.session_state['default_prompt_author'] = 'unknown'
st.session_state['default_prompt_author_institution'] = 'unknown'
st.session_state['default_prompt_description'] = 'unknown'
st.session_state['default_instructions'] = """1. Refactor the unstructured OCR text into a dictionary based on the JSON structure outlined below.
2. You should map the unstructured OCR text to the appropriate JSON key and then populate the field based on its rules.
3. Some JSON key fields are permitted to remain empty if the corresponding information is not found in the unstructured OCR text.
4. Ignore any information in the OCR text that doesn't fit into the defined JSON structure.
5. Duplicate dictionary fields are not allowed.
6. Ensure that all JSON keys are in lowercase.
7. Ensure that new JSON field values follow sentence case capitalization.
8. Ensure all key-value pairs in the JSON dictionary strictly adhere to the format and data types specified in the template.
9. Ensure the output JSON string is valid JSON format. It should not have trailing commas or unquoted keys.
10. Only return a JSON dictionary represented as a string. You should not explain your answer."""
st.session_state['default_json_formatting_instructions'] = """The next section of instructions outlines how to format the JSON dictionary. The keys are the same as those of the final formatted JSON object.
For each key there is a format requirement that specifies how to transcribe the information for that key.
The possible formatting options are:
1. "verbatim transcription" - field is populated with verbatim text from the unformatted OCR.
2. "spell check transcription" - field is populated with spelling corrected text from the unformatted OCR.
3. "boolean yes no" - field is populated with only yes or no.
4. "boolean 1 0" - field is populated with only 1 or 0.
5. "integer" - field is populated with only an integer.
6. "[list]" - field is populated from one of the values in the list.
7. "yyyy-mm-dd" - field is populated with a date in the format year-month-day.
The desired null value is also given. Populate the field with the null value of the information for that key is not present in the unformatted OCR text."""
# Start building the Streamlit app
col_prompt_main_left, ___, col_prompt_main_right = st.columns([6,1,3])
with col_prompt_main_left:
st.title("Custom LLM Prompt Builder")
st.subheader('About')
st.write("This form allows you to craft a prompt for your specific task.")
st.subheader('For Hugging Face Spaces')
st.write("If you create a prompt with the Hugging Face Spaces implementation of VoucherVision, make sure that you download the prompt immediately after you have 'Saved' the prompt. Default storage space on HF Spaces is not persistant, so if you refresh the page your prompt will probably disappear.")
st.write("You can submit your prompt using this link and we will add it to our library so it will always be available.")
st.subheader('How it works')
st.write("1. Edit this page until you are happy with your instructions. We recommend looking at the basic structure, writing down your prompt inforamtion in a Word document so that it does not randomly disappear, and then copying and pasting that info into this form once your whole prompt structure is defined.")
st.write("2. After you enter all of your prompt instructions, click 'Save' and give your file a name.")
st.write("3. This file will be saved as a yaml configuration file in the `..VoucherVision/custom_prompts` folder.")
st.write("4. When you go back the main VoucherVision page you will now see your custom prompt available in the 'Prompt Version' dropdown menu.")
st.write("5. Select your custom prompt. Note, your prompt will only be available for the LLM that you set when filling out the form below.")
dir_prompt = os.path.join(st.session_state.dir_home, 'custom_prompts')
yaml_files = [f for f in os.listdir(dir_prompt) if f.endswith('.yaml')]
col_upload_yaml, col_upload_yaml_2 = st.columns([4,4])
with col_upload_yaml:
# Upload a prompt from your computer
upload_local_prompt_to_server(dir_prompt)
col_select_yaml, col_upload_btn, col_download_btn = st.columns([6,2,2])
with col_select_yaml:
# Dropdown for selecting a YAML file
st.session_state['selected_yaml_file'] = st.selectbox('Select a prompt .YAML file to load:', [''] + yaml_files)
with col_upload_btn:
st.write('##')
# Button to load the selected prompt
st.button('Load Selected Prompt into Builder', on_click=btn_load_prompt, args=[st.session_state['selected_yaml_file'] , dir_prompt])
with col_download_btn:
if st.session_state['selected_yaml_file']:
# Construct the full path to the file
download_file_path = os.path.join(dir_prompt, st.session_state['selected_yaml_file'] )
# Create the download button
st.write('##')
create_download_button_yaml(download_file_path, st.session_state['selected_yaml_file'] )
# Prompt Author Information
st.header("Prompt Author Information")
st.write("We value community contributions! Please provide your name(s) (or pseudonym if you prefer) for credit. If you leave this field blank, it will say 'unknown'.")
st.session_state['prompt_author'] = st.text_input("Enter names of prompt author(s)", value=st.session_state['prompt_info'].get('prompt_author', st.session_state['default_prompt_author']))
st.write("Please provide your institution name. If you leave this field blank, it will say 'unknown'.")
st.session_state['prompt_author_institution'] = st.text_input("Enter name of institution", value=st.session_state['prompt_info'].get('prompt_author_institution', st.session_state['default_prompt_author_institution']))
st.write("Please provide a description of your prompt and its intended task. Is it designed for a specific collection? Taxa? Database structure?")
st.session_state['prompt_description'] = st.text_input("Enter description of prompt", value=st.session_state['prompt_info'].get('prompt_description', st.session_state['default_prompt_description']))
# Input for new file name
st.write('---')
st.header("Prompt Name")
st.write('Provide a name for your custom prompt. It can only conatin letters, numbers, and underscores. No spaces, dashes, or special characters.')
st.session_state['new_prompt_yaml_filename'] = st.text_input("Enter filename to save your prompt as a configuration YAML:", value=None, placeholder='my_prompt_name')
# Define the options for the LLM Model Type dropdown
st.write('---')
st.header("Set LLM Model Type")
llm_options = ['gpt', 'palm']
# Create the dropdown and set the value to session_state['LLM']
st.write("Which LLM is this prompt designed for? This will not restrict its use to a specific LLM, but some prompts will behave in different ways across models.")
st.write("For example, VoucherVision will automatically add multiple JSON formatting blocks to all PaLM 2 prompts to coax PaLM 2 to return a valid JSON object.")
st.session_state['LLM'] = st.selectbox('Set LLM', llm_options, index=llm_options.index(st.session_state.get('LLM', 'gpt')))
st.write('---')
# Instructions Section
st.header("Instructions")
st.write("These are the general instructions that guide the LLM through the transcription task. We recommend using the default instructions unless you have a specific reason to change them.")
st.session_state['instructions'] = st.text_area("Enter instructions:", value=st.session_state['default_instructions'].strip(), height=350, disabled=True)
st.write('---')
# Column Instructions Section
st.header("JSON Formatting Instructions")
st.write("The following section tells the LLM how we want to structure the JSON dictionary. We do not recommend changing this section because it would likely result in unstable and inconsistent behavior.")
st.session_state['json_formatting_instructions'] = st.text_area("Enter column instructions:", value=st.session_state['default_json_formatting_instructions'], height=350, disabled=True)
st.write('---')
col_left, col_right = st.columns([6,4])
with col_left:
st.subheader('Add/Edit Columns')
# Initialize rules in session state if not already present
if 'rules' not in st.session_state or not st.session_state['rules']:
st.session_state['rules']['Dictionary'] = {
"catalog_number": {
"format": "verbatim transcription",
"null_value": "",
"description": "The barcode identifier, typically a number with at least 6 digits, but fewer than 30 digits."
}
}
st.session_state['rules']['SpeciesName'] = {
"taxonomy": ["Genus_species"]
}
new_column_name = st.text_input("Enter a new column name:")
if st.button("Add New Column") and new_column_name:
if new_column_name not in st.session_state['rules']['Dictionary']:
st.session_state['rules']['Dictionary'][new_column_name] = {"format": "", "null_value": "", "description": ""}
st.success(f"New column '{new_column_name}' added. Now you can edit its properties.")
else:
st.error("Column name already exists. Please enter a unique column name.")
# Get columns excluding the protected "catalog_number"
st.write('#')
editable_columns = [col for col in st.session_state['rules']['Dictionary'] if col != "catalog_number"]
column_name = st.selectbox("Select a column to edit:", [""] + editable_columns)
# Handle rules editing
current_rule = st.session_state['rules']['Dictionary'].get(column_name, {
"format": "",
"null_value": "",
"description": ""
})
if 'selected_column' not in st.session_state:
st.session_state['selected_column'] = column_name
# Form for input fields
with st.form(key='rule_form'):
format_options = ["verbatim transcription", "spell check transcription", "boolean yes no", "boolean 1 0", "integer", "[list]", "yyyy-mm-dd"]
current_rule["format"] = st.selectbox("Format:", format_options, index=format_options.index(current_rule["format"]) if current_rule["format"] else 0)
current_rule["null_value"] = st.text_input("Null value:", value=current_rule["null_value"])
current_rule["description"] = st.text_area("Description:", value=current_rule["description"])
commit_button = st.form_submit_button("Commit Column")
default_rule = {
"format": format_options[0], # default format
"null_value": "", # default null value
"description": "", # default description
}
if st.session_state['selected_column'] != column_name:
# Column has changed. Update the session_state selected column.
st.session_state['selected_column'] = column_name
# Reset the current rule to the default for this new column, or a blank rule if not set.
current_rule = st.session_state['rules']['Dictionary'].get(column_name, default_rule.copy())
# Handle commit action
if commit_button and column_name:
# Commit the rules to the session state.
st.session_state['rules']['Dictionary'][column_name] = current_rule.copy()
st.success(f"Column '{column_name}' added/updated in rules.")
# Force the form to reset by clearing the fields from the session state
st.session_state.pop('selected_column', None) # Clear the selected column to force reset
# Layout for removing an existing column
delete_column_name = st.selectbox("Select a column to delete:", [""] + editable_columns, key='delete_column')
if st.button("Delete Column") and delete_column_name:
del st.session_state['rules'][delete_column_name]
st.success(f"Column '{delete_column_name}' removed from rules.")
with col_right:
# Display the current state of the JSON rules
st.subheader('Formatted Columns')
st.json(st.session_state['rules']['Dictionary'])
st.write('---')
col_left_mapping, col_right_mapping = st.columns([6,4])
with col_left_mapping:
st.header("Mapping")
st.write("Assign each column name to a single category.")
st.session_state['refresh_mapping'] = False
# Dynamically create a list of all column names that can be assigned
# This assumes that the column names are the keys in the dictionary under 'rules'
all_column_names = list(st.session_state['rules']['Dictionary'].keys())
categories = ['TAXONOMY', 'GEOGRAPHY', 'LOCALITY', 'COLLECTING', 'MISCELLANEOUS']
if ('mapping' not in st.session_state) or (st.session_state['mapping'] == {}):
st.session_state['mapping'] = {category: [] for category in categories}
for category in categories:
# Filter out the already assigned columns
available_columns = [col for col in all_column_names if col not in st.session_state['assigned_columns'] or col in st.session_state['mapping'].get(category, [])]
# Ensure the current mapping is a subset of the available options
current_mapping = [col for col in st.session_state['mapping'].get(category, []) if col in available_columns]
# Provide a safe default if the current mapping is empty or contains invalid options
safe_default = current_mapping if all(col in available_columns for col in current_mapping) else []
# Create a multi-select widget for the category with a safe default
selected_columns = st.multiselect(
f"Select columns for {category}:",
available_columns,
default=safe_default,
key=f"mapping_{category}"
)
# Update the assigned_columns based on the selections
for col in current_mapping:
if col not in selected_columns and col in st.session_state['assigned_columns']:
st.session_state['assigned_columns'].remove(col)
st.session_state['refresh_mapping'] = True
for col in selected_columns:
if col not in st.session_state['assigned_columns']:
st.session_state['assigned_columns'].append(col)
st.session_state['refresh_mapping'] = True
# Update the mapping in session state when there's a change
st.session_state['mapping'][category] = selected_columns
if st.session_state['refresh_mapping']:
st.session_state['refresh_mapping'] = False
# Button to confirm and save the mapping configuration
if st.button('Confirm Mapping'):
if check_unique_mapping_assignments():
# Proceed with further actions since the mapping is confirmed and unique
pass
with col_right_mapping:
# Display the current state of the JSON rules
st.subheader('Formatted Column Maps')
st.json(st.session_state['mapping'])
st.write('---')
st.header("Save and Download Custom Prompt")
st.write('Once you click save, validation checks will verify the formatting and then a download button will appear so that you can ***save a local copy of your custom prompt.***')
col_left_save, col_right_save, _ = st.columns([2,2,8])
with col_left_save:
# Button to save the new YAML file
if st.button('Save YAML', type='primary'):
if st.session_state['new_prompt_yaml_filename']:
if check_unique_mapping_assignments():
if check_prompt_yaml_filename(st.session_state['new_prompt_yaml_filename']):
save_prompt_yaml(st.session_state['new_prompt_yaml_filename'], col_right_save)
else:
st.error("File name can only contain letters, numbers, underscores, and dashes. Cannot contain spaces.")
else:
st.error("Mapping contains an error. Make sure that each column is assigned to only ***one*** category.")
else:
st.error("Please enter a filename.")
st.write('---')
st.header("Return to VoucherVision")
if st.button('Exit'):
st.session_state.proceed_to_build_llm_prompt = False
st.session_state.proceed_to_main = True
st.rerun()
with col_prompt_main_right:
if st.session_state['user_clicked_load_prompt_yaml'] is None: # see if user has loaded a yaml to edit
st.session_state['show_prompt_name_e'] = f"Prompt Status :arrow_forward: Building prompt from scratch"
if st.session_state['new_prompt_yaml_filename']:
st.session_state['show_prompt_name_w'] = f"New Prompt Name :arrow_forward: {st.session_state['new_prompt_yaml_filename']}.yaml"
else:
st.session_state['show_prompt_name_w'] = f"New Prompt Name :arrow_forward: [PLEASE SET NAME]"
else:
st.session_state['show_prompt_name_e'] = f"Prompt Status: Editing :arrow_forward: {st.session_state['selected_yaml_file']}"
if st.session_state['new_prompt_yaml_filename']:
st.session_state['show_prompt_name_w'] = f"New Prompt Name :arrow_forward: {st.session_state['new_prompt_yaml_filename']}.yaml"
else:
st.session_state['show_prompt_name_w'] = f"New Prompt Name :arrow_forward: [PLEASE SET NAME]"
st.subheader(f'Full Prompt')
st.write(st.session_state['show_prompt_name_e'])
st.write(st.session_state['show_prompt_name_w'])
st.write("---")
st.session_state['prompt_info'] = {
'prompt_author': st.session_state['prompt_author'],
'prompt_author_institution': st.session_state['prompt_author_institution'],
'prompt_description': st.session_state['prompt_description'],
'LLM': st.session_state['LLM'],
'instructions': st.session_state['instructions'],
'json_formatting_instructions': st.session_state['json_formatting_instructions'],
'rules': st.session_state['rules'],
'mapping': st.session_state['mapping'],
}
st.json(st.session_state['prompt_info'])
def content_header():
# Header section, run, quick start, API report
col_run_1, col_run_2, col_run_3, col_run_4 = st.columns([2,2,2,2])
# Progress bar
col_run_info_1 = st.columns([1])[0]
with col_run_info_1:
# Progress
st.subheader("Overall Progress")
overall_progress_bar = st.progress(0)
text_overall = st.empty() # Placeholder for current step name
st.subheader('Transcription Progress')
batch_progress_bar = st.progress(0)
text_batch = st.empty() # Placeholder for current step name
progress_report = ProgressReport(overall_progress_bar, batch_progress_bar, text_overall, text_batch)
st.info("***Note:*** There is a known bug with tabs in Streamlit. If you update an input field it may take you back to the 'Project Settings' tab. Changes that you made are saved, it's just an annoying glitch. We are aware of this issue and will fix it as soon as we can.")
st.write("If you use VoucherVision frequently, you can change the default values that are auto-populated in the form below. In a text editor or IDE, edit the first few rows in the file `../VoucherVision/vouchervision/VoucherVision_Config_Builder.py`")
with col_run_1:
show_header_welcome()
st.subheader('Run VoucherVision')
if not check_if_usable():
st.button("Start Processing", type='primary', disabled=True)
# st.error(":heavy_exclamation_mark: Required API keys not set. Please visit the 'API Keys' tab and set the Google Vision OCR API key and at least one LLM key.")
st.error(":heavy_exclamation_mark: Required API keys not set. Please set the API keys as 'Secrets' for your Hugging Face Space. Visit the 'Settings' tab at the top of the page.")
else:
if st.button(f"Start Processing{st.session_state['processing_add_on']}", type='primary'):
# First, write the config file.
write_config_file(st.session_state.config, st.session_state.dir_home, filename="VoucherVision.yaml")
path_custom_prompts = os.path.join(st.session_state.dir_home,'custom_prompts',st.session_state.config['leafmachine']['project']['prompt_version'])
# Define number of overall steps
progress_report.set_n_overall(N_OVERALL_STEPS)
progress_report.update_overall(f"Starting VoucherVision...")
# Call the machine function.
last_JSON_response, total_cost, st.session_state['zip_filepath'] = voucher_vision(None, st.session_state.dir_home, path_custom_prompts, None, progress_report,path_api_cost=os.path.join(st.session_state.dir_home,'api_cost','api_cost.yaml'), is_real_run=True)
if total_cost:
st.success(f":money_with_wings: This run cost :heavy_dollar_sign:{total_cost:.4f}")
# Format the JSON string for display.
if last_JSON_response is None:
st.markdown(f"Last JSON object in the batch: NONE")
else:
try:
formatted_json = json.dumps(json.loads(last_JSON_response), indent=4, sort_keys=False)
except:
formatted_json = json.dumps(last_JSON_response, indent=4, sort_keys=False)
st.markdown(f"Last JSON object in the batch:\n```\n{formatted_json}\n```")
st.balloons()
if st.session_state['zip_filepath']:
create_download_button(st.session_state['zip_filepath'])
st.button("Refresh", on_click=refresh)
with col_run_2:
st.subheader('Quick Start')
st.write('1. We include a single image for testing. Without uploading your own images, you can select options below and press "Start Processing" to try VoucherVision.')
st.write('2. Name your run --- If the same name already exist, VV will append the date to the run name.')
st.write('3. Choose a LLM version --- Only LLMs with valid keys will appear in the dropdown list.')
st.write('4. Select a prompt version --- Start with "Version 2". Custom Prompts will include ".yaml" in the name. You can build your own Custom Prompt in the Prompt Builder.')
st.markdown('5. Upload images --- Up to ~100 images can be uploaded in the Hugging Face Spaces implementation. If you want to process more images at once (and have more control in general) then use the [GitHub version](https://github.com/Gene-Weaver/VoucherVision). If you pay for persistent storage for your HF Space, then you may be able to process more too.')
with col_run_3:
st.subheader('')
st.write('6. LeafMachine2 collage --- If selected, LeafMachine2 will isolate all text from the image and create a label collage, which will be sent to the OCR algorithm instead of the full image. This improves OCR detection for small or finely written text.')
st.write('7. OCR overlay images --- If selected, VoucherVision will overlay the OCR detections onto the input image. This is useful for debugging transcription errors to see if the OCR failed or if the LLM failed.')
st.write('8. Start processing --- Wait for VoucherVision to finish.')
st.write('9. Download results --- Click the "Download Results" button to save the VoucherVision output to your computer. ***Output files will disappear if you start a new run or restart the Space.***')
st.write('10. Editing the LLM transcriptions --- Use the VoucherVisionEditor to revise and correct any mistakes or ommissions.')
with col_run_4:
st.subheader('Available LLMs and APIs')
show_available_APIs()
st.info('Until the end of 2023, Azure OpenAI models will be available for anyone to use here. Then only PaLM 2 will be available. To use all services, duplicate this Space and provide your own API keys.')
########################################################################################################
### Main Settings ####
########################################################################################################
def content_tab_settings():
st.write("---")
st.header("Configuration Settings")
col_project_1, col_project_2, col_project_3 = st.columns([2,2,2])
st.write("---")
st.header('Input Images')
st.write('Upload a batch of images using the uploader below. These images will be store temporarily on this server. Each time you upload new images the ***previously uploaded images will be deleted***. You can also clear these cached images by pressing the "Clear Staged Images" button.')
col_local_1, col_local_2 = st.columns([2,6])
st.write("---")
st.header('LeafMachine2 Label Collage')
col_cropped_1, col_cropped_2 = st.columns([4,4])
st.write("---")
st.header('OCR Overlay Image')
col_ocr_1, col_ocr_2 = st.columns([4,4])
### Project
with col_project_1:
st.subheader('Run name')
st.session_state.config['leafmachine']['project']['run_name'] = st.text_input("Run name", st.session_state.config['leafmachine']['project'].get('run_name', ''),
label_visibility='collapsed')
st.write("Run name will be the name of the final zipped folder.")
### LLM Version
with col_project_2:
# Determine the available versions based on the API keys present
available_versions = []
for api_name, versions in st.session_state['LLM_VERSIONS'].items():
key_state = st.session_state['api_name_to_key_state'][api_name]
if st.session_state.get(key_state, False):
available_versions.extend(versions)
# Show available LLM versions in a select box if there are any
st.subheader('LLM Version')
if available_versions:
# Get current selection from session_state, defaulting to the first available version
current_selection = st.session_state.config['leafmachine'].get('LLM_version', available_versions[0])
# Update the selection with a selectbox
st.session_state.config['leafmachine']['LLM_version'] = st.selectbox(
"LLM version", available_versions,
index=available_versions.index(current_selection),
label_visibility='collapsed'
)
st.markdown("""***Note:*** GPT-4 is significantly more expensive than GPT-3.5""")
else:
st.error("No LLM versions are available due to missing API keys.")
### Prompt Version
with col_project_3:
st.subheader('Prompt Version')
versions, default_version = get_prompt_versions(st.session_state.config['leafmachine']['LLM_version'])
if versions:
selected_version = st.session_state.config['leafmachine']['project'].get('prompt_version', default_version)
if selected_version not in versions:
selected_version = default_version
st.session_state.config['leafmachine']['project']['prompt_version'] = st.selectbox("Prompt Version", versions, index=versions.index(selected_version),label_visibility='collapsed')
st.markdown("Several prompts are provided. Visit the 'Prompt Builder' tab to upload your own prompt. If you would like to make your prompt available to others or have the prompt in the dropdown by default, [please submit the yaml through this form.](https://forms.gle/d1sHV5Y7Y5NxMQzM9)")
if st.button("Build Custom LLM Prompt",help="It may take a moment for the page to refresh."):
st.session_state.proceed_to_build_llm_prompt = True
st.rerun()
### Input Images Local
with col_local_1:
st.session_state['dir_uploaded_images'] = os.path.join(st.session_state.dir_home,'uploads')
st.session_state['dir_uploaded_images_small'] = os.path.join(st.session_state.dir_home,'uploads_small')
uploaded_files = st.file_uploader("Upload Images", type=['jpg', 'jpeg'], accept_multiple_files=True)
if uploaded_files:
# Clear input image gallery and input list
clear_image_gallery()
# Process the new iamges
for uploaded_file in uploaded_files:
file_path = save_uploaded_file(st.session_state['dir_uploaded_images'], uploaded_file)
st.session_state['input_list'].append(file_path)
img = Image.open(file_path)
img.thumbnail((GALLERY_IMAGE_SIZE, GALLERY_IMAGE_SIZE), Image.Resampling.LANCZOS)
file_path_small = save_uploaded_file(st.session_state['dir_uploaded_images_small'], uploaded_file, img)
st.session_state['input_list_small'].append(file_path_small)
print(uploaded_file.name)
# Set the local images to the uploaded images
st.session_state.config['leafmachine']['project']['dir_images_local'] = st.session_state['dir_uploaded_images']
n_images = len([f for f in os.listdir(st.session_state.config['leafmachine']['project']['dir_images_local']) if os.path.isfile(os.path.join(st.session_state.config['leafmachine']['project']['dir_images_local'], f))])
st.session_state['processing_add_on'] = f" {n_images} Images"
uploaded_files = None
st.info(f"Processing ***{n_images}*** images from {st.session_state.config['leafmachine']['project']['dir_images_local']}")
st.button("Use Test Image",help="This will clear any uploaded images and load the 1 provided test image.",on_click=use_test_image)
# Show uploaded images gallery (thumbnails only)
with col_local_2:
if st.session_state['input_list_small']:
st.subheader('Image Gallery')
if len(st.session_state['input_list_small']) > MAX_GALLERY_IMAGES:
# Only take the first 100 images from the list
images_to_display = st.session_state['input_list_small'][:MAX_GALLERY_IMAGES]
else:
# If there are less than 100 images, take them all
images_to_display = st.session_state['input_list_small']
st.image(images_to_display)
with col_cropped_1:
default_crops = st.session_state.config['leafmachine']['cropped_components'].get('save_cropped_annotations', ['leaf_whole'])
st.write("Prior to transcription, use LeafMachine2 to crop all labels from input images to create label collages for each specimen image. (Requires GPU)")
st.session_state.config['leafmachine']['use_RGB_label_images'] = st.checkbox("Use LeafMachine2 label collage for transcriptions", st.session_state.config['leafmachine'].get('use_RGB_label_images', False))
st.session_state.config['leafmachine']['cropped_components']['save_cropped_annotations'] = st.multiselect("Components to crop",
['ruler', 'barcode','label', 'colorcard','map','envelope','photo','attached_item','weights',
'leaf_whole', 'leaf_partial', 'leaflet', 'seed_fruit_one', 'seed_fruit_many', 'flower_one', 'flower_many', 'bud','specimen','roots','wood'],default=default_crops)
with col_cropped_2:
ba = os.path.join(st.session_state.dir_home,'demo', 'ba','ba2.png')
image = Image.open(ba)
st.image(image, caption='LeafMachine2 Collage', output_format = "PNG")
with col_ocr_1:
st.write('This will plot bounding boxes around all text that Google Vision was able to detect. If there are no boxes around text, then the OCR failed, so that missing text will not be seen by the LLM when it is creating the JSON object. The created image will be viewable in the VoucherVisionEditor.')
st.session_state.config['leafmachine']['do_create_OCR_helper_image'] = st.checkbox("Create image showing an overlay of the OCR detections", st.session_state.config['leafmachine'].get('do_create_OCR_helper_image', False))
with col_ocr_2:
ocr = os.path.join(st.session_state.dir_home,'demo', 'ba','ocr.png')
image_ocr = Image.open(ocr)
st.image(image_ocr, caption='OCR Overlay Images', output_format = "PNG")
########################################################################################################
### Main ####
########################################################################################################
def main():
with st.sidebar:
sidebar_content()
# Main App
content_header()
tab_settings = st.container()
with tab_settings:
content_tab_settings()
########################################################################################################
### STREAMLIT APP START ####
########################################################################################################
st.set_page_config(layout="wide", page_icon='img/icon.ico', page_title='VoucherVision')
########################################################################################################
### STREAMLIT INIT STATES ####
########################################################################################################
if 'config' not in st.session_state:
st.session_state.config, st.session_state.dir_home = build_VV_config()
setup_streamlit_config(st.session_state.dir_home)
if 'proceed_to_main' not in st.session_state:
st.session_state.proceed_to_main = True
if 'proceed_to_build_llm_prompt' not in st.session_state:
st.session_state.proceed_to_build_llm_prompt = False
if 'proceed_to_private' not in st.session_state:
st.session_state.proceed_to_private = False
if 'dir_uploaded_images' not in st.session_state:
st.session_state['dir_uploaded_images'] = os.path.join(st.session_state.dir_home,'uploads')
validate_dir(os.path.join(st.session_state.dir_home,'uploads'))
if 'dir_uploaded_images_small' not in st.session_state:
st.session_state['dir_uploaded_images_small'] = os.path.join(st.session_state.dir_home,'uploads_small')
validate_dir(os.path.join(st.session_state.dir_home,'uploads_small'))
if 'prompt_info' not in st.session_state:
st.session_state['prompt_info'] = {}
if 'rules' not in st.session_state:
st.session_state['rules'] = {}
if 'zip_filepath' not in st.session_state:
st.session_state['zip_filepath'] = None
if 'input_list' not in st.session_state:
st.session_state['input_list'] = []
if 'input_list_small' not in st.session_state:
st.session_state['input_list_small'] = []
if 'selected_yaml_file' not in st.session_state:
st.session_state['selected_yaml_file'] = None
if 'new_prompt_yaml_filename' not in st.session_state:
st.session_state['new_prompt_yaml_filename'] = None
if 'show_prompt_name_e' not in st.session_state:
st.session_state['show_prompt_name_e'] = None
if 'show_prompt_name_w' not in st.session_state:
st.session_state['show_prompt_name_w'] = None
if 'user_clicked_load_prompt_yaml' not in st.session_state:
st.session_state['user_clicked_load_prompt_yaml'] = None
if 'processing_add_on' not in st.session_state:
st.session_state['processing_add_on'] = ' 1 Image'
if 'LLM_VERSIONS' not in st.session_state:
st.session_state['LLM_VERSIONS'] = {
'OpenAI API': ["GPT 4", "GPT 3.5"],
'Azure API': ["Azure GPT 4", "Azure GPT 3.5"],
'Palm API': ["PaLM 2"]
}
if 'api_name_to_key_state ' not in st.session_state:
st.session_state['api_name_to_key_state'] = {
'OpenAI API': 'has_key_openai',
'Google OCR API': 'has_key_google_OCR',
'Palm API': 'has_key_palm2',
'Azure API': 'has_key_azure'
}
# Initialize API key states if not already in session_state
for api_name, key_state in st.session_state['api_name_to_key_state'].items():
if key_state not in st.session_state:
st.session_state[key_state] = False
########################################################################################################
### STREAMLIT SESSION GUIDE ####
########################################################################################################
if st.session_state.proceed_to_build_llm_prompt:
build_LLM_prompt_config()
elif st.session_state.proceed_to_main:
main() |