-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.py
3148 lines (2468 loc) · 70.2 KB
/
lib.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 collections
import re
from itertools import chain
import yaml
import xml.etree.ElementTree as ET
def parseArgs(args):
vol = None
lid = None
kwargs = {}
pargs = []
good = True
for arg in args:
if arg.isdigit() or '-' in arg:
if '-' in arg:
(b, e) = arg.split('-', 1)
if b.isdigit() and e.isdigit():
values = set(range(int(b), int(e) + 1))
else:
print(f"Unrecognized argument `{arg}`")
good = False
continue
else:
values = {int(arg)}
if vol is None:
vol = values
elif lid is None:
lid = values
else:
kv = arg.split("=", 1)
if len(kv) == 1:
pargs.append(arg)
else:
(k, v) = kv
if k == "orig":
v = set(v.split(","))
kwargs[k] = v
if vol is not None:
vol = {f"{i:>02}" for i in vol}
if lid is not None:
lid = {f"p{i:>04}" for i in lid}
return (good, vol, lid, kwargs, pargs)
def ucfirst(x, lower=True):
return (x[0].upper() + (x[1:].lower() if lower else x[1:])) if x else x
def longestFirst(x):
return -len(x)
def applyCorrections(corrections, doc, text):
if doc in corrections:
for (correctRe, correctRepl) in corrections[doc]:
(text, n) = correctRe.subn(correctRepl, text)
if n == 0:
print(text)
print(f"\tCORRECTION {doc} {correctRe.pattern} did not apply")
elif n > 1:
print(text)
print(f"\tCORRECTION {doc} {correctRe.pattern} applied {n} times")
return text
# SOURCE CORRECTIONS
CORRECTIONS = {
"01:p0203": ((re.compile(r"""(<p\ rend="font-size:)\ 8\.5;""", re.S), r"\1 12;"),),
"01:p0663": ((re.compile(r""">\(1\) Dirck""", re.S), r">1) Dirck"),),
"02:p0480": ((re.compile(r"""<p\b[^>]*>p\.r cento<lb/>\s*</p>\s*""", re.S), r""),),
"04:p0496": ((re.compile(r"""I( en 9 maart 1683)""", re.S), r"""1\1"""),),
"05:p0439": ((re.compile(r"""<p\b[^>]*>i<lb/>\s*</p>\s*""", re.S), r""),),
"05:p0779": (
(
re.compile(
r"""
(
<pb\ n="793"[^>]*>
\s*
<fw\b[^>]*>[^<]*</fw>
\s*
)
<note\b[^>]*>(.*?)</note>
""",
re.S | re.X,
),
r"\1<p>\2</p>",
),
),
"06:p0844": (
(
re.compile(
r"""
<p\b[^>]*>([^<]*)<lb/>\s*</p>
(
\s*
<pb\ n="894"[^>]*>
)
""",
re.S | re.X,
),
r"<note>\1</note>\2",
),
),
"07:p0003": ((re.compile(r"""(<head\b[^>]*>)(CHRIS)""", re.S), r"""\1I. \2"""),),
"07:p0660": ((re.compile(r"""(<head\b[^>]*>XX)L""", re.S), r"""\1II"""),),
"09:p0233": (
(
re.compile(
r"""
<head\b[^>]*>
[^<]*
<lb/>
\s*
</head>
\s*
<p\b[^>]*>
[^<]*
<lb/>
\s*
</p>
\s*
<fw\b[^>]*>
[^<]*
</fw>
\s*
(<pb\ n="254")
""",
re.S | re.X,
),
r"\1",
),
),
"10:p0857": ((re.compile(r"""decem¬ber""", re.S), r"""december"""),),
"10:p0749": (
(
re.compile(
r"""(<pb n="799"[^>]*>\s*<fw\b[^>]*>.*?</fw>\s*)(</p>\s*)""", re.S
),
r"""\2\1""",
),
(
re.compile(
r"""(<pb n="997"[^>]*>\s*<fw\b[^>]*>.*?</fw>\s*)(</p>\s*)""", re.S
),
r"""\2\1""",
),
),
"11:p0226": (
(re.compile(r"""\((niet getekend wegens ziekte)\]""", re.S), r"""(\1)"""),
),
}
CORRECTION_ALLOWED = {
"01:p0004": {"author"},
"01:p0007": {"place", "title"},
"01:p0018": {"title"},
"01:p0056": {"title"},
"01:p0105": {"place", "author", "title"},
"01:p0106": {"author", "title"},
"01:p0121": {"author", "title"},
"01:p0129": {"author"},
"01:p0247": {"author"},
"01:p0302": {"place", "author", "title"},
"01:p0433": {"place", "author", "title"},
"01:p0482": {"place", "author", "title"},
"01:p0152": {"rawdate", "day", "month", "year", "title"},
"02:p0311": {"author", "title"},
"03:p0192": {"rawdate", "day", "title"},
"04:p0241": {"rawdate", "day", "title"},
"04:p0493": {"author"},
"04:p0496": {"month", "title"},
"06:p0065": {"author"},
"06:p0275": {"author"},
"06:p0402": {"author"},
"06:p0406": {"author", "title"},
"06:p0750": {"author"},
"06:p0897": {"author"},
"07:p0003": {"seq"},
"07:p0290": {"author"},
"07:p0353": {"author"},
"07:p0381": {"author"},
"07:p0396": {"author"},
"07:p0413": {"author"},
"07:p0456": {"author"},
"07:p0467": {"author"},
"07:p0479": {"author"},
"07:p0485": {"author"},
"07:p0517": {"author"},
"07:p0534": {"author"},
"07:p0537": {"author"},
"07:p0547": {"author"},
"07:p0552": {"author"},
"07:p0583": {"author"},
"07:p0596": {"author"},
"07:p0607": {"author"},
"07:p0610": {"author"},
"07:p0640": {"author"},
"07:p0651": {"author"},
"07:p0657": {"author"},
"07:p0660": {"seq", "author"},
"07:p0661": {"author"},
"07:p0684": {"author"},
"07:p0693": {"author"},
"07:p0706": {"author"},
"07:p0707": {"author"},
"07:p0710": {"author"},
"07:p0744": {"author"},
"07:p0745": {"author"},
"07:p0746": {"rawdate", "day", "author", "title"},
"07:p0754": {"author"},
"08:p0128": {"author"},
"08:p0224": {"author"},
"08:p0234": {"rawdate", "day", "title"},
"08:p0235": {"seq"},
"09:p0070": {"rawdate", "day", "month", "year"},
"09:p0344": {"seq", "rawdate", "day", "month", "year", "author", "title"},
"09:p0628": {"seq", "rawdate", "day", "month", "year", "author", "title"},
"10:p0087": {"author"},
"10:p0297": {"rawdate", "day", "month", "year"},
"10:p0399": {"rawdate", "day", "month", "year"},
"11:p0224": {"seq"},
"11:p0226": {"author"},
"12:p0001": {"author"},
"12:p0003": {"author"},
"12:p0083": {"author"},
"12:p0183": {"author"},
"13:p0340": {"author"},
"13:p0362": {"author"},
"13:p0626": {"author", "title"},
}
CORRECTION_FORBIDDEN = {
"01:p0008": {"place"},
"01:p0087": {"place"},
}
FROM_PREVIOUS = {"01:p0056"}
CORRECTION_HEAD = {
"01:p0734": (
re.compile(r"""<head .*?</p>""", re.S),
(
"VI. "
"ANTONIO VAN DIEMEN, PHILIPS LUCASZ, CAREL RENIERS "
"(EN DE GEASSUMEERDE RADEN) "
"ABRAHAM WELSING EN CORNELIS VAN DER LIJN, "
"BATAVIA. "
"30 december 1638."
),
),
}
TITLE_REST = {
"zonder plaats datum": dict(place="zonder plaats", rawdate="zonder datum"),
"ongedateerd zonder plaats": dict(place="zonder plaats", rawdate="zonder datum"),
"het cachet van die door ziekte niet zelf kon tekenen": {},
"zonder datum 1729": {},
}
TITLE_BRACKETS = {
f"({x.strip()})"
for x in """
EN de GEASSUMEERDE RADEN
niet getekend wegens ziekte
vermoedelijk 30 november
""".strip().split(
"\n"
)
}
DISTILL_SPECIALS = {
"13:p0626": dict(
title="Bijlage ladinglijst van twaalf retourschepen vertrokken op 15 en 30 oktober, 6 november 1760, 19 januari en 25 april 1761",
rawdate="25 april 1761",
place="Batavia",
author="",
authorFull="",
rest="",
)
}
MONTH_DEF = """
januari
februari
maart
april
mei
juni
juli
augustus
september
oktober
october
november
december
decem¬ber
""".strip().split(
"\n\n"
)
MONTH_VARIANTS = {}
MONTHS = set()
MONTH_NUM = {}
for (i, nameInfo) in enumerate(MONTH_DEF):
(intention, *variants) = nameInfo.strip().split()
MONTH_NUM[intention] = i + 1
MONTHS.add(intention)
for abb in (intention, intention[0:3], intention[0:4]):
MONTH_VARIANTS[abb] = intention
for variant in variants:
for abb in (
variant,
variant[0:3],
f"{variant[0:3]}.",
f"{variant[0:4]}.",
):
MONTH_VARIANTS[abb] = intention
MONTH_DETECT_PAT = "|".join(
sorted(
set(re.escape(mv) for mv in chain(MONTH_NUM, MONTH_VARIANTS)), key=longestFirst
)
)
PLACE_DEF = """
Afrika
Amboina
Amsterdam
Banda-Neira
bandaneira
banda-neira
banda
Bantam
Batavia
ratavia
ba¬tavia
Deventer
Fort
eort
Hoek
Hollandia
Jakatra
Kasteel
Makéan
Maleyo
Mauritius
Nassau
_
neira
Ngofakiaha
Nieuw
Nieuw Hollandia
nieuw-hollandia
Rede
Schip
Straat
Sunda
Ternate
Utrecht
Vere
Vlakke
Wapen
Wesel
""".strip().split(
"\n\n"
)
PLACE_LOWERS = set(
"""
aan
boord
de
eiland
het
in
nabij
op
rede
schip
ter
van
voor
zuidpunt
""".strip().split()
)
PLACE_VARIANTS = {}
PLACES_LOWER = set()
for (i, nameInfo) in enumerate(PLACE_DEF):
(intention, *variants) = nameInfo.strip().split()
if intention == "_":
intention = ""
else:
PLACES_LOWER.add(intention.lower())
PLACE_VARIANTS[intention] = intention
PLACE_VARIANTS[intention.lower()] = intention
for variant in variants:
PLACE_VARIANTS[variant] = intention
PLACE_DETECT_PAT = "|".join(
sorted(set(re.escape(mv) for mv in chain(PLACE_VARIANTS)), key=longestFirst)
)
LOWERS_PAT = "|".join(
sorted(set(re.escape(mv) for mv in PLACE_LOWERS), key=longestFirst)
)
DETECT_STATUS_RE = re.compile(
r"""
\(?
(
[ck]opie
|geheim
|secreet
)
\.?
\)?
\.?
""",
re.S | re.I | re.X,
)
DETECT_AUTHOR_RE = re.compile(
r"""
^
\s*
(.*)?
\s*
$
""",
re.S | re.X,
)
DETECT_SEQ_RE = re.compile(
r"""
^
(
[IVXLCDM1]+
\s*
[IVXLCDMm1liTUH]*
(?:
\s*
[aA]
)?
\b
)
\.?
""",
re.S | re.X,
)
DETECT_DATE_RE = re.compile(
fr"""
\(?
\s*
(
(?:
[0-9I]{{1,2}}
|
(?:[0-9I]\ [0-9I])
)
(?:
\s+en\s+
(?:
[0-9I]{{1,2}}
|
(?:[0-9I]\ [0-9I])
)
)?
\s+
(?: {MONTH_DETECT_PAT} )
\s*
1
\s*
[6-8]
\s*
[0-9]
\s*
[0-9]
\s*
(?:
\?
|
\s*\(\?\)
)?
)
\s*
\)?
\s*
\.?
\s*
""",
re.S | re.X,
)
DETECT = dict(
seq=re.compile(
r"""
^
(
[IVXLCDM1]+
\s*
[IVXLCDMm1liTUH]*
(?:
\s*
[aA]
)?
\b
)
\.?
""",
re.S | re.X,
),
rawdate=re.compile(
fr"""
\(?
\s*
(
(?:
[0-9I]{{1,2}}
|
(?:[0-9I]\ [0-9I])
)
(?:
\s+en\s+
(?:
[0-9I]{{1,2}}
|
(?:[0-9I]\ [0-9I])
)
)?
\s+
(?: {MONTH_DETECT_PAT} )
\s+
1[6-8]
[0-9]{{2}}
\s*
(?:
\?
|
\s*\(\?\)
)?
)
\s*
\)?
\s*
\.?
\s*
""",
re.S | re.X,
),
place=re.compile(
fr"""
(
(?:
\b
(?: {PLACE_DETECT_PAT} | {LOWERS_PAT})
\b
[ .,]*
)*
(?:
\b
(?: {PLACE_DETECT_PAT} )
\b
[ .,]*
)
(?:
\b
(?: {PLACE_DETECT_PAT} | {LOWERS_PAT})
\b
[ .,]*
)*
)
""",
re.S | re.I | re.X,
),
author=DETECT_AUTHOR_RE,
authorFull=DETECT_AUTHOR_RE,
)
NUM_SANITIZE_RE = re.compile(r"""[0-9][0-9 ]*[0-9]""", re.S)
def numSanitize(match):
return f" {match.group(0).replace(' ', '')} "
# CONFIG READING
def readYaml(fileName):
if os.path.exists(fileName):
with open(fileName) as y:
y = yaml.load(y, Loader=yaml.FullLoader)
else:
y = {}
return y
# LOCATIONS
LOCAL = os.path.expanduser("~/local")
BASE = os.path.expanduser("~/github")
ORG = "Dans-labs"
REPO = "clariah-gm"
REPO_DIR = f"{BASE}/{ORG}/{REPO}"
SOURCE_DIR = f"{LOCAL}/{REPO}"
DECL_PATH = f"{REPO_DIR}/yaml"
META_DECL_FILE = f"{DECL_PATH}/meta.yaml"
META_DECL = readYaml(META_DECL_FILE)
VERSION_SRC = META_DECL["versionSrc"]
VERSION_TF = META_DECL["versionTf"]
IN_DIR = f"{SOURCE_DIR}/{VERSION_SRC}/tei"
TRIM_DIR = f"{SOURCE_DIR}/{VERSION_SRC}/trim"
REPORT_DIR = f"{REPO_DIR}/trimreport"
XML_DIR = f"{REPO_DIR}/xml"
LAST_STAGE = 3
TF_DIR = f"{REPO_DIR}/tf"
OUT_DIR = f"{TF_DIR}/{VERSION_TF}"
MERGE_DOCS = {
"06:p0406": ("06:p0407",),
}
SKIP_DOCS = {x for x in chain.from_iterable(MERGE_DOCS.values())}
HI_CLEAN_STRONG_RE = re.compile(r"""<hi\b[^>]*>([^<]*)</hi>""", re.S)
# FILESYSTEM OPERATIONS
def docSummary(docs):
nDocs = len(docs)
rep = " 0x" if not nDocs else f" 1x {docs[0]}" if nDocs == 1 else ""
if not rep:
examples = " ".join(docs[0:2])
rest = " ..." if nDocs > 2 else ""
rep = f"{nDocs:>3}x {examples}{rest}"
return f"{rep:<30}"
def clearTree(path):
"""Remove all files from a directory, recursively, but leave subdirs.
Reason: we want to inspect output in an editor.
But if we remove the directories, the editor looses its current directory
all the time.
"""
subdirs = []
with os.scandir(path) as dh:
for (i, entry) in enumerate(dh):
name = entry.name
if name.startswith("."):
continue
if entry.is_file():
os.remove(f"{path}/{name}")
elif entry.is_dir():
subdirs.append(name)
for subdir in subdirs:
clearTree(f"{path}/{subdir}")
if subdir == "rest":
os.rmdir(f"{path}/{subdir}")
def initTree(path, fresh=False):
exists = os.path.exists(path)
if fresh:
if exists:
clearTree(path)
if not exists:
os.makedirs(path, exist_ok=True)
# SOURCE READING
PAGENUM_RE = re.compile(
r"""<interpGrp type="page"><interp>([0-9]+)</interp></interpGrp>""", re.S
)
def getPage(path):
with open(path) as fh:
text = fh.read()
match = PAGENUM_RE.search(text)
return f"p{int(match.group(1)):>04}" if match else None
def getVolumes(srcDir):
volumes = []
with os.scandir(srcDir) as dh:
for entry in dh:
if entry.is_dir():
vol = entry.name
if not vol.isdigit():
continue
volumes.append(f"{int(vol):>02}")
return sorted(volumes)
def getLetters(srcDir, idMap=None):
letters = []
collisions = 0
lidSet = set()
with os.scandir(srcDir) as dh:
for entry in dh:
if entry.is_file():
name = entry.name
if name.endswith(".xml"):
pureName = name[0:-4]
if idMap is not None:
lid = getPage(f"{srcDir}/{name}")
if lid in lidSet:
collisions += 1
lidSet.add(lid)
idMap[pureName] = lid
letters.append(pureName)
if collisions:
print(f"MAPPING from letter ids to first pages: {collisions} collisions")
return ()
return tuple(sorted(letters))
# ANALYSIS
NUM_RE = re.compile(r"""[0-9]""", re.S)
def nodeInfo(node, analysis, after=False):
tag = node.tag
atts = node.attrib
if not atts:
analysis[f"{tag}.."] += 1
else:
for (k, v) in atts.items():
vTrim = NUM_RE.sub("n", v)
if k == "value":
vTrim = "x"
isLayout = k == "rend"
if after:
if isLayout:
analysis[f" {tag}.{k}={v}"] += 1
else:
analysis[f"{tag}.{k}={vTrim}"] += 1
else:
if not isLayout:
analysis[f"{tag}.{k}={vTrim}"] += 1
for child in node:
nodeInfo(child, analysis, after=after)
def analyse(text, after=False):
analysis = collections.Counter()
root = ET.fromstring(text)
nodeInfo(root, analysis, after=after)
return analysis
BODY_RE = re.compile(r"""<body[^>]*>(.*?)</body>""", re.S)
def combineTexts(first, following):
bodies = []
for text in following:
match = BODY_RE.search(text)
bodies.append(match.group(1))
return first.replace("</body", ("\n".join(bodies)) + "</body>")
# TOP-LEVEL TRIM
def trim(stage, givenVol, givenLid, trimPage, processPage, *args, **kwargs):
SRC = IN_DIR if stage == 0 else f"{TRIM_DIR}{stage - 1}"
DST = XML_DIR if stage == LAST_STAGE else f"{TRIM_DIR}{stage}"
REP = f"{REPORT_DIR}{stage}"
initTree(REP)
volumes = getVolumes(SRC)
analysis = collections.Counter()
analysisAfter = collections.Counter()
info = dict(
table=0,
docs=[],
metas=0,
metasUnknown=[],
metasDistilled=collections.defaultdict(dict),
nameDiag=collections.defaultdict(
lambda: collections.defaultdict(lambda: collections.defaultdict(list))
),
metaValues=collections.defaultdict(
lambda: collections.defaultdict(lambda: collections.defaultdict(list))
),
metaDiag=collections.defaultdict(dict),
captionInfo=collections.defaultdict(list),
captionNorm=collections.defaultdict(list),
captionVariant=collections.defaultdict(list),
captionRoman=collections.defaultdict(list),
folioResult=collections.defaultdict(list),
folioTrue=collections.defaultdict(list),
folioFalse=collections.defaultdict(list),
folioUndecided=collections.defaultdict(lambda: collections.defaultdict(list)),
headInfo=collections.defaultdict(list),
remarks=collections.Counter(),
remarkInfo=collections.defaultdict(lambda: collections.defaultdict(list)),
heads={},
bigTitle={},
splits=[],
splitsX=[],
)
mergeText = {}
previousDoc = None
for vol in volumes:
if givenVol is not None and vol not in givenVol:
continue
print(f"\rvolume {vol}" + " " * 70)
volDir = vol.lstrip("0") if stage == 0 else vol
thisSrcDir = f"{SRC}/{volDir}"
thisDstDir = f"{DST}/{vol}"
rest = "/rest" if stage == 1 else ""
initTree(thisDstDir, fresh=True)
initTree(f"{thisDstDir}{rest}", fresh=True)
info["vol"] = vol
idMap = {} if stage == 0 else None
letters = getLetters(thisSrcDir, idMap=idMap)
if stage == 1:
for name in letters:
lid = name if idMap is None else idMap[name]
if givenLid is not None and lid not in givenLid:
continue
doc = f"{vol}:{lid}"
if doc in SKIP_DOCS:
continue
if doc in MERGE_DOCS:
with open(f"{thisSrcDir}/{name}.xml") as fh:
text = fh.read()
followTexts = []
for followDoc in MERGE_DOCS[doc]:
followName = followDoc.split(":", 1)[1] + ".xml"
with open(f"{thisSrcDir}/{followName}") as fh:
followTexts.append(fh.read())
mergeText[doc] = combineTexts(text, followTexts)
for name in letters:
lid = name if idMap is None else idMap[name]
if givenLid is not None and lid not in givenLid:
continue
doc = f"{vol}:{lid}"
if stage == 1 and doc in SKIP_DOCS:
continue
sys.stderr.write(f"\r\t{lid} ")
info["doc"] = doc
info["docs"].append(doc)
if stage == 1 and doc in mergeText:
text = mergeText[doc]
else:
with open(f"{thisSrcDir}/{name}.xml") as fh:
text = fh.read()
if stage == 1:
text = applyCorrections(CORRECTIONS, doc, text)
origText = text
thisAnalysis = analyse(text)
for (path, count) in thisAnalysis.items():
analysis[path] += count
text = trimDocument(
stage, text, trimPage, info, processPage, previousDoc, *args, **kwargs
)
if text is None:
dstName = f"{lid}.xml"
with open(f"{thisDstDir}/rest/{dstName}", "w") as fh:
fh.write(origText)
continue
dstName = f"{lid}.xml"
with open(f"{thisDstDir}/{dstName}", "w") as fh:
fh.write(text)
thisAnalysisAfter = analyse(text, after=True)
for (path, count) in thisAnalysisAfter.items():
analysisAfter[path] += count
previousDoc = doc
print("\rdone" + " " * 70)
docs = info["docs"]
totalDocs = len(docs)
print(f"{totalDocs} documents")
with open(f"{REP}/elementsIn.tsv", "w") as fh:
for (path, amount) in sorted(analysis.items()):
fh.write(f"{path}\t{amount}\n")
with open(f"{REP}/elementsOut.tsv", "w") as fh:
for (path, amount) in sorted(analysisAfter.items()):
fh.write(f"{path}\t{amount}\n")
if stage == 0:
metasUnknown = info["metasUnknown"]
print(f"\t{len(metasUnknown):>3} docs with unrecognized metadata")
with open(f"{REP}/metaUnrecognized.txt", "w") as fh:
for (doc, meta) in sorted(metasUnknown):
fh.write(f"{doc}\n")
for (k, v) in meta.items():
fh.write(f"\t{k:<10} = {v}\n")
fh.write("\n")
elif stage == 1:
captionInfo = info["captionInfo"]
captionNorm = info["captionNorm"]
captionVariant = info["captionVariant"]
captionRoman = info["captionRoman"]
if captionNorm or captionVariant or captionInfo or captionRoman:
print("CAPTIONS:")
print(f"\t{len(captionNorm):>3} verified names")
print(f"\t{len(captionVariant):>3} unresolved variants")
print(f"\t{len(captionRoman):>3} malformed roman numerals")
with open(f"{REP}/fwh-yes.tsv", "w") as fh:
for (captionSrc, tag) in (
(captionNorm, "OK"),
(captionVariant, "XX"),
(captionInfo, "II"),
(captionRoman, "RR"),
):
for caption in sorted(captionSrc):