forked from Gene-Weaver/VoucherVisionEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVoucherVisionEditor.py
More file actions
3771 lines (3022 loc) · 177 KB
/
VoucherVisionEditor.py
File metadata and controls
3771 lines (3022 loc) · 177 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 streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import json, os, argparse, shutil, re, toml, math, yaml, tempfile, zipfile, base64, webbrowser, threading, subprocess, platform
from PIL import Image
from utils import *
from io import BytesIO
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
from annotated_text import annotated_text
from datetime import datetime
from contextlib import contextmanager
import cProfile
import pstats
from utils import get_wfo_url, ScreenResolution
from text import HelpText
# For Table View
from streamlit.components.v1 import html
from itables import JavascriptFunction
import itables.options as opt
from itables import to_html_datatable, init_notebook_mode, show, JavascriptCode
from itables.downsample import as_nbytes, nbytes
from itables.sample_dfs import get_indicators
# init_notebook_mode(all_interactive=True)
opt.maxBytes = 0 # Set maxBytes to 0 to remove any size restrictions
opt.maxRows = 0 # No limit on number of rows
opt.maxColumns = 0 # No limit on number of columns
# pip install streamlit pandas Pillow openpyxl streamlit-aggrid
# Windows
# streamlit run your_script.py -- --SAVE_DIR /path/to/save/dir
# Linux
# export SAVE_DIR=/path/to/save/dir && streamlit run your_script.py
### To run:
# streamlit run VoucherVisionEditor.py --
# --base-path D:/D_Desktop/LM2/Asa_Gray/Transcription
# --save-dir D:/D_Desktop/LM2
# streamlit run VoucherVisionEditor.py --
# --base-path D:/Dropbox/LM2_Env/VoucherVision_Datasets/POC_chatGPT__2022_09_07_thru12_S3_jacortez_AllAsia/2022_09_07_thru12_S3_jacortez_AllAsia_2023_06_16__02-12-26
# --save-dir D:/D_Desktop/OUT
os.chdir(os.path.dirname(os.path.realpath(__file__)))
st.set_page_config(layout="wide",
page_icon='img/icon.ico',
page_title='VoucherVision Editor',
menu_items={"Report a Bug": "https://forms.gle/kP8imC9JQTPLrXgg8","About":"VoucherVision was created and is maintained by William Weaver, University of Michigan. Please see doi:10.1002/ajb2.16256 for more information."},
initial_sidebar_state="expanded",)
LAST_UPDATED = "Dec 19, 2024 --- v3"
###########################################################################################################################
######## If true, this will let you host the project remotely
######## Otherwise all project info will be hosted inside VoucherVisionEditor/ on the local machine
###########################################################################################################################
if "USE_REMOTE" not in st.session_state:
st.session_state.USE_REMOTE = False
if "project_dir" not in st.session_state:
st.session_state.project_dir = ''
###########################################################################################################################
if "screen_width" not in st.session_state:
screen = ScreenResolution()
st.session_state.screen_width, st.session_state.screen_height = screen.get_smallest_monitor()
if "start_editing" not in st.session_state:
st.session_state.start_editing = False
if "hide_columns_in_editor" not in st.session_state:
st.session_state.hide_columns_in_editor = []
# Initialize Streamlit Session State if it hasn't been initialized yet
if "row_to_edit" not in st.session_state:
st.session_state.row_to_edit = 0
if 'data' not in st.session_state:
st.session_state.data = None
if "file_name" not in st.session_state:
st.session_state.file_name = None
if "user_input" not in st.session_state:
st.session_state.user_input = {}
if "table_height_holder" not in st.session_state:
st.session_state.table_height_holder = 0
if "clear_count" not in st.session_state:
st.session_state.clear_count = 0
if "track_edits" not in st.session_state:
st.session_state.track_edits = []
if "current_options" not in st.session_state:
st.session_state.setdefault('current_options', [] if st.session_state.track_edits else [])
if "progress_counter" not in st.session_state:
st.session_state.progress_counter = 0
if "progress_counter_overall" not in st.session_state:
st.session_state.progress_counter_overall = 0
if "progress" not in st.session_state:
st.session_state.progress = 0
if "entries_per_page" not in st.session_state:
st.session_state.entries_per_page = 10
if "progress_index" not in st.session_state:
st.session_state.progress_index = 0
if "access_option" not in st.session_state:
st.session_state.access_option = 'Labeler'
if "prompt_mapping" not in st.session_state:
st.session_state.prompt_mapping = None
# Store the previous value of st.session_state.access_option
if 'previous_access_option' not in st.session_state:
st.session_state.previous_access_option = 'Labeler'
if 'image_option' not in st.session_state:
# st.session_state.image_option = 'Cropped'
st.session_state.image_option = 'Original'
if 'last_image_option' not in st.session_state:
st.session_state.last_image_option = ''
if 'default_to_original' not in st.session_state:
st.session_state.default_to_original = True
if 'view_option' not in st.session_state:
st.session_state.view_option = "Form View"
if 'show_helper_text' not in st.session_state:
st.session_state.show_helper_text = False
if 'set_image_size' not in st.session_state:
st.session_state.set_image_size = 'Custom'
if 'set_image_size_previous' not in st.session_state:
st.session_state.set_image_size_previous = 'Custom'
if 'set_image_size_px' not in st.session_state:
if st.session_state.screen_height >= 1600:
st.session_state.set_image_size_px = 1000
elif st.session_state.screen_height >= 1400:
st.session_state.set_image_size_px = 900
elif st.session_state.screen_height >= 1100:
st.session_state.set_image_size_px = 850
elif st.session_state.screen_height >= 1000:
st.session_state.set_image_size_px = 800
elif st.session_state.screen_height >= 850:
st.session_state.set_image_size_px = 650
else:
st.session_state.set_image_size_px = 500
if 'set_image_size_pxh' not in st.session_state:
st.session_state.set_image_size_pxh = 80
if 'set_map_height_pxh' not in st.session_state:
st.session_state.set_map_height_pxh = 200
if 'image_fill' not in st.session_state:
st.session_state.image_fill = "More - Image Right"
if 'use_extra_image_options' not in st.session_state:
st.session_state.use_extra_image_options = False
if 'is_fitted_image' not in st.session_state:
st.session_state.is_fitted_image = False
if 'fitted_image_width' not in st.session_state:
st.session_state.fitted_image_width = 600
if 'n_columns' not in st.session_state:
st.session_state.n_columns = 26
if 'working_file' not in st.session_state:
st.session_state.working_file = None
if 'prompt_name' not in st.session_state:
st.session_state.prompt_name = None
if 'prompt_json' not in st.session_state:
st.session_state.prompt_json = None
if 'form_hint_location' not in st.session_state:
st.session_state.form_hint_location = 'Left'
if 'search_term' not in st.session_state:
st.session_state.search_term = ''
if 'color_map_order' not in st.session_state:
st.session_state.color_map_order = ["#7fbfff", "#f6a14f", "#48ca48", "#bf7fbf", "#ff3333" , "#787878", "#ff00fb"]
if 'color_map_order_text' not in st.session_state:
st.session_state.color_map_order_text = [":blue", ":orange", ":green", ":violet", ":red" , ":gray", ":rainbow"]
if 'color_map_json' not in st.session_state:
st.session_state.color_map_json = {}
if 'color_map_text' not in st.session_state:
st.session_state.color_map_text = {}
if 'wfo_match_level' not in st.session_state:
st.session_state.wfo_match_level = "No Match"
if 'image_rotation' not in st.session_state:
st.session_state.image_rotation = "0"
if 'image_rotation_change' not in st.session_state:
st.session_state.image_rotation_change = True
if 'relative_path_to_static' not in st.session_state:
st.session_state.relative_path_to_static = ''
if 'image_path' not in st.session_state:
st.session_state.image_path = ''
if 'current_time' not in st.session_state:
st.session_state.current_time = 'NA'
if 'hide_fields' not in st.session_state:
st.session_state.hide_fields = []
if 'add_fields' not in st.session_state:
st.session_state.add_fields = {}
if 'set_map_height' not in st.session_state:
st.session_state.set_map_height = True
if 'user_uniqname' not in st.session_state:
st.session_state.user_uniqname = ''
if 'user_uniqname_key' not in st.session_state:
st.session_state.user_uniqname_key = 6787987987
if 'dialog_closed' not in st.session_state:
st.session_state.dialog_closed = False
if 'group_options_tracker' not in st.session_state:
st.session_state.group_options_tracker = {}
if 'n_manual_data' not in st.session_state:
st.session_state.n_manual_data = 0
if 'n_total_data' not in st.session_state:
st.session_state.n_total_data = 0
if 'tool_access' not in st.session_state:
st.session_state.tool_access = {
'show_skip_specimen': False,
'form': True, #ALWAYS TRUE
'arrow': True,
'hints': True,
'ocr': False,
'wfo_badge': True,
'taxa_links': True,
'wfo_links': True,
'additional_info': True,
'cap': True,
'search': False,
}
if 'pwd' not in st.session_state:
st.session_state.pwd = 'vouchervisionadmin'
if 'image_rotation_previous' not in st.session_state:
st.session_state.image_rotation_previous = ''
if 'location_google_search' not in st.session_state:
st.session_state.location_google_search = "Top" # "Top", "Hint Panel", "Bottom"
if 'google_search_new_window' not in st.session_state:
st.session_state.google_search_new_window = False #TODO
if 'grouping' not in st.session_state:
st.session_state.grouping = None
# Initialize a state to know whether the button was clicked or not
if "button_clicked" not in st.session_state:
st.session_state.button_clicked = False
if "form_width" not in st.session_state:
st.session_state.wrap_len = 30
st.session_state.form_width_1 = 30
st.session_state.form_width_2 = 50
if "distance_GPS_warn" not in st.session_state: # Can be configured
st.session_state.distance_GPS_warn = 100
if 'zoom_dist' not in st.session_state: # Can be configured
st.session_state.zoom_dist = 3000
if 'pinpoint' not in st.session_state:
st.session_state.pinpoint = "Broad"
if 'coordinates_dist' not in st.session_state:
st.session_state.coordinates_dist = None
if 'fullpath_working_file' not in st.session_state:
st.session_state.fullpath_working_file = None
if 'dir_home' not in st.session_state:
st.session_state.dir_home = os.path.dirname(__file__)
st.session_state.dir_settings = os.path.join(st.session_state.dir_home,'settings')
st.session_state.settings_file = ""
if 'data' not in st.session_state:
st.session_state.data = None
if 'wiki_file_list' not in st.session_state:
st.session_state.wiki_file_list = []
if 'wiki_file_dict' not in st.session_state:
st.session_state.wiki_file_dict = {}
if 'search_results_duckduckgo' not in st.session_state:
st.session_state.search_results_duckduckgo = None
if 'search_info_plants' not in st.session_state:
st.session_state.search_info_plants = ['order','family','scientificName', 'scientificNameAuthorship', 'genus','subgenus', 'specificEpithet', 'infraspecificEpithet',]
if 'search_info_geo' not in st.session_state:
st.session_state.search_info_geo = ['country','stateProvince','county', 'municipality', 'minimumElevationInMeters','maximumElevationInMeters', 'locality', 'habitat','decimalLatitude', 'decimalLongitude', 'verbatimCoordinates',]
if 'search_info_people' not in st.session_state:
st.session_state.search_info_people = ['identifiedBy','recordedBy',]
if 'BASE_PATH' not in st.session_state:
st.session_state.BASE_PATH = ''
if 'BASE_PATH_MANUAL' not in st.session_state:
st.session_state.BASE_PATH_MANUAL = None
if 'bp_text' not in st.session_state:
st.session_state.bp_text = '''
## Running VVE from the command line (optional)
#### Save Directory and Base Path Configuration
When launching the VoucherVision Editor (VVE) from the command line, two optional arguments can be specified: `--save-dir` and `--base-path`.
- `--save-dir` defines where the edited file will be saved. VVE never overwrites the original transcription file. This must be the full file path to where the edited transcription.xlsx should be saved. If you need to pause an editing run and resume it at a later time, then the last "edited" file becomes the new input file, but `--save-dir` can remain the same because it will simply increment after each save.
- `--base-path` optional. Reroutes the file paths in the original transcription file ***if the files have been moved***. The original transcription file saves the full paths to the transcription JSON files, cropped labels images, and the original full specimen images. If the computer where VVE is running has access to these files and those file locations have not changed, then the `--base-path` option is not needed. But in the event that the original file paths are broken, this will rebuild the file paths to the new locations.
If `--save-dir` and `--base-path` are not provided in the command line arguments, you can specify them below.
'''
if 'save_dir_help' not in st.session_state:
st.session_state.save_dir_help = """
Defines where the edited file will be saved.
VVE never overwrites the original transcription file.
This must be the full file path to where the edited transcription.xlsx should be saved.
If you need to pause an editing run and resume it at a later time,
then the last "edited" file becomes the new input file,
but --save-dir can remain the same because it will simply increment after each session.
"""
if 'base_path_help' not in st.session_state:
st.session_state.base_path_help = """
Reroutes the file paths in the original transcription file if the files have been moved.
The original transcription file saves the full paths to the transcription JSON files,
cropped labels images, and the original full specimen images.
If the computer where VVE is running has access to these files and those file locations have not changed,
then the --base-path option is not needed.
But in the event that the original file paths are broken, this will rebuild the file paths to the new locations.
For example, if the old path in your file is: 'C:/Users/old_user/Documents/Project/Transcription/File.json'
and the new base path you enter is: 'D:/New_Project_Location/'
then the new path for the file will become: 'D:/New_Project_Location/Transcription/File.json'.
"""
parser = argparse.ArgumentParser(description='Define save location of edited file.')
# Add parser argument for save directory
parser.add_argument('--save-dir', type=str, default=None,
help='Directory to save output files')
parser.add_argument('--base-path', type=str, default='',
help='New base path to replace the existing one, up to "/Transcription"')
parser.add_argument('--prompt-version', type=str, default='',
help='Prompt version used for VoucherVision. V1 has 26 total columns. V2 has 30 column (all headers are lowercase, have underscores)')
# Parse the arguments
try:
args = parser.parse_args()
except SystemExit as e:
# This exception will be raised if --help or invalid command line arguments
# are used. Currently streamlit prevents the program from exiting normally
# so we have to do a hard exit.
os._exit(e.code)
###############################################################
################# Config ####################
###############################################################
def setup_streamlit_config(mapbox_key=None):
# Define the directory path and filename
dir_path = ".streamlit"
file_path = os.path.join(dir_path, "config.toml")
# Check if directory exists, if not create it
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# If the mapbox_key is empty, and the config file already has a mapbox key, don't overwrite the file
# if mapbox_key == None:
# if os.path.exists(file_path):
# config_data = toml.load(file_path)
# existing_key = config_data.get('mapbox', {}).get('token', None)
# if existing_key is not None and existing_key != '':
# return
# Create or modify the file with the provided content
config_content = f"""
[theme]
primaryColor = "#00ff00"
backgroundColor="#1a1a1a"
secondaryBackgroundColor="#303030"
textColor = "cccccc"
[server]
enableStaticServing = true
runOnSave = true
port = 8523
[runner]
fastReruns = false
"""
if mapbox_key:
config_content += f"""
[mapbox]
token = "{mapbox_key}"
"""
with open(file_path, "w") as f:
f.write(config_content.strip())
###############################################################
################# Definitions ####################
###############################################################
# st.session_state.color_map = {
# "TAXONOMY": 'blue',
# "GEOGRAPHY": 'orange',
# "LOCALITY": 'green',
# "COLLECTING": 'violet',
# "MISC": 'red',
# # "OCR": '#7fbfff',
# }
# st.session_state.color_map_json = {
# "TAXONOMY": "#7fbfff", # pastel blue
# "GEOGRAPHY": "#f6a14f", # pastel orange
# "LOCALITY": "#48ca48", # pastel green
# "COLLECTING": "#bf7fbf", # pastel purple
# "MISC": "#ff3333", # pastel red
# }
# def set_column_groups():
# # if st.session_state.n_columns == 26: # Version 1 prompts
# if st.session_state.prompt_version == 'v1':
# st.session_state.grouping = {
# "TAXONOMY": ["Catalog Number", "Genus", "Species", "subspecies", "variety", "forma",],
# "GEOGRAPHY": ["Country", "State", "County", "Verbatim Coordinates",],
# "LOCALITY": ["Locality Name", "Min Elevation", "Max Elevation", "Elevation Units",],
# "COLLECTING": ["Datum","Cultivated","Habitat","Collectors","Collector Number", "Verbatim Date","Date", "End Date",],
# }
# # elif st.session_state.n_columns == 30: # Version 2 prompts
# if st.session_state.prompt_version == 'v2':
# st.session_state.grouping = {
# "TAXONOMY": ["catalog_number", "genus", "species", "subspecies", "variety", "forma",],
# "GEOGRAPHY": ["country", "state", "county", "verbatim_coordinates","decimal_coordinates"],
# "LOCALITY": ["locality_name", "min_elevation", "max_elevation", "elevation_units",],
# "COLLECTING": ["datum","cultivated","habitat","plant_description","collectors","collector_number", "determined_by", "verbatim_date","date", "end_date",],
# }
# else:
# raise
def set_column_groups():
try:
with open(st.session_state.settings_file, 'r') as file:
st.session_state.settings_file_dict = yaml.safe_load(file)
st.session_state.add_fields = st.session_state.settings_file_dict['editor']['add_fields']
st.session_state.hide_fields = st.session_state.settings_file_dict['editor']['hide_fields']
except:
pass
mapping = st.session_state.prompt_mapping
# Initialize an empty dictionary for the new grouping
new_grouping = {}
ind = 0
temp_map = {}
# Iterate over the mapping
for group, columns in mapping.items():
temp_map[group] = ind
# Create a new group in the new_grouping dictionary with the list of columns
if columns:
new_grouping[group] = columns
st.session_state.color_map_json[group] = st.session_state.color_map_order[ind]
st.session_state.color_map_text[group] = st.session_state.color_map_order_text[ind]
ind += 1
# Add the new columsn to the list
for group, columns in st.session_state.add_fields.items():
if (group in new_grouping) and columns:
# Group exists, append the columns if not empty
if not isinstance(new_grouping[group], list):
new_grouping[group] = [new_grouping[group]] # Ensure it's a list
new_grouping[group].extend(columns) # Append new columns
else:
st.session_state.color_map_json[group] = st.session_state.color_map_order[ind]
st.session_state.color_map_text[group] = st.session_state.color_map_order_text[ind]
# Group doesn't exist or has no columns, assign new columns
new_grouping[group] = (columns)
ind += 1
# Add the new columns to the CSV
# Update the st.session_state.grouping with the new grouping
st.session_state.grouping = new_grouping
###############################################################
################# Utils ####################
###############################################################
def unzip_and_setup_path(uploaded_file, target_dir):
if uploaded_file is not None:
with st.spinner(f'Extracting files to [{target_dir}]'):
with zipfile.ZipFile(uploaded_file, 'r') as zip_ref:
zip_ref.extractall(target_dir)
st.success("File unpacked successfully")
# def upload_and_unzip():
# project_dir = os.path.join(st.session_state.dir_home, 'projects')
# os.makedirs(project_dir, exist_ok=True)
# uploaded_file = st.file_uploader("Add a .zip file to the projects folder. Once added, you can select the project and then choose a transcription file to edit. ",
# type='zip',accept_multiple_files=False,)
# if uploaded_file is not None:
# # Construct the target directory path
# # Assuming `dir_home` and `projects` are defined or replace with actual values
# filename_zip = uploaded_file.name
# base_filename = filename_zip.rsplit('.', 1)[0] # Remove the .zip extension
# target_dir = os.path.join(project_dir, base_filename)
# os.makedirs(target_dir, exist_ok=True) # Create target directory if it doesn't exist
# # Unzip and set up the path
# unzip_and_setup_path(uploaded_file, target_dir)
# # Update BASE_PATH to the new directory containing the unpacked files
# st.session_state.BASE_PATH = target_dir
# print(f"BASE = {target_dir}")
# subdirs = [d for d in os.listdir(project_dir) if os.path.isdir(os.path.join(project_dir, d))]
# # Create a select box for choosing a subdirectory
# selected_subdir = st.selectbox("Select a project:", subdirs)
# st.session_state.BASE_PATH = os.path.join(project_dir, selected_subdir)
# st.info(f"Working from: {st.session_state.BASE_PATH}")
def resolve_actual_path(directory):
"""Resolve the actual path to handle different mappings."""
return os.path.realpath(directory)
def get_mounted_volumes():
"""Returns a list of currently mounted volumes on macOS."""
volumes = []
if platform.system() == 'Darwin': # macOS
volumes_dir = '/Volumes/'
if os.path.exists(volumes_dir):
volumes = [os.path.join(volumes_dir, d) for d in os.listdir(volumes_dir) if os.path.isdir(os.path.join(volumes_dir, d))]
return volumes
def find_available_project_dir(project_dir_list):
"""Find the available project directory from a list of paths."""
if not project_dir_list:
raise ValueError("The project directory list is empty.")
system_platform = platform.system()
# Handle Windows paths
if system_platform == 'Windows':
for directory in project_dir_list:
resolved_path = resolve_actual_path(directory)
# If the resolved path exists, return it
if os.path.exists(resolved_path):
return resolved_path
# Handle macOS paths
elif system_platform == 'Darwin':
mounted_volumes = get_mounted_volumes()
# Try replacing "S:" with each mounted volume and check if path exists
for directory in project_dir_list:
for volume in mounted_volumes:
print(f"Mounted Volume: {volume}, DIR: {directory}")
possible_mappings = [
directory.replace("S:", volume),
directory.replace("Curatorial Projects/VoucherVision", "VoucherVision").replace("S:", volume)
]
print(f" Possible Mappings: {possible_mappings}")
for path in possible_mappings:
if os.path.exists(path):
return os.path.realpath(path) # Return the resolved path directly
# If none of the paths resolve, raise an error
return None
@st.dialog("Add new user")
def add_new_user():
st.warning(f"Do you want to add {st.session_state.user_uniqname} as a new user?")
c1, c2 = st.columns(2)
with c1:
if st.button(f"No"):
st.session_state.user_uniqname = ''
st.session_state.project_dir = ''
st.session_state.user_uniqname_key +=1
st.rerun()
with c2:
if st.button(f"Add :violet-background[{st.session_state.user_uniqname}]"):
if st.session_state.USE_REMOTE:
st.session_state.project_dir = os.path.join(st.session_state.BASE_PATH_MANUAL, st.session_state.user_uniqname)
else:
st.session_state.project_dir = os.path.join(st.session_state.dir_home, 'projects', st.session_state.user_uniqname)
os.makedirs(st.session_state.project_dir, exist_ok=True)
st.rerun()
def upload_and_unzip():
file_path = os.path.join(st.session_state.dir_home, 'settings', 'default.yaml')
c_left, c_right = st.columns([8,2])
with c_right:
st.markdown(""":violet-background[NOTE:]\n\n- Refreshing your browser will restart VoucherVisionEditor from this page and reset all settings\n\n- In the Editor, every change you make is immediately saved to the session's .xlsx file""")
st.markdown(f"Last Updated: {LAST_UPDATED}")
with c_left:
# Load existing settings
st.session_state.settings = load_yaml_settings(file_path)
if st.session_state.settings is None:
st.session_state.settings = {
'editor': {
'hide_fields': [],
'add_fields': {},
}
,'locations': {
'project_dir': 'local',
}
}
# save_yaml_settings(file_path, st.session_state.settings)
project_dir_list = st.session_state.settings['locations']['project_dir']
if st.session_state.settings['locations']['project_dir'] != "local":
try:
st.session_state.USE_REMOTE = True
# Check for the first available directory in the list
available_project_dir = None
available_project_dir = find_available_project_dir(project_dir_list)
if available_project_dir is None:
# If no directories are found, raise an error and disable remote usage
raise FileNotFoundError("None of the project directories are accessible")
else:
project_dir_list = [available_project_dir]
# if platform.system() == 'Darwin':
# raise NotImplementedError("macOS (Darwin) handling is not implemented yet")
except Exception as e:
st.session_state.USE_REMOTE = False
# if platform.system() == 'Darwin':
# raise NotImplementedError("macOS (Darwin) handling is not implemented yet")
st.error(f"The settings/default.yaml file location for the project_dir is set to {project_dir_list} but none are accessible. VoucherVisionEditor will default to loading/storing data locally within VoucherVisionEditor/projects/")
st.error(str(e))
else:
st.session_state.USE_REMOTE = False
# Remote file handling
if st.session_state.USE_REMOTE:
if isinstance(project_dir_list, str):
project_dir_list = [project_dir_list]
st.session_state.BASE_PATH_MANUAL = st.selectbox("Set Project Directory", options=project_dir_list, index=project_dir_list.index(available_project_dir), disabled=True)
if st.session_state.BASE_PATH_MANUAL is not None:
st.session_state.user_uniqname = st.text_input("Set Uniqname", value=st.session_state.user_uniqname, key=st.session_state.user_uniqname_key)
if st.session_state.user_uniqname == '':
st.warning("Uniqname cannot be empty. Please enter your Uniqname.")
else:
if not os.path.exists(os.path.join(st.session_state.BASE_PATH_MANUAL, st.session_state.user_uniqname)):
add_new_user()
else:
st.session_state.project_dir = os.path.join(st.session_state.BASE_PATH_MANUAL, st.session_state.user_uniqname)
# Local file handling
else:
st.session_state.user_uniqname = st.text_input("Set Uniqname", value=st.session_state.user_uniqname, key=st.session_state.user_uniqname_key)
if st.session_state.user_uniqname == '':
st.warning("Uniqname cannot be empty. Please enter your Uniqname.")
else:
if not os.path.exists(os.path.join(st.session_state.dir_home, 'projects', st.session_state.user_uniqname)):
add_new_user()
else:
st.session_state.project_dir = os.path.join(st.session_state.dir_home, 'projects', st.session_state.user_uniqname)
if st.session_state.project_dir != '' and st.session_state.user_uniqname != '':
uploaded_file = st.file_uploader("Add a .zip file to the projects folder. Once added, you can select the project and then choose a transcription file to edit.",
type='zip', accept_multiple_files=False)
# Initialize an indicator for a newly uploaded project
new_project_added = False
if uploaded_file is not None:
# Construct the target directory path
filename_zip = uploaded_file.name
base_filename = filename_zip.rsplit('.', 1)[0] # Remove the .zip extension
target_dir = os.path.join(st.session_state.project_dir, base_filename)
if not os.path.exists(target_dir):
os.makedirs(target_dir, exist_ok=True) # Create target directory if it doesn't exist
# Unzip and set up the path
unzip_and_setup_path(uploaded_file, target_dir)
uploaded_file = None
# Indicate a new project has been added to update BASE_PATH later
new_project_added = True
print(f"BASE = {target_dir}")
# Initialize an empty list to store subdirectories
subdirs = []
# Iterate through all items in the project directory
for item in os.listdir(st.session_state.project_dir):
# Create the full path of the item
item_path = os.path.join(st.session_state.project_dir, item)
# Check if the item is a directory and not named "CONFIG"
if os.path.isdir(item_path) and item != "CONFIG":
# If it's a valid subdirectory, add it to the subdirs list
subdirs.append(item)
# Create a select box for choosing a subdirectory
selected_subdir = st.selectbox("Select a project:", subdirs)
# # Update BASE_PATH based on the user's actions
# if new_project_added:
# # If a new project was uploaded, use its path
# st.session_state.BASE_PATH = target_dir
# elif selected_subdir:
# # Otherwise, update BASE_PATH to the selected subdirectory
# st.session_state.BASE_PATH = os.path.join(project_dir, selected_subdir)
# st.info(f"Working from: {st.session_state.BASE_PATH}")
# else:
# pass
# Update BASE_PATH based on the user's actions
if new_project_added:
# If a new project was uploaded, use its path
st.session_state.BASE_PATH = os.path.join(st.session_state.project_dir, selected_subdir)
elif selected_subdir:
# Otherwise, update BASE_PATH to the selected subdirectory
st.session_state.BASE_PATH = os.path.join(st.session_state.project_dir, selected_subdir)
st.info(f"Working from: {st.session_state.BASE_PATH}")
else:
pass
def prompt_for_mapbox_key():
# Define the directory path and filename
dir_path = ".streamlit"
file_path = os.path.join(dir_path, "config.toml")
# Check if directory exists, if not create it
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# If config file exists, load existing Mapbox key, if any
existing_key = None
if os.path.exists(file_path):
config_data = toml.load(file_path)
existing_key = config_data.get('mapbox', {}).get('token', None)
# Ask the user for their Mapbox key (pre-fill with existing key if available)
st.markdown("""#### Mapbox Key""")
st.markdown("""VVE will display the location of valid GPS coordinates on a map to aid with review. We use the Mapbox API for this service. Providing no key will rely on the free
public API, which may meet your needs. If maps no longer display, or if you have a Mapbox key, then enter it below. The key will only be stored locally on your device in the `VoucherVisionEditor/.streamlit/config.toml` file. These files are created on first startup.""")
st.markdown("""You may update the key at any time. To remove an existing key, delete the `config.toml` file.""")
if existing_key is not None and existing_key != '':
st.info("Mapbox key present in the /.streamlit/config.toml file!")
mapbox_key = st.text_input('Enter your Mapbox key here:', '')
return mapbox_key
# Function to convert image to base64
def image_to_base64(img):
buffered = BytesIO()
img.save(buffered, format="JPEG")
return base64.b64encode(buffered.getvalue()).decode()
# Use SAVE_DIR where needed
# def save_data():
# # Check the file extension and save to the appropriate format
# if st.session_state.file_name.endswith('.csv'):
# file_path = os.path.join(st.session_state.SAVE_DIR, st.session_state.file_name)
# st.session_state.data.to_csv(file_path, index=False)
# # st.success('Saved (CSV)')
# print(f"Saved (CSV) {file_path}")
# elif st.session_state.file_name.endswith('.xlsx'):
# file_path = os.path.join(st.session_state.SAVE_DIR, st.session_state.file_name)
# st.session_state.data.to_excel(file_path, index=False)
# # st.success('Saved (XLSX)')
# print(f"Saved (XLSX) {file_path}")
# else:
# st.error('Unknown file format.')
def save_data_skipped(new_skipped_data):
try:
# st.session_state.data = pd.read_excel(st.session_state.BASE_PATH_transcription_LLM, dtype=str)
file_path = os.path.join(st.session_state.SAVE_DIR, st.session_state.file_name_skipped)
# Check if skipped file already exists
if os.path.exists(file_path):
# Load existing skipped data
existing_data = pd.read_excel(file_path, dtype=str)
# Check for duplicate based on the first column value
first_column = existing_data.columns[0]
if new_skipped_data[first_column].iloc[0] not in existing_data[first_column].values:
# Append if no duplicate
updated_data = pd.concat([existing_data, new_skipped_data], ignore_index=True)
updated_data.to_excel(file_path, index=False)
print(f"Appended to existing file (XLSX) {file_path}")
else:
print(f"Duplicate row based on {first_column}, skipping save.")
else:
# Save initial headers and first row if file does not exist
new_skipped_data.to_excel(file_path, index=False)
print(f"Created new file and saved (XLSX) {file_path}")
except Exception as e:
print(f"Error occurred: {e}")
st.error(f'Error saving the file: {e}')
def save_data():
# Check the file extension and save to the appropriate format
# if st.session_state.file_name.endswith('.csv'):
# file_path = os.path.join(st.session_state.SAVE_DIR, st.session_state.file_name)
# st.session_state.data.to_csv(file_path, index=False)
# # st.success('Saved (CSV)')
# print(f"Saved (CSV) {file_path}")
# elif st.session_state.file_name.endswith('.xlsx'):
try:
# Ensure the file path is absolute
# save_dir = st.session_state.SAVE_DIR
# if not os.path.isabs(save_dir):
# save_dir = os.path.abspath(save_dir)
file_path = os.path.join(st.session_state.SAVE_DIR, st.session_state.file_name)
st.session_state.data_edited.to_excel(file_path, index=False)
print(f"Saved (XLSX) {file_path}")
except Exception as e:
print(f"Error occurred: {e}")
st.error(f'Error saving the file: {e}')
def create_save_dir(transcription_index, add_prefix = False):
# Use the first path from the 'path_to_content' column as a base to determine the directory
first_path_to_content = st.session_state.data['path_to_content'][0]
# Split the path into components, handling drive letters separately on Windows
# Handle platform-specific path splitting
if platform.system() == 'Windows':
# On Windows, use os.path.splitdrive to handle drive letters
drive, path_tail = os.path.splitdrive(first_path_to_content)
parts = path_tail.split(os.path.sep)
elif platform.system() == 'Darwin':
# On macOS, there's no drive letter, treat the path as Unix-style
drive = '' # No drive on macOS, so keep it empty
parts = first_path_to_content.split(os.path.sep)
# If the first element is empty (leading '/'), remove it
if parts[0] == '':
parts = parts[1:]
# Check if we have a valid transcription index
if transcription_index is None or transcription_index >= len(parts):
raise ValueError("Transcription index is not found in the path")
# Construct the SAVE_DIR from the path
if platform.system() == 'Darwin':
save_dir = os.path.join('/', *parts[:transcription_index ])#+ 3]) ### TODO check to see if it works for brad still
else:
save_dir = os.path.join(drive + os.path.sep, *parts[:transcription_index + 1])
# macOS-specific adjustment: prepend '/' to make sure the path is absolute
# if platform.system() == 'Darwin':
# print(f" Adding leading / for macOS")
# print(f" --> {save_dir}")
# save_dir = os.path.join('/', save_dir) # Ensure the path is absolute
# print(f" --> {save_dir}")
# Ensure the directory exists, create it if it doesn't
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# Set SAVE_DIR in session state
st.session_state.SAVE_DIR = save_dir
# For debugging: print the final save directory
print(f"Save directory --> {st.session_state.SAVE_DIR}")
def get_current_datetime():
# Get the current date and time
now = datetime.now()
# Format it as a string, replacing colons with underscores
datetime_iso = now.strftime('%Y_%m_%dT%H_%M_%S')
return datetime_iso
def load_notes():
# Check if the file exists
if not os.path.exists(st.session_state.BASE_PATH_notes):
# File does not exist, create it with the initial dict
st.session_state.notes_data = {"NOTES": ""}
# Ensure the directory exists before writing the file
os.makedirs(os.path.dirname(st.session_state.BASE_PATH_notes), exist_ok=True)
# Write the initial data to the file
with open(st.session_state.BASE_PATH_notes, 'w') as file:
json.dump(st.session_state.notes_data, file)
else:
# File exists, load its contents into session state
with open(st.session_state.BASE_PATH_notes, 'r') as file:
st.session_state.notes_data = json.load(file)
def save_notes(text):
# Create the data structure to save
notes_data = {"NOTES": text}
# Ensure the directory exists before writing the file
os.makedirs(os.path.dirname(st.session_state.BASE_PATH_notes), exist_ok=True)
# Write the data to the file
with open(st.session_state.BASE_PATH_notes, 'w') as file:
json.dump(notes_data, file)
# Optionally update session state with the saved text
st.session_state.notes_data = notes_data
# C:\Users\Will\Downloads\mistralmed_pv5_trOCRhand_angio
def load_data():
if 'data' not in st.session_state or st.session_state.data is None:
if st.session_state.BASE_PATH:
st.session_state.BASE_PATH_transcription = os.path.join(st.session_state.BASE_PATH, 'Transcription')
st.session_state.BASE_PATH_transcription_LLM = os.path.join(st.session_state.BASE_PATH, 'Transcription', 'transcribed.xlsx')
st.session_state.BASE_PATH_transcription_LLM_prior = os.path.join(st.session_state.BASE_PATH, 'Transcription', 'transcribed_prior_to_subsetting.xlsx')
st.session_state.BASE_PATH_notes = os.path.join(st.session_state.BASE_PATH, 'Transcription', 'notes.json')
load_notes()
xlsx_LLM = [st.session_state.BASE_PATH_transcription_LLM]
xlsx_files = [file for file in os.listdir(st.session_state.BASE_PATH_transcription) if file.endswith('.xlsx')]
st.session_state.LLM_file = st.selectbox(
"LLM Transcription",
xlsx_LLM,
index=0,
placeholder="",
disabled=True,