-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert_pp4.py
498 lines (465 loc) · 15.4 KB
/
convert_pp4.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
#!/usr/bin/env python3
#
import getopt, sys, os
import re
from bs4 import BeautifulSoup
# ----------------------------------------------------------------------------
#
# convert_pp2.py: converts from betacode to UTF-8, and post processes
# final sigmas.
# Computes IDs like "<id>page383-section383b</id>
# and <speaker>Ἑρμογένησ</speaker>
# depending on information in the XML.
#
# Usage:
# python3 convert_pp2.py -f plat.laws_gk.xml
# ... (lots of output)
# READY
# OUTPUT: plat.laws_gk.brat
#
# Optional arguments:
# -m cltk :uses the cltk beta-utf8 converter instead of
# TrieConvert.py
# -s :split lines on "."
# -t :tokenise lines
# -v :verbose output
# -S :speaker ID in ID
#
# Converted output in plat.laws_gk.brat
#
# Needs: bs4 and TrieConvert.py and/or CLTK installed.
# ( easy_install beautifulsoup4 )
# ( pip install beautifulsoup4 )
#
# ----------------------------------------------------------------------------
# Convert beta to utf8
try:
from cltk.corpus.greek.beta_to_unicode import Replacer
from lxml import etree
r = Replacer()
# and 20150804:
from cltk.tokenize.sentence import TokenizeSentence
from cltk.stop.greek.stops import STOPS_LIST
tokenizer = TokenizeSentence('greek')
#
from nltk.tokenize.punkt import PunktLanguageVars
plv = PunktLanguageVars() #not useful
except:
print(" No CLTK/NTLK toolkits found." )
r = None
#tokenizer.tokenize_sentences(sentence)
#tokens = plv.word_tokenize(sentence.lower())
# Or this way
try:
import TrieConvert
t = TrieConvert.beta2unicodeTrie()
except:
print( "TrieConvert not found." )
t = None
if not t and not r:
print("No conversion/tokenisation possible.")
sys.exit(1)
afile = None
split = False
tokenise = False
verbose = False
mode = "trie"
# Pattern for final sigma conversion (need greek colon?)
SRCH = "σ"
REPL = "ς"
#
def final_sigma(l):
cnt = 0
new_l = ""
new_l = []
for w in l.split():
if w[-1] == SRCH:
new_w = w[:-1] + REPL
if verbose:
print( "endsigma", w, "->", new_w )
cnt += 1
elif len(w) > 1 and w[-2] == SRCH and w[-1] in [".", ","]: # the Trie seems to do these
new_w = w[:-2] + REPL + w[-1]
if verbose:
print( "endsigma", w, "->", new_w )
cnt += 1
else:
if verbose:
pass
#print( "e =", w )
new_w = w
new_l.append(new_w)
return " ".join(new_l), cnt
def beta2utf(form):
#return form #for quick testing
if mode == "none":
return form
if mode == "cltk":
if r:
uni_form = r.beta_code(form)
return uni_form
else:
print( "CLTK not present." )
sys.exit(1)
else:
uni_form, b = t.convert(form)
if b:
print( "----------> ERROR <-----------" )
bf.write( "----------> ERROR <-----------\n" )
print( uni_form )
print( form )
bf.write( uni_form+"\n" )
bf.write( form+"\n" )
print
print( b )
bf.write( b+"\n" )
sys.exit(1)
uniform, cnt = final_sigma(uni_form)
uniform, cntc = re.subn(":", "·", uniform) #count?
return uniform
class ID():
def __init__(self):
self.current_id = {}
for i in ["book", "chapter", "page", "section"]:
self.current_id[i] = "?"
self.book = ""
self.chapter = ""
self.page = ""
self.para = ""
self.section = ""
self.speaker = ""
def get_id(self):
id = ""
# skip if "?" ? Allow to set on startup for missing/start?
for i in ["book", "chapter", "page", "section"]:
if str(self.current_id[i]) != '?':
id += i + "" + str(self.current_id[i])+ "-"
id = id[:-1]
return id
def parse_speaker(self, sib):
if sib:
form = sib.string.strip().upper() # make upper case for Beta Code converter
uni_form = beta2utf(form)
self.speaker = uni_form
print( "NEW ID", self.get_id() )
def parse(self, sib):
if sib.name == "milestone":
old_id = self.get_id()
try:
unit = sib["unit"]
except KeyError:
unit = None
try:
n = sib["n"]
except KeyError:
n = None
try:
ed = sib["ed"]
except KeyError:
ed = None
if unit and n:
self.current_id[unit] = n
if self.get_id() != old_id:
#print( "OLD ID", old_id )
print( "NEW ID", self.get_id() )
return old_id != self.get_id() #return True if changed
elif sib.name == "div1": #has book info
try:
typ = sib["type"]
except KeyError:
typ = None
try:
n = sib["n"]
except KeyError:
n = None
my_id.current_id[typ] = n
print( "NEW ID", self.get_id() )
try:
opts, args = getopt.getopt(sys.argv[1:], "f:m:stv", [])
except getopt.GetoptError as err:
print(str(err))
sys.exit(1)
for o, a in opts:
if o in ("-f"):
afile = a
elif o in ("-m"):
mode = a
elif o in ("-s"):
split = True
elif o in ("-t"):
tokenise = True
elif o in ("-v"):
verbose = True
else:
assert False, "unhandled option"
if not afile:
print("Need a file ("+sys.argv[0]+" -f FILE).")
sys.exit(1)
# UTF8 output
file_n, file_e = os.path.splitext(afile)
bratfile = file_n + ".brat"
tei = open(afile).read()
soup = BeautifulSoup(tei, ['lxml', 'xml'])
if verbose:
print(soup.prettify())
print
print
#print( soup.findAll('sp') )
print( len(soup.findAll('sp')) )
print
print
#print( soup.findAll('p') )
print( len(soup.findAll('p')) )
sys.exit(1)
#
def handle_sib0(sib, level=0, hist=[]):
print( "ENTER ->", level, hist, sib.name )
for x in sib.find_next(): #could be none
print( x )
try:
x_children = x.find_all() #also contents/siblings
#print( level ) #, repr(sib_children) )
for child in x_children:
handle_sib(child, level+1, hist + [x.name])
except AttributeError:
print( level, "NO CHILDREN", repr(sib) )
print( "LEAVE <-", sib.name )
# GLOBAL
#
output = []
stats = {}
def output_converted(sib, output, hist=[]):
print( sib, hist )
if len(sib.strip()) > 0:
print("BETAC", sib.strip())
sentences = [ sib.strip() ]
i = 0
while i < len(sentences):
form = sentences[i].strip().upper() # make upper case for Beta Code converter
if not form:
i += 1
continue
#if i < len(sentences)-1 and sentences[i+1].strip() == ".":
# form += " ."
# i += 1
uni_form = beta2utf(form)
print("GREEK", uni_form)
# tokenise here, this is more like an alternative for "split" above
output.append(uni_form)
i += 1
#bf.write( ' '.join( output )+"\n" )
return output
def write_output(output, bf):
s = ""
x = ' '.join(output)
tmp = x.split() #make sure only single spaces
x = ' '.join(tmp)
for w in x.split():
if w[-1:] == ".":
s += w[:-1] + " ."
form = s.strip().upper() # make upper case for Beta Code converter
uni_form = beta2utf(form)
bf.write( uni_form+"\n" )
s = ""
elif w[-1:] == ",":
s += w[:-1] + " , "
else:
if w not in ['\n', '\t']:
s += w + " "
if s:
form = s.strip().upper() # make upper case for Beta Code converter
uni_form = beta2utf(form)
bf.write( uni_form+"\n" )
def handle_sib(sib, bf, level=0, hist=[]):
global output, stats
#print( "ENTER ->", level, hist, sib.name )
# before milestone and speaker, output?
if sib.name == "milestone":
write_output(output, bf)
output = []
if my_id.parse(sib):
bf.write( "\n<id>"+my_id.get_id()+"</id>\n" ) #maybe between <id>
#return #assume no text inside milestone
if sib.name == "speaker": #sp?
write_output(output, bf)
output = []
my_id.parse_speaker(sib)
bf.write( "\n<speaker>"+my_id.speaker+"</speaker>\n" )
return #need a return, otherwise we include speaker as CONTENTS also
# decide on high level if to skip here (output?)
if sib.name in ["del", "bibl"]: #SKIP ["l"]
print( "SKIP:", sib )
path = ["SKIP"] + hist
try:
stats[repr(path)] += 1
except KeyError:
stats[repr(path)] = 1
return
try:
for x in sib.contents:
# print( "CONTENTS", x )
if x.name:
handle_sib(x, bf, level+1, hist+[x.name])
else:
print( "CONTENTS", x, hist, output )
#bf.write( x + "\n" )
if sib:
output.append( x )
#converted_output = output_converted(x, output, hist)
#if converted_output:
# print( "COUT", converted_output )
# bf.write( ' '.join( converted_output )+"\n" )
except AttributeError:
print( "NONE" )
#print( "LEAVE <-", sib.name )
try:
stats[repr(hist)] += 1
except KeyError:
stats[repr(hist)] = 1
my_id = ID()
'''
Plato:
<body>
<div1 type="book" n="1">
<milestone unit="page" n="624"/>
Thuc:
<body>
<div1 n="1" type="book"><p>
<milestone unit="chapter" n="1"/>
'''
with open(bratfile, "w") as bf:
div1s = soup.findAll('div1')
if len(div1s) == 0:
div1s = soup.findAll('group')
if len(div1s) == 0:
div1s = soup.findAll('body')
for div1 in div1s:
my_id.parse(div1)
bf.write( "<id>"+my_id.get_id()+"</id>\n" ) #maybe between <id>
handle_sib(div1, bf, 0, [div1.name])
write_output( output, bf )
'''
#print()
#print("\n", sib, sib.name, sib.string)
# PJB still messy, if time, redo
#
p = sib.parent
if sib.name == "del":
print("DEL", sib)
next(sps_siblings_iter, None) #skip this one
continue
if sib.name == "milestone":
if my_id.parse(sib):
# HERE WE SHOULD WRITE OUTPUT
bf.write( ' '.join( output )+"\n" )
output = []
bf.write( "\n<id>"+my_id.get_id()+"</id>\n" ) #maybe between <id>
#next(sps_siblings_iter, None) #milestone can contain text
#use next_element ?
#print( "NEXT", sib.next_element )
continue
if sib.name == "speaker":
my_id.parse_speaker(sib)
# maybe no ouput if speaker ID in ID tag
# HERE WE SHOULD WRITE OUTPUT
bf.write( ' '.join( output )+"\n" )
output = []
bf.write( "\n<speaker>"+my_id.speaker+"</speaker>\n" )
next(sps_siblings_iter, None) #don't keep?
continue
if sib.name == "bibl": #like DEL
print("BIBL", sib)
next(sps_siblings_iter, None) #don't keep?
continue
# the contents of the following tags is not included
if sib.name in ["castlist", "castitem", "role", "term"]: #like DEL
print("CAST", sib)
next(sps_siblings_iter, None) #don't keep?
continue
if sib.name == "l": #like DEL
print("L", sib)
#
# For pass2 we could add output like this: (convert string!)
# bf.write("<L>"+sib.string+"</L>\n") #or sib.get_text()
# or just a <L>..</L> and the string on the next line,
# like the speaker texts.
#
next(sps_siblings_iter, None) #don't keep?
continue
if sib.name == "q": #like DEL
print("Q", sib) #shoudl take sib in (recursive) routine
sys.exit(1)
next(sps_siblings_iter, None) #don't keep?
continue
if sib.name == "cit": #like DEL
print("CIT", sib)
next(sps_siblings_iter, None) #don't keep?
continue
# from the following tags we include <tag>contents</tag>
if sib.name in ["p", "sp", "add", "quote", "gap", "text", "emph"]:
# TODO, sp moet annotatie worden, <sp> is alles van speaker.
# TODO betere XML parsing...
# output quote here?
# problem: introduces linefeeds... assemble in pass2?
if sib.name == "add":
print( "ADD:"+sib.string )
continue #handle on next level
if sib.name: # and sib.name not in ["del", "milestone", "speaker", "bibl", "l", "q"]:
print("\nUNHANDLED", sib.name)
#print( sib.prettify() )
sys.exit(1)
# left is text
if len(sib.strip()) > 0:
print("BETAC", sib.strip())
sentences = [ sib.strip() ]
i = 0
while i < len(sentences):
form = sentences[i].strip().upper() # make upper case for Beta Code converter
if not form:
i += 1
continue
#if i < len(sentences)-1 and sentences[i+1].strip() == ".":
# form += " ."
# i += 1
uni_form = beta2utf(form)
print("GREEK", uni_form)
# tokenise here, this is more like an alternative for "split" above
output.append(uni_form)
i += 1
bf.write( ' '.join( output )+"\n" )
output = []
print( "READY")
print( "OUTPUT:", bratfile )
'''
print( "Stats:" )
for s in sorted(stats, key=stats.get, reverse=True): #s is repr() strings
if s[2:6] != "SKIP":
print( s, stats[s] )
print("---")
for s in sorted(stats, key=stats.get, reverse=True):
if s[2:6] == "SKIP":
print( s, stats[s] )
print( "OUTPUT", bratfile )
'''
UNHANDLED:
<quote type="verse"><l met="dactylic">au(/th toi di/kh e)sti\ qew=n oi(\ *)/olumpon e)/xousin,</l></quote>
<bibl n="Hom. Od. 19.43">Hom. Od. 19.43</bibl>
<bibl n="Hom. Il. 2.108">
Hom. Il. 2.108
</bibl>
<cit>
<quote type="verse">
<l met="c">
e)/nqa ke sh\ boulh\ dhlh/setai, oi(=' a)goreu/eis.
</l>
</quote>
<bibl>
Hom. Il. 14.96
</bibl>
</cit>
<term>fai/netai</term>
<emph>mh/pw me/g' ei)/ph|s</emph>
STRANGE:
BETAC a)lhqe/stata le/geis, w)= *me/gille, kai\ e)gw\ poih/sw tau=q' ou(/tws kai\ <su\> sulla/mbane.
GREEK ἀληθέστατα λέγεις, ὦ Μέγιλλε, καὶ ἐγὼ ποιήσω ταῦθ’ οὕτως καὶ <σὺ> συλλάμβανε.
'''