-
Notifications
You must be signed in to change notification settings - Fork 0
/
lift.py
4227 lines (4226 loc) · 197 KB
/
lift.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
#!/usr/bin/env python3
# coding=UTF-8
"""This module controls manipulation of LIFT files and objects"""
""""(Lexical Interchange FormaT), both for reading and writing"""
import logsetup
log=logsetup.getlog(__name__)
# logsetup.setlevel('INFO',log) #for this file
logsetup.setlevel('DEBUG',log) #for this file
log.info("Importing lift.py")
# try:
# from lxml import etree as ET
# log.info("using lxml to parse XML")
# lxml=True
# except:
log.info("using xml.etree to parse XML")
lxml=False
from xmletfns import * # from xml.etree import ElementTree as ET
import xmlfns
import sys
import pathlib
import threading
import shutil
import datetime
import re #needed?
import os
import rx
import ast #For string list interpretation
import copy
import collections
try: #Allow this module to be used without translation
_
except:
def _(x):
return x
"""This returns the root node of an ElementTree tree (the entire tree as
nodes), to edit the XML."""
class Object(object):
pass
class TreeParsed(object):
def __init__(self, lift):
self=Tree(lift).parsed
log.info(self.glosslang)
Tree.__init__(self, db, guid=guid)
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class BadParseError(Error):
def __init__(self, filename):
self.filename = filename
class Lift(object): #fns called outside of this class call self.nodes here.
"""The job of this class is to expose the LIFT XML as python object
attributes. Nothing more, not thing else, should be done here."""
def __init__(self, filename, tostrip=False):
self.debug=False
self.filename=filename #lift_file.liftstr()
self.logfile=filename+".changes"
self.urls={} #store urls generated
"""Problems reading a valid LIFT file are dealt with in main.py"""
try:
self.read() #load and parse the XML file. (Should this go to check?)
except:
raise BadParseError(self.filename)
self.getglosslangs() #sets: self.glosslangs
if tostrip:
return #we're done, if this is a template read
backupbits=[filename,'_',
datetime.datetime.utcnow().isoformat()[:-16], #once/day
'.txt']
self.backupfilename=''.join(backupbits)
"""I should skip some checks in certain cases, like working with the
CAWL template"""
self.getentries()
self.getsenses()
self.getanalangs() #sets: self.analangs, self.audiolangs
self.getpss() #all ps values, in a prioritized list
self.slicebyerror()
self.slicebyps()
self.slicebyid()
self.slicebylx()
self.slicebylc() #1.14s
#the following should probably replaced by getsenseidsbyps everywhere
"""These three get all possible langs by type"""
self.legacylangconvert() #update from any old language forms to xyz-x-py
self.getentrieswanalangdata() #sets: self.(n)entriesw(lexeme|citation)data
self.getsenseswglosslangdata() #sets: self.nsensesw(gloss|defn)data
#HERE
self.getfieldnames() #sets self.fieldnames (of entry)
self.getsensefieldnames() #sets self.sensefieldnames (fields of sense)
self.legacyverificationconvert() #data to form nodes (no name changes)
self.getfieldswsoundfiles() #sets self.nfields & self.nfieldswsoundfiles
log.info("Working on {} with {} entries, with lexeme data counts: {}, "
"citation data counts: {} and {} senses".format(filename,self.nguids,
self.nentrieswlexemedata,
self.nentrieswcitationdata,
self.nsenseids))
log.info("Found gloss data counts: {}, definition counts: {}"
"".format(
self.nsenseswglossdata,
self.nsenseswdefndata,
))
#This may be superfluous:
self.getsenseidsbyps() #sets: self.senseidsbyps and self.nsenseidsbyps
"""This is very costly on boot time, so this one line is not used:"""
# self.getguidformstosearch() #sets: self.guidformstosearch[lang][ps]
self.lcs=self.citations()
self.lxs=self.lexemes()
self.getlocations()
self.defaults=[ #these are lift related defaults
'analang',
'glosslangs',
'audiolang'
]
self.slists() #sets: self.c self.v, not done with self.segmentsnotinregexes[lang]
self.extrasegments() #tell me if there's anything not in a V or C regex.
# self.findduplicateforms()
self.findduplicateexamples()
"""Think through where this belongs; what classes/functions need it?"""
self.morphtypes=self.getmorphtypes()
log.info("Language initialization done.")
def retarget(self,urlobj,target,showurl=False):
k=self.urlkey(urlobj.kwargs)
urlobj.kwargs['retarget']=target
k2=self.urlkey(urlobj.kwargs)
if k2 not in self.urls:
self.urls[k2]=copy.deepcopy(urlobj)
self.urls[k2].retarget(target)
if showurl:
log.info("URL for retarget: {}".format(self.urls[k2].url))
return self.urls[k2]
def urlkey(self,kwargs):
kwargscopy=kwargs.copy() #for only differences that change the URL
kwargscopy.pop('showurl',False)
k=tuple(sorted([(str(x),str(y)) for (x,y) in kwargscopy.items()]))
return k
def get(self, target, node=None, **kwargs):
"""This method calls for a URL object, if it's not already there.
Followup methods include
LiftURL.get() on that object: to get the desired text/attr/node
lift.retarget(): to move from one url to a parent (e.g., the sense
node containing a found example) before LiftURL.get() again
get entries: lift.get("entry").get()
lift.get("entry".get('guid'))
get senses: lift.get("sense").get()
lift.get("sense".get('senseid'))
get *all* pss: lift.get("ps").get('value')
Never ask for just the form! give the parent, to get a particular form:
lift.get("lexeme/form").get('text')
lift.get("example/form").get('text')
lift.get("example/translation/form").get('text')
lift.get("citation/form").get('text')
just 1 of each pss: dict.fromkeys(lift.get("ps").get('value'))
get tone value (from example):
lift.get("example/tonefield/form/text",location=location).get('text')
get tone value (from sense, UF):
lift.get('toneUFfield/form/text', senseid=senseid).get('text')
lift.get('sense/toneUFfield/form/text', senseid=senseid).get('text')
location: lift.get('locationfield', senseid=senseid).get('text')
"""
if node is None:
node=self.nodes
what=kwargs.get('what','node')
path=kwargs.get('path',[])
if type(path) is not list:
path=kwargs['path']=[path]
showurl=kwargs.get('showurl',False)
kwargs['target']=target # we want target to be kwarg for LiftURL
k=self.urlkey(kwargs)
if k not in self.urls:
if showurl:
log.debug("Calling LiftURL with {}".format(kwargs))
self.urls[k]=LiftURL(base=node,**kwargs) #needs base and target to be sensible; attribute?
else:
log.log(4,"URL key found: {} ({})".format(k,self.urls[k].url))
if self.urls[k].base == node:
log.log(4,"Same base {}, moving on.".format(node))
else:
log.log(4,"Different base of same tag ({}; {}≠{}), rebasing."
"".format(node.tag,self.urls[k].base,node))
self.urls[k].rebase(node)
if showurl:
log.info("Using URL {}".format(self.urls[k].url))
return self.urls[k] #These are LiftURL objects
def makenewguid(self):
from random import randint
log.info("Making a new unique guid")
"""f'{int:x}:' gives int in lowercase hexidecimal"""
def gimmeint():
return f'{randint(0, 15):x}'
def rxi(y):
o=''
for i in range(y):
o+=gimmeint()
return o
allguids=list(self.guids)+list(self.senseids)
guid=allguids[0]
while guid in allguids:
guid=rxi(8)+'-'+rxi(4)+'-'+rxi(4)+'-'+rxi(4)+'-'+rxi(12)
return guid
def addentry(self, showurl=False, **kwargs):
# kwargs are ps, analang, glosslang, langform, glossform,glosslang2,
# glossform2
log.info("Adding an entry")
self.makenewguid()
guid=senseid=self.makenewguid()
while guid == senseid:
senseid=self.makenewguid()
log.info('newguid: {}'.format(guid))
log.info('newsenseid: {}'.format(senseid))
now=getnow()
analang=kwargs['analang']
entry=ET.SubElement(self.nodes, 'entry', attrib={
'dateCreated':now,
'dateModified':now,
'guid':guid,
'id':(kwargs['form'][analang]+'_'+str(guid))
})
lexicalunit=ET.SubElement(entry, 'lexical-unit', attrib={})
"""Just adding citation, not lexeme forms, with this function,
though we need the lexeme field (above) to be there"""
# form=ET.SubElement(lexicalunit, 'form',
# attrib={'lang':analang})
# text=ET.SubElement(form, 'text')
# text.text=kwargs['form'][analang]
"""At some point, I'll want to distinguish between these two"""
citation=ET.SubElement(entry, 'citation', attrib={})
form=ET.SubElement(citation, 'form', attrib={'lang':analang})
text=ET.SubElement(form, 'text')
text.text=kwargs['form'][analang]
del kwargs['form'][analang] #because we're done with this.
sense=ET.SubElement(entry, 'sense', attrib={'id':senseid})
grammaticalinfo=ET.SubElement(sense, 'grammatical-info',
attrib={'value':kwargs['ps']})
definition=ET.SubElement(sense, 'definition')
for glosslang in kwargs['form']: #now just glosslangs
form=ET.SubElement(definition, 'form',
attrib={'lang':glosslang})
text=ET.SubElement(form, 'text')
text.text=kwargs['form'][glosslang]
gloss=ET.SubElement(sense, 'gloss',
attrib={'lang':glosslang})
text=ET.SubElement(gloss, 'text')
text.text=kwargs['form'][glosslang]
self.write()
"""Since we added a guid and senseid, we want to refresh these"""
self.getguids()
self.getsenseids()
return senseid
def evaluatenode(self,node):
if node is None:
log.info("Sorry, this didn't return a node: {}".format(node))
return
if node.text is not None:
try:
l=ast.literal_eval(node.text)
except SyntaxError: #if the literal eval doesn't work, it's a string
l=node.text
if type(l) != list: #in case eval worked, but didn't produce a list
log.log(2,"One item: {}; {}".format(l, type(l)))
l=[l,]
else:
log.log(2,"empty verification list found")
l=list()
return l
"""Make this a class!!!"""
def legacylangconvert(self):
formnodes=self.nodes.findall(".//form")
formlangs=set([i.get('lang') for i in formnodes])
langs=self.analangs+self.glosslangs
langs=set([i for i in langs if i])
log.info("looking to convert pylangs for {}".format(langs))
for lang in langs:
for flang in pylanglegacy(lang),pylanglegacy2(lang):
if flang in formlangs:
log.info("Found {}; converting to {}".format(flang,
pylang(lang)))
for n in self.nodes.findall(".//form[@lang='{}']"
"".format(flang)):
# log.info("{}; {}".format(n.tag,n.attrib))
n.set('lang',pylang(lang))
def modverificationnode(self,senseid,vtype,ftype,analang,**kwargs):
# use self.verificationtextvalue(profile,ftype,lang=None,value=None)
"""this node stores a python symbolic representation, specific to an
analysis language"""
showurl=kwargs.get('showurl')
add=kwargs.get('add',None)
rms=kwargs.get('rms',[])
addifrmd=kwargs.get('addifrmd',False) #not using this anywhere; point?
textnode, fieldnode, sensenode=self.addverificationnode(
senseid,vtype,ftype,analang)
# prettyprint(textnode)
# prettyprint(fieldnode)
l=self.evaluatenode(textnode) #this is the python evaluation of textnode
# log.info("l (before): {}>".format(l))
# prettyprint(textnode)
changed=False
i=len(l)
for rm in rms:
if rm != None and rm in l:
i=l.index(rm) #be ready to replace
l.remove(rm)
changed=True
if (add != None and add not in l #if there, v-if rmd, or not changing
and (addifrmd == False or changed == True)):
l.insert(i,add) #put where removed from, if done.
changed=True
textnode.text=str(l)
# log.info("l (after): {}> (changed: {})".format(l,changed))
# prettyprint(textnode)
if changed:
self.updatemoddatetime(senseid=senseid,write=kwargs.get('write'))
# log.info("Empty node? {}; {}".format(textnode.text,l))
if not l:
log.debug("removing empty verification node from this sense")
sensenode.remove(fieldnode)
# else:
# log.info("Not removing empty node")
def getverificationnodevaluebyframe(self,senseid,vtype,ftype,analang,frame):
# use self.verificationtextvalue(profile,ftype,lang=None,value=None)
raise
# log.info("{}; {}; {}; {}; {}".format(senseid,vtype,ftype,analang,frame))
nodes=self.getverificationnode(senseid,vtype,ftype,analang)
vft=nodes[0] #this is a text node
l=self.evaluatenode(vft) #this is the python evaluation of vf.text
# log.info("text: {}; vf: {}".format(l,vf.text))
values=[]
if l is not None:
for field in l:
# log.info("field value: {}".format(field))
if frame in field:
values.append(field)
return values
def legacyverificationconvert(self):
# This is used only on boot, to categorically convert any fields where
# text was kept in the field, rather than in a form node
# start_time=time.time() testing only
nfixed=0
# This is used in cases where form@lang wasn't specified, so now we make
# it up, and trust the user can fix if this is guessed wrong
try:
lang=pylang(self.analang)
except AttributeError:
return #if there is no analang, there are no legacy fields either
#any verification field, anywhere:
allfieldnames=[i.get('type') for i in self.nodes.findall(".//field")]
fieldnames=[i for i in set(allfieldnames) if i and 'verification' in i]
for fieldname in fieldnames:
vf=self.nodes.findall(".//field[@type='{}']".format(fieldname))
for f in vf:
if not nodehasform(f):
nfixed+=1
log.info("Found legacy verification node ({}):"
"".format(fieldname))
prettyprint(f)
t=f.text
f.text=None
Node.makeformnode(f,lang=lang,text=t)
log.info("Converted to:")
prettyprint(f)
# log.info("Found {} legacy verification nodes in {} seconds".format(
log.info("Found {} legacy verification nodes".format(
nfixed,
# time.time()-start_time)
))
def getverificationnode(self,senseid,vtype,ftype,analang):
raise
sensenode=node=self.getsensenode(senseid=senseid)
if node is None:
log.info("Sorry, this didn't return a node: {}".format(senseid))
return
pylang=pylang(analang)
vf=sensenode.find("field[@type='{} {} verification']/form[@lang='{}']"
"/text/../..".format(vtype,ftype,pylang))
vft=sensenode.find("field[@type='{} {} verification']/form[@lang='{}']"
"/text".format(vtype,ftype,pylang))
return vft,vf,sensenode #textnode, fieldnode, sensenode
def addverificationnode(self,senseid,vtype,ftype,analang):
# use self.verificationtextvalue(profile,ftype,lang=None,value=None)
raise
# This no longer accounts for legacy fields, as those should be
# converted at boot.
vft,vf,sensenode=self.getverificationnode(senseid,vtype,ftype,analang)
# log.info("vft: {}, vf: {}, sensenode: {}".format(vft,vf,sensenode))
# prettyprint(vft)
# prettyprint(vf)
t=None #this default will give no text node value
if not isinstance(vft,ET.Element): #only then add fields
# log.info("Empty vft; adding verification field")
vf=Node(sensenode, tag='field',
attrib={'type':"{} {} verification".format(vtype,
ftype)})
vft=vf.makeformnode(lang=pylang(analang),text=t,gimmetext=True)
return vft,vf,sensenode #textnode, fieldnode, sensenode
def getentries(self):
self.entries=[Entry(self.nodes,i,annotationlang=self.annotationlang)
for i in self.nodes
if i.tag == 'entry']
# self.nentries=len(self.entries)
# log.info("nentries: {}".format(self.nentries))
self.entries=[i for i in self.entries if i.sense]
self.nentries=len(self.entries)
# log.info("nentries: {}".format(self.nentries))
def getsenses(self):
self.senses=[i for j in self.entries for i in j.senses]
self.nsenses=len(self.senses)
def slicebyid(self):
self.entrydict={i.guid:i for i in self.entries}
self.sensedict={i.id:i for i in self.senses}
self.guids=self.entrydict.keys()
self.nguids=len(self.guids)
self.senseids=self.sensedict.keys()
self.nsenseids=len(self.guids)
def slicebyps(self):
#This can be converted to by profile in main.py
self.entriesbyps={ps:[i for i in self.entries
if i.sense.psvalue() == ps
]
for ps in self.pss
}
self.sensesbyps={ps:[i for i in self.senses if i.psvalue() == ps]
for ps in self.pss
}
def slicebyerror(self):
keys=set([(i.cawln,', '.join(i.collectionglosses)) for i in self.senses
if not i.imgselectiondir
])
errors={k:
[i.id for i in self.senses
if not i.imgselectiondir
if i.cawln == k[0]
if ', '.join(i.collectionglosses) == k[1]
]
for k in keys
}
# log.info("Errors ({}): {}".format(len(errors),errors))
if keys:
log.info("keys ({}): {}".format(len(keys),list(keys)[:min(len(keys)-1,5)]))
for cawl,glosses in list(errors)[:min(len(errors),5)]:
log.error("Neither CAWL line nor English glosses point "
"to a real directory, so I can't tell which image "
"directory to use for these senses. "
"\nFurthermore, I don't have both the line and glosses, "
"so I can't construct a directory name to write to: "
"{}-{} ({}): {}"
"".format(cawl,glosses,len(errors[(cawl,glosses)]),
errors[(cawl,glosses)][:min(len(errors[(cawl,glosses)]),5)]))
def slicebylx(self):
#This can be converted to by profile in main.py
self.entriesbylx={l:{t:[j for j in self.entries
if t == j.lx.textvaluebylang(l)
]
for t in [i.lx.textvaluebylang(l)
for i in self.entries]
if t #don't give None keys
}
for l in self.analangs
}
def slicebylc(self):
#This can be converted to by profile in main.py
self.entriesbylc={l:{t:[j for j in self.entries
if t == j.lc.textvaluebylang(l)
]
for t in [i.lc.textvaluebylang(l)
for i in self.entries]
if t #don't give None keys
}
for l in self.analangs
}
def slicebypl(self):
#This can be converted to by profile in main.py
self.entriesbypl={l:{t:[j for j in self.entries
if t == j.plvalue('Plural',l)
]
for t in [i.plvalue('Plural',l)
for i in self.entries]
}
for l in self.analangs
}
def slicebyimp(self):
#This can be converted to by profile in main.py
self.entriesbyimp={l:{i.imp.textvaluebylang(l):i}
for i in self.entries
if hasattr(i,'imp')
for l in self.analangs
if l in i.imp.forms
}
def slicebyftype(self):
self.entriesbyftype={f:{l:{i.fields[f].textvaluebylang(lang=l):i}}
for i in self.entries
for f in i.fields
for l in self.analangs
if l in i.fields[f].forms
}
self.sensesbyftype={f:{l:{t:[i for i in self.senses
if f in i.fields
if t == i.fields[f].textvaluebylang(l)
]
}}
for i in self.senses
for f in i.fields
for l in self.analangs
if l in i.fields[f].forms
for t in [i.fields[f].textvaluebylang(l)]
}
# log.info("senses: {}".format(self.senses))
# log.info("nsenses: {}".format(len(self.senses)))
def getentrynode(self,**kwargs):
if not kwargs:
return self.entries #these are class Entry
else:
return self.get('entry',**kwargs).get() #these are not
def getsensenode(self,**kwargs):
# log.info("senseid: {}".format(senseid))
x=self.get('sense',**kwargs,
# showurl=True
).get()
# log.info("x: {}".format(x))
if x:
return x[0]
def addmodexamplefields(self,**kwargs):
"""WRONG: framed now contains a dictionary for analang, to store different
forms for lx, lc, pl and imp. So we need to find that (only) by
framed.framed[analang][ftype] glosses are still by
framed.framed[analang], as those fields are not typically glossed
independently
"""
log.info(_("Adding values (in lift.py) : {}").format(kwargs))
#These should always be there:
senseid=kwargs.get('senseid')
location=kwargs.get('location')
fieldtype=kwargs.get('fieldtype','tone') # needed? ever not 'tone'?
oldtonevalue=kwargs.get('oldfieldvalue',None)
showurl=kwargs.get('showurl',False)
# ftype=kwargs.get('ftype')
if not oldtonevalue:
exfieldvalue=self.get("example/tonefield/form/text",
senseid=senseid,
location=location,
showurl=showurl
).get('node')
else:
exfieldvalue=self.get("example/tonefield/form/text",
senseid=senseid,
tonevalue=oldtonevalue, #to clear just "NA" values
showurl=showurl,
location=location
).get('node')
# Set values for any duplicates, too. Don't leave inconsisted data.
tonevalue=kwargs.get('fieldvalue') #don't test for this above
analang=kwargs.get('analang')
write=kwargs.get('write',False)
framed=kwargs.get('framed',None)
if framed:
forms=framed.framed #because this should always be framed, with correct form
glosslangs=framed.glosslangs
if exfieldvalue:
for e in exfieldvalue:
e.text=tonevalue
# If we modify the tone value, check for form and gloss conformity:
if framed: #if it's specified, that is...
formvaluenode=self.get("example/form/text", senseid=senseid,
analang=analang, location=location, showurl=True).get('node')
if formvaluenode:
formvaluenode=formvaluenode[0]
if forms[analang] != formvaluenode.text:
log.debug("Form changed! ({}≠{})".format(
forms[analang],
formvaluenode.text))
formvaluenode.text=forms[analang]
elif analang in forms:
log.error("Found example with tone value field, but no form "
"field? ({}-{}); adding".format(senseid,location))
example=self.get("example", senseid=senseid,
location=location, showurl=True).get('node')
Node.makeformnode(example[0],analang,forms[analang])
glossesnode=self.get("example/translation",
senseid=senseid,
location=location,
showurl=showurl
).get('node')
#If the glosslang data isn't all provided, ignore it.
for lang in [g for g in glosslangs if g in forms and forms[g]]:
glossvaluenode=self.get("form/text",
node=glossesnode[0], senseid=senseid,
glosslang=lang,
location=location,
showurl=showurl
).get('node')
log.debug("glossvaluenode: {}".format(glossvaluenode))
if glossvaluenode:
glossvaluenode=glossvaluenode[0]
if forms[lang] != glossvaluenode.text:
log.debug("Gloss changed! ({}≠{})".format(forms[lang],
glossvaluenode.text))
glossvaluenode.text=forms[lang]
elif lang in forms:
log.debug("Gloss missing for lang {}; adding".format(lang))
Node.makeformnode(glossesnode[0],lang,forms[lang])
elif not framed:
log.error("No node found, nor form info provided! {}-{}"
"".format(senseid,location))
else: #If not already there, make it.
log.info("Didn't find that example already there, creating it...")
sensenode=self.getsensenode(senseid=senseid)
if sensenode is None:
log.info("Sorry, this didn't return a node: {}".format(senseid))
return
attrib={'source': 'AZT sort on {}'.format(getnow())}
p=Node(sensenode, tag='example', attrib=attrib)
p.makeformnode(analang,forms[analang])
"""Until I have reason to do otherwise, I'm going to assume these
fields are being filled in in the glosslang language."""
fieldgloss=Node(p,tag='translation',attrib={'type':'Frame translation'})
for lang in glosslangs:
if lang in forms:
fieldgloss.makeformnode(lang,forms[lang])
exfieldvalue=p.makefieldnode(fieldtype,glosslangs[0],text=tonevalue,
gimmetext=True)
p.makefieldnode('location',glosslangs[0],text=location)
if write:
self.write()
self.updatemoddatetime(senseid=senseid,write=write)
def forminnode(self,node,value):
"""Returns True if `value` is in *any* text node child of any form child
of node: [node/'form'/'text' = value] Is this needed?"""
for f in node.findall('form'):
for t in f.findall('text'):
if t.text == value:
return True
return False
def convertalltodecomposed(self):
"""Do we want/need this? Not using anywhere..."""
for form in self.nodes.findall('.//form'):
if form.get('lang') in self.analangs:
for t in form.findall('.//text'):
t.text=rx.makeprecomposed(t.text)
def findduplicateforms(self):
"""This removes duplicate form nodes in lx or lc nodes, not much point.
"""
dup=False
for entry in self.nodes:
formparents=entry.findall('lexical-unit')+entry.findall('citation')
for fp in formparents:
for lang in self.analangs:
forms=fp.findall('form[@lang="{}"]'.format(lang))
if len(forms) >1:
log.info("Found multiple form fields in an entry: {}"
"".format([x.find('text').text for x in forms]))
dup=True
if not dup:
log.info("No duplicate form fields were found in the lexicon.")
def findduplicateexamples(self):
def noninteger(x):
try:
int(x)
except (ValueError,TypeError):
return x
emptytextnode=EmptyTextNodePlaceholder()
dup=False
senses=self.nodes.findall('entry/sense')
for sense in senses:
t = threading.Thread(target=self.findduplicateexample,
args=(sense,noninteger,emptytextnode))
t.start()
def findduplicateexample(self,sense,noninteger,emptytextnode):
senseid=sense.get('id')
for l in self.locations:
examples=sense.findall('example/field[@type="location"]/'
'form[text="{}"]/../..'.format(l)) #'senselocations'
if len(examples)>1:
log.error("Found multiple/duplicate examples (of the same "
"location ({}) in the same sense ({}): {})"
"".format(l,senseid,[
x.findall('form[@lang="{}"]/text'.format(lang)).text
for x in examples
for lang in self.analangs
if x.find('form[@lang="{}"]/text'.format(lang))]))
"""Before implementing the following, we need a test for
presence of audio file link, and different tone values,
including which to preserve if different (i.e., not '')"""
# for e in examples[1:]:
# sense.remove(e)
dup=True
nodes={}
uniq={}
first={}
langs=self.analangs+self.glosslangs
for n in self.analangs:
nodes['al-'+n]=[]
for n in self.glosslangs:
nodes['gl-'+n]=[]
for n in ['value']:
nodes[n]=[]
for example in examples:
for lang in self.analangs:
# log.info("looking for {} (analang) data".format(lang))
l=example.findall("form[@lang='{}']/text"
"".format(lang))
"""I actually don't want data from alternate analangs.
A→Z+T should be producing examples with exactly
one analang (at least for now), so if I find one
here, that should be good."""
# if not l:
# log.info("empty node found for {}".format(lang))
# l=[emptytextnode] #must distinguish empty/missing nodes
nodes['al-'+lang].extend(l)
for lang in self.glosslangs:
# log.info("looking for {} (glosslang) data".format(lang))
g=example.findall("translation/form[@lang='{}']"
"/text".format(lang))
if not g:
# log.info("No text node found for {}".format(lang))
g=[emptytextnode]
for gi in g:
# if gi.text and ('‘' in gi.text or '’' in gi.text):
gi.text=rx.stripquotes(gi.text)
nodes['gl-'+lang].extend(g)
#This should ultimately have [@lang='{}'].analang
t=example.findall("field[@type='tone']/form/text")
if not t:
log.info("empty tone node found")
t=[emptytextnode]
nodes['value'].extend(t)
for n in nodes:
"""Collect all distinct values, not considering
missing nodes (None) or values that differ only by
initial or final quotes. Notably, i.text as None is
allowed, as this is an important difference to track"""
uniq[n]=list(set([rx.stripquotes(textornone(i))
for i in nodes[n]
if i is not None]))
if [n for n in uniq if len(uniq[n]) >1]: #any multiples
# if not [l for l in langs if len(uniq[l]) >1]: #nonlang
if not [l for l in uniq if len(uniq[l]) >1
if l != 'value']: #nonlang
nonint=[noninteger(j) for j in uniq['value'] #nonint
if noninteger(j) is not None]
nonnone=[j for j in uniq['value'] #nonint
if j is not None]
if not nonint or len(nonint) >1:
if nonnone and len(nonnone) == 1:
"""This is where we save an integer tone
value, and ditch a None value."""
log.info("A single non-None value found: {}"
"".format(nonnone[0]))
savevalue=nonnone[0]
else:
log.info("Sorry, I don't know how to combine "
"these example values: {} ({}) "
"(senseid: {})"
"".format(uniq[n],n,senseid))
continue
else: #only one noninteger tone value
savevalue=nonint[0]
log.info("A single non-integer value found: {}"
"".format(nonint[0]))
log.info("These examples have the same "
"language data, so we will merge their "
"tone values, if possible. ({})"
"".format(uniq))
for example in examples:
#This should ultimately have [@lang='{}'].analang
l=[i.text for i in example.findall(
'form[@lang="{}"]/text'
''.format(self.analangs[0]))
if i]
url=("field[@type='tone']/form[text='{}']"
"".format(savevalue))
if not example.find(url):
et=example.find(
"field[@type='tone']/form/text"
)
if not et:
et=emptytextnode
log.info("Removing duplicate ({}) "
"example with value: {}"
"".format(l, et.text))
sense.remove(example)
else:
log.info("Keeping duplicate ({}) "
"example with value: {}".format(l,
savevalue))
else:
log.info("It looks like we are dealing with "
"different language data in the examples, so "
"you will need to resolve this manually: {}"
"".format(uniq))
else:
log.info("It looks like all examples have all the same "
"values, so we're deleting all but the first: {}"
"".format(uniq))
for example in examples[1:]:
sense.remove(example)
# self.write()
# else:
# if not dup:
# log.info("No duplicate examples (same sense and location) were "
# "found in the lexicon.")
def addtoneUF(self,senseid,group,analang,guid=None,**kwargs):
showurl=kwargs.get('showurl',False)
write=kwargs.get('write',True)
node=self.get('sense',senseid=senseid,showurl=showurl).get()
if node == []:
log.info("Sorry, this didn't return a node: guid {}; senseid {}"
"".format(guid,senseid))
return
t=self.get('field/form/text',node=node[0],ftype='tone',
showurl=showurl
).get()
if t == []:
# log.info("No sense level tone field found, making")
p=Node(node[0],tag='field',attrib={'type':'tone'})
p.makeformnode(analang,text=group)
else:
# log.info("Sense level tone field found ({}), using".format(
# t[0].text
# ))
t[0].text=group
# t=self.get('field/form/text',node=node[0],ftype='tone',
# showurl=True
# ).get()
# log.info("Sense level tone field now ‘{}’.".format(t[0].text))
# prettyprint(node[0])
self.updatemoddatetime(guid=guid,senseid=senseid,write=write)
"""<field type="tone">
<form lang="en"><text>toneinfo for sense.</text></form>
</field>"""
def addmediafields(self, node, url, lang,**kwargs):
"""This fuction will add an XML node to the lift tree, like a new
example field."""
"""The program should know before calling this, that there isn't
already the relevant node --since it is agnostic of what is already
there."""
showurl=kwargs.get('showurl',False)
write=kwargs.get('write',True)
# log.info("Adding {} value to {} location".format(url,node))
possibles=node.findall("form[@lang='{lang}']/text".format(lang=lang))
for possible in possibles:
# log.info("Checking possible: {} (index: {})".format(possible,
# possibles.index(possible)))
if hasattr(possible,'text'):
if possible.text == url:
# log.info("This one is already here; not adding.")
return
form=Node(node,tag='form',attrib={'lang':lang})
t=form.maketextnode(text=url)
# prettyprint(node)
"""Can't really do this without knowing what entry or sense I'm in..."""
if write:
self.write()
def addmodcitationfields(self,entry,langform,lang):
citation=entry.find('citation')
if citation is None:
citation=Node(entry, tag='citation')
citation.makeformnode(lang=lang,text=langform)
def addpronunciationfields(self,**kwargs):
"""This fuction will add an XML node to the lift tree, like a new
pronunciation field."""
"""The program should know before calling this, that there isn't
already the relevant node."""
guid=kwargs.get('guid',None)
senseid=kwargs.get('senseid',None)
if guid is not None:
node=self.get('entry',guid=guid,showurl=True).get()[0]
elif senseid is not None:
node=self.get('entry',senseid=senseid,showurl=True).get()[0]
analang=kwargs.get('analang')
glosslangs=kwargs.get('glosslangs')
forms=kwargs.get('framed').forms
fieldtype=kwargs.get('fieldtype','tone')
fieldvalue=kwargs.get('fieldvalue')
location=kwargs.get('location')
p=Node(node, tag='pronunciation')
p.makeformnode(lang=analang,text=forms[analang])
p.makefieldnode(type=fieldtype,lang=glosslangs[0],text=fieldvalue)
for lang in glosslangs:
p.makefieldnode(type='gloss',lang=lang,text=forms[lang])
p.maketraitnode(type='location',value=location)
if senseid is not None:
self.updatemoddatetime(senseid=senseid)
elif guid is not None:
self.updatemoddatetime(guid=guid)
self.write()
"""End here:""" #build up, or down?
"""<pronunciation>
<form lang="gnd"><text>dìve</text></form>
<field type="tone">
<form lang="gnd"><text>LM</text></form>
</field>
<trait name="location" value="Isolation"/>
</pronunciation>
<pronunciation>
<form lang="gnd"><text>Languageform here</text></form>
<field type="tone"><form lang="en"><text>HL representation</text></form></field>
<field type="gloss"><form lang="fr"><text>Gloss here</text></form></field>
<trait name="location" value="With Other Stuff" />
</pronunciation>
"""
def updatemoddatetime(self,guid=None,senseid=None,write=True):
"""This updates the fieldvalue, ignorant of current value."""
if senseid is not None:
surl=self.get('sense',senseid=senseid) #url object
for s in surl.get():
s.attrib['dateModified']=getnow() #node
eurl=self.get('entry',senseid=senseid) #url object
for e in eurl.get():
e.attrib['dateModified']=getnow() #node
elif guid is not None: #only if no senseid given
for e in self.get('entry',guid=guid).get():
e.attrib['dateModified']=getnow()
if write:
self.write()
def read(self):
"""this parses the lift file into an entire ElementTree tree,
for reading or writing the LIFT file."""
log.info("Reading LIFT file: {}".format(self.filename))
self.tree,self.nodes=readxml(self.filename)
# self.tree=ET.parse(self.filename)
# self.nodes=self.tree.getroot()
log.info("Done reading LIFT file.")
"""This returns the root node of an ElementTree tree (the entire
tree as nodes), to edit the XML."""
def writegzip(self,dir=None,filename=None):
import gzip
if filename is None:
filename=self.filename
compressed=filename+'_'+getnow()+'.gz'
if dir != None:
compressed=os.path.join(dir,compressed)
data=self.write()
with open(filename,'r') as d:
data=d.read()
with gzip.open(compressed, "wt") as f:
f.write(data)
f.close()
d.close()
return compressed
def writelzma(self,filename=None):
try:
import lzma
except ImportError:
from backports import lzma
"""This writes changes back to XML."""
"""When this goes into production, change this:"""
#self.tree.write(self.filename, encoding="UTF-8")
if filename is None:
filename=self.filename
compressed=filename+'_'+getnow()+'.7z'
data=self.write()
with open(filename,'r') as d:
data=d.read()
# with lzma.LZMAFile(compressed,'w') as t:
with lzma.open(compressed, "wt") as f:
f.write(data)
f.close()
# t.write(d)
# t.close()
d.close()
return compressed
def write(self,filename=None):
"""This writes changes back to XML."""
if filename is None:
filename=self.filename
write=0
nodes=self.nodes
xmlfns.indent(self.nodes)
tree=ET.ElementTree(self.nodes)
try:
tree.write(filename+'.part', encoding="UTF-8")
write=True
except:
log.error("There was a problem writing to partial file: {}"
"".format(filename+'.part'))
if write:
try:
os.replace(filename+'.part',filename)
except:
log.error("There was a problem writing {} file to {} "
"directory. This is what's here: {}".format(
pathlib.Path(filename).name, pathlib.Path(filename).parent,
os.listdir(pathlib.Path(filename).parent)))
def getanalangs(self):
"""These are ordered by frequency in the database"""
self.audiolangs=[]
self.analangs=[]
lxl=[j for k in [i.lx.langs()
for i in self.entries]
for j in k
]
lcl=[j for k in [i.lc.langs()
for i in self.entries]
for j in k
]
pronl=[j for k in [i.ph.langs()
for i in self.entries
if hasattr(i,'ph')]
for j in k
]
langsbycount=collections.Counter(lxl+lcl+pronl)
self.analangs=[i[0] for i in langsbycount.most_common()
if i[0] != 'x-unk'] #I assume will never analyze this