-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcs_annotator_app.py
More file actions
3334 lines (2869 loc) · 112 KB
/
Copy pathcs_annotator_app.py
File metadata and controls
3334 lines (2869 loc) · 112 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
# cs_annotator_app.py
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog, messagebox, simpledialog
from tkinter.scrolledtext import ScrolledText
import os
import re
import csv
import json
import sys
from cs_pipeline import Annotator, DEFAULTS
try:
import tksheet
except Exception:
tksheet = None
DARK_BG = "#222222"
DARK_FG = "#e6e6e6"
ACCENT = "#3a7bd5"
APP_DIR = os.path.join(os.path.expanduser("~"), ".cs_annotator")
LAST_PROJECT_PTR = os.path.join(APP_DIR, "last_project.json")
PROJECT_EXT = ".trenproj"
class App(tk.Tk):
def _set_runtime_workdir(self):
"""
Ensure relative resource paths resolve correctly.
- In dev: set CWD to the directory containing this file.
- In PyInstaller (frozen): set CWD to the bundle extraction dir (sys._MEIPASS).
This prevents errors like:
[Errno 2] No such file or directory: 'frequent_tr_words.txt'
when downstream code uses relative opens.
"""
try:
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
base = sys._MEIPASS
else:
base = os.path.dirname(os.path.abspath(__file__))
# If a bundled resources folder exists, prefer it so relative opens work
res_dir = os.path.join(base, "resources")
if os.path.isdir(res_dir):
os.chdir(res_dir)
elif base and os.path.isdir(base):
os.chdir(base)
except Exception:
pass
_LEIPZIG_APPENDIX_TEXT = """Appendix: List of Standard Abbreviations
1 first person
2 second person
3 third person
A agent-like argument of canonical transitive verb
ABL ablative
ABS absolutive
ACC accusative
ADJ adjective
ADV adverb(ial)
AGR agreement
ALL allative
ANTIP antipassive
APPL applicative
ART article
AUX auxiliary
BEN benefactive
CAUS causative
CLF classifier
COM comitative
COMP complementizer
COMPL completive
COND conditional
COP copula
CVB converb
DAT dative
DECL declarative
DEF definite
DEM demonstrative
DET determiner
DIST distal
DISTR distributive
DU dual
DUR durative
ERG ergative
EXCL exclusive
F feminine
FOC focus
FUT future
GEN genitive
IMP imperative
INCL inclusive
IND indicative
INDF indefinite
INF infinitive
INS instrumental
INTR intransitive
IPFV imperfective
IRR irrealis
LOC locative
M masculine
N neuter
N- non- (e.g. NSG nonsingular, NPST nonpast)
NEG negation, negative
NMLZ nominalizer/nominalization
NOM nominative
OBJ object
OBL oblique
P patient-like argument of canonical transitive verb
PASS passive
PFV perfective
PL plural
POSS possessive
PRED predicative
PRF perfect
PRS present
PROG progressive
PROH prohibitive
PROX proximal/proximate
PST past
PTCP participle
PURP purposive
Q question particle/marker
QUOT quotative
RECP reciprocal
REFL reflexive
REL relative
RES resultative
S single argument of canonical intransitive verb
SBJ subject
SBJV subjunctive
SG singular
TOP topic
TR transitive
VOC vocative
"""
# Auto-Glossing Tool
def _collect_mixed_rows(self):
"""Collect MIXED rows from the current model, in visible order."""
items = []
if not getattr(self, 'blocks', None):
return items
def sent_id_for_block(bi: int):
try:
blk = self.blocks[bi]
except Exception:
return ""
for rr in blk:
try:
if str(rr.get('token', '')).strip() == 'SentenceID':
v = str(rr.get('label', '') or rr.get('gloss', '') or '').strip()
return v
except Exception:
continue
return ""
for vis_r in sorted(getattr(self, '_row_index_map', {}).keys()):
if vis_r in getattr(self, '_sep_rows', set()):
continue
bidx, ridx = self._row_index_map.get(vis_r, (None, None))
if bidx is None:
continue
try:
row = self.blocks[bidx][ridx]
except Exception:
continue
tok = str(row.get('token', '') or '').strip()
if self._is_meta_row_token(tok):
continue
lab = str(row.get('label', '') or '').strip()
if lab.upper() == 'MIXED':
items.append({
'vis_r': vis_r,
'bidx': bidx,
'ridx': ridx,
'sent_id': sent_id_for_block(bidx),
})
return items
def open_auto_glossing_tool(self):
"""Open Auto-Glossing Tool window (UI skeleton)."""
if getattr(self, '_ag_win', None) is not None and self._ag_win.winfo_exists():
try:
self._ag_win.deiconify()
self._ag_win.lift()
except Exception:
pass
return
self._ag_items = []
self._ag_i = 0
win = tk.Toplevel(self)
win.title('Auto-Glossing Tool')
win.geometry('820x420')
win.configure(bg=DARK_BG)
win.transient(self)
outer = ttk.Frame(win, style='Dark.TFrame')
outer.pack(fill='both', expand=True, padx=10, pady=10)
# progress left, sentence id right
top = ttk.Frame(outer, style='Dark.TFrame')
top.pack(fill='x', pady=(0, 10))
self._ag_status_var = tk.StringVar(value='0/0')
self._ag_sent_var = tk.StringVar(value='SentenceID: ')
ttk.Label(top, textvariable=self._ag_status_var, style='Dark.TLabel').pack(side='left')
ttk.Label(top, textvariable=self._ag_sent_var, style='Dark.TLabel').pack(side='right')
# Content area
body = ttk.Frame(outer, style='Dark.TFrame')
body.pack(fill='both', expand=True)
body.grid_columnconfigure(0, weight=1)
body.grid_columnconfigure(1, weight=0)
body.grid_columnconfigure(2, weight=1)
card = ttk.Frame(body, style='Dark.TFrame')
card.grid(row=0, column=1, sticky='n')
# Make the card content symmetric
card.grid_columnconfigure(0, weight=0)
card.grid_columnconfigure(1, weight=1)
# Item
ttk.Label(card, text='Item', style='Dark.TLabel').grid(row=0, column=0, sticky='w', pady=(0, 6))
self._ag_item_var = tk.StringVar(value='')
ent_item = ttk.Entry(card, textvariable=self._ag_item_var, style='Dark.TEntry', width=64, state='readonly')
ent_item.grid(row=0, column=1, sticky='we', padx=(12, 0), pady=(0, 6))
# Gloss
ttk.Label(card, text='Gloss', style='Dark.TLabel').grid(row=1, column=0, sticky='w', pady=(0, 6))
self._ag_gloss_var = tk.StringVar(value='')
ent_gls = ttk.Entry(card, textvariable=self._ag_gloss_var, style='Dark.TEntry', width=64)
ent_gls.grid(row=1, column=1, sticky='we', padx=(12, 0), pady=(0, 6))
# Auto-gloss button under Gloss (aligned with entries)
btn_row = ttk.Frame(card, style='Dark.TFrame')
btn_row.grid(row=2, column=1, sticky='w', padx=(12, 0), pady=(2, 12))
btn_autogloss = ttk.Button(btn_row, text='Auto-Gloss', style='Dark.TButton', command=self._ag_auto_gloss_current)
btn_autogloss.pack(side='left')
# Separator
ttk.Separator(card, orient='horizontal').grid(row=3, column=0, columnspan=2, sticky='we', pady=(6, 10))
# Label row
ttk.Label(card, text='Label', style='Dark.TLabel').grid(row=4, column=0, sticky='w', pady=(0, 6))
self._ag_label_var = tk.StringVar(value='')
ent_lab = ttk.Entry(card, textvariable=self._ag_label_var, style='Dark.TEntry', width=18)
ent_lab.grid(row=4, column=1, sticky='w', padx=(12, 0), pady=(0, 6))
# Label buttons (grid, symmetric)
lblbtns = ttk.Frame(card, style='Dark.TFrame')
lblbtns.grid(row=5, column=0, columnspan=2, sticky='we', pady=(4, 0))
labels = ["TR", "EN", "MIXED", "UID", "NE", "LANG3", "OTHER"]
for i, lab in enumerate(labels):
r = i // 4
c = i % 4
b = ttk.Button(lblbtns, text=lab, style='Dark.TButton', width=10,
command=lambda L=lab: self._ag_set_label(L))
b.grid(row=r, column=c, padx=4, pady=4, sticky='we')
for c in range(4):
lblbtns.grid_columnconfigure(c, weight=1)
# Appendix button
ttk.Button(card, text='Leipzig Gloss Appendix', style='Dark.TButton',
command=self._open_leipzig_appendix).grid(row=6, column=0, columnspan=2, sticky='we', pady=(10, 0))
# prev left, next right
nav = ttk.Frame(outer, style='Dark.TFrame')
nav.pack(fill='x', pady=(12, 0))
ttk.Button(nav, text='◀', style='Dark.TButton', width=4, command=self._ag_prev).pack(side='left')
ttk.Button(nav, text='▶', style='Dark.TButton', width=4, command=self._ag_next).pack(side='right')
def _on_close():
try:
self._ag_commit_current_to_model()
win.destroy()
except Exception:
pass
finally:
self._ag_win = None
# shortcuts
try:
# Auto-gloss
win.bind('<Command-Return>', lambda e: (self._ag_auto_gloss_current(), 'break'))
win.bind('<Control-Return>', lambda e: (self._ag_auto_gloss_current(), 'break'))
# Navigation
win.bind('<Left>', lambda e: (self._ag_prev(), 'break'))
win.bind('<Right>', lambda e: (self._ag_next(), 'break'))
except Exception:
pass
win.protocol('WM_DELETE_WINDOW', _on_close)
self._ag_win = win
self._ag_refresh_items()
def _open_leipzig_appendix(self):
# reuse window if already open
if getattr(self, '_ag_appendix_win', None) is not None:
try:
if self._ag_appendix_win.winfo_exists():
self._ag_appendix_win.deiconify()
self._ag_appendix_win.lift()
return
except Exception:
pass
win = tk.Toplevel(self)
win.title('Leipzig Gloss Appendix')
win.geometry('720x520')
win.configure(bg=DARK_BG)
win.transient(self)
frm = tk.Frame(win, bg=DARK_BG)
frm.pack(fill='both', expand=True, padx=10, pady=10)
txt = ScrolledText(frm, wrap='none', bg='#1b1b1b', fg=DARK_FG, insertbackground='white')
txt.pack(fill='both', expand=True)
try:
txt.configure(font=('Menlo', 12))
except Exception:
pass
txt.insert('1.0', self._LEIPZIG_APPENDIX_TEXT)
txt.configure(state='disabled')
def _on_close():
try:
win.destroy()
except Exception:
pass
finally:
self._ag_appendix_win = None
win.protocol('WM_DELETE_WINDOW', _on_close)
self._ag_appendix_win = win
# Navigation and sync edit helpers
def _ag_prev(self):
if not self._ag_items:
return
if self._ag_i > 0:
self._ag_commit_current_to_model()
self._ag_i -= 1
self._ag_load_current()
def _ag_next(self):
if not self._ag_items:
return
j = self._ag_i + 1
while j < len(self._ag_items):
it = self._ag_items[j]
try:
row = self.blocks[it['bidx']][it['ridx']]
if str(row.get('label', '')).upper() == 'MIXED':
self._ag_commit_current_to_model()
self._ag_i = j
self._ag_load_current()
return
except Exception:
pass
j += 1
def _ag_set_label(self, lab: str):
try:
self._ag_label_var.set(str(lab))
except Exception:
pass
def _ag_commit_current_to_model(self):
"""Commit the current tool fields into the main model + grid.
This runs only when navigating away (or on close).
"""
if not getattr(self, '_ag_items', None):
return
it = self._ag_items[self._ag_i]
bidx, ridx, vis_r = it['bidx'], it['ridx'], it['vis_r']
try:
row = self.blocks[bidx][ridx]
except Exception:
return
row['label'] = self._ag_label_var.get()
row['gloss'] = self._ag_gloss_var.get()
try:
if getattr(self, 'sheet', None) is not None:
self.sheet.set_cell_data(vis_r, 2, row['label'])
self.sheet.set_cell_data(vis_r, 3, row['gloss'])
if hasattr(self.sheet, 'refresh'):
self.sheet.refresh()
except Exception:
pass
# Auto-Gloss handler for current item
def _ag_auto_gloss_current(self):
if not self._ag_items:
return
it = self._ag_items[self._ag_i]
try:
row = self.blocks[it['bidx']][it['ridx']]
except Exception:
return
if str(row.get('label', '')).upper() != 'MIXED':
self.bell()
return
gloss = self._auto_gloss_mixed_token(row.get('token', ''))
if gloss:
self._ag_gloss_var.set(gloss)
def _ag_update_status(self):
n = len(getattr(self, '_ag_items', []) or [])
i = getattr(self, '_ag_i', 0)
try:
lab = ''
if getattr(self, '_ag_items', None):
it = self._ag_items[self._ag_i]
row = self.blocks[it['bidx']][it['ridx']]
lab = str(row.get('label', '')).upper()
self._ag_status_var.set(f"{lab} {i + 1}/{n}" if n else "0/0")
except Exception:
pass
def _ag_refresh_items(self):
try:
self._ag_items = self._collect_mixed_rows() or []
except Exception:
self._ag_items = []
self._ag_i = 0
if not self._ag_items:
try:
self._ag_item_var.set("")
self._ag_label_var.set("")
self._ag_gloss_var.set("")
self._ag_sent_var.set("SentenceID: ")
self._ag_update_status()
except Exception:
pass
messagebox.showinfo("Auto-Glossing Tool", "No MIXED items found.")
return
self._ag_load_current()
def _ag_load_current(self):
if not getattr(self, '_ag_items', None):
return
it = self._ag_items[self._ag_i]
bidx, ridx, vis_r = it['bidx'], it['ridx'], it['vis_r']
try:
row = self.blocks[bidx][ridx]
except Exception:
return
try:
self._ag_item_var.set(str(row.get('token', '') or ''))
self._ag_label_var.set(str(row.get('label', '') or ''))
self._ag_gloss_var.set(str(row.get('gloss', '') or ''))
sid = it.get('sent_id', '') or ''
self._ag_sent_var.set(f"SentenceID: {sid}" if sid else "SentenceID: ")
except Exception:
pass
# sync selection in main grid
try:
if getattr(self, 'sheet', None) is not None:
self._cancel_edit_if_any()
self.sheet.select_cell(vis_r, 2)
self.sheet.see(vis_r, 2)
except Exception:
pass
self._ag_update_status()
def __init__(self):
super().__init__()
# Make relative resource file opens work in both dev and packaged app
self._set_runtime_workdir()
# Ensure menu callbacks exist even if refactors happen
if not hasattr(self, 'open_auto_glossing_tool') and hasattr(self, '_open_auto_glossing_tool_impl'):
self.open_auto_glossing_tool = self._open_auto_glossing_tool_impl
self.title("TREN Annotator")
self.geometry("1200x720")
self.configure(bg=DARK_BG)
self._init_style()
self.annotator = None
self.current_text = ""
self.current_output = ""
self.current_path = None
# tablw model
self.blocks = []
self._row_index_map = {}
self._sep_rows = set()
self._core_headers = ["Token", "Item", "Label", "Gloss"]
self._extra_headers = [] # user-added columns
self.cfg = DEFAULTS.copy()
self._build_menu()
self._build_toolbar()
self._build_body()
self._bind_keys()
self._last_pos = None
self._relabel_busy = False
self._active_area = "text" # "text" or "sheet"
# search dialog state
self._search_win = None
self._search_var = tk.StringVar(value="")
self._search_target = "text"
self._search_matches = [] # list of match locations
self._search_index = -1
self._search_after_id = None
self._conc_win = None
self._sentence_win = None
self._freq_win = None
self._ag_win = None
# concordance (KWIC) state
self._conc_query_var = tk.StringVar(value="")
self._conc_ctx_var = tk.IntVar(value=30)
self._conc_ci_var = tk.BooleanVar(value=True)
self._conc_regex_var = tk.BooleanVar(value=False)
self._conc_tree = None
self._conc_count_var = tk.StringVar(value="0 matches")
self._conc_hit_spans = {}
# grid clipboard (for copy/cut/paste)
self._grid_clipboard = None
# full edit window
self._full_win = None
self._full_sheet = None
self._active_sheet = None # main sheet or full sheet, whichever has focus
# auto-restore last project (if exists)
try:
self.after(50, self._auto_restore_last_project)
except Exception:
pass
# confirm on close
try:
self.protocol("WM_DELETE_WINDOW", self._on_close_request)
except Exception:
pass
# Auto-gloss helpers
def _split_mixed_token(self, token: str):
"""Split token into (stem_hint, suffix_hint). If no delimiter, allow delimiterless parsing."""
s = "" if token is None else str(token).strip()
if not s:
return "", ""
if "-" in s:
stem, suf = s.rsplit("-", 1)
return stem, suf
if "'" in s:
stem, suf = s.rsplit("'", 1)
return stem, suf
return "", s
def _suffix_registry(self):
"""Inclusive suffix registry. Some suffixes return alternative glosses."""
V_A = "ae"
V_I = "ıiuü"
def rx(p):
return re.compile(p)
return [
# Inflectional
("ABL", 3, [rx(rf"^[dt][{V_A}]n$")], "ABL"),
("LOC", 2, [rx(rf"^[dt][{V_A}]$")], "LOC"),
("GEN", 3, [rx(rf"^n?[{V_I}]n$")], "GEN"),
("DAT", 2, [rx(rf"^y?[{V_A}]$")], "DAT"),
("ACC", 2, [rx(rf"^y?[{V_I}]$")], "ACC"),
("INS_COM", 3, [rx(rf"^y?l[{V_A}]$")], ["INS", "COM"]),
("INS_COM_SPEECH", 3, [rx(r"^n[ae]n$")], ["INS", "COM"]),
("PL", 3, [rx(rf"^l[{V_A}]r$")], "PL"),
# Possessive (heuristic)
("POSS.1SG", 2, [rx(rf"^[{V_I}]m$")], "POSS.1SG"),
("POSS.2SG", 2, [rx(rf"^[{V_I}]n$")], "POSS.2SG"),
("POSS.3SG", 2, [rx(rf"^s?[{V_I}]$")], "POSS.3SG"),
("POSS.3PL", 4, [rx(rf"^l[{V_A}]r[{V_I}]$")], "POSS.3PL"),
("POSS.PLX", 4, [rx(rf"^[{V_I}].z$")], ["POSS.1PL", "POSS.2PL"]),
# Derivational (inclusive)
("AGT", 3, [rx(rf"^[cç][{V_I}]$")], "AGT"),
("NMLZ", 3, [rx(rf"^l[{V_I}]k$")], "NMLZ"),
("PRIV", 3, [rx(rf"^s[{V_I}]z$")], "PRIV"),
("ATTR", 2, [rx(rf"^l[{V_I}]$")], "ATTR"),
("SIM_ADV", 2, [rx(rf"^c[{V_A}]$")], ["SIM", "ADV"]),
("SIM", 3, [rx(rf"^ms[{V_I}]$")], "SIM"),
# verbal nominalizers/participles
("NMLZ_V", 2, [rx(rf"^m[{V_A}]$")], "NMLZ"),
("PTCP", 2, [rx(rf"^[{V_A}]n$")], "PTCP"),
("NMLZ_DIK", 4, [rx(rf"^[dt][{V_I}]k$")], "NMLZ"),
]
def _auto_gloss_candidates(self, token: str):
"""Return candidate gloss strings: stem-GLOSS-GLOSS... (inclusive)."""
stem_hint, suf_hint = self._split_mixed_token(token)
s = "" if token is None else str(token).strip()
if not s:
return []
remaining = "" if suf_hint is None else str(suf_hint).strip().casefold()
if not remaining:
return []
registry = self._suffix_registry()
chain = []
guard = 0
while remaining and guard < 12:
guard += 1
matched = False
for L in (5, 4, 3, 2, 1):
if len(remaining) < L:
continue
cand = remaining[-L:]
for _name, _maxlen, patterns, glosses in registry:
if L > _maxlen:
continue
ok = False
for pat in patterns:
try:
if pat.match(cand):
ok = True
break
except Exception:
continue
if not ok:
continue
remaining = remaining[:-L]
if isinstance(glosses, list):
chain.append([str(x) for x in glosses])
else:
chain.append([str(glosses)])
matched = True
break
if matched:
break
if not matched:
break
if not chain:
return []
stem = (stem_hint or "").strip()
if not stem:
consumed = len(str(suf_hint).strip()) - len(remaining)
base = str(suf_hint).strip()
stem = base[:max(0, len(base) - consumed)].strip() or str(token).strip()
chain = list(reversed(chain))
cands = [""]
for alts in chain:
new_cands = []
for pref in cands:
for g in alts:
new_cands.append((pref + "-" + g) if pref else g)
cands = new_cands
out = []
for gseq in cands:
if gseq:
out.append(stem + "-" + gseq)
seen = set()
uniq = []
for x in out:
if x not in seen:
uniq.append(x)
seen.add(x)
return uniq
def _auto_gloss_mixed_token(self, token: str):
cands = self._auto_gloss_candidates(token)
return cands[0] if cands else ""
def _init_style(self):
style = ttk.Style(self)
try:
style.theme_use('clam')
except Exception:
pass
style.configure('Dark.TButton', background="#2e2e2e", foreground=DARK_FG,
padding=6, focusthickness=3, focuscolor=ACCENT)
style.map('Dark.TButton', background=[('active', '#3a3a3a')])
style.configure('Dark.TCheckbutton', background=DARK_BG, foreground=DARK_FG)
style.map('Dark.TCheckbutton', background=[('active', DARK_BG)])
# generic dark ttk widgets
style.configure('Dark.TFrame', background=DARK_BG)
style.configure('Dark.TLabel', background=DARK_BG, foreground=DARK_FG)
style.configure('Dark.TEntry', fieldbackground="#1b1b1b", background=DARK_BG,
foreground=DARK_FG, insertcolor="white")
style.configure('Dark.TSpinbox', fieldbackground="#1b1b1b", background=DARK_BG,
foreground=DARK_FG, insertcolor="white")
# concordance treeview
style.configure('Conc.Treeview',
background="#1b1b1b",
fieldbackground="#1b1b1b",
foreground=DARK_FG,
bordercolor="#404040",
lightcolor="#404040",
darkcolor="#404040")
style.map('Conc.Treeview',
background=[('selected', '#2b2b2b')],
foreground=[('selected', 'white')])
style.configure('Conc.Treeview.Heading',
background="#171717",
foreground=DARK_FG,
bordercolor="#404040")
def _build_menu(self):
menubar = tk.Menu(self, tearoff=False)
filem = tk.Menu(menubar, tearoff=False, bg=DARK_BG, fg=DARK_FG)
filem.add_command(label="Open Input (⌘O / Ctrl+O)", command=self.open_input)
filem.add_command(label="Run (⌘R / Ctrl+R)", command=self.run_pipeline)
filem.add_command(label="Save Output As... (⌘S / Ctrl+S)", command=self.save_output)
filem.add_separator()
filem.add_command(label="Exit", command=self.destroy)
menubar.add_cascade(label="File", menu=filem)
projm = tk.Menu(menubar, tearoff=False, bg=DARK_BG, fg=DARK_FG)
projm.add_command(label="New Project", command=self.new_project)
projm.add_separator()
projm.add_command(label="Open Project Save...", command=self.open_project_save)
projm.add_command(label="Save Project Progress...", command=self.save_project_progress)
menubar.add_cascade(label="Project", menu=projm)
annm = tk.Menu(menubar, tearoff=False, bg=DARK_BG, fg=DARK_FG)
annm.add_command(label="Add New Column...", command=self._add_new_column_dialog)
annm.add_separator()
annm.add_command(label="Cut Cell(s)", command=self.cut_selected_cells)
annm.add_command(label="Copy Cell(s)", command=self.copy_selected_cells)
annm.add_command(label="Paste Cell(s)", command=self.paste_selected_cells)
annm.add_command(label="Clear Selected Cell(s)", command=self.clear_selected_cells)
annm.add_separator()
annm.add_command(label="Insert Row Before", command=self.insert_row_before)
annm.add_command(label="Remove Row", command=self.remove_selected_row)
menubar.add_cascade(label="Annotation", menu=annm)
editm = tk.Menu(menubar, tearoff=False, bg=DARK_BG, fg=DARK_FG)
editm.add_command(label="View Full Edit Window...", command=self.open_full_edit_window)
menubar.add_cascade(label="Edit Window", menu=editm)
toolsm = tk.Menu(menubar, tearoff=False, bg=DARK_BG, fg=DARK_FG)
toolsm.add_command(label="Auto-Glossing Tool...", command=self.open_auto_glossing_tool)
toolsm.add_separator()
toolsm.add_command(label="Concordance (KWIC)...", command=self.open_concordance)
toolsm.add_command(label="Show Sentence (Context)", command=self.show_sentence_context)
toolsm.add_command(label="Word Frequency List...", command=self.open_word_frequency)
menubar.add_cascade(label="Tools", menu=toolsm)
self.config(menu=menubar)
# Window close handling
def _has_unsaved_progress(self):
try:
if self.txt_input.get("1.0", "end-1c").strip():
return True
except Exception:
pass
try:
if getattr(self, 'blocks', None):
# non-empty blocks means there is annotation state
return True
except Exception:
pass
return False
def _on_close_request(self):
# Ask to save progress before closing
if not self._has_unsaved_progress():
try:
self.destroy()
except Exception:
pass
return
res = messagebox.askyesnocancel(
"Close",
"Save project progress before closing?"
)
if res is None:
return # cancel
if res is True:
self.save_project_progress()
try:
self.destroy()
except Exception:
pass
# Project Save/Load
def new_project(self):
if messagebox.askyesno("New Project", "Start a new project? Unsaved progress will be lost.") is False:
return
self.blocks = []
self._row_index_map = {}
self._sep_rows = set()
self._extra_headers = []
self.cfg = DEFAULTS.copy()
try:
self.txt_input.delete("1.0", "end")
except Exception:
pass
if self.sheet is not None:
try:
self.sheet.headers(self._all_headers())
self.sheet.set_sheet_data([])
if hasattr(self.sheet, "refresh"):
self.sheet.refresh()
except Exception:
pass
try:
os.makedirs(APP_DIR, exist_ok=True)
if os.path.isfile(LAST_PROJECT_PTR):
os.remove(LAST_PROJECT_PTR)
except Exception:
pass
self._grid_clipboard = None
self._search_matches = []
self._search_index = -1
self._last_pos = None
def save_project_progress(self):
name = simpledialog.askstring("Save Project", "Name your project save:")
if not name:
return
try:
os.makedirs(APP_DIR, exist_ok=True)
except Exception:
pass
path = os.path.join(APP_DIR, name + PROJECT_EXT)
# confirm overwrite
if os.path.isfile(path):
if messagebox.askyesno("Overwrite?", f"A save named '{name}' already exists. Overwrite?") is False:
return
try:
text_cursor = self.txt_input.index("insert")
except Exception:
text_cursor = None
try:
sheet_sel = self.sheet.get_currently_selected() if self.sheet is not None else None
grid_pos = (sheet_sel.row, sheet_sel.column) if sheet_sel is not None else None
except Exception:
grid_pos = None
payload = {
"version": 1,
"name": name,
"input_text": self.txt_input.get("1.0", "end-1c"),
"cfg": self.cfg,
"blocks": self.blocks,
"extra_headers": self._extra_headers,
"text_cursor": text_cursor,
"grid_pos": grid_pos,
}
try:
with open(path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
except Exception as e:
messagebox.showerror("Save error", str(e))
return
try:
with open(LAST_PROJECT_PTR, "w", encoding="utf-8") as f:
json.dump({"path": path}, f)
except Exception:
pass
messagebox.showinfo("Project saved", f"Saved project:\n{path}")
def open_project_save(self):
path = filedialog.askopenfilename(
title="Open Project Save",
initialdir=APP_DIR if os.path.isdir(APP_DIR) else None,
filetypes=[("Project Saves", f"*{PROJECT_EXT}"), ("All files", "*.*")]
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as f:
payload = json.load(f)
except Exception as e:
messagebox.showerror("Open error", str(e))
return
self.cfg = payload.get("cfg", DEFAULTS.copy())
self.blocks = payload.get("blocks", [])
self._extra_headers = payload.get("extra_headers", [])
self.txt_input.delete("1.0", "end")
self.txt_input.insert("1.0", payload.get("input_text", ""))
self._renumber_tokens()
self._rebuild_grid_from_model()
try:
if payload.get("text_cursor"):
self.txt_input.mark_set("insert", payload.get("text_cursor"))
except Exception:
pass
try:
gp = payload.get("grid_pos")
if gp and self.sheet is not None:
r, c = gp
self.sheet.select_cell(r, c)
self.sheet.see(r, c)
except Exception:
pass
try:
os.makedirs(APP_DIR, exist_ok=True)
with open(LAST_PROJECT_PTR, "w", encoding="utf-8") as f:
json.dump({"path": path}, f)
except Exception:
pass
messagebox.showinfo("Project loaded", f"Loaded project:\n{path}")
def _auto_restore_last_project(self):
try:
if not os.path.isfile(LAST_PROJECT_PTR):
return
with open(LAST_PROJECT_PTR, "r", encoding="utf-8") as f:
ptr = json.load(f)
path = ptr.get("path")
if not path or not os.path.isfile(path):
return
except Exception:
return
try:
with open(path, "r", encoding="utf-8") as f:
payload = json.load(f)
except Exception:
return
try:
self.cfg = payload.get("cfg", DEFAULTS.copy())
self.blocks = payload.get("blocks", [])
self._extra_headers = payload.get("extra_headers", [])
except Exception:
return
try:
self.txt_input.delete("1.0", "end")