-
Notifications
You must be signed in to change notification settings - Fork 2
/
xmlFromTf.py
373 lines (314 loc) · 11 KB
/
xmlFromTf.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
import sys
import os
from textwrap import dedent
from tf.app import use
from tf.core.helpers import initTree, xmlEsc, unexpanduser as ux
from lib import (
ORG,
REPO,
VERSION_TF,
TF_DIR,
ENTITY_TF,
ENTITY_MOD,
XMLOUT_DIR,
)
HELP = """
Convert TF to simplified TEI including the named entities, if present.
python3 xmlFromTf.py [version] [--help]
--help: print this text and exit
version: the tf data version to use as input.
If left out, the most recent version will be chosen.
The result ends up in directory
/xmlout/version
of this repo, and is filled with files 01.xml, ..., 14.xml,
one file for each volume.
"""
HEADER_FEATURES = """
page
title
rawdate
seq
place
year
month
day
author
authorFull
""".strip().split()
ATTS_PROTO = dict(
page=["n"],
note=[("mark", "n")],
remark=[("", "resp", "#editor")],
folio=[("", "type", "folio")],
cell=[("col", "n"), ("x", "rend", "offset-")],
row=[("row", "n")],
)
ATTS = {
elem: [
(att, att, None) if type(att) is str else (*att, None) if len(att) == 2 else att
for att in atts
]
for (elem, atts) in ATTS_PROTO.items()
}
RENAME_PROTO = dict(
page=("", "pb"),
line=("", "lb"),
para="p",
head="opener",
subhead="head",
remark="note",
folio="ref",
)
RENAME = {
orig: (newName, newName) if type(newName) is str else newName
for (orig, newName) in RENAME_PROTO.items()
}
NO_NEWLINE_BEFORE = set(
"""
folio
line
""".strip().split()
)
NO_NEWLINE_AFTER = set(
"""
folio
""".strip().split()
)
class Convert:
def __init__(self, version):
self.good = True
self.literal = False
tfInDir = f"{TF_DIR}/{version}"
if not os.path.isdir(tfInDir):
print(f"No TF input in in version {version}")
self.good = False
return
entityTfDir = f"{ENTITY_TF}/{version}"
doEntities = os.path.exists(entityTfDir)
doEntitiesRep = "WITH" + ("" if doEntities else "OUT") + " entities"
mods = dict(mod=f"{ENTITY_MOD}:clone") if doEntities else {}
print(f"Converting TF version {version} to XML {doEntitiesRep}")
A = use(
f"{ORG}/{REPO}:clone",
checkout="clone",
**mods,
version=version,
silent="terse",
)
self.A = A
self.destDir = f"{XMLOUT_DIR}/{A.version}"
def doLetter(self, letter, literal=None):
"""Convert individual letter to XML.
Note on entities.
Every word that is part of an entity will be wrapped in `<e>` elements
separately. This is because we cannot guarantees that entities respect
boundaries of other elements.
The `eid` attribute can be used to string entity words that belong to the
same entity together.
"""
if not self.good:
return
if literal is not None:
self.literal = literal
literal = self.literal
A = self.A
N = A.api.N
L = A.api.L
F = A.api.F
Fs = A.api.Fs
header = []
pNest = 0
cellNest = 0
hasP = False
allNest = 0
inExtraP = False
elemStack = []
for feat in HEADER_FEATURES:
value = xmlEsc(Fs(feat).v(letter))
header.append(f"""<interp type="{feat}">{value}</interp>""")
header = "\n".join(header)
body = []
for (node, boundary) in N.walk(nodes=L.d(letter), events=True):
trans = F.trans.v(node) or ""
punc = F.punc.v(node) or ""
if boundary is None:
entityId = F.entityId.v(node) or ""
entityKind = F.entityKind.v(node) or ""
if entityId or entityKind:
eBefore = f"""<name key="{entityId}" type="{entityKind}">"""
eAfter = """</name>"""
else:
eBefore = ""
eAfter = ""
if allNest == 0:
if not inExtraP and (trans + punc).strip():
body.append("<p>")
inExtraP = True
trans = xmlEsc(trans)
if F.isnum.v(node):
trans = f'<num type="numerator">{trans}</num>'
elif F.isden.v(node):
trans = f'<num type="denominator">{trans}</num>'
elif F.isq.v(node):
trans = f'<num type="fraction">{trans}</num>'
elif F.isemph.v(node):
trans = f"<emph>{trans}</emph>"
elif F.issub.v(node):
trans = f'<hi rend="sub">{trans}</hi>'
elif F.issuper.v(node):
trans = f'<hi rend="super">{trans}</hi>'
elif F.isund.v(node):
trans = f'<hi rend="underline">{trans}</hi>'
elif F.isref.v(node):
trans = f"<ref>{trans}</ref>"
elif F.isspecial.v(node):
trans = f"<distinct>{trans}</distinct>"
body.append(f"{eBefore}{trans}{eAfter}{xmlEsc(punc)}")
else:
elem = F.otype.v(node)
(elemStartOut, elemEndOut) = (
(elem, elem) if literal else RENAME.get(elem, (elem, elem))
)
if boundary and not elemStartOut or not boundary and elemStartOut:
attStr = ""
for (attName, attNameOut, attValue) in ATTS.get(elem, []):
if attValue is None:
attValue = Fs(attName).v(node)
elif attValue.endswith("-"):
rawValue = Fs(attName).v(node)
attValue = (
None if rawValue is None else f"{attValue}{rawValue}"
)
if attValue is not None:
attStr += (
f' {attName if literal else attNameOut}="{attValue}"'
)
if boundary:
newLine = "" if elem in NO_NEWLINE_AFTER else "\n"
if literal or elemStartOut:
if cellNest and elemEndOut == "head":
elemEndOut = "label"
elemOutRep = f"</{elemEndOut}>"
allNest -= 1
if elemEndOut == "p":
pNest -= 1
elif elemEndOut == "cell":
cellNest -= 1
elemStack.pop()
else:
if elemEndOut == "lb" and elemStack and elemStack[-1] == "row":
elemOutRep = ""
newLine = ""
else:
elemOutRep = f"<{elemEndOut}{attStr}/>"
body.append(f"{elemOutRep}{newLine}")
if elemEndOut == "ref":
if pNest == 0:
body.append("</p>\n")
else:
newLine = "" if elem in NO_NEWLINE_BEFORE else "\n"
if literal or elemStartOut:
if cellNest and elemStartOut == "head":
elemStartOut = "label"
elemOutRep = f"<{elemStartOut}{attStr}>"
if allNest == 0 and inExtraP:
body.append("</p>\n")
inExtraP = False
allNest += 1
if elemEndOut == "p":
pNest += 1
hasP = True
elif elemEndOut == "cell":
cellNest += 1
elemStack.append(elemStartOut)
else:
elemOutRep = ""
if elemEndOut == "ref":
if pNest == 0:
body.append("<p>")
body.append(f"{newLine}{elemOutRep}")
if not hasP:
body.append("<p/>")
body = "".join(body)
return dedent(
"""\
<text>
{}
<body>
{}
</body>
</text>
"""
).format(header, body)
def doVolume(self, v, literal=None):
if not self.good:
return
if literal is not None:
self.literal = literal
A = self.A
L = A.api.L
title = A.sectionStrFromNode(v)
destDir = self.destDir
destFile = f"{destDir}/{title}.xml"
letters = L.d(v, otype="letter")
letterText = "\n\n".join(self.doLetter(letter) for letter in letters)
xml = dedent(
"""\
<TEI xmlns="http://www.tei-c.org/ns/1.0">
<teiHeader>
<fileDesc>
<titleStmt>
<title>Generale Missieven, volume {}</title>
</titleStmt>
<publicationStmt>
<p>More info on https://github.com/CLARIAH/wp6-missieven
and https://github.com/cltl/voc-missives
</p>
</publicationStmt>
<sourceDesc>
<p>Text and markup of General Missieven,
after extensive cleaning of structure,
still with many OCR errors,
and with named entities marked.
</p>
<p>The structure cleaning has been carried out by Dirk Roorda,
and the result is delivered as a text-fabric dataset.
</p>
<p>The named entities are marked by means of a workflow
carried out by Sophie Arnoult, and the results are delivered
as text-fabric features.
</p>
<p>The combination of cleaned text and entities have been converted
to this TEI-XML by means of a program.
</p>
</sourceDesc>
</fileDesc>
</teiHeader>
{}
</TEI>
"""
).format(title, letterText)
with open(destFile, "w") as fh:
fh.write(xml)
print(f"volume {title} => {ux(destFile)}")
def doWork(self, literal=None):
if not self.good:
return
if literal is not None:
self.literal = literal
A = self.A
F = A.api.F
destDir = self.destDir
initTree(destDir, fresh=True, gentle=True)
for v in F.otype.s("volume"):
self.doVolume(v)
def main():
args = () if len(sys.argv) == 1 else tuple(sys.argv[1:])
version = VERSION_TF if len(args) == 0 else args[0]
if "--help" in args:
print(HELP)
return True
CV = Convert(version)
CV.doWork()
if __name__ == "__main__":
sys.exit(main())