Repository navigation
Expand file tree
/
Copy pathmake_patch.py
More file actions
1265 lines (1085 loc) · 52.3 KB
/
Copy pathmake_patch.py
File metadata and controls
1265 lines (1085 loc) · 52.3 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
#!/usr/bin/env python3
"""
make_patch.py — Generate a .patch file for a KIParla TSV from a lemmatization CSV.
Usage:
python make_patch.py <wip_csv> <source_tsv> [<output_patch>]
python make_patch.py --batch <wip_subdir> [<source_root>]
The lemmatization CSV (from wip/) carries corrected form/span alongside lemma/upos
annotations. This script extracts the transcription-level corrections and generates
a unified diff patch for the source TSV.
What is patched:
- form, span columns (shared between CSV and TSV); values are stripped
- missing speaker/tu_id values are auto-filled from CSV or neighboring tokens
- jefferson_feats: only Lang=XXX entries from the CSV are merged in; if span
changed, span-derived features (Intonation, Interrupted, Truncated, Volume)
are recomputed from the new span; all other TSV features are preserved
- Token deletions: TSV tokens absent from the CSV (e.g. second half of a merge)
- Begin=/End= alignment is auto-transferred to neighboring tokens where possible
- prolongations/pace/guesses/overlaps are auto-transferred to the preceding
kept token when its form was extended by exactly the dropped token's form
(a clean merge), with char positions shifted by the length gained
- Token additions: CSV tokens absent from the TSV are listed in the recap only
- `id`: recomputed as a monotonic 0-based position within each TU, from final
row order — independent of `token_id`, whose numeric suffix stays stable/
creation-order and can go out of sequence after a split or add
- `unit` column: dropped from the output (pure duplicate of `tu_id`)
What is NOT patched:
- `type` (annotation-only classification, not derived here)
- Lemma/upos (annotation-only, not in source TSV)
- Annotation sub-token rows (numeric token_id + letter suffix, e.g. 4-7a)
Output:
patches/<CORPUS>/<FILE>.vert.tsv.patch — apply with: git apply <patch>
patches/<CORPUS>/<FILE>.vert.tsv.recap.md — manual follow-up actions, ordered by row
Validation:
- Every token in both CSV and TSV must have non-empty span and form values
Batch mode:
- Given a wip subfolder (e.g. wip/KIP), patches all *.csv files inside it
- Source TSV paths are inferred as ../<CORPUS>/tsv/<FILE>.vert.tsv unless
<source_root> is provided explicitly
The output patch can be applied with:
cd <KIP-module-dir> && git apply ../lemmatization-project/patches/KIP/BOA1007.vert.tsv.patch
"""
import csv
import io
import sys
import difflib
import re
from datetime import date
from pathlib import Path
TOOLS_DIR = Path(__file__).resolve().parent
if str(TOOLS_DIR) not in sys.path:
sys.path.insert(0, str(TOOLS_DIR))
from variety import is_syntactic
from jefferson_feats import (
SPAN_DERIVED_FEAT_KEYS,
parse_feats,
format_feats,
feats_from_span,
form_from_span,
)
PATCHABLE_COLS = ['span', 'form']
# TSV-only columns that may need manual attention after structural changes
MANUAL_COLS = ['prolongations', 'pace', 'guesses', 'overlaps']
# pace/guesses/overlaps encode zero-based char positions over `form` as
# `<start>-<end>`, optionally with a `Fast=`/`Slow=` prefix (pace) or a
# `(group_id)` suffix (pace/overlaps) — see README's vert.tsv column
# reference. prolongations uses `<char_id>x<count>`.
_POS_PAIR_RE = re.compile(r'(\d+)-(\d+)')
_PROLONG_RE = re.compile(r'(\d+)x(\d+)')
def _shift_positions(value: str, offset: int) -> str:
"""Shift every `<start>-<end>` char-position pair in *value* by *offset*."""
return _POS_PAIR_RE.sub(lambda m: f'{int(m.group(1)) + offset}-{int(m.group(2)) + offset}', value)
def _shift_prolongations(value: str, offset: int) -> str:
"""Shift every `<char_id>x<count>` pair in *value* by *offset*."""
return _PROLONG_RE.sub(lambda m: f'{int(m.group(1)) + offset}x{m.group(2)}', value)
_POSITIONAL_COL_SHIFTERS = {
'pace': _shift_positions,
'guesses': _shift_positions,
'overlaps': _shift_positions,
'prolongations': _shift_prolongations,
}
# One span entry: optional `Fast=`/`Slow=` prefix (pace), `<start>-<end>`,
# optional `(group_id)` suffix (pace/overlaps).
_SPAN_ENTRY_RE = re.compile(r'^(?P<prefix>[A-Za-z]+=)?(?P<start>\d+)-(?P<end>\d+)(?P<suffix>\(.*\))?$')
def _merge_positional_feature(prev_value: str, dropped_value: str, offset: int, col: str) -> str:
"""Shift *dropped_value* (from a token being merged away) by *offset*
characters and append it to *prev_value*.
For pace/guesses/overlaps, if the shifted span picks up exactly where
the kept token's last span of the same kind (prefix + group id) left
off, or starts inside it (the kept span can run past the original form,
e.g. `0-8` on a 7-char form) — the normal case for a token that was itself one continuous
slow/fast/overlap span — the two are collapsed into one continuous
span instead of two adjacent comma-separated entries (`Slow=0-4(0)` +
`Slow=4-7(0)` → `Slow=0-7(0)`, not `Slow=0-4(0),Slow=4-7(0)`).
"""
shifted = _POSITIONAL_COL_SHIFTERS[col](dropped_value, offset)
if prev_value in ('_', ''):
return shifted
if col == 'prolongations':
return f'{prev_value},{shifted}'
prev_entries = prev_value.split(',')
shifted_entries = shifted.split(',')
last = _SPAN_ENTRY_RE.match(prev_entries[-1])
first_new = _SPAN_ENTRY_RE.match(shifted_entries[0])
if (last and first_new
and last.group('prefix') == first_new.group('prefix')
and last.group('suffix') == first_new.group('suffix')
and int(first_new.group('start')) <= int(last.group('end'))):
prev_entries[-1] = (
f"{last.group('prefix') or ''}{last.group('start')}-"
f"{max(int(last.group('end')), int(first_new.group('end')))}"
f"{last.group('suffix') or ''}"
)
shifted_entries = shifted_entries[1:]
return ','.join(prev_entries + shifted_entries)
# Legacy curly-brace enriched notation: {P} for shortpause, {tag}/{multi_word_tag}
# for non-verbal-behavior (spaces stored as underscores). normalize.py's decision
# is to preserve literal (.)/((tag)) notation rather than rewrite it — see
# meta_tag()'s docstring. Some wip/*.csv rows a lemmatizer never touched still
# carry the legacy form copied verbatim from an older TSV pull; without this,
# comparing them against a (correctly literal) source TSV would look like a
# genuine edit and silently reintroduce the legacy notation into the corpus.
_LEGACY_TAG_RE = re.compile(r'^\{([^{}]+)\}$')
def normalize_legacy_pause_nvb(value: str) -> str:
"""Canonicalize legacy {P}/{tag} notation to literal (.)/((tag)).
Leaves everything else untouched, including the lemmatization project's
own CoNLL-U placeholder forms ([PAUSE]/[NVB]), which are a distinct,
intentional convention for the `form` column and not a legacy notation.
"""
if value == '{P}':
return '(.)'
m = _LEGACY_TAG_RE.match(value)
if m:
return '((' + m.group(1).replace('_', ' ') + '))'
return value
def is_missing(value: str | None) -> bool:
return value is None or value.strip() in {'', '_'}
def is_subtoken(token_id: str) -> bool:
"""Annotation sub-token rows (4-7a, 4-7b) are not source TSV tokens.
Keep lexical token ids such as ``12bis``; only the numeric-hyphen-letter
pattern is treated as an annotation-internal subtoken.
"""
return bool(re.fullmatch(r'\d+-\d+[A-Za-z]', token_id))
def read_csv(path: Path) -> dict[str, dict]:
"""Return {token_id: row_dict} in insertion order, skipping sub-token rows.
Handles BOM. All values are stripped of leading/trailing whitespace.
"""
rows = {}
with open(path, newline='', encoding='utf-8-sig') as f:
for row in csv.DictReader(f):
tid = row['token_id'].strip()
if not is_subtoken(tid):
row = {k: (v or '').strip() for k, v in row.items()}
# `space_after` is its own CSV column; fold it back into the
# feature string the rest of the script reads SpaceAfter from.
if row.get('space_after') == 'SpaceAfter=No':
jf = [x for x in row.get('jefferson_feats', '_').split('|') if x not in ('', '_')]
row['jefferson_feats'] = '|'.join(jf + ['SpaceAfter=No'])
rows[tid] = row
return rows
def validate_required_token_fields(rows: list[dict] | dict[str, dict], source_name: str) -> None:
"""Fail if any token has an empty span/form after normalization."""
items = rows.items() if isinstance(rows, dict) else (
(row.get('token_id', '?'), row) for row in rows
)
for token_id, row in items:
for field in ('span', 'form'):
value = row.get(field, '')
if not value.strip():
raise ValueError(
f"{source_name}: token `{token_id}` has empty `{field}`"
)
def read_tsv(path: Path) -> tuple[list[str], list[dict], list[str], str]:
"""Return (header_cols, row_dicts_ordered, raw_lines, eol).
Opens in binary mode to preserve original line endings (CRLF or LF).
"""
raw_bytes = path.read_bytes()
eol = '\r\n' if b'\r\n' in raw_bytes else '\n'
lines = raw_bytes.decode('utf-8').splitlines(keepends=True)
header = lines[0].rstrip('\r\n').split('\t')
rows = []
for line in lines[1:]:
parts = line.rstrip('\r\n').split('\t')
rows.append(dict(zip(header, parts)))
return header, rows, lines, eol
def parse_align(s: str) -> dict[str, str]:
"""'Begin=4.696|End=5.034' → {'Begin': '4.696', 'End': '5.034'}"""
if not s or s == '_':
return {}
d = {}
for part in s.split('|'):
if '=' in part:
k, v = part.split('=', 1)
d[k] = v
return d
def format_align(d: dict[str, str]) -> str:
"""{'Begin': '4.696', 'End': '5.034'} → 'Begin=4.696|End=5.034'"""
if not d:
return '_'
parts = []
for k in ('Begin', 'End'):
if k in d:
parts.append(f'{k}={d[k]}')
for k, v in d.items():
if k not in ('Begin', 'End'):
parts.append(f'{k}={v}')
return '|'.join(parts)
def row_to_line(row: dict, header: list[str], eol: str) -> str:
return '\t'.join(row.get(c, '_') for c in header) + eol
def update_jefferson_feats(tsv_value: str, csv_value: str, span_changed: bool,
new_span: str, old_span: str = '',
old_form: str = '', new_form: str = '') -> str:
"""Compute the patched jefferson_feats for a kept token.
Rules:
- Only Lang=XXX from the CSV is considered; all other CSV features are ignored.
- If span changed: span-derived features (SPAN_DERIVED_FEAT_KEYS) are recomputed
from new_span and replace their counterparts in the TSV value — *unless* a
feature (Volume, in practice) wasn't derivable from old_span either, meaning
it was inherited from a wider multi-token °...° span the edited token merely
sits inside (only that span's boundary tokens carry a literal `°` — see
feats_from_span); in that case this token-local edit tells us nothing new
about it, so it's carried over rather than silently dropped.
- Non-span features (ProsodicLink, SpaceAfter, Nonce, Variety, …) are always
preserved from the TSV.
- Lang from CSV is merged in last, overriding any Lang already present.
- SpaceAfter=No from the CSV is also merged in (an elision such as "l'" is
glued to the next token). A token carrying SpaceAfter=No is an elision, not
a truncated word, so a Truncated=Yes derived only from its trailing
apostrophe is dropped.
- An elision replaced by a full word (form `c'` → `cioè`) loses the SpaceAfter=No
it had, unless the CSV carries it: the word is not glued to the next token.
"""
tsv_feats = parse_feats(tsv_value)
# Extract only Lang=* from the CSV
csv_feats = parse_feats(csv_value)
lang_feats = {k: v for k, v in csv_feats.items() if k == 'Lang'}
if span_changed:
derived = feats_from_span(new_span)
old_derived = feats_from_span(old_span)
merged = {k: v for k, v in tsv_feats.items() if k not in SPAN_DERIVED_FEAT_KEYS}
for key in SPAN_DERIVED_FEAT_KEYS:
if key in derived:
merged[key] = derived[key]
elif key not in old_derived and key in tsv_feats:
merged[key] = tsv_feats[key]
else:
merged = dict(tsv_feats)
merged.update(lang_feats)
if csv_feats.get('SpaceAfter') == 'No':
merged['SpaceAfter'] = 'No'
elif old_form.endswith("'") and new_form and not new_form.endswith("'"):
merged.pop('SpaceAfter', None)
if merged.get('SpaceAfter') == 'No':
merged.pop('Truncated', None)
return format_feats(merged)
def infer_type(csv_row: dict) -> str:
"""Infer a sensible TSV type for a newly inserted token."""
span = csv_row.get('span', '')
form = csv_row.get('form', '')
# Accept both the current (.)/((...)) notation and the legacy {P}/{tag}
# notation, since wip/*.csv files not yet reprocessed through the
# tools/ pipeline may still use the old form.
if span in ('(.)', '{P}') or form in ('(.)', '{P}', '[PAUSE]'):
return 'shortpause'
if (
(span.startswith('((') and span.endswith('))'))
or (span.startswith('{') and span.endswith('}'))
or form in ('[NVB]',)
):
return 'nonverbalbehavior'
if form == 'x':
return 'unknown'
return 'linguistic'
def infer_missing_metadata(
field: str,
csv_row: dict,
current_row: dict | None = None,
prev_row: dict | None = None,
next_row: dict | None = None,
) -> str:
"""Fill missing speaker/tu_id conservatively from CSV or neighboring rows."""
current_row = current_row or {}
csv_value = csv_row.get(field, '_')
if not is_missing(csv_value):
return csv_value
current_value = current_row.get(field, '_')
if not is_missing(current_value):
return current_value
prev_value = prev_row.get(field, '_') if prev_row is not None else '_'
next_value = next_row.get(field, '_') if next_row is not None else '_'
if field == 'speaker':
current_tu = current_row.get('tu_id', '_')
prev_same_tu = (
prev_row is not None and not is_missing(current_tu)
and prev_row.get('tu_id') == current_tu
and not is_missing(prev_value)
)
next_same_tu = (
next_row is not None and not is_missing(current_tu)
and next_row.get('tu_id') == current_tu
and not is_missing(next_value)
)
if prev_same_tu:
return prev_value
if next_same_tu:
return next_value
if not is_missing(prev_value) and prev_value == next_value:
return prev_value
if not is_missing(prev_value) and is_missing(next_value):
return prev_value
if not is_missing(next_value) and is_missing(prev_value):
return next_value
return '_'
def make_added_row(
csv_row: dict,
tsv_header: list[str],
prev_row: dict | None = None,
next_row: dict | None = None,
) -> dict:
"""Build a new TSV row for a token present in CSV but absent in TSV."""
row = {c: '_' for c in tsv_header}
row['token_id'] = csv_row['token_id']
row['span'] = normalize_legacy_pause_nvb(csv_row.get('span', '_') or '_')
csv_form = csv_row.get('form', '_') or '_'
if csv_form in ('[PAUSE]', '[NVB]'):
row['form'] = row['span'] # CoNLL-U placeholder — mirror span, see PATCHABLE_COLS loop
else:
row['form'] = normalize_legacy_pause_nvb(csv_form)
row['tu_id'] = infer_missing_metadata(
field='tu_id',
csv_row=csv_row,
current_row=row,
prev_row=prev_row,
next_row=next_row,
)
# jefferson_feats for new tokens: span-derived features + Lang from CSV only
span_feats = feats_from_span(row['span'])
csv_jf = parse_feats(csv_row.get('jefferson_feats', '_'))
lang_feats = {k: v for k, v in csv_jf.items() if k == 'Lang'}
span_feats.update(lang_feats)
row['jefferson_feats'] = format_feats(span_feats)
if 'type' in row:
row['type'] = infer_type(csv_row)
row['speaker'] = infer_missing_metadata(
field='speaker',
csv_row=csv_row,
current_row=row,
prev_row=prev_row,
next_row=next_row,
)
return row
def _build_new_rows(
csv_rows: dict[str, dict],
tsv_header: list[str],
tsv_rows: list[dict],
eol: str,
) -> tuple[list[dict], list[dict], list[dict], list[dict]]:
"""
Produce corrected row dicts and structured recap data grouped by change type.
Returns:
final_rows: list of dicts in TSV column order (with corrections applied)
change_items: one dict per changed field — {token_id, field, before, after}
drop_items: one dict per dropped token — {token_id, tu_id, span, form,
jefferson_feats, notes: list[str]}
add_items: one dict per added token — {token_id, tu_id, span, form,
jefferson_feats, type, notes: list[str]}
"""
col_set = set(tsv_header)
change_items: list[dict] = []
drop_items: list[dict] = []
add_items: list[dict] = []
new_rows: list[dict] = []
kept_rows_by_id: dict[str, dict] = {}
pending_begin: str | None = None
pending_begin_source: dict | None = None # drop_item that owns the pending Begin
tsv_ids_seen: set[str] = set()
for idx, tsv_row in enumerate(tsv_rows):
tid = tsv_row.get('token_id', '')
if tid not in csv_rows:
# ── DROPPED token ────────────────────────────────────────────────
align_d = parse_align(tsv_row.get('align', '_'))
notes: list[str] = []
if 'End' in align_d:
if new_rows:
prev = new_rows[-1]
prev_align = parse_align(prev.get('align', '_'))
if 'End' not in prev_align:
prev_align['End'] = align_d['End']
prev['align'] = format_align(prev_align)
notes.append(f"✅ End={align_d['End']} → `{prev['token_id']}`")
else:
notes.append(
f"❌ End conflict: End={align_d['End']} but "
f"`{prev['token_id']}` already has End={prev_align['End']}"
)
else:
notes.append(f"❌ End={align_d['End']} — no previous token")
if 'Begin' in align_d:
if pending_begin is not None:
notes.append(
f"❌ Begin conflict: pending Begin={pending_begin} "
f"overwritten by Begin={align_d['Begin']}"
)
pending_begin = align_d['Begin']
manual_losses = {c: tsv_row[c] for c in MANUAL_COLS if c in tsv_row and tsv_row[c] != '_'}
# If this token's content was appended onto the immediately
# preceding kept token's form (a clean merge, e.g. "elle"+"due"
# → "elledue" — the documented "second half of a merge" case),
# transfer its positional features instead of just losing them,
# shifting char positions by the length of the kept token's
# original form.
transferred: set[str] = set()
if manual_losses and new_rows:
prev = new_rows[-1]
dropped_form = tsv_row.get('form', '')
prev_form = prev.get('form', '')
if dropped_form and prev_form.endswith(dropped_form) and len(prev_form) > len(dropped_form):
offset = len(prev_form) - len(dropped_form)
for col, value in manual_losses.items():
prev[col] = _merge_positional_feature(prev.get(col, '_'), value, offset, col)
notes.append(f"✅ {col}=`{value}` → `{prev['token_id']}` (shifted +{offset})")
transferred.add(col)
# A pace/guess span is stored per token (`Slow=0-4(0)` on every
# token it covers). A dropped token that sits inside such a span,
# with the same span continuing on the kept tokens on both sides,
# takes nothing with it: the neighbours already carry the span.
def _span_keys(value: str) -> set[tuple]:
keys = set()
for entry in value.split(','):
m = _SPAN_ENTRY_RE.match(entry)
if m:
keys.add((m.group('prefix'), m.group('suffix')))
return keys
prev_kept = new_rows[-1] if new_rows else None
next_kept = next((r for r in tsv_rows[idx + 1:] if r.get('token_id', '') in csv_rows), None)
for c in ('pace', 'guesses'):
if c in manual_losses and c not in transferred and prev_kept and next_kept:
keys = _span_keys(manual_losses[c])
if keys and keys <= _span_keys(prev_kept.get(c, '_')) \
and keys <= _span_keys(next_kept.get(c, '_')):
notes.append(f"✅ {c}=`{manual_losses[c]}` già coperto dai token vicini")
transferred.add(c)
for c, v in manual_losses.items():
if c not in transferred:
notes.append(f"⚠️ {c}=`{v}`")
drop_item: dict = {
'token_id': tid,
'tu_id': tsv_row.get('tu_id', '?'),
'span': tsv_row.get('span', '_'),
'form': tsv_row.get('form', '_'),
'jefferson_feats': tsv_row.get('jefferson_feats', '_'),
'old_row': dict(tsv_row),
'notes': notes,
# CSV row that absorbed this drop (for the `merge` column)
'anchor': new_rows[-1]['token_id'] if new_rows else None,
}
drop_items.append(drop_item)
if 'Begin' in align_d:
pending_begin_source = drop_item
continue
# ── KEPT token ────────────────────────────────────────────────────────
new_row = dict(tsv_row)
old_row_snapshot = dict(tsv_row)
tsv_ids_seen.add(tid)
csv_row = csv_rows[tid]
any_content_changed = False
span_changed = False
form_changed = False
span_pending = False
for col in PATCHABLE_COLS:
if col in col_set and col in csv_row:
raw_val = csv_row[col]
if col == 'span' and raw_val == '_':
# span still to be filled in by hand in the CSV: it is a
# placeholder, never a value to write into the corpus.
span_pending = True
continue
if col == 'form' and raw_val in ('[PAUSE]', '[NVB]'):
# [PAUSE]/[NVB] are the lemmatization project's own
# CoNLL-U placeholder forms (see conllu2wip.py) — not
# meant for the corpus `form` column. Per the
# normalize.py decision (literal notation, form==span
# for pause/NVB tokens), mirror the token's own span
# instead of writing the placeholder into the corpus.
# `span` is processed first (PATCHABLE_COLS order), so
# new_row['span'] already reflects this same update.
new_val = new_row.get('span', '')
else:
new_val = normalize_legacy_pause_nvb(raw_val)
old_val = new_row.get(col, '')
if new_val and new_val != old_val:
new_row[col] = new_val
any_content_changed = True
if col == 'span':
span_changed = True
elif col == 'form':
form_changed = True
# An `unknown` token whose span was transcribed (no longer x-only)
# is now an ordinary linguistic token.
if (
'type' in col_set
and span_changed
and old_row_snapshot.get('type') == 'unknown'
and not re.fullmatch(r'x+', new_row.get('span', ''))
):
new_row['type'] = 'linguistic'
if 'jefferson_feats' in col_set:
old_jf = new_row.get('jefferson_feats', '_')
new_jf = update_jefferson_feats(
tsv_value=old_jf,
csv_value=csv_row.get('jefferson_feats', '_'),
span_changed=span_changed,
new_span=new_row.get('span', '_'),
old_span=old_row_snapshot.get('span', '_'),
old_form=old_row_snapshot.get('form', ''),
new_form=new_row.get('form', ''),
)
if new_jf != old_jf:
new_row['jefferson_feats'] = new_jf
any_content_changed = True
prev_kept_row = new_rows[-1] if new_rows else None
next_kept_row = None
for lookahead_row in tsv_rows[idx + 1:]:
lookahead_tid = lookahead_row.get('token_id', '')
if lookahead_tid in csv_rows:
next_kept_row = lookahead_row
break
for field in ('tu_id', 'speaker'):
if field in col_set and is_missing(new_row.get(field, '_')):
inferred_value = infer_missing_metadata(
field=field,
csv_row=csv_row,
current_row=new_row,
prev_row=prev_kept_row,
next_row=next_kept_row,
)
if not is_missing(inferred_value):
new_row[field] = inferred_value
any_content_changed = True
if pending_begin is not None:
align_d = parse_align(new_row.get('align', '_'))
if 'Begin' not in align_d:
align_d['Begin'] = pending_begin
new_row['align'] = format_align(align_d)
if pending_begin_source is not None:
pending_begin_source['notes'].append(
f"✅ Begin={pending_begin} → `{tid}`"
)
else:
if pending_begin_source is not None:
pending_begin_source['notes'].append(
f"❌ Begin={pending_begin} conflict: `{tid}` already has "
f"Begin={align_d['Begin']}"
)
pending_begin = None
pending_begin_source = None
new_rows.append(new_row)
kept_rows_by_id[tid] = new_row
# Snapshot deferred: new_row may still be modified by ADD section (align)
if any_content_changed:
change_notes: list[str] = []
if span_pending:
change_notes.append('⚠️ span `_` nel CSV: da compilare, span del TSV non toccato')
if form_changed and not span_changed:
# Check whether the new form is derivable from the (unchanged) span
span = new_row.get('span', '_')
expected_form = form_from_span(span)
if expected_form is not None and new_row.get('form') != expected_form:
change_notes.append('⚠️ forma non derivabile dallo span — verifica manuale')
change_items.append({
'token_id': tid,
'tu_id': tsv_row.get('tu_id', '?'),
'old_row': old_row_snapshot,
'new_row': new_row, # mutable ref — finalized after ADD section
'notes': change_notes,
})
# Tokens in CSV but not in TSV (ADD)
final_rows: list[dict] = []
final_ids = list(csv_rows)
for pos, tid in enumerate(final_ids):
if tid in kept_rows_by_id:
final_rows.append(kept_rows_by_id[tid])
continue
csv_row = csv_rows[tid]
prev_row = final_rows[-1] if final_rows else None
next_row = None
for next_tid in final_ids[pos + 1:]:
if next_tid in kept_rows_by_id:
next_row = kept_rows_by_id[next_tid]
break
new_row = make_added_row(csv_row, tsv_header, prev_row=prev_row, next_row=next_row)
notes = []
if prev_row is not None and prev_row.get('tu_id') == new_row.get('tu_id'):
prev_align = parse_align(prev_row.get('align', '_'))
if 'End' in prev_align:
new_align = parse_align(new_row.get('align', '_'))
new_align['End'] = prev_align.pop('End')
prev_row['align'] = format_align(prev_align)
new_row['align'] = format_align(new_align)
notes.append(f"✅ End={new_align['End']} ← `{prev_row['token_id']}`")
if next_row is not None and next_row.get('tu_id') == new_row.get('tu_id'):
next_align = parse_align(next_row.get('align', '_'))
new_align = parse_align(new_row.get('align', '_'))
if 'Begin' in next_align and 'Begin' not in new_align:
new_align['Begin'] = next_align.pop('Begin')
next_row['align'] = format_align(next_align)
new_row['align'] = format_align(new_align)
notes.append(f"✅ Begin={new_align['Begin']} ← `{next_row['token_id']}`")
# Only the first/last token of a TU is expected to carry Begin=/End=
# at all (see README's `align` column) — an added token strictly
# inside a TU has correct (empty) alignment as-is and needs no
# manual check.
is_tu_first = prev_row is None or prev_row.get('tu_id') != new_row.get('tu_id')
is_tu_last = next_row is None or next_row.get('tu_id') != new_row.get('tu_id')
final_align = parse_align(new_row.get('align', '_'))
if (is_tu_first and 'Begin' not in final_align) or (is_tu_last and 'End' not in final_align):
notes.append("⚠️ verifica allineamento manualmente")
final_rows.append(new_row)
add_items.append({
'token_id': tid,
'tu_id': new_row.get('tu_id', '?'),
'span': new_row.get('span', '_'),
'form': new_row.get('form', '_'),
'jefferson_feats': new_row.get('jefferson_feats', '_'),
'type': new_row.get('type', '_'),
'new_row': dict(new_row),
'notes': notes,
})
# `id` is recomputed as a monotonic per-TU position, independent of
# `token_id`'s suffix — splits/adds keep token_id stable (creation-order,
# possibly out of sequence) while `id` always reflects true row order.
if 'id' in col_set:
next_id_by_tu: dict[str, int] = {}
for row in final_rows:
tu = row.get('tu_id', '_')
row['id'] = str(next_id_by_tu.get(tu, 0))
next_id_by_tu[tu] = int(row['id']) + 1
return final_rows, change_items, drop_items, add_items
def build_new_rows(
csv_rows: dict[str, dict],
tsv_header: list[str],
tsv_rows: list[dict],
eol: str,
) -> tuple[list[dict], list[dict], list[dict], list[dict]]:
"""``_build_new_rows`` on the transcription rows, then the syntactic rows back.
The ``syntactic`` rows of the TSV (components of multiword tokens, ``5-7a``) are not
in the transcription and the CSV sub-token rows are skipped by ``read_csv``, so the
diff must not see them: they would all look like dropped tokens. They travel with
their surface token; those of a token that no longer exists are reported as dropped.
`id` is computed on the transcription rows only (a syntactic row keeps its own).
"""
main_rows = [r for r in tsv_rows if not is_syntactic(r)]
children: dict[str, list[dict]] = {}
for r in tsv_rows:
if is_syntactic(r):
children.setdefault(r['token_id'][:-1], []).append(r)
final_rows, change_items, drop_items, add_items = _build_new_rows(
csv_rows, tsv_header, main_rows, eol)
if not children:
return final_rows, change_items, drop_items, add_items
out: list[dict] = []
for row in final_rows:
out.append(row)
out.extend(children.pop(row['token_id'], []))
for orphans in children.values():
for r in orphans:
drop_items.append({
'token_id': r['token_id'], 'tu_id': r.get('tu_id', '_'),
'span': r.get('span', '_'), 'form': r.get('form', '_'),
'jefferson_feats': r.get('jefferson_feats', '_'),
'notes': ['❌ syntactic row of a token that no longer exists'],
})
return out, change_items, drop_items, add_items
def _mc(value: str) -> str:
"""Escape | in a Markdown table cell (| breaks column parsing)."""
return value.replace('|', '\\|')
def _row_to_tsv(row: dict, header: list[str]) -> str:
return '\t'.join(row.get(c, '_') for c in header)
def _status_icon(notes: list[str]) -> str:
if any(note.startswith('❌') for note in notes):
return '❌'
if any(note.startswith('⚠️') for note in notes):
return '⚠️'
return '✅'
# Plain-text tags, not emoji: emoji glyph width is inconsistent across
# fonts/renderers (variation selectors, ambiguous East Asian Width), which
# breaks monospace column alignment in the raw Markdown source. ASCII tags
# align predictably with any character-counting formatter.
LIVELLO_LABEL = {
'✅': '[OK] gestito automaticamente',
'⚠️': '[WARN] verifica manuale',
'❌': '[FAIL] conflitto',
}
TIPO_LABEL = {
'change': '[MOD] modifica',
'drop': '[DEL] eliminazione',
'add': '[ADD] aggiunta',
}
# Columns shown in their own dedicated table columns; everything else that
# differs lands in "altro".
_RECAP_OWN_COLS = {'token_id', 'id', 'span', 'form'}
def _cell(type_: str, col: str, old_row: dict | None, new_row: dict | None) -> str:
"""Render one field as a recap table cell: `prima` → `dopo` for a change,
a single backticked value for add/drop, or '' if there's nothing to show."""
if type_ == 'change':
ov, nv = old_row.get(col, '_'), new_row.get(col, '_')
if ov == nv:
return f'`{_mc(ov)}`' if ov not in ('_', '') else ''
return f'`{_mc(ov)}` → `{_mc(nv)}`'
row = old_row if type_ == 'drop' else new_row
v = row.get(col, '_')
return f'`{_mc(v)}`' if v not in ('_', '') else ''
def _altro_cell(type_: str, old_row: dict | None, new_row: dict | None,
tsv_header: list[str], notes: list[str]) -> str:
"""Everything that changed (or is set) outside token_id/id/span/form,
plus any ⚠️/❌ notes, as one cell — one `campo: prima → dopo` per line.
✅ notes (successful automatic Begin/End or positional-feature transfer)
are dropped here: what they report is already visible from the field
diffs themselves (the receiving token's own row shows the field
changing), so repeating it as a note is just noise. ⚠️/❌ notes carry
information the diffs don't (why something needs a manual look, or a
conflict), so those stay.
"""
parts: list[str] = []
for col in tsv_header:
if col in _RECAP_OWN_COLS or col == 'tu_id':
continue
if type_ == 'change':
ov, nv = old_row.get(col, '_'), new_row.get(col, '_')
if ov != nv:
parts.append(f'{col}: `{_mc(ov)}` → `{_mc(nv)}`')
else:
row = old_row if type_ == 'drop' else new_row
v = row.get(col, '_')
if v not in ('_', ''):
parts.append(f'{col}: `{_mc(v)}`')
parts.extend(_mc(note) for note in notes if not note.startswith('✅'))
return ' · '.join(parts)
def merge_status_by_token(change_items, drop_items, add_items, csv_ids):
"""{csv token_id: (status, note)} for every CSV row touched by the patch.
status is 'OK' (merged automatically), 'WARN' (needs a manual look) or
'FAIL' (a conflict the patch could not resolve). A change or an add is
judged by its own notes. A dropped TSV token has no CSV row, so a problem
with it is flagged on the CSV row that absorbed it (the previous kept
token, or the first row if there is none). Untouched rows are absent.
"""
rank = {'OK': 0, 'WARN': 1, 'FAIL': 2}
status: dict[str, tuple[str, list[str]]] = {}
def clean(note):
return re.sub(r'^[^\w`(]+', '', note).replace('`', '').strip()
def mark(tid, icon, notes, prefix=''):
if tid is None:
return
st = {'✅': 'OK', '⚠️': 'WARN', '❌': 'FAIL'}[icon]
texts = [prefix + clean(n) for n in notes if not n.startswith('✅')]
old_st, old_notes = status.get(tid, ('OK', []))
status[tid] = (st if rank[st] > rank[old_st] else old_st, old_notes + texts)
for item in (*change_items, *add_items):
mark(item['token_id'], _status_icon(item.get('notes', [])), item.get('notes', []))
first = csv_ids[0] if csv_ids else None
for item in drop_items:
mark(item.get('anchor') or first, _status_icon(item.get('notes', [])),
item.get('notes', []), prefix=f"del {item['token_id']}: ")
return status
def write_review_csv(csv_p: Path, out_p: Path, status: dict) -> None:
"""Copy of the wip CSV with `merge` (OK / WARN / FAIL / _) and `note` as
the first two columns, for scanning the rows that need a manual look.
A derived file: the wip CSV itself is never touched. Sub-token rows
(4-7a) follow their parent."""
raw = csv_p.read_bytes().decode('utf-8').lstrip('\ufeff')
eol = '\r\n' if '\r\n' in raw else '\n'
rows = list(csv.reader(io.StringIO(raw, newline='')))
if not rows:
return
header = rows[0]
ti = header.index('token_id')
out = [['merge', 'note'] + header]
for r in rows[1:]:
tid = r[ti].strip()
m = re.fullmatch(r'(\d+-\d+)[A-Za-z]', tid)
st, notes = status.get(m.group(1) if m else tid, ('_', []))
out.append([st, ' | '.join(notes) or '_'] + r)
out_p.parent.mkdir(parents=True, exist_ok=True)
buf = io.StringIO()
csv.writer(buf, lineterminator=eol).writerows(out)
out_p.write_bytes(buf.getvalue().encode('utf-8'))
# snapshot of the wip CSV as it was when this review was generated: the
# common ancestor for pull_review_edits' three-way merge.
base_p = review_base_path(out_p)
base_p.parent.mkdir(parents=True, exist_ok=True)
base_p.write_bytes(raw.encode('utf-8'))
def review_base_path(review_p: Path) -> Path:
return review_p.parent / '.review-base' / (review_p.name.removesuffix('.review.csv') + '.csv')
def pull_review_edits(csv_p: Path, review_p: Path) -> bool:
"""Carry edits made in <FILE>.review.csv back into the wip CSV.
The review file is a generated copy with two extra leading columns
(`merge`, `note`), and the place where the work is done: cells, rows
added, removed or moved, token merges and a/b splits are all edited
there. The snapshot taken at generation time is the common ancestor.
* wip unchanged since the snapshot: the review's rows become the wip
CSV (any edit, structural or not).
* wip also edited: a three-way merge per cell, possible only if the
review kept the same rows in the same order. A cell edited only in the
review is written to the wip CSV; edited only in wip is kept; edited in
both to different values is a conflict and wip wins (reported).
* wip edited AND rows changed in the review: nothing can be merged
safely. Returns False and leaves every file untouched (the review too,
so no work is lost): the caller must not regenerate.
"""
base_p = review_base_path(review_p)
if not (review_p.exists() and base_p.exists() and csv_p.exists()):
return True
def load(path, skip=0, aligned=False):
raw = path.read_bytes().decode('utf-8').lstrip('\ufeff')
rows = csv.reader(io.StringIO(raw, newline=''), skipinitialspace=aligned)
if aligned:
# a CSV editor may have padded the columns to align them
rows = [[c.strip() for c in r][skip:] for r in rows]
return [r for r in rows if any(r)], raw # and added blank lines
return [r[skip:] for r in rows], raw
review, _ = load(review_p, skip=2, aligned=True)
base, _ = load(base_p)
wip, wip_raw = load(csv_p)
base_s = [[c.strip() for c in r] for r in base]
if not review or review[0] != base_s[0] or wip[0] != base[0]:
print(f"ERRORE {review_p.name}: colonne cambiate, modifiche NON riportate in wip "
f"(il review non e' stato toccato)", file=sys.stderr)
return False
if review == base_s:
return True
ti = base[0].index('token_id')
def write_wip(rows):
eol = '\r\n' if '\r\n' in wip_raw else '\n'
buf = io.StringIO()
csv.writer(buf, lineterminator=eol).writerows(rows)
bom = b'\xef\xbb\xbf' if csv_p.read_bytes().startswith(b'\xef\xbb\xbf') else b''
csv_p.write_bytes(bom + buf.getvalue().encode('utf-8'))
if wip == base:
added = [r[ti] for r in review if r[ti] not in {b[ti] for b in base}]
removed = [b[ti] for b in base if b[ti] not in {r[ti] for r in review}]
write_wip(review)
print(f"Riportate in {csv_p.name} le modifiche di {review_p.name} "
f"({len(added)} righe aggiunte, {len(removed)} tolte)")
return True
same_rows = len(review) == len(base) == len(wip) and \
[r[ti] for r in review] == [r[ti] for r in base_s] == [r[ti] for r in wip]
if not same_rows:
print(f"ERRORE {review_p.name}: righe cambiate nel review E modifiche al wip dopo la "
f"generazione del review. Non posso unirle: modifiche NON riportate, review e wip "
f"non toccati. Rigenera il review dal wip (tenendone una copia) oppure sposta a "
f"mano le modifiche.", file=sys.stderr)
return False
pulled = conflicts = 0
for i in range(1, len(base)):
for j, name in enumerate(base[0]):
b, r, w = base[i][j], review[i][j], wip[i][j]
if r == b.strip():
continue
if w == b:
wip[i][j] = r