-
Notifications
You must be signed in to change notification settings - Fork 1
/
tfFromATF.py
1474 lines (1204 loc) · 37.4 KB
/
tfFromATF.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 sys
import os
import re
import collections
import json
from unicodedata import name as uname
from shutil import rmtree
from glob import glob
from tf.fabric import Fabric
from tf.convert.walker import CV
# LOCATIONS
BASE = os.path.expanduser('~/github')
ORG = 'Nino-cunei'
REPO = 'oldbabylonian'
VERSION_SRC = '0.2'
VERSION_TF = '0.2'
REPO_DIR = f'{BASE}/{ORG}/{REPO}'
TRANS_DIR = f'{REPO_DIR}/sources/cdli/transcriptions'
WRITING_DIR = f'{REPO_DIR}/sources/writing'
SIGN_FILE = 'GeneratedSignList.json'
SIGN_PATH = f'{WRITING_DIR}/{SIGN_FILE}'
IN_DIR = f'{TRANS_DIR}/{VERSION_SRC}'
TF_DIR = f'{REPO_DIR}/tf'
OUT_DIR = f'{TF_DIR}/{VERSION_TF}'
# CHARACTERS
prime = "'"
ellips = '…'
emphatic = {
's,': 'ş',
't,': 'ţ',
}
unknownStr = 'xX'
unknownSet = set(unknownStr)
lowerLetterStr = 'abcdefghijklmnopqrstuvwyz' + ''.join(emphatic.values())
upperLetterStr = lowerLetterStr.upper()
lowerLetterStr += prime
div = '÷'
digitStr = f'0123456789{div}'
divRe = re.compile(r'''([0-9])/([0-9])''')
def divRepl(match):
return f'{match.group(1)}{div}{match.group(2)}'
times = '×'
excl = '¡'
graphemeStr = f'{times}{excl}'
operatorStr = '.+/:'
operatorSet = set(operatorStr)
flagging = {
'*': 'collated',
'!': 'remarkable',
'?': 'question',
'#': 'damage',
}
flagStr = ''.join(flagging)
clusterChars = (
('┌', '┐', '_', '_', 'langalt'),
('◀', '▶', '{', '}', 'det'),
('∈', '∋', '(', ')', 'uncertain'),
('〖', '〗', '[', ']', 'missing'),
('«', '»', '<<', '>>', 'excised'),
('⊂', '⊃', '<', '>', 'supplied'),
)
clusterCharsB = {x[0] for x in clusterChars}
clusterCharsE = {x[1] for x in clusterChars}
clusterCharsA = {x[0] for x in clusterChars} | {x[1] for x in clusterChars}
clusterCharsO = {x[2] for x in clusterChars} | {x[3] for x in clusterChars}
clusterType = {x[0]: x[4] for x in clusterChars}
clusterAtfE = {x[0]: x[1] for x in clusterChars}
clusterAtfB = {x[1]: x[0] for x in clusterChars}
clusterAtf = {x[0]: x[2] for x in clusterChars}
clusterAtf.update({x[1]: x[3] for x in clusterChars})
clusterAtfInv = {co: ca for (ca, co) in clusterAtf.items()}
readingPat = (
f'(?:(?:[{lowerLetterStr}{upperLetterStr}]'
f'[{lowerLetterStr}{upperLetterStr}{digitStr}{prime}]*'
f')|{ellips}|[{unknownStr}])'
f'[{flagStr}]*'
)
graphemePat = (
r'\|?'
f'[{upperLetterStr}]'
f'[{upperLetterStr}{digitStr}{operatorStr}]*'
r'\|?'
)
def makeClusterEscRepl(cab, cae):
def repl(match):
return f'{cab}{match.group(2)}{cae}'
return repl
clusterEscRe = {}
clusterEscRepl = {}
for (cab, cae, cob, coe, ctp) in clusterChars:
if cob == coe:
clusterEscRe[cab] = re.compile(f'''({re.escape(cob)}(.*?){re.escape(coe)})''')
clusterEscRepl[cab] = makeClusterEscRepl(cab, cae)
def clusterCheck(text):
return clusterORe.findall(text)
def transEsc(text):
text = divRe.sub(divRepl, text)
text = text.replace('...', ellips)
text = text.replace('x(', f'{times}(')
text = text.replace('!(', f'{excl}(')
for (exp, abb) in emphatic.items():
text = text.replace(exp, abb)
for (cab, cae, cob, coe, ctp) in clusterChars:
if cob == coe:
text = clusterEscRe[cab].sub(clusterEscRepl[cab], text)
else:
text = text.replace(cob, cab).replace(coe, cae)
return text
def transUnEsc(text):
for (cab, cae, cob, coe, ctp) in clusterChars:
text = text.replace(cab, cob).replace(cae, coe)
for (exp, abb) in emphatic.items():
text = text.replace(abb, exp)
text = text.replace(excl, '!')
text = text.replace(times, 'x')
text = text.replace(ellips, '...')
text = text.replace(div, '/')
return text
def makeAscii(r):
for (rin, rout) in transAscii.items():
r = r.replace(rin, rout)
return r.lower()
clusterA = re.escape(''.join(clusterCharsA))
clusterB = re.escape(''.join(clusterCharsB))
clusterE = re.escape(''.join(clusterCharsE))
clusterO = re.escape(''.join(clusterCharsO))
inside = r'''(?:\s+)'''
outside = r'''\s*'''
spaceB = r'''(?:\s+|^)'''
spaceE = r'''(?:\s+|$)'''
bO = r'\('
bC = r'\)'
insaneRe = re.compile(r'''[^0-9a-zA-Z$(){}\[\]<>.,:=$#&@"'?!/+*| _-]''')
transRe = re.compile(r'''^([0-9a-zA-Z']+)\.\s+(.+)$''')
translationRe = re.compile(r'''^tr\.([^:]+):\s*(.*)''')
collectionRe = re.compile(r'''^(\S+)\s+([0-9]+)\s*,?\s*([^&+]*)(?:[&+]|$)''')
commentRe = re.compile(r'∈\$(.*?)\$∋''')
numeralBackRe = re.compile(f'''(n|(?:[0-9]+(?:{div}[0-9]+)?))∈([^∋]+)∋''')
numeralRe = re.compile(f'''(n|(?:[0-9]+(?:{div}[0-9]+)?)){bO}({readingPat}){bC}''')
withGraphemeBackRe = re.compile(f'''([{graphemeStr}])∈([^∋]+)∋''')
withGraphemeRe = re.compile(f'''({readingPat})([{graphemeStr}]){bO}({graphemePat}){bC}''')
numeral2Re = re.compile(r'''([0-9]+∈[^∋]+∋)''')
clusterORe = re.compile(f'[{clusterO}]')
clusterTermRe = re.compile(f'^[{clusterA}]*$')
cSpaceBRe = re.compile(f'{outside}([{clusterB}]){inside}')
cSpaceERe = re.compile(f'{inside}([{clusterE}]){outside}')
wHyphenBRe = re.compile(f'{spaceB}([{clusterB}]*)-')
wHyphenERe = re.compile(f'-([{clusterE}]*){spaceE}')
cHyphenBRe = re.compile(f'([{clusterB}]+)-')
cHyphenERe = re.compile(f'-([{clusterE}]+)')
cFlagRe = re.compile(f'[{clusterA}]([{flagStr}]+)[{clusterA}]')
inlineCommentRe = re.compile(r'''^├[^┤]*┤$''')
# TF CONFIGURATION
slotType = 'sign'
generic = {
'name': 'AbB Old Babylonian Cuneiform',
'editor': 'Cale Johnson et. al.',
'institute': 'CDL',
'converters': 'Cale Johnson, Dirk Roorda',
}
otext = {
'fmt:text-orig-full': '{atfpre}{atf}{atfpost}{after}',
'fmt:text-ling-full': '{atfpre}{reading/grapheme}{atfpost}{after}',
'fmt:text-graph-full': '{atfpre}{givengrapheme/grapheme/reading}{atfpost}{after}',
'fmt:text-uni-full': '{atfpre}{unicode}{atfpost}{uafter}',
'sectionFeatures': 'pnumber,face',
'sectionTypes': 'document,face',
}
intFeatures = set('''
primeln
primecol
repeat
srcLnNum
trans
volume
'''.strip().split()) | set(flagging.values()) | set(clusterType.values())
featureMeta = {
'after': {
'description': 'what comes after a sign (- or space)',
},
'atf': {
'description': (
'full atf of a sign (without cluster chars)'
' or word (including cluster chars)'
),
},
'atfpost': {
'description': 'atf of cluster closings at sign',
},
'atfpre': {
'description': 'atf of cluster openings at sign',
},
'col': {
'description': 'ATF column number',
},
'collated': {
'description': 'whether a sign is collated (*)',
},
'collection': {
'description': 'collection of a document',
},
'comment': {
'description': '$ comment to line or inline comment to slot ($ and $)',
},
'damage': {
'description': 'whether a sign is damaged',
},
'det': {
'description': 'whether a sign is a determinative gloss - between braces { }',
},
'docnote': {
'description': 'additional remarks in the document identification',
},
'docnumber': {
'description': 'number of a document within a collection-volume',
},
'excised': {
'description': 'whether a sign is excised - between double angle brackets << >>',
},
'face': {
'description': 'full name of a face including the enclosing object',
},
'fraction': {
'description': 'fraction of a numeral',
},
'givengrapheme': {
'description': 'grapheme given in transcription by !() or x()',
},
'grapheme': {
'description': 'grapheme of a sign',
},
'lang': {
'description': 'language of a document',
},
'langalt': {
'description': (
'1 if a sign is in the alternate language (i.e. Sumerian)'
' - between underscores _ _'
),
},
'ln': {
'description': 'ATF line number, may be $ or #, without prime',
},
'missing': {
'description': 'whether a sign is missing - between square brackets [ ]',
},
'object': {
'description': 'name of an object of a document',
},
'operator': {
'description': 'the ! or x in a !() or x() construction',
},
'pnumber': {
'description': 'P number of a document',
},
'primecol': {
'description': 'whether a prime is present on a column number',
},
'primeln': {
'description': 'whether a prime is present on a line number',
},
'question': {
'description': 'whether a sign has the question flag (?)',
},
'reading': {
'description': 'reading of a sign',
},
'remarks': {
'description': '# comment to line',
},
'remarkable': {
'description': 'whether a sign is remarkable (!)',
},
'repeat': {
'description': 'repeat of a numeral; the value n (unknown) is represented as -1',
},
'srcfile': {
'description': 'source file name of a document',
},
'srcLn': {
'description': 'full line in source file',
},
'srcLnNum': {
'description': 'line number in source file',
},
'supplied': {
'description': 'whether a sign is supplied - between angle brackets < >',
},
'trans': {
'description': 'whether a line has a translation',
},
'translation@en': {
'description': 'translation of line in language en = English',
},
'type': {
'description': 'name of a type of cluster or kind of sign',
},
'uafter': {
'description': 'what comes after a sign when represented as unicode (space)',
},
'uncertain': {
'description': 'whether a sign is uncertain - between brackets ( )',
},
'unicode': {
'description': 'unicode representation of a sign, based on reading and grapheme',
},
'volume': {
'description': 'volume of a document within a collection',
},
}
# ATF INTERPRETATION
transUni = {
'sz': 'š',
's,': 'ṣ',
"s'": 'ś',
't,': 'ṭ',
'h,': 'ḫ',
}
transAscii = {rout.upper(): rin for (rin, rout) in transUni.items()}
VAR_OBJ = 'object'
DEFAULT_OBJ = 'tablet'
OBJECTS = set('''
tablet
envelope
case
'''.strip().split())
FACES = set('''
obverse
reverse
left edge
upper edge
lower edge
bottom
surface a
seal 1
'''.strip().split())
FACES_CORRECTION = {
'overse': 'obverse',
'obverrse': 'obverse',
}
COL_CORRECTION = {
'second': 'column',
}
COMMENTS = '''
(uninscribed)
(needs to be added)
'''
COMMENTS = {c.strip() for c in COMMENTS.strip('\n').split('\n')}
COMMENT_PATTERN = r'''
(?:
^
(?:
(?: maybe)?
(?:
(?:
(?:at \s+ least)
| about
)?
\s*
(?:
(?:
[0-9]+
(?:-[0-9]+)?
)
| one | two | three | four | five | six | seven | eight | nine | ten
)
\s+
lines?
)
| rest | obverse | reverse | seal |
(?:
beginning
(?: \s+ lines?)?
)
|
(?: blank \s+ space)
| single | double
)?
\s*
(?:
(?:
broken
(?:\s+ off)?
)
| blank | illegible | unreadable | uninscribed | destroyed | missing | erased | effaced
| ruling | impression |
(?: not \s+ inscribed) |
(?: of \s+ traces)
)?
$
)
|
(?:
^
reading
)
'''
COMMENT_RE = re.compile(COMMENT_PATTERN, re.X)
def bracketBackRepl(match):
return f'{match.group(1)}({match.group(2)})'
def wHyphenBRepl(match):
return f' {match.group(1)}'
def wHyphenERepl(match):
return f'{match.group(1)} '
def cHyphenBRepl(match):
return f'-{match.group(1)}'
def cHyphenERepl(match):
return f'{match.group(1)}-'
def insaneRepl(match):
return f'┣{match.group(0)}┫'
def cSpaceBRepl(match):
return ' ' + match.group(1)
def cSpaceERepl(match):
return match.group(1) + ' '
commentNotes = []
def commentRepl(match):
comment = match.group(1)
commentIndex = len(commentNotes)
commentNotes.append(comment.strip())
return f'├{commentIndex}┤'
# ERROR HANDLING
def showDiags(diags, kind, batch=20):
if not diags:
print('No diags')
else:
for (diag, srcs) in sorted(diags.items()):
print(f'{kind} {diag}')
for (src, data) in sorted(srcs.items()):
print(f'\t{src} ({len(data)}x)')
for (l, line, doc, sore) in sorted(data)[0:batch]:
soreRep = '' if sore is None else f'"{sore}" in '
print(f'\t\t{l} in {doc}: {soreRep}{line}')
if len(data) > batch:
print(f'\t\t + more')
# SET UP CONVERSION
def getMapping():
with open(SIGN_PATH) as fh:
signs = json.load(fh)['signs']
print(f'{len(signs)} signs in the json sign file')
mapping = collections.defaultdict(set)
for (sign, signInfo) in signs.items():
uniStr = signInfo['signCunei']
values = signInfo['values']
for value in values:
valueAscii = makeAscii(value)
mapping[valueAscii].add(uniStr)
print(f'{len(mapping)} distinct values in table')
return mapping
def getSources():
if os.path.exists(OUT_DIR):
rmtree(OUT_DIR)
os.makedirs(OUT_DIR, exist_ok=True)
# list all sources
return tuple(
os.path.splitext(os.path.basename(f))[0]
for f in glob(f'{IN_DIR}/*.txt')
)
def getConverter():
TF = Fabric(locations=OUT_DIR)
return CV(TF)
def checkSane(line):
inSane = insaneRe.findall(line)
insaneRep = ''
lineMsg = line
if inSane:
sep = ''
for c in sorted(inSane):
try:
name = uname(c)
except ValueError:
name = '??'
insaneRep += f"{sep}┣{c}┫ = {ord(c):>04x} = {name}"
sep = '; '
lineMsg = insaneRe.sub(insaneRepl, line)
line = insaneRe.sub('', line)
return (insaneRep, lineMsg, line)
# DIRECTOR
def director(cv):
sources = getSources()
mapping = getMapping()
curDocument = None
recentObject = None
curFace = None
recentColumn = None
curLine = None
recentTrans = None
curCluster = collections.defaultdict(list)
clusterStatus = {typ: False for typ in clusterType}
curSign = None
skip = False
i = 0
pNum = None
pNums = {}
warnings = collections.defaultdict(lambda: collections.defaultdict(set))
errors = collections.defaultdict(lambda: collections.defaultdict(set))
# sub director: setting up a document node
def uni(reading, grapheme, sep=''):
uReading = '|'.join(mapping.get(reading, (reading,))) if reading is not None else ''
uGrapheme = '|'.join(mapping.get(grapheme, (grapheme,))) if grapheme is not None else ''
result = uReading
if grapheme:
result += f'{sep}({uGrapheme})'
return result
def documentStart():
# we build nodes for documents, faces, lines
# the node is stored in the cur-variables
# we remember the latest object and column specs
# object and column is stored in the recent variables
nonlocal curDocument
nonlocal pNum
nonlocal skip
documentEnd()
identifiers = line[1:].split('=')
pNum = identifiers[0].strip()
docNum = identifiers[-1].strip()
other = pNums.get(pNum, None)
if other is not None:
(otherSrc, otherI) = other
rep = f'{pNum} also in {otherSrc}:{otherI}'
errors[f'document: duplicate pnums'][src].add((i, line, pNum, rep))
skip = True
return
curDocument = cv.node('document')
pNums[pNum] = (src, i)
sys.stderr.write(f'{src:<15} : {i:>4} : {pNum:<20}\r')
cv.feature(
curDocument,
pnumber=pNum,
srcfile=src,
srcLnNum=i,
srcLn=line,
)
skip = False
docnumber = None
docnote = None
match = collectionRe.match(docNum)
if not match:
warnings[f'document: malformed collection volume, number'][src].add(
(i, line, pNum, docNum)
)
docnote = docNum
else:
collection = match.group(1)
volume = match.group(2)
docnumber = match.group(3).strip()
docnote = None
if docnumber:
docnumber = docnumber.replace('pl. ', '').strip()
docnumParts = docnumber.split(',', 1)
if len(docnumParts) == 1:
docnote = None
else:
docnumber = docnumParts[0].strip()
docnote = docnumParts[1].strip()
if ' ' in docnumber:
warnings[f'document: unusual number'][src].add(
(i, line, pNum, docnumber)
)
docnote = docnumber
docnumber = None
cv.feature(curDocument, collection=collection, volume=volume)
if docnumber:
cv.feature(curDocument, docnumber=docnumber)
if docnote:
cv.feature(curDocument, docnote=docnote)
# sub director: terminating a document node
def documentEnd():
nonlocal curDocument
nonlocal recentObject
if curDocument is None:
return
faceEnd()
recentObject = None
cv.terminate(curDocument)
if not cv.linked(curDocument):
errors[f'document: empty'][src].add((i, line, pNum, None))
curDocument = None
# sub director: processing an # metadata line
def processMeta():
lineInfo = line[1:].strip()
if not curDocument:
errors[f'meta: outside document'][src].add((i, line, pNum, lineInfo))
return
if len(line) > 1 and line[1] == ' ':
commentInsert(meta=True)
return
match = translationRe.match(lineInfo)
if match:
lang = match.group(1)
trans = match.group(2)
if not curLine:
errors[f'meta: translation outside line'][src].add((i, line, pNum, lineInfo))
return
cv.feature(curLine, **{'trans': 1, f'translation@{lang}': trans})
return
if lineInfo.startswith('atf:l'):
errors[f'meta: no space after atf:'][src].add((i, line, pNum, None))
lineInfo = 'atf: l' + lineInfo[5:]
fields = lineInfo.split(maxsplit=1)
if fields[0] == 'atf:':
infoFields = fields[1].split(maxsplit=1)
if len(infoFields) != 2:
errors[f'meta: invalid'][src].add((i, line, pNum, fields[1]))
return
(key, value) = infoFields
value = value.strip()
if value.startswith('='):
newValue = value[1:].strip()
errors[f'meta: spurious ='][src].add((i, line, pNum, f'"{value}" => "{newValue}"'))
value = newValue
cv.feature(curDocument, **{key: value})
else:
errors[f'meta: unknown kind'][src].add((i, line, pNum, fields[0]))
return
# sub director: processing an @ specifier
def processAtSpec():
lineInfo = line[1:].strip()
fields = lineInfo.split(maxsplit=1)
typ = fields[0]
subType = fields[1] if len(fields) == 2 else None
if typ == 'column' or typ in COL_CORRECTION:
if typ in COL_CORRECTION:
typCorr = COL_CORRECTION[typ]
errors[f'structure: column correction'][src].add((i, line, pNum, f'{typ} => {typCorr}'))
typ = typCorr
columnSet(subType)
elif typ == 'object':
objectSet(subType)
elif typ in OBJECTS:
objectSet(lineInfo)
elif typ in FACES or typ in FACES_CORRECTION:
if typ in FACES_CORRECTION:
faceCorr = FACES_CORRECTION[typ]
errors[f'structure: face correction'][src].add((i, line, pNum, f'{typ} => {faceCorr}'))
faceStart(faceCorr)
else:
faceStart(lineInfo)
else:
errors[f'structure: unrecognized @'][src].add((i, line, pNum, lineInfo))
# sub director: setting the object type
def objectSet(typ):
nonlocal recentObject
nonlocal recentColumn
if typ is None:
errors[f'structure: object without type'][src].add((i, line, pNum, None))
faceEnd()
recentColumn = None
recentObject = typ
# sub director: setting up a face node
def faceStart(faceName):
nonlocal curFace
nonlocal recentObject
faceEnd()
curFace = cv.node('face')
if recentObject is None:
errors[f'structure: object missing'][src].add((i, line, pNum, faceName))
recentObject = DEFAULT_OBJ
objSpec = recentObject if recentObject and recentObject != DEFAULT_OBJ else ''
sep = ' - ' if objSpec and faceName else ''
faceSpec = f'{objSpec}{sep}{faceName or ""}'
cv.feature(
curFace,
object=recentObject,
face=faceSpec,
srcfile=src,
srcLnNum=i,
srcLn=line,
)
def faceEnd():
nonlocal recentColumn
nonlocal curFace
if curFace is None:
return
lineEnd()
recentColumn = None
cv.terminate(curFace)
if not cv.linked(curFace):
errors[f'structure: face empty'][src].add((i, line, pNum, None))
curFace = None
# sub director: setting the column number
def columnSet(number):
nonlocal recentColumn
if number is None:
errors[f'structure: column without number'][src].add((i, line, pNum, None))
lineEnd()
recentColumn = number
# sub director: setting up a comment line
# comments are $ lines.
# We interpret a comment line as a line with one empty slot.
# The comment it self is a feature of the line node.
def commentInsert(meta=False):
nonlocal curLine
comment = line[1:].strip()
if not meta and comment not in COMMENTS and not COMMENT_RE.match(comment):
warnings[f'comment: unrecognized'][src].add((i, line, pNum, comment))
if meta:
if transLine is None:
errors[f'comment: # line without preceding transcription line'][src].add(
(i, line, pNum, comment)
)
else:
prevRemarks = cv.get('remarks', transLine)
combinedRemarks = f'{prevRemarks}\n{comment}' if prevRemarks else comment
cv.feature(transLine, remarks=combinedRemarks)
else:
lineEnd()
curLine = cv.node('line')
emptySlot = cv.slot()
cv.feature(emptySlot, type='empty')
cv.feature(
curLine,
ln='$',
comment=comment,
srcfile=src,
srcLnNum=i,
srcLn=line,
)
if recentColumn is not None:
cv.feature(curLine, col=recentColumn)
cv.terminate(curLine)
curLine = None
# sub director: setting up a line node
def lineStart(ln):
nonlocal curLine
nonlocal recentTrans
lineEnd()
curLine = cv.node('line')
hasPrimeLn = "'" in ln
if hasPrimeLn:
ln = ln.replace("'", '')
cv.feature(
curLine,
ln=ln,
srcfile=src,
srcLnNum=i,
srcLn=line,
)
if hasPrimeLn:
cv.feature(curLine, primeln=1)
if recentColumn is not None:
hasPrimeCol = "'" in recentColumn
col = recentColumn.replace("'", '') if hasPrimeCol else recentColumn
cv.feature(curLine, col=col)
if hasPrimeCol:
cv.feature(curLine, primecol=1)
recentTrans = recentTrans.strip() + ' '
commentNotes.clear()
recentTrans = commentRe.sub(commentRepl, recentTrans)
for (cab, cae, cob, coe, ctp) in clusterChars:
bCount = recentTrans.count(cab)
eCount = recentTrans.count(cae)
if bCount != eCount:
errors[f'cluster: unbalanced {cob} {coe}'][src].add(
(i, line, pNum, f'{bCount} vs {eCount}')
)
changed = False
if cSpaceBRe.search(recentTrans):
recentTrans = cSpaceBRe.sub(cSpaceBRepl, recentTrans)
changed = True
if cSpaceERe.search(recentTrans):
recentTrans = cSpaceERe.sub(cSpaceERepl, recentTrans)
changed = True
recentTrans = recentTrans.strip()
if changed:
errors[f'cluster: space near edge'][src].add((i, line, pNum, transUnEsc(recentTrans)))
def lineEnd():
nonlocal curLine
if curLine is None:
return
cv.terminate(curLine)
if not cv.linked(curLine):
errors[f'line: empty'][src].add((i, line, pNum, None))
curLine = None
# sub director: adding data to a line node
# this is itself a complicated generator with sub gens
def lineData():
nonlocal curLine
nonlocal recentTrans
curWord = None
for typ in clusterStatus:
clusterStatus[typ] = False
if wHyphenBRe.search(recentTrans):
errors[f'line: words starting with -'][src].add((i, line, pNum, None))
recentTrans = wHyphenBRe.sub(wHyphenBRepl, recentTrans)
if wHyphenERe.search(recentTrans):
errors[f'line: words ending with -'][src].add((i, line, pNum, None))
recentTrans = wHyphenERe.sub(wHyphenERepl, recentTrans)
if cHyphenBRe.search(recentTrans):
errors[f'line: clusters starting with -'][src].add((i, line, pNum, None))
recentTrans = cHyphenBRe.sub(cHyphenBRepl, recentTrans)
if cHyphenERe.search(recentTrans):
errors[f'line: clusters ending with -'][src].add((i, line, pNum, None))
recentTrans = cHyphenERe.sub(cHyphenERepl, recentTrans)
words = recentTrans.split()
# subsub director: processing cluster chars
def clusterChar(before):
nonlocal part
brackets = ''
if cFlagRe.search(part):
errors[f'cluster: flag enclosed in cluster chars'][src].add(
(i, line, pNum, transUnEsc(part))
)
flags = ''
while part:
refChar = part[0] if before else part[-1]
if refChar in flagging:
flags += refChar
else:
if refChar not in clusterCharsA:
break
if refChar in clusterCharsB:
cab = refChar
cob = clusterAtf[cab]
ctp = clusterType[cab]
if before:
brackets += cab
else:
brackets = cab + brackets