-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1517 lines (1179 loc) · 50.9 KB
/
utils.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 font
from tkinter import ttk, font, simpledialog, messagebox
import random
from pymongo import MongoClient
import threading
import re
from jsonFunctions import *
from datetime import datetime
import certifi
import enchant
from shared_utils import compare_norm_texts
ca = certifi.where()
class LabelSeparator(tk.Frame):
def __init__(self, parent, text="", *args, **kwargs):
super().__init__(parent, *args, **kwargs)
# The separator is stretched across the entire width of the frame
self.separator = ttk.Separator(self, orient=tk.HORIZONTAL)
self.separator.grid(row=0, column=0, sticky="ew", pady=0)
# The label is placed above the separator
self.label = ttk.Label(self, text=text)
self.label.grid(row=0, column=0)
# Configure the frame to expand the column, allowing the separator to fill the space
self.grid_columnconfigure(0, weight=1)
# Adjust label placement using the 'sticky' parameter to center it
# 'ns' means north-south, which centers the label vertically in the grid cell
self.label.grid_configure(sticky="ns")
class FontSizeChanger:
def __init__(self, position, root, font_size=12):
self.root = root
self.font_size = font_size
self.exlude_widgets = []
# "+" button to increase font size
increase_font_button = tk.Button(
position, text="+", command=self.increase_font_size
)
increase_font_button.pack(side=tk.LEFT, padx=(10, 0), pady=10)
# "-" button to decrease font size
decrease_font_button = tk.Button(
position, text="-", command=self.decrease_font_size
)
decrease_font_button.pack(side=tk.LEFT, padx=(0, 10), pady=10)
def add_exclude_widget(self, widget):
self.exlude_widgets.append(widget)
def increase_font_size(self):
"""Increases the font size by 1 if it's less than 30.
Also updates the font size and window size.
"""
if self.font_size < 30:
self.font_size += 1
self.update_font_size(self.root)
self.update_window_size(enlarge=True)
def decrease_font_size(self):
"""Decreases the font size by 1 if it's greater than 10.
Also updates the font size and window size.
"""
if self.font_size > 10:
self.font_size -= 1
self.update_font_size(self.root)
self.update_window_size(enlarge=False)
def update_font_size_wrapper(self):
"""Prepares to update the whole program using a recursive function that takes the root frame and updates all the child widgets."""
self.update_font_size(self.root)
def update_font_size(self, widget):
"""A recursive function to update the font size of a widget and its child widgets.
Args:
widget (object): The tkinter object to update the font size for.
"""
new_font = font.Font(size=self.font_size)
try:
if widget not in self.exlude_widgets:
widget.configure(font=new_font)
except:
pass
for child in widget.winfo_children():
self.update_font_size(child)
def update_window_size(self, enlarge):
"""Updates the window size to accommodate the text with the new font size.
Args:
enlarge (boolean): If True, makes the window bigger. If False, makes the window smaller.
"""
if enlarge:
num = 40
else:
num = -40
# Get the current size of the window
current_width = self.root.winfo_width()
current_height = self.root.winfo_height()
# Calculate a new height, but ensure it's within the screen's limits
screen_height = self.root.winfo_screenheight()
new_height = min(current_height + num, screen_height)
# Calculate a new Width, but ensure it's within the screen's limits
screen_width = self.root.winfo_screenwidth()
new_width = min(current_width + num * 2, screen_width)
# Update the window size using geometry
self.root.geometry(f"{new_width}x{new_height}")
self.root.update()
class ProgressIndicator:
def __init__(self, position, dialog_change_function=None):
"""
Initializes a ProgressIndicator object.
Args:
position (tkinter.Tk): The position where the labels will be placed.
"""
self.dialog_change_function = dialog_change_function
# Dialog label
self.dialog_label = tk.Label(position, text="Dialog:")
self.dialog_label.pack(side=tk.LEFT, padx=10, pady=10)
# Current dialog number entry and total dialogs label
self.entry = tk.Entry(position, font=('Arial', 12), width=5)
self.entry.pack(side=tk.LEFT, padx=5, pady=10)
self.entry.bind('<FocusOut>', self.update_label)
self.total_dialogs_label = tk.Label(position, text="/ 0")
self.total_dialogs_label.pack(side=tk.LEFT, padx=5, pady=10)
# Current turn label
self.current_turn_label = tk.Label(position, text="")
self.current_turn_label.pack(side=tk.LEFT, padx=10, pady=10)
self.current_dialog_num = -1
def update_label(self, event):
# Get the value from the entry widget and update the label
new_value = self.entry.get()
if new_value.isdigit(): # Ensure the input is a number
self.dialog_change_function(int(new_value))
else:
# Display an error message
messagebox.showerror("Error", "Please enter a number")
return "break"
def get_widget(self):
return self.entry
def update_current_turn_dialog_labels(
self, json_data, dialog_num, dialog_id, turn_num, count_turns
):
"""Updates the indicator of where the annotator is (in what dialog and what turn).
Args:
dialog_num (int): The dialog the annotator is on.
turn_num (int): The turn the annotator is on.
json_data (string): The json data.
count_turns (int): The number of turns in the dialog.
"""
self.current_dialog_num = dialog_num
completed_turns_counter = 0
for key in JsonFunctions.get_turns(json_data, dialog_id):
if key.isdigit():
if int(key) < turn_num:
completed_turns_counter += 1
else:
break
# Updates the entry widget with the current dialog number
self.entry.delete(0, tk.END)
self.entry.insert(0, str(dialog_num + 1))
# Updates the total dialogs label
self.total_dialogs_label.config(
text=f"/ {len(json_data)}"
)
# Updates the turn progress label
self.current_turn_label.config(
text=f"Turn: {completed_turns_counter+1}/{count_turns}"
)
class MongoData:
def __init__(self, root, connection_string, login):
"""
Initializes an instance of the MongoData class.
Args:
root (object): The root object of the Tkinter application.
connection_string (str): The connection string for the MongoDB database.
"""
self.root = root
self.client = MongoClient(connection_string, tlsCAFile=ca)
self.db = self.client.require_rewrite_b
self.username = login["username"]
self.filename = login["filename"]
self.saving_in_progress = False
self.needs_clarification = None
def check_needs_clarification(self, json_data):
if not json_data:
self.needs_clarification = False
return
dialog_data = next(iter(json_data))
if "needs_clarification" in json_data[dialog_data]["dialog"]["1"].keys():
self.needs_clarification = True
else:
self.needs_clarification = False
def get_saving_status(self):
return self.saving_in_progress
def load_file(self):
"""
Choose a file and load its data.
Returns:
str: Status message indicating the result of the file loading process.
"""
if self.filename is None or self.username is None:
raise Exception("login details missing")
data = None
filename = self.filename
username = self.username
if "asi" in re.split(r'[ _\-]', filename):
collection = self.db.json_annotations
query = {"file_id": filename, "username": username}
result = collection.find_one(query)
if result != None:
data = result['json_data']
if data == None:
query = {"file_id": filename}
collection = self.db.json_batches
result = collection.find_one(query)
if result == None:
print("File does not exist")
self.show_error_file_not_found()
return "done"
else:
data = result["json_data"]
print(f"batch_{filename} loaded successfully. (username: {username})")
if "asi" in re.split(r'[ _\-]', filename):
new_data = {}
for dialog_key, dialog_data in data.items():
new_dialog = {"number_of_turns": 0,
"annotator_id": username,
"dialog": {}}
for index, value in enumerate(dialog_data["dialog"]):
new_dialog["dialog"][str(index)] = value
new_dialog["number_of_turns"] += 1
if index > 0:
new_dialog["dialog"][str(index)]["requires_rewrite"] = dialog_data[str(index)]["requires_rewrite"]
new_dialog["dialog"][str(index)]["enough_context"] = dialog_data[str(index)]["enough_context"]
new_data[dialog_key] = new_dialog
data = new_data
self.filename = filename
self.username = username
self.check_needs_clarification(data)
return self.fill_dialogs(data)
def get_needs_clarification(self):
return self.needs_clarification
def save_json(self, json_data, dialog_id):
"""
Opens a thread and sends the user's progress to the MongoDB.
"""
self.saving_in_progress = True
# Wrap the save_json logic in a method that can be run in a thread
thread = threading.Thread(
target=self.save_to_mongo,
args=(
json_data,
dialog_id,
),
)
thread.start()
# Optionally, you can join the thread if you need to wait for it to finish
# thread.join()
def show_error_file_not_found(self):
"""
Displays an error message indicating that the file was not found and attempts to close the program.
"""
# Show error message
tk.messagebox.showerror("Error", "File not found")
# Attempt to close the program
self.root.destroy()
def get_username(self):
return self.username
def get_filename(self):
return self.filename
def save_to_mongo(self, json_data, dialog_id):
"""
Saves the given JSON data for a specific dialog to MongoDB.
Args:
json_data (dict): The JSON data to be saved.
dialog_id (str): The ID of the dialog.
Returns:
bool: True if the save operation was successful, False otherwise.
"""
json_data[dialog_id]["annotator_id"] = self.username
collection = self.db.json_annotations_dialogs
query = {"username": self.username, "file_id": self.filename, "dialog_id": dialog_id}
my_values = {
"$set": {
"username": self.username,
"file_id": self.filename,
"dialog_id": dialog_id,
"dialog_data": json_data[dialog_id],
}
}
update_result = collection.update_one(query, my_values, upsert=True)
self.saving_in_progress = False # changes this to let the program know the request is over
if update_result.acknowledged:
print(f"Dialog with username: {self.username} | filename: {self.filename} | dialog: {dialog_id} updated.")
return True
else:
return False
def fill_dialogs(self, json_data):
"""
Fills the dialogs in the empty json data with all the annotations the annotator already made.
"""
collection = self.db.json_annotations_dialogs
query = {"username": self.username, "file_id": self.filename}
results = collection.find(query)
for result in results:
json_data[result["dialog_id"]] = result["dialog_data"]
return json_data
class LoadingScreen:
def __init__(self, root):
"""
Initializes a LoadingScreen object.
Parameters:
- root: The root Tkinter window.
"""
self.root = root
self.loading_screen = None
self.active = False
def show_loading_screen(self, message="Loading..."):
"""
Displays the loading screen.
This method creates a new Toplevel window and displays a loading screen
with a label showing a customizable message. The loading screen prevents
the user from interacting with the main window.
"""
self.loading_screen = tk.Toplevel(self.root)
self.loading_screen.title("Please wait...")
self.loading_screen.geometry("300x150") # Adjusted size
self.loading_screen.transient(self.root)
self.loading_screen.grab_set()
# Center the loading screen relative to the main window
self.loading_screen.geometry(
"+%d+%d"
% (
self.root.winfo_rootx() + (self.root.winfo_width() - 300) // 2,
self.root.winfo_rooty() + (self.root.winfo_height() - 150) // 2,
)
)
# Make the loading screen appear on top of other windows
self.loading_screen.attributes("-topmost", True)
loading_label = tk.Label(self.loading_screen, text=message, wraplength=250)
loading_label.pack(pady=20)
self.root.update()
self.active = True
def close_loading_screen(self):
"""
Closes the loading screen.
This method destroys the loading screen window, allowing the user to
continue interacting with the main window.
"""
if self.loading_screen:
self.loading_screen.destroy()
self.loading_screen = None
self.active = False
def is_active(self):
return self.active
class RequireRewriteCheckBox:
def __init__(self, position, root, update_enough_focus_state=None):
self.root = root
self.position = position
self.function = update_enough_focus_state
self.requires_rewrite_frame = tk.Frame(root)
position.add(self.requires_rewrite_frame, stretch="always", height=30)
LabelSeparator(
self.requires_rewrite_frame, text="Requires Rewrite"
).pack(fill=tk.X)
self.requires_rewrite_grid = tk.Frame(self.requires_rewrite_frame)
self.requires_rewrite_grid.pack(fill=tk.BOTH, padx=10, pady=10)
self.choice_var = tk.IntVar(value=-1)
self.circle1 = tk.Radiobutton(
self.requires_rewrite_grid,
text="Requires Rewrite",
variable=self.choice_var,
value=1,
command=lambda: update_enough_focus_state() if update_enough_focus_state is not None else None
)
self.circle2 = tk.Radiobutton(
self.requires_rewrite_grid,
text="Doesn't Require Rewrite",
variable=self.choice_var,
value=0,
command=lambda: update_enough_focus_state() if update_enough_focus_state is not None else None
)
self.circle1.grid(row=0, column=0, sticky="w", padx=5, pady=0)
self.circle2.grid(row=1, column=0, sticky="w", padx=5, pady=0)
def on_select(self):
"""
This method is called when an option is selected.
It prints the value of the selected option.
"""
print(self.choice_var.get())
def update_entry_text(self, dialog_id, turn_num, json_data):
"""
Updates the marked choice based on the given dialog ID, turn number, and JSON data.
Args:
dialog_id (int): The ID of the dialog.
turn_num (int): The turn number.
json_data (dict): The JSON data containing the dialog information.
Returns:
None
"""
entry_text = JsonFunctions.get_require_rewrite(json_data, dialog_id, turn_num)
if entry_text is not None and entry_text != -1:
self.choice_var.set(int(entry_text))
else:
self.choice_var.set(-1)
if self.function is not None:
self.function()
def update_json_data(self, dialog_id, turn_id, json_data):
"""
Updates the JSON data with the new value from the requires_rewrite Entry widget.
Args:
dialog_id: The ID of the dialog.
turn_id: The turn ID.
json_data: The JSON data.
Returns:
dict: The modified JSON data.
"""
new_value = self.choice_var.get()
json_data = JsonFunctions.change_requires_rewrite(json_data, dialog_id, turn_id, new_value)
return json_data
def is_empty(self):
"""
Check if the choice variable is empty.
Returns:
bool: True if the choice variable is empty, False otherwise.
"""
if self.choice_var.get() == -1:
return True
return False
def requires_rewrite_positive(self):
"""
Check if the choice variable is set to 1.
Returns:
bool: True if the choice variable is 1, False otherwise.
"""
if self.choice_var.get() == 1:
return True
return False
def get_requires_rewrite(self):
"""
Get the value of the choice variable.
Returns:
The value of the choice variable.
"""
return self.choice_var.get()
def set_requires_rewrite(self, value):
"""
Sets the value of requires_rewrite.
Args:
value: The new value for requires_rewrite.
Returns:
None
"""
self.choice_var.set(value)
if self.function is not None:
self.function()
def focus_on(self):
pass
class NeedsClarificationCheckBox:
def __init__(self, position, root):
self.root = root
self.position = position
self.requires_rewrite_frame = tk.Frame(root)
position.add(self.requires_rewrite_frame, stretch="always", height=30)
LabelSeparator(
self.requires_rewrite_frame, text="Needs Clarification Checkbox"
).pack(fill=tk.X)
self.requires_rewrite_grid = tk.Frame(self.requires_rewrite_frame)
self.requires_rewrite_grid.pack(fill=tk.BOTH, padx=10, pady=10)
self.choice_var = tk.IntVar(value=-1)
self.circle1 = tk.Radiobutton(
self.requires_rewrite_grid,
text="Needs Clarification",
variable=self.choice_var,
value=1,
)
self.circle2 = tk.Radiobutton(
self.requires_rewrite_grid,
text="Doesn't Need Clarification",
variable=self.choice_var,
value=0,
)
self.circle1.grid(row=0, column=0, sticky="w", padx=5, pady=0)
self.circle2.grid(row=1, column=0, sticky="w", padx=5, pady=0)
def on_select(self):
"""
This method is called when an option is selected.
It prints the value of the selected option.
"""
print(self.choice_var.get())
def update_entry_text(self, dialog_id, turn_num, json_data):
"""
Updates the marked choice based on the given dialog ID, turn number, and JSON data.
Args:
dialog_id (int): The ID of the dialog.
turn_num (int): The turn number.
json_data (dict): The JSON data containing the dialog information.
Returns:
None
"""
entry_text = JsonFunctions.get_needs_clarification(json_data, dialog_id, turn_num)
if entry_text is not None and entry_text != -1:
self.choice_var.set(int(entry_text))
else:
self.choice_var.set(-1)
def update_json_data(self, dialog_id, turn_id, json_data):
"""
Updates the JSON data with the new value from the needs_clarification Entry widget.
Args:
dialog_id: The ID of the dialog.
turn_id: The turn ID.
json_data: The JSON data.
Returns:
dict: The modified JSON data.
"""
new_value = self.choice_var.get()
json_data = JsonFunctions.change_needs_clarification(json_data, dialog_id, turn_id, new_value)
return json_data
def is_empty(self):
"""
Check if the choice variable is empty.
Returns:
bool: True if the choice variable is empty, False otherwise.
"""
if self.choice_var.get() == -1:
return True
return False
def needs_clarification_positive(self):
"""
Check if the choice variable is set to 1.
Returns:
bool: True if the choice variable is 1, False otherwise.
"""
if self.choice_var.get() == 1:
return True
return False
def get_needs_clarification(self):
"""
Get the value of the choice variable.
Returns:
The value of the choice variable.
"""
return self.choice_var.get()
def set_needs_clarification(self, value):
"""
Sets the value of needs_clarification.
Args:
value: The new value for needs_clarification.
Returns:
None
"""
self.choice_var.set(value)
def focus_on(self):
pass
class EnoughContext:
def __init__(self, position, root):
self.root = root
self.position = position
self.base_frame = tk.Frame(root)
position.add(self.base_frame, stretch="always", height=30)
LabelSeparator(self.base_frame, text="Enough Context Checkbox").pack(fill=tk.X)
self.grid_frame = tk.Frame(self.base_frame)
self.grid_frame.pack(fill=tk.BOTH, padx=10, pady=10)
self.choice_var = tk.IntVar(value=-1)
self.circle1 = tk.Radiobutton(
self.grid_frame, text="Enough Context", variable=self.choice_var, value=1
)
self.circle2 = tk.Radiobutton(
self.grid_frame,
text="Not Enough Context",
variable=self.choice_var,
value=0,
)
self.circle1.grid(row=0, column=0, sticky="w", padx=5, pady=0)
self.circle2.grid(row=1, column=0, sticky="w", padx=5, pady=0)
def update_entry_text(self, dialog_id, turn_num, json_data):
"""
Updates the marked choice based on the provided dialog ID, turn number, and JSON data.
Args:
dialog_id (int): The ID of the dialog.
turn_num (int): The turn number.
json_data (dict): The JSON data containing the context.
Returns:
None
"""
entry_text = JsonFunctions.get_context(json_data, dialog_id, turn_num)
if entry_text is not None and entry_text != -1:
self.choice_var.set(int(entry_text))
else:
self.choice_var.set(-1)
def update_json_data(self, dialog_id, turn_id, json_data):
"""
Updates the JSON data with the new value from the requires_rewrite Entry widget.
Args:
dialog_id: The ID of the dialog.
turn_id: The turn ID.
json_data: The JSON data.
Returns:
dict: The modified JSON data.
"""
new_value = self.choice_var.get()
json_data = JsonFunctions.change_context(json_data, dialog_id, turn_id, new_value)
return json_data
def is_empty(self):
"""
Check if the choice variable is empty.
Returns:
bool: True if the choice variable is empty, False otherwise.
"""
if self.choice_var.get() == -1:
return True
return False
def context_positive(self):
"""
Checks if the choice variable is equal to 1 and returns True if it is, otherwise returns False.
"""
if self.choice_var.get() == 1:
return True
return False
def get_context(self):
"""
Returns the current context selected by the user.
Returns:
str: The selected context.
"""
return self.choice_var.get()
def set_context(self, value):
"""
Sets the context value for the choice variable.
Parameters:
- value: The value to set as the context.
Returns:
None
"""
self.choice_var.set(value)
def focus_on(self):
pass
class DialogFrame:
def __init__(self, position, root):
"""
Initializes the DialogFrame class.
Args:
position: The position of the frame.
root: The root window.
"""
self.root = root
# Frame for Dialog widgets
self.dialog_frame_base = tk.Frame(root, height=1)
position.add(self.dialog_frame_base, stretch="always", height=100)
LabelSeparator(self.dialog_frame_base, text="Dialog Text").pack(
fill=tk.X, side=tk.TOP
)
# Frame to hold the Text widget and Scrollbar
self.text_frame = tk.Frame(self.dialog_frame_base)
self.text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Scrollbar for dialog text
self.scrollbar = tk.Scrollbar(self.text_frame)
self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# tk.Text for dialog
self.dialog_text = tk.Text(
self.text_frame, wrap=tk.WORD, state="disabled", yscrollcommand=self.scrollbar.set
)
self.dialog_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Configure the scrollbar to work with the text widget
self.scrollbar.config(command=self.dialog_text.yview)
def update_dialog_text(self, new_text):
"""
Updates the DialogFrame window with new text.
Args:
new_text (string): The new text to update.
"""
# Enable the widget to modify text
self.dialog_text.config(state="normal")
# Update the text
self.dialog_text.delete(1.0, tk.END)
self.dialog_text.insert(tk.END, new_text)
# Disable the widget to prevent user edits
self.dialog_text.config(state="disabled")
# Scroll to the end of the dialog text
self.dialog_text.see(tk.END)
def display_dialog(self, dialog_id, turn_num, json_data):
"""
Displays a specific dialog in the DialogFrame window.
Args:
dialog_id (int): The ID of the dialog to access.
turn_num (int): The turn number until which to create the text.
json_data (string): The JSON data to use.
"""
dialog_text_content = ""
turns = JsonFunctions.get_turns(json_data, dialog_id, only_annotatable=False)
for i in range(0, turn_num + 1):
turn_data = JsonFunctions.get_turn(json_data, dialog_id, i)
if i == 0:
if len(turn_data['answer']) == 0 or turn_data['answer'] == None:
turn_text = f"Turn {turn_data['turn_num']}:\n"
turn_text += f"Intro: {turn_data['original_question']}:\n"
turn_text += "-" * 40 + "\n" # Separator line
dialog_text_content += turn_text
continue
# Format each turn
turn_text = f"Turn {turn_data['turn_num']}:\n"
turn_text += f"U.u: {turn_data['original_question']}\n"
if i < turn_num:
turn_text += f"U.s: {turn_data['answer']}\n"
turn_text += "-" * 40 + "\n" # Separator line
# Append this turn's text to the dialog text content
dialog_text_content += turn_text
# Update the dialog text widget using the new method
self.update_dialog_text(dialog_text_content)
def scroll_up(self):
self.dialog_text.yview_scroll(-10, "units")
def scroll_down(self):
self.dialog_text.yview_scroll(10, "units")
class Rewrites():
def __init__(self, position, root):
"""
Initializes the Rewrites object.
Parameters:
- position (tk.Position): The position object to manage the layout.
- root (tk.Tk): The root Tkinter window.
"""
self.rewrites = {}
self.root = root
self.rewrites_frame_base = tk.Frame(root)
position.add(self.rewrites_frame_base, stretch="always", height=70)
LabelSeparator(self.rewrites_frame_base, text="Rewrites").pack(fill=tk.X)
# inside Frame for rewrites annotation entries
self.rewrite_table_grid = tk.Frame(self.rewrites_frame_base)
self.rewrite_table_grid.pack(fill=tk.BOTH, padx=10, pady=10)
text = tk.Label(self.rewrite_table_grid, text="Text")
score = tk.Label(self.rewrite_table_grid, text="Score")
optimal = tk.Label(self.rewrite_table_grid, text="Optimal")
# Place the labels in the grid
text.grid(row=0, column=1, sticky='nsew')
score.grid(row=0, column=2, sticky='nsew')
optimal.grid(row=0, column=3, sticky='nsew')
# Configure the frame columns to expand with the window size
self.rewrite_table_grid.columnconfigure(0, weight = 1)
self.rewrite_table_grid.columnconfigure(1, weight = 50)
self.rewrite_table_grid.columnconfigure(2, weight = 1)
self.rewrite_table_grid.columnconfigure(3, weight = 1)
#label that appear if there are no rewrites
self.no_rewrites_label = tk.Label(self.rewrite_table_grid, text="No rewrites in this turn.")
self.no_rewrites_label.grid(column=1, row=3)
self.no_rewrites_label.grid_remove() # This hides the label initially
def show_no_rewrites_label(self):
self.no_rewrites_label.grid()
def hide_no_rewrites_label(self):
self.no_rewrites_label.grid_remove()
def update_rewrites(self, dialog_id, turn_num, json_data):
if not self.rewrites == {}:
for rewrite in self.rewrites.values():
rewrite.optimal.destroy()
rewrite.score.destroy()
rewrite.text.destroy()
rewrite.rewrite_label.destroy()
valid_rewrites_len = 0
rewrite_row = 1
self.rewrites = {}
for rewrite_key, rewrite_value in JsonFunctions.get_rewrites(json_data, dialog_id, turn_num).items():
if not {"text", "optimal", "score"}.issubset(rewrite_value.keys()):
print(JsonFunctions.get_rewrites(json_data, dialog_id, turn_num))
raise Exception(f"The value(s) are not in the rewrite keys: {rewrite_value.keys()}")
duplicate = False
for exsiting_rewrite in self.rewrites.values():
if compare_norm_texts(exsiting_rewrite.get_text(), rewrite_value['text']):
exsiting_rewrite.duplicates.append(rewrite_key)
duplicate = True
if duplicate == False:
self.rewrites[rewrite_key] = (SingleRewrite(rewrite_value['text'], rewrite_value['optimal'], rewrite_value['score'], rewrite_row, self))
rewrite_row += 1
valid_rewrites_len += 1
if valid_rewrites_len == 0:
self.no_rewrites_label.grid() # Show the label
else:
self.no_rewrites_label.grid_remove() # Hide the label
def update_json_data(self, dialog_id, turn_num, json_data):
"""
Updates the JSON data with the scores and optimal values for rewrites.
Args:
dialog_id (str): The ID of the dialog.
turn_num (int): The turn number.
json_data (dict): The JSON data to be updated.
Returns:
dict: The updated JSON data.
"""
def update_rewrite_field_json(rewrite_key, field, value):
JsonFunctions.change_rewrite_field(json_data, dialog_id, turn_num, rewrite_key, field, value)