-
Notifications
You must be signed in to change notification settings - Fork 4
/
TranscriptionPearl_beta-2024111.py
2605 lines (2056 loc) · 121 KB
/
TranscriptionPearl_beta-2024111.py
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 tkinter as tk
from tkinter import filedialog, messagebox, ttk, simpledialog
from tkinterdnd2 import DND_FILES, TkinterDnD
import pandas as pd
import fitz, re, base64, os, shutil, time, asyncio, string, json
from PIL import Image, ImageTk, ImageOps
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
# # Import Local Scripts
from util.subs.ImageSplitter import ImageSplitter
# OpenAI API
from openai import OpenAI
import openai
# Antrhopic API
from anthropic import AsyncAnthropic # Parallel API Calls
import anthropic
# Google API
import google.generativeai as genai
from google.generativeai.types import HarmCategory, HarmBlockThreshold
class App(TkinterDnD.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.title("Transcription Pearl 1.0 beta") # Set the window title
self.link_nav = 0
self.geometry("1200x800")
if os.name == 'nt': # For Windows use the .ico file
try:
self.iconbitmap("util/pb.ico")
except:
pass # If icon file is not found, use default icon
# Flags, Toggles, and Variables
self.save_toggle = False
self.find_replace_toggle = False
self.original_image = None
self.photo_image = None
self.current_scale = 1
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=0) # Top frame
self.grid_rowconfigure(1, weight=1) # Main frame
self.grid_rowconfigure(2, weight=0) # Bottom frame
self.top_frame = tk.Frame(self)
self.top_frame.grid(row=0, column=0, sticky="nsew")
self.top_frame.grid_columnconfigure(0, weight=0)
self.top_frame.grid_columnconfigure(1, weight=1)
self.top_frame.grid_columnconfigure(2, weight=0)
self.top_frame.grid_columnconfigure(3, weight=0)
self.top_frame.grid_columnconfigure(4, weight=0)
self.top_frame.grid_columnconfigure(5, weight=0)
text_label = tk.Label(self.top_frame, text="Displayed Text:")
text_label.grid(row=0, column=0, sticky="w", padx=5, pady=5)
self.text_type_label = tk.Label(self.top_frame, text="None")
self.text_type_label.grid(row=0, column=1, sticky="w", padx=5, pady=5)
self.button1 = tk.Button(self.top_frame, text="<<", command=lambda: self.navigate_images(-2))
self.button1.grid(row=0, column=2, sticky="e", padx=5, pady=5)
self.button2 = tk.Button(self.top_frame, text="<", command=lambda: self.navigate_images(-1))
self.button2.grid(row=0, column=3, sticky="e", padx=5, pady=5)
self.page_counter_var = tk.StringVar()
self.page_counter_var.set("0 / 0")
page_counter_label = tk.Label(self.top_frame, textvariable=self.page_counter_var)
page_counter_label.grid(row=0, column=4, sticky="e", padx=5, pady=5)
self.button4 = tk.Button(self.top_frame, text=">", command=lambda: self.navigate_images(1))
self.button4.grid(row=0, column=5, sticky="e", padx=5, pady=5)
self.button5 = tk.Button(self.top_frame, text=">>", command=lambda: self.navigate_images(2))
self.button5.grid(row=0, column=6, sticky="e", padx=5, pady=5)
self.main_frame = tk.PanedWindow(self, orient=tk.HORIZONTAL)
self.main_frame.grid(row=1, column=0, sticky="nsew")
self.text_display = self.create_text_widget(self.main_frame, "File to Edit", state="normal")
self.image_display = tk.Canvas(self.main_frame, borderwidth=2, relief="groove")
self.image_display.create_image(0, 0, anchor="nw", image=self.photo_image)
self.main_frame.add(self.text_display)
self.main_frame.add(self.image_display)
self.bottom_frame = tk.Frame(self)
self.bottom_frame.grid_rowconfigure(0, weight=1)
self.bottom_frame.grid(row=2, column=0, sticky="nsew")
self.bottom_frame.grid_columnconfigure(0, weight=1)
self.bottom_frame.grid_columnconfigure(1, weight=1)
button_frame = tk.Frame(self.bottom_frame)
button_frame.grid(row=0, column=0, sticky="nsw")
button_frame.grid_columnconfigure(0, weight=0)
button_frame.grid_columnconfigure(1, weight=0)
button_frame.grid_columnconfigure(2, weight=1)
button_frame.grid_rowconfigure(0, weight=1)
button_frame.grid_rowconfigure(1, weight=1)
button_frame.grid_rowconfigure(2, weight=1)
button_frame.grid_rowconfigure(3, weight=1)
textbox_frame = tk.Frame(self.bottom_frame)
textbox_frame.grid(row=0, column=1, sticky="nsew")
textbox_frame.grid_columnconfigure(0, weight=0)
textbox_frame.grid_columnconfigure(1, weight=1)
textbox_frame.grid_rowconfigure(0, weight=1)
textbox_frame.grid_rowconfigure(1, weight=1)
textbox_frame.grid_rowconfigure(2, weight=1)
# Initialize initial settings
self.initialize_temp_directory()
self.enable_drag_and_drop()
self.create_menus()
self.create_key_bindings()
self.bind_key_universal_commands(self.text_display)
self.initialize_settings()
def create_menus(self):
self.menu_bar = tk.Menu(self)
self.config(menu=self.menu_bar)
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="File", menu=self.file_menu)
self.edit_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="Edit", menu=self.edit_menu)
self.process_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="Process", menu=self.process_menu)
self.file_menu.add_command(label="New Project", command=self.create_new_project)
self.file_menu.add_command(label="Open Project", command=self.open_project)
self.file_menu.add_command(label="Save Project As...", command=self.save_project_as)
self.file_menu.add_command(label="Save Project", command=self.save_project)
self.file_menu.add_separator()
self.file_menu.add_command(label="Import Images Only", command=lambda: self.open_folder(toggle="Images without Text"))
self.file_menu.add_command(label="Import Text and Images", command=lambda: self.open_folder(toggle="Images with Text"))
self.file_menu.add_command(label="Import PDF", command=self.open_pdf)
self.file_menu.add_separator()
self.file_menu.add_command(label="Export", command=self.manual_export)
self.file_menu.add_separator()
self.file_menu.add_command(label="Settings", command=self.create_settings_window)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command=self.quit)
self.edit_menu.add_command(label="Undo", command=self.undo)
self.edit_menu.add_command(label="Redo", command=self.redo)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Cut", command=self.cut)
self.edit_menu.add_command(label="Copy", command=self.copy)
self.edit_menu.add_command(label="Paste", command=self.paste)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Rotate Image Clockwise", command=lambda: self.rotate_image("clockwise"))
self.edit_menu.add_command(label="Rotate Image Counter-clockwise", command=lambda: self.rotate_image("counter-clockwise"))
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Revert Current Page", command=self.revert_current_page)
self.edit_menu.add_command(label="Revert All Pages", command=self.revert_all_pages)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Find and Replace", command=self.find_and_replace)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Edit Current Image", command=self.edit_single_image)
self.edit_menu.add_command(label="Edit All Images", command=self.edit_all_images)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Delete Current Image", command=self.delete_current_image)
self.process_menu.add_command(label="Recognize Text on Current Page", command=lambda: self.ai_function(all_or_one_flag="Current Page", ai_job="HTR"))
self.process_menu.add_command(label="Recognize Text on All Pages", command=lambda: self.ai_function(all_or_one_flag="All Pages", ai_job="HTR"))
self.process_menu.add_separator()
self.process_menu.add_command(label="Correct Text on Current Page", command=lambda: self.ai_function(all_or_one_flag="Current Page", ai_job="Correct"))
self.process_menu.add_command(label="Correct Text on All Pages", command=lambda: self.ai_function(all_or_one_flag="All Pages", ai_job="Correct"))
def create_key_bindings(self):
# Navigation bindings
self.bind("<Control-Home>", lambda event: self.navigate_images(-2))
self.bind("<Control-Left>", lambda event: self.navigate_images(-1))
self.bind("<Control-Right>", lambda event: self.navigate_images(1))
self.bind("<Control-End>", lambda event: self.navigate_images(2))
# Rotation bindings
self.bind("<Control-bracketright>", lambda event: self.rotate_image("clockwise"))
self.bind("<Control-bracketleft>", lambda event: self.rotate_image("counter-clockwise"))
# Project management bindings
self.bind("<Control-n>", lambda event: self.create_new_project()) # Fixed missing angle brackets
self.bind("<Control-e>", lambda event: self.export()) # Fixed syntax and missing angle brackets
self.bind("<Control-s>", lambda event: self.save_project()) # Added parentheses for method call
self.bind("<Control-o>", lambda event: self.open_project()) # Added parentheses for method call
# Edit bindings
self.bind("<Control-z>", lambda event: self.undo()) # Added parentheses for method call
self.bind("<Control-y>", lambda event: self.redo()) # Added parentheses for method call
# Find and Replace bindings
self.bind("<Control-f>", lambda event: self.find_and_replace()) # Added parentheses for method call
# Clipboard bindings
self.bind("<Control-c>", lambda event: self.copy()) # Added parentheses for method call
self.bind("<Control-x>", lambda event: self.cut()) # Added parentheses for method call
self.bind("<Control-v>", lambda event: self.paste()) # Added parentheses for method call
# Revert bindings
self.bind("<Control-r>", lambda event: self.revert_current_page()) # Added parentheses for method call
self.bind("<Control-Shift-r>", lambda event: self.revert_all_pages()) # Added parentheses for method call
# Image management bindings
self.bind("<Control-d>", lambda event: self.delete_current_image()) # Added parentheses for method call
self.bind("<Control-i>", lambda event: self.edit_single_image()) # Added parentheses for method call
self.bind("<Control-Shift-i>", lambda event: self.edit_all_images()) # Added parentheses for method call
# AI function bindings
self.bind("<Control-1>", lambda event: self.ai_function(all_or_one_flag="Current Page", ai_job="HTR"))
self.bind("<Control-Shift-1>", lambda event: self.ai_function(all_or_one_flag="All Pages", ai_job="HTR"))
self.bind("<Control-2>", lambda event: self.ai_function(all_or_one_flag="Current Page", ai_job="Correct"))
self.bind("<Control-Shift-2>", lambda event: self.ai_function(all_or_one_flag="All Pages", ai_job="Correct"))
# Mouse bindings
self.image_display.bind("<Control-MouseWheel>", self.zoom)
self.image_display.bind("<MouseWheel>", self.scroll)
self.image_display.bind("<ButtonPress-1>", self.start_pan)
self.image_display.bind("<B1-Motion>", self.pan)
def create_image_widget(self, frame, image_path, state):
# Load the image
original_image = Image.open(image_path)
self.photo_image = ImageTk.PhotoImage(original_image)
# Create a canvas and add the image to it
self.canvas = tk.Canvas(frame, borderwidth=2, relief="groove")
self.canvas.create_image(0, 0, anchor="nw", image=self.photo_image)
self.canvas.grid(sticky="nsew")
# Bind zoom and scroll events
self.canvas.bind("<Control-MouseWheel>", self.zoom)
self.canvas.bind("<MouseWheel>", self.scroll)
return self.canvas
def create_text_widget(self, frame, label_text, state):
# Create a Text widget to display the contents of the selected file
text_display = tk.Text(frame, wrap="word", state=state, undo=True)
# Make the font size 16
text_display.config(font=("Arial", 12))
text_display.grid(sticky="nsew")
return text_display
def bind_key_universal_commands(self, text_widget):
text_widget.bind('<Control-h>', self.find_and_replace)
text_widget.bind('<Control-f>', self.find_and_replace)
text_widget.bind('<Control-z>', self.undo)
text_widget.bind('<Control-y>', self.redo)
# Initialize Settings Functions
def initialize_settings(self):
# Get the appropriate app data directory
if os.name == 'nt': # Windows
app_data = os.path.join(os.environ['APPDATA'], 'TranscriptionPearl')
else: # Linux/Mac
app_data = os.path.join(os.path.expanduser('~'), '.transcriptionpearl')
# Create the directory if it doesn't exist
os.makedirs(app_data, exist_ok=True)
# Define settings file path
self.settings_file_path = os.path.join(app_data, 'settings.json')
# Initialize other settings...
self.main_df = pd.DataFrame(columns=["Index", "Page", "Original_Text", "Initial_Draft_Text",
"Final_Draft", "Image_Path", "Text_Path", "Text_Toggle"])
# First set default values
self.restore_defaults()
# Define model list
self.model_list = [
"gpt-4o",
"gpt-4o-2024-08-06",
"gpt-4o-mini",
"claude-3-5-sonnet-20241022",
"claude-3-5-sonnet-20240620",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"gemini-1.5-flash-001",
"gemini-1.5-flash-002",
"gemini-1.5-pro-001",
"gemini-1.5-pro-002"
]
# Check if settings file exists and load it
if os.path.exists(self.settings_file_path):
self.load_settings()
def initialize_temp_directory(self):
self.temp_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "util", "temp")
self.images_directory = os.path.join(self.temp_directory, "images")
# Clear the temp directory if it exists
if os.path.exists(self.temp_directory):
try:
shutil.rmtree(self.temp_directory)
except Exception as e:
messagebox.showerror("Error", f"Failed to clear temp directory: {e}")
self.error_logging(f"Failed to clear temp directory: {e}")
# Recreate the temp and images directories
try:
os.makedirs(self.temp_directory, exist_ok=True)
os.makedirs(self.images_directory, exist_ok=True)
except Exception as e:
messagebox.showerror("Error", f"Failed to create temp directories: {e}")
self.error_logging(f"Failed to create temp directories: {e}")
# Reset the main DataFrame
self.main_df = pd.DataFrame(columns=["Index", "Page", "Original_Text", "Initial_Draft_Text", "Final_Draft", "Image_Path", "Text_Path", "Text_Toggle"])
self.page_counter = 0
# Settings Window
def create_settings_window(self):
self.toggle_button_state()
self.settings_window = tk.Toplevel(self)
self.settings_window.title("Settings")
self.settings_window.geometry("1200x875")
self.settings_window.attributes("-topmost", True)
self.settings_window.protocol("WM_DELETE_WINDOW", lambda: self.on_settings_window_close(self.settings_window))
self.settings_window.grid_columnconfigure(0, weight=1)
self.settings_window.grid_columnconfigure(1, weight=4)
self.settings_window.grid_rowconfigure(0, weight=1)
left_frame = tk.Frame(self.settings_window)
left_frame.grid(row=0, column=0, sticky="nsew")
right_frame = tk.Frame(self.settings_window)
right_frame.grid(row=0, column=1, sticky="nsew")
# Left menu
menu_options = [
"APIs and Login Settings",
"HTR Settings",
"Correct Text Settings",
"",
"Load Settings",
"Save Settings",
"Restore Defaults",
"Done"
]
for i, option in enumerate(menu_options):
if option == "":
# Add an empty label with a specific height to create space above the "Load Settings" button
empty_label = tk.Label(left_frame, text="", height=26)
empty_label.grid(row=i, column=0)
else:
button = tk.Button(left_frame, text=option, width=30, command=lambda opt=option: self.show_settings(opt, right_frame))
button.grid(row=i, column=0, padx=10, pady=5, sticky="w")
# Right frame
self.show_settings("General Settings", right_frame)
def show_settings(self, option, frame):
for widget in frame.winfo_children():
widget.destroy()
if option == "APIs and Login Settings":
self.show_api_settings(frame)
elif option == "HTR Settings":
self.show_HTR_settings(frame)
elif option == "Correct Text Settings":
self.show_correct_text_settings(frame)
elif option == "Load Settings":
self.load_settings()
elif option == "Save Settings":
self.save_settings()
elif option == "Restore Defaults":
self.restore_defaults()
elif option == "Done":
self.on_settings_window_close(self.settings_window)
def show_api_settings(self, frame):
# OpenAI
openai_label = tk.Label(frame, text="OpenAI API Key:")
openai_label.grid(row=0, column=0, padx=10, pady=5, sticky="w")
self.openai_entry = tk.Entry(frame, width=130)
self.openai_entry.insert(0, self.openai_api_key)
self.openai_entry.grid(row=0, column=1, columnspan=3, padx=10, pady=5, sticky="w")
self.openai_entry.bind("<KeyRelease>", lambda event: setattr(self, 'openai_api_key', self.openai_entry.get()))
# Anthropic
anthropic_label = tk.Label(frame, text="Anthropic API Key:")
anthropic_label.grid(row=4, column=0, padx=10, pady=5, sticky="w")
self.anthropic_entry = tk.Entry(frame, width=130)
self.anthropic_entry.insert(0, self.anthropic_api_key)
self.anthropic_entry.grid(row=4, column=1, padx=10, pady=5, sticky="w")
self.anthropic_entry.bind("<KeyRelease>", lambda event: setattr(self, 'anthropic_api_key', self.anthropic_entry.get()))
# Google
google_api_key_label = tk.Label(frame, text="Google API Key:")
google_api_key_label.grid(row=11, column=0, padx=10, pady=5, sticky="w")
self.google_api_key_entry = tk.Entry(frame, width=130)
self.google_api_key_entry.insert(0, self.google_api_key)
self.google_api_key_entry.grid(row=11, column=1, columnspan=3, padx=10, pady=5, sticky="w")
self.google_api_key_entry.bind("<KeyRelease>", lambda event: setattr(self, 'google_api_key', self.google_api_key_entry.get()))
def show_HTR_settings(self, frame):
explanation_label = tk.Label(frame, text=f"""The HTR function sends each image to the API simultaneously and asks it to transcribe the material.""", wraplength=675, justify=tk.LEFT)
explanation_label.grid(row=0, column=0, columnspan=3, padx=10, pady=5, sticky="w")
model_label = tk.Label(frame, text="Select model for HTR:")
model_label.grid(row=1, column=0, padx=10, pady=5, sticky="w")
self.HTR_model_var = tk.StringVar(value=self.HTR_model)
dropdown = ttk.Combobox(frame, textvariable=self.HTR_model_var, values=self.model_list, state="readonly", width=30)
dropdown.grid(row=1, column=1, padx=10, pady=5, sticky="w")
# Update the model variable when the dropdown is changed
dropdown.bind("<<ComboboxSelected>>", lambda event: setattr(self, 'HTR_model', dropdown.get()))
general_label = tk.Label(frame, text="General Instructions:")
general_label.grid(row=2, column=0, padx=10, pady=5, sticky="w")
self.HTR_general_entry = tk.Text(frame, height=5, width=60, wrap=tk.WORD)
self.HTR_general_entry.insert(tk.END, self.HTR_system_prompt)
self.HTR_general_entry.grid(row=2, column=1, padx=10, pady=5, sticky="w")
# Update the general instructions when the text is changed
self.HTR_general_entry.bind("<KeyRelease>", lambda event: setattr(self, 'HTR_system_prompt', self.HTR_system_prompt.get("1.0", tk.END)))
general_scrollbar = tk.Scrollbar(frame, command=self.HTR_general_entry.yview)
general_scrollbar.grid(row=2, column=2, sticky="ns")
self.HTR_general_entry.config(yscrollcommand=general_scrollbar.set)
detailed_label = tk.Label(frame, text="Detailed Instructions:")
detailed_label.grid(row=3, column=0, padx=10, pady=5, sticky="w")
self.HTR_detailed_entry = tk.Text(frame, height=20, width=60, wrap=tk.WORD)
self.HTR_detailed_entry.insert(tk.END, self.HTR_user_prompt)
self.HTR_detailed_entry.grid(row=3, column=1, padx=10, pady=5, sticky="w")
# Update the detailed instructions when the text is changed
self.HTR_detailed_entry.bind("<KeyRelease>", lambda event: setattr(self, 'HTR_user_prompt', self.HTR_user_prompt.get("1.0", tk.END)))
detailed_scrollbar = tk.Scrollbar(frame, command=self.HTR_detailed_entry.yview)
detailed_scrollbar.grid(row=3, column=2, sticky="ns")
self.HTR_detailed_entry.config(yscrollcommand=detailed_scrollbar.set)
val_label = tk.Label(frame, text=f"Validation Text:")
val_label.grid(row=4, column=0, padx=10, pady=5, sticky="w")
self.val_label_entry = tk.Text(frame, height=1, width=60)
self.val_label_entry.insert(tk.END, self.HTR_val_text)
self.val_label_entry.grid(row=4, column=1, padx=10, pady=5, sticky="w")
self.val_label_entry.bind("<KeyRelease>", lambda event: setattr(self, 'HTR_val_text', self.HTR_val_text.get("1.0", tk.END)))
self.HTR_general_entry.bind("<KeyRelease>", lambda event: setattr(self, 'HTR_system_prompt', self.HTR_general_entry.get("1.0", "end-1c")))
self.HTR_detailed_entry.bind("<KeyRelease>", lambda event: setattr(self, 'HTR_user_prompt', self.HTR_detailed_entry.get("1.0", "end-1c")))
self.val_label_entry.bind("<KeyRelease>", lambda event: setattr(self, 'HTR_val_text', self.val_label_entry.get("1.0", "end-1c")))
def show_correct_text_settings(self, frame):
explanation_label = tk.Label(frame, text=f"""The main function processes each page of text and the corresponding image and by default is used to correct an initially HTRed text.""", wraplength=675, justify=tk.LEFT)
explanation_label.grid(row=0, column=0, columnspan=3, padx=10, pady=5, sticky="w")
model_label = tk.Label(frame, text="Model:")
model_label.grid(row=2, column=0, padx=10, pady=5, sticky="w")
self.main_model_var = tk.StringVar(value=self.correct_model)
dropdown = ttk.Combobox(frame, textvariable=self.main_model_var, values=self.model_list, state="readonly", width=30)
dropdown.grid(row=2, column=1, padx=10, pady=5, sticky="w")
dropdown.bind("<<ComboboxSelected>>", lambda event: setattr(self, 'correct_text_model', self.main_model_var.get()))
general_label = tk.Label(frame, text="General Instructions:")
general_label.grid(row=3, column=0, padx=10, pady=5, sticky="w")
self.main_general_entry = tk.Text(frame, height=5, width=60, wrap=tk.WORD)
self.main_general_entry.insert(tk.END, self.correct_system_prompt)
self.main_general_entry.grid(row=3, column=1, padx=10, pady=5, sticky="w")
self.main_general_entry.bind("<KeyRelease>", lambda event: setattr(self, 'correct_text_system_prompt', self.main_general_entry.get("1.0", tk.END)))
general_scrollbar = tk.Scrollbar(frame, command=self.main_general_entry.yview)
general_scrollbar.grid(row=3, column=2, sticky="ns")
self.main_general_entry.config(yscrollcommand=general_scrollbar.set)
detailed_label = tk.Label(frame, text="Detailed Instructions:")
detailed_label.grid(row=4, column=0, padx=10, pady=5, sticky="w")
self.main_detailed_entry = tk.Text(frame, height=20, width=60, wrap=tk.WORD)
self.main_detailed_entry.insert(tk.END, self.correct_user_prompt)
self.main_detailed_entry.grid(row=4, column=1, padx=10, pady=5, sticky="w")
self.main_detailed_entry.bind("<KeyRelease>", lambda event: setattr(self, 'correct_text_user_prompt', self.main_detailed_entry.get("1.0", tk.END)))
detailed_scrollbar = tk.Scrollbar(frame, command=self.main_detailed_entry.yview)
detailed_scrollbar.grid(row=4, column=2, sticky="ns")
self.main_detailed_entry.config(yscrollcommand=detailed_scrollbar.set)
val_label = tk.Label(frame, text=f"Validation Text:")
val_label.grid(row=5, column=0, padx=10, pady=5, sticky="w")
self.val_label_entry = tk.Text(frame, height=1, width=60)
self.val_label_entry.insert(tk.END, self.correct_val_text)
self.val_label_entry.grid(row=5, column=1, padx=10, pady=5, sticky="w")
self.val_label_entry.bind("<KeyRelease>", lambda event: setattr(self, 'correct_text_val_text_a', self.val_label_entry.get("1.0", tk.END)))
self.main_general_entry.bind("<KeyRelease>", lambda event: setattr(self, 'correct_system_prompt', self.main_general_entry.get("1.0", "end-1c")))
self.main_detailed_entry.bind("<KeyRelease>", lambda event: setattr(self, 'correct_user_prompt', self.main_detailed_entry.get("1.0", "end-1c")))
self.val_label_entry.bind("<KeyRelease>", lambda event: setattr(self, 'correct_val_text', self.val_label_entry.get("1.0", "end-1c")))
def save_settings(self):
settings = {
# HTR Settings
'HTR_system_prompt': self.HTR_system_prompt,
'HTR_user_prompt': self.HTR_user_prompt,
'HTR_val_text': self.HTR_val_text,
'HTR_model': self.HTR_model,
# Correct Text Settings
'correct_system_prompt': self.correct_system_prompt,
'correct_user_prompt': self.correct_user_prompt,
'correct_val_text': self.correct_val_text,
'correct_model': self.correct_model,
# API Keys
'openai_api_key': self.openai_api_key,
'anthropic_api_key': self.anthropic_api_key,
'google_api_key': self.google_api_key,
# Model List
'model_list': self.model_list
}
try:
with open(self.settings_file_path, 'w') as f:
json.dump(settings, f, indent=4)
# Check if settings window exists before showing the message
if hasattr(self, 'settings_window') and self.settings_window.winfo_exists():
messagebox.showinfo("Success", "Settings saved successfully!", parent=self.settings_window)
else:
messagebox.showinfo("Success", "Settings saved successfully!")
except Exception as e:
if hasattr(self, 'settings_window') and self.settings_window.winfo_exists():
messagebox.showerror("Error", f"Failed to save settings: {e}", parent=self.settings_window)
else:
messagebox.showerror("Error", f"Failed to save settings: {e}")
def load_settings(self):
try:
with open(self.settings_file_path, 'r') as f:
settings = json.load(f)
# HTR Settings
self.HTR_system_prompt = settings.get('HTR_system_prompt', self.HTR_system_prompt)
self.HTR_user_prompt = settings.get('HTR_user_prompt', self.HTR_user_prompt)
self.HTR_val_text = settings.get('HTR_val_text', self.HTR_val_text)
self.HTR_model = settings.get('HTR_model', self.HTR_model)
# Correct Text Settings
self.correct_system_prompt = settings.get('correct_system_prompt', self.correct_system_prompt)
self.correct_user_prompt = settings.get('correct_user_prompt', self.correct_user_prompt)
self.correct_val_text = settings.get('correct_val_text', self.correct_val_text)
self.correct_model = settings.get('correct_model', self.correct_model)
# API Keys
self.openai_api_key = settings.get('openai_api_key', '')
self.anthropic_api_key = settings.get('anthropic_api_key', '')
self.google_api_key = settings.get('google_api_key', '')
# Model List
self.model_list = settings.get('model_list', self.model_list)
# Update UI if settings window is open
if hasattr(self, 'settings_window') and self.settings_window.winfo_exists():
self.show_settings("APIs and Login Settings", self.settings_window.winfo_children()[1])
self.show_settings("HTR Settings", self.settings_window.winfo_children()[1])
self.show_settings("Correct Text Settings", self.settings_window.winfo_children()[1])
except FileNotFoundError:
self.restore_defaults()
except Exception as e:
messagebox.showerror("Error", f"Failed to load settings: {e}")
def restore_defaults(self):
self.HTR_system_prompt = '''Your task is to accurately transcribe handwritten historical documents, minimizing the CER and WER. Work character by character, word by word, line by line, transcribing the text exactly as it appears on the page. To maintain the authenticity of the historical text, retain spelling errors, grammar, syntax, and punctuation as well as line breaks. Transcribe all the text on the page including headers, footers, marginalia, insertions, page numbers, etc. If these are present, insert them where indicated by the author (as applicable). In your response, write: "Transcription:" followed only by your accurate transcription'''
self.HTR_user_prompt = '''Carefully transcribe this page from an 18th/19th century document. In your response, write: "Transcription:" followed only by your accurate transcription.'''
self.HTR_val_text = "Transcription:"
self.HTR_model = "gemini-1.5-pro-002"
self.correct_system_prompt = '''Your task is to compare handwritten pages of text with corresponding draft transcriptions, correcting the transcription to produce an accurate, publishable transcript. Be sure that the spelling, syntax, punctuation, and line breaks in the transcription match those on the handwritten page to preserve the historical integrity of the document. Numbers also easily misread, so pay close attention to digits. You must also ensure that the transcription begins and ends in the same place as the handwritten document. Include any catchwords at the bottom of the page. In your response write "Corrected Transcript:" followed by your corrected transcription.'''
self.correct_user_prompt = '''Your task is to use the handwritten page image to correct the following transcription, retaining the spelling, syntax, punctuation, line breaks, catchwords, etc of the original.\n\n{text_to_process}'''
self.correct_val_text = "Corrected Transcript:"
self.correct_model = "claude-3-5-sonnet-20240620"
self.model_list = [
"gpt-4o",
"gpt-4o-2024-08-06",
"gpt-4o-mini",
"claude-3-5-sonnet-20241022",
"claude-3-5-sonnet-20240620",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"gemini-1.5-flash-001",
"gemini-1.5-flash-002",
"gemini-1.5-pro-001",
"gemini-1.5-pro-002"
]
self.openai_api_key = ""
self.anthropic_api_key = ""
self.google_api_key = ""
def on_settings_window_close(self, window):
self.toggle_button_state()
window.destroy()
# Image and Navigation Functions
def navigate_images(self, direction):
self.update_df()
total_images = len(self.main_df) - 1
if total_images >= 0:
if direction == -2: # Go to the first image
self.page_counter = 0
elif direction == -1: # Go to the previous image
if self.page_counter > 0:
self.page_counter -= 1
elif direction == 1: # Go to the next image
if self.page_counter < total_images:
self.page_counter += 1
elif direction == 2: # Go to the last image
self.page_counter = total_images
elif direction == 0: # Go to a specific image
self.page_counter = self.link_nav
# Update the current image path
self.current_image_path = self.main_df.loc[self.page_counter, 'Image_Path']
# Load the new image
self.load_image(self.current_image_path)
# Load the text file
self.load_text()
self.counter_update()
def counter_update(self):
total_images = len(self.main_df) - 1
if total_images >= 0:
self.page_counter_var.set(f"{self.page_counter + 1} / {total_images + 1}")
else:
self.page_counter_var.set("0 / 0")
def start_pan(self, event):
self.image_display.scan_mark(event.x, event.y)
def pan(self, event):
self.image_display.scan_dragto(event.x, event.y, gain=1)
def zoom(self, event):
scale = 1.5 if event.delta > 0 else 0.6667
original_width, original_height = self.original_image.size
new_width = int(original_width * self.current_scale * scale)
new_height = int(original_height * self.current_scale * scale)
if new_width < 50 or new_height < 50:
return
resized_image = self.original_image.resize((new_width, new_height), Image.LANCZOS)
self.photo_image = ImageTk.PhotoImage(resized_image)
self.image_display.delete("all")
self.image_display.create_image(0, 0, anchor="nw", image=self.photo_image)
self.image_display.config(scrollregion=self.image_display.bbox("all"))
self.current_scale *= scale
def scroll(self, event):
self.image_display.yview_scroll(int(-1*(event.delta/120)), "units")
def load_image(self, image_path):
# Load the image
self.original_image = Image.open(image_path)
# Apply the current scale to the image
original_width, original_height = self.original_image.size
new_width = int(original_width * self.current_scale)
new_height = int(original_height * self.current_scale)
self.original_image = self.original_image.resize((new_width, new_height), Image.LANCZOS)
self.photo_image = ImageTk.PhotoImage(self.original_image)
# Update the canvas item
self.image_display.delete("all")
self.image_display.create_image(0, 0, anchor="nw", image=self.photo_image)
# Update the scroll region
self.image_display.config(scrollregion=self.image_display.bbox("all"))
def encode_image(self, image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def resize_image(self, image_path, output_path, max_size=1980):
with Image.open(image_path) as img:
# Get the original image size
width, height = img.size
# Determine the larger dimension
larger_dimension = max(width, height)
# Calculate the scaling factor
scale = max_size / larger_dimension
# Calculate new dimensions
new_width = int(width * scale)
new_height = int(height * scale)
# Resize the image
img = img.resize((new_width, new_height), Image.LANCZOS)
img = ImageOps.exif_transpose(img)
# Save the image with high quality
img.save(output_path, "JPEG", quality=95)
def process_new_images(self, source_paths):
successful_copies = 0
for source_path in source_paths:
new_index = len(self.main_df)
file_extension = os.path.splitext(source_path)[1].lower()
new_file_name = f"{new_index+1:04d}_p{new_index+1:03d}{file_extension}"
dest_path = os.path.join(self.images_directory, new_file_name)
try:
# Instead of directly copying, resize and save the image
self.resize_image(source_path, dest_path)
text_file_name = f"{new_index+1:04d}_p{new_index+1:03d}.txt"
text_file_path = os.path.join(self.images_directory, text_file_name)
with open(text_file_path, "w", encoding='utf-8') as f:
f.write("")
new_row = pd.DataFrame({
"Index": [new_index],
"Page": [f"{new_index+1:04d}_p{new_index+1:03d}"],
"Original_Text": [""],
"Initial_Draft_Text": [""],
"Final_Draft": [""],
"Image_Path": [dest_path],
"Text_Path": [text_file_path],
"Text_Toggle": ["Original Text"]
})
self.main_df = pd.concat([self.main_df, new_row], ignore_index=True)
successful_copies += 1
except Exception as e:
print(f"Error processing file {source_path}: {e}")
messagebox.showerror("Error", f"Failed to process the image {source_path}:\n{e}")
if successful_copies > 0:
self.refresh_display()
else:
print("No images were successfully processed")
messagebox.showinfo("Information", "No images were successfully processed")
def delete_current_image(self):
if self.main_df.empty:
messagebox.showinfo("No Images", "No images to delete.")
return
if not messagebox.askyesno("Confirm Delete", "Are you sure you want to delete the current image? This action cannot be undone."):
return
try:
current_index = self.page_counter
# Store the path of files to be deleted
image_to_delete = self.main_df.loc[current_index, 'Image_Path']
text_to_delete = self.main_df.loc[current_index, 'Text_Path']
# Remove the row from the DataFrame
self.main_df = self.main_df.drop(current_index).reset_index(drop=True)
# Delete the actual files
try:
if os.path.exists(image_to_delete):
os.remove(image_to_delete)
if os.path.exists(text_to_delete):
os.remove(text_to_delete)
except Exception as e:
self.error_logging(f"Error deleting files: {str(e)}")
# Renumber the remaining entries
for idx in range(len(self.main_df)):
# Update Index
self.main_df.at[idx, 'Index'] = idx
# Create new page number
new_page = f"{idx+1:04d}_p{idx+1:03d}"
self.main_df.at[idx, 'Page'] = new_page
# Get old file paths
old_image_path = self.main_df.loc[idx, 'Image_Path']
old_text_path = self.main_df.loc[idx, 'Text_Path']
# Create new file paths
new_image_name = f"{idx+1:04d}_p{idx+1:03d}{os.path.splitext(old_image_path)[1]}"
new_text_name = f"{idx+1:04d}_p{idx+1:03d}.txt"
new_image_path = os.path.join(os.path.dirname(old_image_path), new_image_name)
new_text_path = os.path.join(os.path.dirname(old_text_path), new_text_name)
# Rename files
if os.path.exists(old_image_path):
os.rename(old_image_path, new_image_path)
if os.path.exists(old_text_path):
os.rename(old_text_path, new_text_path)
# Update paths in DataFrame
self.main_df.at[idx, 'Image_Path'] = new_image_path
self.main_df.at[idx, 'Text_Path'] = new_text_path
# Adjust page counter if necessary
if current_index >= len(self.main_df):
self.page_counter = len(self.main_df) - 1
# Refresh display
if not self.main_df.empty:
self.load_image(self.main_df.loc[self.page_counter, 'Image_Path'])
self.load_text()
else:
# Clear displays if no images remain
self.text_display.delete("1.0", tk.END)
self.image_display.delete("all")
self.text_type_label.config(text="None")
self.counter_update()
except Exception as e:
messagebox.showerror("Error", f"An error occurred while deleting the image: {str(e)}")
self.error_logging(f"Error in delete_current_image: {str(e)}")
def rotate_image(self, direction):
if not hasattr(self, 'original_image') or self.original_image is None:
messagebox.showwarning("Warning", "No image loaded to rotate.")
return
try:
# Rotate the original image
if direction == "clockwise":
self.original_image = self.original_image.rotate(-90, expand=True) # -90 for clockwise
else:
self.original_image = self.original_image.rotate(90, expand=True) # 90 for counter-clockwise
# Get the current image path
current_image_path = self.main_df.loc[self.page_counter, 'Image_Path']
# Save the rotated image
self.original_image.save(current_image_path, quality=95)
# Update the display
original_width, original_height = self.original_image.size
new_width = int(original_width * self.current_scale)
new_height = int(original_height * self.current_scale)
resized_image = self.original_image.resize((new_width, new_height), Image.LANCZOS)
self.photo_image = ImageTk.PhotoImage(resized_image)
# Update the canvas
self.image_display.delete("all")
self.image_display.create_image(0, 0, anchor="nw", image=self.photo_image)
self.image_display.config(scrollregion=self.image_display.bbox("all"))
except Exception as e:
messagebox.showerror("Error", f"An error occurred while rotating the image: {e}")
self.error_logging(f"Error in rotate_image: {str(e)}")
# File Functions
def reset_application(self):
# Clear the main DataFrame
self.main_df = pd.DataFrame(columns=["Index", "Page", "Original_Text", "Initial_Draft_Text", "Final_Draft", "Image_Path", "Text_Path", "Text_Toggle"])
# Reset page counter
self.page_counter = 0
# Reset flags
self.save_toggle = False
self.find_replace_toggle = False
# Clear text displays
self.text_display.delete("1.0", tk.END)
# Clear image display
self.image_display.delete("all")
self.current_image_path = None
self.original_image = None
self.photo_image = None
# Reset zoom and pan
self.current_scale = 1
# Reset counter
self.counter_update()
# Clear project and image directories
self.initialize_temp_directory()
# Clear the find and replace matches DataFrame
self.find_replace_matches_df = pd.DataFrame(columns=["Index", "Page"])
# Update the display
self.text_type_label.config(text="None")
def create_new_project(self):
if not messagebox.askyesno("New Project", "Creating a new project will reset the current application state. This action cannot be undone. Are you sure you want to proceed?"):
return # User chose not to proceed
# Reset the application
self.reset_application()
# Enable drag and drop
self.enable_drag_and_drop()
def save_project(self):
if not hasattr(self, 'project_directory') or not self.project_directory:
# If there's no current project, call save_project_as instead
self.save_project_as()
return
try:
# Get the project name from the directory path
project_name = os.path.basename(self.project_directory)
pbf_file = os.path.join(self.project_directory, f"{project_name}.pbf")
# Ensure text columns are of type 'object' (string)
text_columns = ['Original_Text', 'Initial_Draft_Text', 'Final_Draft','Text_Toggle']
for col in text_columns:
if col in self.main_df.columns:
self.main_df[col] = self.main_df[col].astype('object')
# Update text files with current content
for index, row in self.main_df.iterrows():
text_path = row['Text_Path']
# Determine which text to save based on the Text_Toggle
if row['Text_Toggle'] == 'Final Draft':
text_content = row['Final_Draft']
elif row['Text_Toggle'] == 'Initial Draft':
text_content = row['Initial_Draft_Text']
else:
text_content = row['Original_Text']
# Write the current text content to the file
with open(text_path, 'w', encoding='utf-8') as text_file:
text_file.write(text_content)
# Save the DataFrame to the PBF file
self.main_df.to_csv(pbf_file, index=False, encoding='utf-8')
messagebox.showinfo("Success", f"Project saved successfully to {self.project_directory}")
except Exception as e:
messagebox.showerror("Error", f"Failed to save project: {e}")
self.error_logging(f"Failed to save project: {e}")