-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.py
More file actions
executable file
·2377 lines (2268 loc) · 141 KB
/
Copy pathvalidate.py
File metadata and controls
executable file
·2377 lines (2268 loc) · 141 KB
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
# Copyright © 2023–2026 Dan Zeman <zeman@ufal.mff.cuni.cz>
import sys
import io
import os.path
import argparse
import traceback
# According to https://stackoverflow.com/questions/1832893/python-regex-matching-unicode-properties,
# the regex module has the same API as re but it can check Unicode character properties using \p{}
# as in Perl.
#import re
import regex as re
import unicodedata
from functools import cmp_to_key # for custom partial sorting
# Optionally we can access Wikidata API through the requests library.
# Install the library with pip3 install requests (or python3 -m pip install requests).
# If the library is not installed, this script should still work, just skipping any dereferences of Wikidata codes.
try:
import requests
requests_installed = True
except ImportError:
requests_installed = False
THISDIR=os.path.dirname(os.path.realpath(os.path.abspath(__file__))) # The folder where this script resides.
# Global variables:
curr_fname = None # Current input file
curr_line = 0 # Current line in the input file
sentence_line = 0 # The line in the input file on which the current sentence starts
sentence_id = None # The most recently read sentence id
error_counter = {} # key: error type value: error count
warn_on_missing_files = set() # langspec files which you should warn about in case they are missing (can be deprel, edeprel, feat_val, tokens_w_space)
def warn(msg, testclass, testlevel, testid, lineno=0, explanation=None):
"""
Print the error/warning message.
If lineno is 0, print the number of the current line (most recently read from input).
If lineno is < 0, print the number of the first line of the current sentence.
If lineno is > 0, print lineno (probably pointing somewhere in the current sentence).
If explanation contains a string and this is the first time we are reporting
an error of this type, the string will be appended to the main message. It
can be used as an extended explanation of the situation.
"""
global curr_fname, curr_line, sentence_line, sentence_id, error_counter, args
error_counter[testclass] = error_counter.get(testclass, 0)+1
if args.max_err > 0 and error_counter[testclass] > args.max_err:
if error_counter[testclass] == args.max_err + 1:
print(('...suppressing further errors regarding ' + testclass), file=sys.stderr)
pass # supressed
elif not args.quiet:
if explanation and error_counter[testclass] == 1:
msg += ' ' + explanation
if len(args.input) > 1: # several files, should report which one
if curr_fname=='-':
fn = '(in STDIN) '
else:
fn = '(in '+os.path.basename(curr_fname)+') '
else:
fn = ''
sent = ''
node = ''
# Global variable (last read sentence id): sentence_id
if sentence_id:
sent = ' Sent ' + sentence_id
if lineno > 0:
print("[%sLine %d%s%s]: [L%d %s %s] %s" % (fn, lineno, sent, node, testlevel, testclass, testid, msg), file=sys.stderr)
elif lineno < 0:
print("[%sLine %d%s%s]: [L%d %s %s] %s" % (fn, sentence_line, sent, node, testlevel, testclass, testid, msg), file=sys.stderr)
else:
print("[%sLine %d%s%s]: [L%d %s %s] %s" % (fn, curr_line, sent, node, testlevel, testclass, testid, msg), file=sys.stderr)
def debugnode(nid, node_dict):
"""
Takes node id (variable). Returns a string that also contains node concept
and aligned words if available.
"""
result = nid
if nid in node_dict:
concept = 'UNKNOWN CONCEPT'
alignment = 'UNALIGNED'
if 'concept' in node_dict[nid]:
concept = node_dict[nid]['concept']
if 'alignment' in node_dict[nid] and node_dict[nid]['alignment']['tokstr'] != '':
alignment = node_dict[nid]['alignment']['tokstr']
result = "%s (%s '%s')" % (nid, concept, alignment)
return result
#------------------------------------------------------------------------------
# Support functions.
#------------------------------------------------------------------------------
ws_re = re.compile(r"^\s+$")
def is_whitespace(line):
return ws_re.match(line)
tws_re = re.compile(r"\s+$")
def has_trailing_whitespace(line):
return tws_re.search(line)
def remove_trailing_whitespace(line):
return tws_re.sub('', line)
lws_re = re.compile(r"^\s+")
def remove_leading_whitespace(line):
return lws_re.sub('', line)
#punct_re = re.compile(r"^[-.,;:\?\!\(\)]$")
punct_re = re.compile(r"^\pP+$")
def is_punctuation(x):
return punct_re.match(x)
comment_re = re.compile(r"(.)\#.*")
def remove_inline_comment(line):
return remove_trailing_whitespace(comment_re.sub(r"\1", line))
# For some languages (Arapaho, Navajo, Sanapana, Kukama), the initial block
# contains multiple lines with inter-linear glossing. Each of these lines should
# start with a header but these headers are different in Arapaho vs. the others.
# For our standard, see https://github.com/ufal/UMR/issues/9.
ilg_re = re.compile(r"^(Index|Words|Word Gloss \([a-z]{2,3}\)|Part of Speech|Morphemes|Morpheme Gloss \([a-z]{2,3}\)|Morpheme Category|Sentence|Sentence Gloss \([a-z]{2,3}\)):\s*(.+)")
ilg_old_re = re.compile(r"^(Words|tx|Morphemes|mb|Morpheme Gloss\((?:English|Spanish)\)|ge|Morpheme Cat|ps|Word Gloss|(?:English|Spanish) Sent Gloss:|tr)\s+(.+)")
def is_ilg(line):
return ilg_re.match(line) or ilg_old_re.match(line)
root_re = re.compile(r"^\(")
def is_root(line):
return root_re.match(line)
###!!! See also relation_re below. We should not define the same thing twice. r"^:[-A-Za-z0-9]+" (at this low level we should allow single character after the colon, but we should still require that the first character is a letter)
attr_re = re.compile(r"^:[A-Za-z][-A-Za-z0-9]*")
def is_attribute(line):
return attr_re.match(line)
# Variables: Although UMR 1.0 data avoids non-English letters in the variables,
# the Boulder team says they should not be an issue, as UMR is supposed to work
# for many languages; so we allow them. We require that each variable starts
# with 's' and number (presumably sentence number), although that is not
# necessary for UMR to work either.
variable_re = re.compile(r"^s[0-9]+\p{Ll}+[0-9]*")
align_re = re.compile(r"^s[0-9]+\p{Ll}+[0-9]*:")
def is_alignment(line):
return align_re.match(line)
def shorten(string):
return string if len(string) < 25 else string[:20]+'[...]'
wikidata_cache = {}
def get_wikidata_label(id):
if requests_installed:
if id in wikidata_cache:
return wikidata_cache[id]
# Create parameters.
params = {
'action': 'wbgetentities',
'ids': id,
'format': 'json',
'languages': 'en'
}
# Fetch the API.
data = fetch_wikidata(params)
if data:
# Extract the label.
data = data.json()
label = str(data['entities'][id]['labels']['en']['value'])
wikidata_cache[id] = label
return label
else:
return ''
else:
return ''
def fetch_wikidata(params):
url = 'https://www.wikidata.org/w/api.php'
try:
return requests.get(url, params=params)
except:
return '' # error
#==============================================================================
# Level 1 tests. Only technical format backbone.
#==============================================================================
sentid_re = re.compile(r"^#\s*::\s*(snt[0-9]+)(?:\s|$)")
sentid_tokens_re = re.compile(r"^#\s*::\s*(snt[0-9]+)\s+(.+)$")
def sentences(inp, args):
"""
`inp` a file-like object yielding lines as unicode
`args` are needed for choosing the tests
This function does elementary checking of the input and yields one
sentence at a time from the input stream.
This function is a generator. The caller can call it in a 'for x in ...'
loop. In each iteration of the caller's loop, the generator will generate
the next sentence, that is, it will read the next sentence from the input
stream. (Technically, the function returns an object, and the object will
then read the sentences within the caller's loop.)
A sentence in a UMR file consists of:
- Comment lines. Their first character is '#'. Some of them may contain
machine-readable metadata. Others can be ignored.
(Note: With the option --allow-inline-comments, comments can occur also
on other lines. Everything from the # character to the end of the line
will then be ignored, the part before the # character is a line of
another type.)
- Empty lines. An empty line separates two annotation blocks of the same
sentence (e.g., document level graph from sentence level graph). Two empty
lines separate sentences. Empty lines must not occur inside annotation
blocks, e.g., inside the sentence level graph.
- Interlinear glossing lines. The line starts with a header that specifies
type of the contents on the line, then there are space-separated words
or morphs or their glosses (possible in multiple languages).
- Graph lines (either sentence level graph, or document level annotation).
They may start with whitespace (' ', "\t") and they typically do, except
for the first line of the graph. Whitespace can be ignored (but we may
want to report trailing whitespace, just to tidy up). After whitespace,
there must be either the opening bracket ('(') or a colon (':'). One or
more closing brackets may occur at the end of the line; they are never
put on a line of their own.
- Every opening bracket must be immediately followed by a variable id (e.g.,
's1p'), a slash ('/'), and a concept string.
- Every colon must be immediately followed by a relation/attribute label,
then whitespace and either an atomic value, or a string in double quotes,
or the opening bracket of a child node.
- The alignment block has its own type of lines. It starts with a variable
id of a concept node in the sentence graph, followed by a colon and
a space, followed by an integer range (e.g. '2-2'). These are 1-based
indices of tokens that represent the concept node on the surface. '0-0'
means that the concept is not overtly represented on the surface.
"""
# global curr_line ... holds the 1-based number of the last read line; used in error messages
# global sentence_line ... holds the 1-based number of the first line of the current sentence; used in error messages
# global sentence_id ... holds the id of the current sentence (or better: the most recently seen sentence id); used in error messages
global curr_line, sentence_line, sentence_id
blocks = [] # List of the annotation blocks (sentence annotation, document level annotation) of the current sentence.
bline0 = None # Number of the line where the current block starts.
comments = [] # List of the comment lines at the beginning of the current block.
lines = [] # List of the non-comment lines of the current block.
corrupt = False # In case of spurious line check the remaining lines of the sentence but do not yield the sentence for further processing.
testlevel = 1
testclass = 'Format'
for line_counter, line in enumerate(inp):
curr_line = line_counter + 1
if not sentence_line:
sentence_line = curr_line
if not bline0:
bline0 = curr_line
line = line.rstrip("\n")
if args.inline_comments:
line = remove_inline_comment(line)
if has_trailing_whitespace(line):
if args.check_trailing_whitespace:
testid = 'trailing-whitespace'
testmessage = 'Trailing whitespace should be removed.'
warn(testmessage, testclass, testlevel, testid)
line = remove_trailing_whitespace(line)
validate_unicode_normalization(line)
# Unlike trailing whitespace, leading whitespace is legitimate (indentation) but we ignore it anyway.
line = remove_leading_whitespace(line)
if not line: # empty line means end of block (and possibly end of sentence)
if comments or lines: # end of an annotation block
blocks.append({'line0': bline0, 'comments': comments, 'lines': lines})
bline0 = None
comments = []
lines = []
# Sentences typically have 4 annotation blocks: 1. intro; 2. sentence level; 3. alignment; 4. document level.
# If we see more blocks, maybe someone forgot to add a second empty line between sentences.
if len(blocks) > 4:
testid = 'too-many-blocks'
testmessage = 'Too many annotation blocks within one sentence. There should be two empty lines after each sentence.'
warn(testmessage, testclass, testlevel, testid)
corrupt = True
else: # two consecutive empty lines = end of sentence
if blocks:
if len(blocks) < 4:
testid = 'too-few-blocks'
testmessage = 'Too few annotation blocks in the sentence. Expected introduction, sentence level graph, alignment, and document level annotation.'
warn(testmessage, testclass, testlevel, testid)
corrupt = True
if not corrupt:
yield blocks
blocks = []
bline0 = None
comments = []
lines = []
corrupt = False
else:
testid = 'extra-empty-line'
testmessage = 'Spurious empty line. One empty line is expected after every annotation block and two after every sentence.'
warn(testmessage, testclass, testlevel=testlevel, testid=testid)
elif line[0] == '#':
# We will really validate sentence ids later. But now we want to remember
# everything that looks like a sentence id and use it in the error messages.
# Line numbers themselves may not be sufficient if we are reading multiple
# files from a pipe.
match = sentid_re.match(line)
if match:
sentence_id = match.group(1)
if not lines: # before sentence
comments.append(line)
else:
testid = 'misplaced-comment'
testmessage = 'Spurious comment line. Comments are only allowed before a sentence.'
warn(testmessage, testclass, testlevel, testid)
corrupt = True
elif is_root(line) or is_attribute(line) or is_alignment(line):
lines.append(line)
elif is_ilg(line):
lines.append(line)
else:
testid = 'invalid-line'
testmessage = f"Spurious line: '{line}'. All non-empty lines should start with the '#' character, opening bracket, colon, node variable id, or one of the interlinear glossing keywords. Leading whitespace is permitted."
warn(testmessage, testclass, testlevel, testid)
corrupt = True
else: # end of file
if blocks: # These should have been yielded on an empty line!
testid = 'missing-empty-line'
testmessage = 'Missing empty line after the last sentence.'
warn(testmessage, testclass, testlevel, testid)
if len(blocks) < 4:
testid = 'too-few-blocks'
testmessage = 'Too few annotation blocks in the sentence. Expected introduction, sentence level graph, alignment, and document level annotation.'
warn(testmessage, testclass, testlevel, testid)
corrupt = True
if not corrupt:
yield blocks
#------------------------------------------------------------------------------
# Low-level tests: character encoding, line break format etc.
#------------------------------------------------------------------------------
def validate_unicode_normalization(text):
"""
Tests that letters composed of multiple Unicode characters (such as a base
letter plus combining diacritics) conform to NFC normalization (canonical
decomposition followed by canonical composition).
"""
normalized_text = unicodedata.normalize('NFC', text)
if text != normalized_text:
# Find the first unmatched character and include it in the report.
firsti = -1
inpfirst = ''
nfcfirst = ''
for i in range(len(text)):
if text[i] != normalized_text[i]:
firsti = i
inpfirst = unicodedata.name(text[i])
nfcfirst = unicodedata.name(normalized_text[i])
break
testlevel = 1
testclass = 'Unicode'
testid = 'unicode-normalization'
testmessage = f"Unicode not normalized: character[{firsti}] is {inpfirst}, should be {nfcfirst}."
warn(testmessage, testclass, testlevel, testid)
def validate_newlines(inp):
"""
To be called after the input has been read. If the input uses '\r\n' as
line breaks, inp.newlines will have been set to '\r\n'. For Unix-style
line breaks, it should be empty. (Not sure what happens if the file is
inconsistent and line breaks are mixed.)
"""
if inp.newlines and inp.newlines != '\n':
testlevel = 1
testclass = 'Format'
testid = 'non-unix-newline'
testmessage = 'Only the unix-style LF line terminator is allowed.'
warn(testmessage, testclass, testlevel, testid)
#==============================================================================
# Level 2 tests. General structure, known and/or unique labels, but not rules
# for concept-relation or attribute-value compatibility.
#==============================================================================
# Concepts: Normally we expect lowercase letters, hyphens and Western digits;
# but the letters can be non-English and there can probably be various other
# markers. On the other hand, we must disallow the parentheses, and we should
# also disallow '#' so that comment handling is easier (although strictly speaking
# comments should not occur here).
concept_re = re.compile(r"^[^\s\(\):\#]+")
relation_re = re.compile(r"^:[-A-Za-z0-9]+")
string_re = re.compile(r'^"([^"]+)"') # occasionally there are even string values with spaces
number_re = re.compile(r"^([0-9]+(?:[\.:][0-9]+)?)(\s|\)|$)") # we need to recognize following closing bracket but we must not consume it; besides decimal '.', also recognize ':' in time expressions ('23:45')
atom_re = re.compile(r"^([-+a-z0-9]+)(\s|\)|$)") # enumerated values of some attributes, including integers (but also '3rd'), polarity values ('+', '-'), or node references ('s5p')
# Atoms do not contain uppercase letters. We still need a regular expression for
# such erroneous atoms so that we can recognize them and do not issue misleading
# error messages.
ucatom_re = re.compile(r"^([-+a-z0-9A-Z_]+)(\s|\)|$)")
tokrng_re = re.compile(r"^0-0|([1-9][0-9]*)-([1-9][0-9]*)$")
tokrngs_re = re.compile(r"^(?:0-0|([1-9][0-9]*)-([1-9][0-9]*)(,\s*[1-9][0-9]*-[1-9][0-9]*)*)$")
tokrng_neg_re = re.compile(r"^-1--1|0-0|([1-9][0-9]*)-([1-9][0-9]*)$")
tokrngs_neg_re = re.compile(r"^(?:-1--1|0-0|([1-9][0-9]*)-([1-9][0-9]*)(,\s*[1-9][0-9]*-[1-9][0-9]*)*)$")
svariable_re = re.compile(r"^s[0-9]+s0")
dvariable_re = re.compile(r"^([a-z]+(?:-[a-z91]+)*|s[0-9]+[a-z]+[0-9]*)(\s|\)|$)") # constant or concept node id (constant may include the have-condition-91 predicate, which is why [91] is also allowed); we need to recognize following closing bracket but we must not consume it
def validate_sentence_metadata(sentence, known_ids, args):
"""
Verifies the first annotation block of a sentence. There must be a comment
line with the sentence id, and the list of tokens. Various datasets use
various formats and there is no specification, so we try to standardize it
(see https://github.com/ufal/UMR/issues/9). The validator should be able to
digest the other formats, too, but it should issue a warning.
"""
testlevel = 2
testclass = 'Metadata'
matched=[]
tokens_included = False
iline = sentence[0]['line0']
# Thanks to previous tests, we can be sure that there is at least one
# annotation block. However, we cannot be sure that it has comments.
if 'comments' in sentence[0]:
comments = sentence[0]['comments']
for c in comments:
# The first block either contains one comment line with both the
# sentence id and the sequence of tokens (English, Chinese), or it
# contains multiple lines, the first one is a comment with sentence id
# only, the following ones are not comments and they contain inter-
# linear glosses, starting with the actual token sequence.
match = sentid_re.match(c)
if match:
# So the comment starts with a sentence id. Does it also contain the
# sequence of tokens?
match2 = sentid_tokens_re.match(c)
if match2:
matched.append(match2)
tokens_included = True
testid = 'tokens-in-sent-id-comment'
testmessage = 'The comment line with the sentence id seems to also contain the tokens, which is deprecated.'
warn(testmessage, 'Warning', testlevel, testid, lineno=-1)
else:
matched.append(match)
iline += len(sentence[0]['comments'])
if not matched:
testid = 'missing-sent-id'
testmessage = 'Missing sentence id.'
warn(testmessage, testclass, testlevel, testid, lineno=-1)
elif len(matched)>1:
testid = 'multiple-sent-id'
testmessage = 'Multiple sentence ids.'
warn(testmessage, testclass, testlevel, testid, lineno=-1)
else:
# Uniqueness of sentence ids should be tested treebank-wide, not just file-wide.
# For that to happen, all three files should be tested at once.
sid = matched[0].group(1)
if sid in known_ids:
testid = 'non-unique-sent-id'
testmessage = f"Non-unique sentence id '{sid}'."
warn(testmessage, testclass, testlevel, testid, lineno=-1)
known_ids.add(sid)
# Save the tokens so we can access them later.
if tokens_included:
if args.check_wide_space:
tokens = matched[0].group(2).split(' ')
empty_tokens = [x for x in tokens if x == '' or ws_re.match(x)]
if empty_tokens:
testid = 'empty-token'
testmessage = f"Empty token (i.e., two consecutive whitespace characters) in '{matched[0].group(2)}'."
warn(testmessage, testclass, testlevel, testid, lineno=-1)
else:
tokens = re.split(r"\s+", matched[0].group(2))
sentence[0]['tokens'] = tokens
if sentence[0]['lines']:
testid = 'tokens-vs-ilg'
testmessage = "No interlinear glosses are expected because tokens were already introduced on the sentence id line."
warn(testmessage, testclass, testlevel, testid, lineno=sentence[0]['line0']+len(sentence[0]['comments']))
# If we did not find the sentence id line or it did not contain the tokens,
# look for the interlinear glosses (including the tokens).
if not tokens_included:
if not 'lines' in sentence[0]:
testid = 'missing-ilg'
testmessage = "Expecting list of tokens/words (optionally followed by interlinear glosses)."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
sentence[0]['tokens'] = []
return
# Following the proposal in https://github.com/ufal/UMR/issues/9,
# we expect the following lines in any order (header is capitalized
# and terminated by a colon, ':'; glosses can be in any language,
# with the ISO 639 language code given in parentheses):
# Index: 1 2 3 4
# Words: Estonci volili parlament .
# Word Gloss (en): Estonians elected parliament .
# Word Gloss (es): Estonios eligieron parlamento .
# Morphemes: Eston -c -i vol -il -i parlament -0 .
# Morpheme Gloss (en): Estonia DERIV PL.NOM elect PAST.PART PL.MASC.ANIM parliament SG.ACC .
# Morpheme Gloss (es): Estonia DERIV PL.NOM elegir PAST.PART PL.MASC.ANIM parlamento SG.ACC .
# Sentence: Estonci volili parlament.
# Sentence Gloss (en): Estonians elected the parliament.
# Sentence Gloss (es): Los estonios eligieron el parlamento.
# The following was not in the proposal but it is used in Arapaho/Navajo and it makes sense, so why not allow it.
# Part of Speech: PROPN VERB NOUN PUNCT
# Morpheme Category: adv v:PRVB v:QUAL ...
lines = sentence[0]['lines']
ilg = {}
for l in lines:
match = ilg_re.match(l)
match_old = ilg_old_re.match(l)
if match:
header = match.group(1)
items = re.split(r"\s+", match.group(2))
if header in ilg:
testid = 'duplicate-ilg'
testmessage = f"Duplicate interlinear glossing line '{header}' (first occurred on line {ilg[header]['line0']})."
warn(testmessage, 'Warning', testlevel, testid, lineno=iline)
ilg[header] = {'items': items, 'line0': iline}
if header == 'Words':
sentence[0]['tokens'] = items
elif match_old:
header = match_old.group(1)
testid = 'obsolete-ilg'
testmessage = f"Obsolete interlinear glossing line (obsolete line header '{header}'; see https://github.com/ufal/UMR/issues/9)."
warn(testmessage, 'Warning', testlevel, testid, lineno=iline)
if header == 'Words' or header == 'tx':
tokens = re.split(r"\s+", match_old.group(2))
sentence[0]['tokens'] = tokens
else:
testid = 'invalid-ilg'
testmessage = "Spurious interlinear glossing line (unknown line header; see https://github.com/ufal/UMR/issues/9)."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
iline += 1
# Check whether the interlinear glosses make sense.
if not 'Words' in ilg:
testid = 'missing-words'
testmessage = "Missing the Words line in the first annotation block."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
sentence[0]['tokens'] = []
elif args.check_ilg:
m = len(ilg['Words']['items'])
for header in ilg:
if re.match(r"^(Index|Word Gloss \([a-z]{2,3}\))$", header):
n = len(ilg[header]['items'])
if n != m:
testid = 'word-gloss-mismatch'
testmessage = f"Words have {m} items while {header} have {n} items."
warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
elif header == 'Index':
expected_items = str([str(x) for x in range(len(ilg[header]['items'])+1)[1:]])
observed_items = str(ilg[header]['items'])
if observed_items != expected_items:
testid = 'spurious-index'
testmessage = f"Incorrect index sequence.\n Expected: {expected_items}\n Observed: {observed_items}"
warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
elif header == 'Morphemes':
n = len(ilg[header]['items'])
if n < m:
testid = 'morpheme-word-mismatch'
testmessage = f"Words have {m} items while Morphemes have only {n} items."
warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
elif re.match(r"^Morpheme Gloss \([a-z]{2,3}\)$", header):
n = len(ilg[header]['items'])
if 'Morphemes' in ilg:
o = len(ilg['Morphemes']['items'])
if n != o:
testid = 'morpheme-gloss-mismatch'
testmessage = f"Morphemes have {o} items while {header} have {n} items."
warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
else:
testid = 'missing-morphemes'
testmessage = "There are morpheme glosses but the Morphemes line is missing."
warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
elif header == 'Sentence':
n = len(ilg[header]['items'])
if n > m:
testid = 'sentence-word-mismatch'
testmessage = f"Words have only {m} items while the (untokenized) Sentence has {n} items."
warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
# It is not clear whether we should require this. Anyway, the difference between Words and Sentence is only tokenization.
# And if the detokenized sentence is important, then it is actually important regardless of whether there is Sentence Gloss.
#elif re.match(r"^Sentence Gloss \([a-z]{2,3}\)$", header):
# if not 'Sentence' in ilg:
# testid = 'missing-sentence'
# testmessage = "There is a sentence gloss but the (original) Sentence line is missing."
# warn(testmessage, testclass, testlevel, testid, lineno=ilg[header]['line0'])
def dominates(var0, var1, node_dict, tried):
"""
Finds out whether node var0 dominates node var1 in the sentence graph,
i.e., there is a directed path whose first relation starts in var0 and last
relation ends in var1. The function is used primarily to detect cycles,
hence it will ignore the few relations that are allowed to form cycles,
:quote and :modal-predicate.
Parameters
----------
var0 : str
Variable (id) of the dominating node.
var1 : str
Variable (id) of the dominated node.
node_dict : dictionary indexed by node ids (variables)
Database of all nodes found in the corpus so far.
tried : dictionary indexed by node ids (variables)
Prevents unbounded recursion. Supply {} when calling the function from
outside. It will record traversing var0 before calling itself recursively.
Returns
-------
bool
True if var0 dominates var1 in the directed graph.
"""
tried[var0] = True
if var0 in node_dict and 'relations' in node_dict[var0]:
children = [r['value'] for r in node_dict[var0]['relations'] if r['type'] == 'node' and r['dir'] == 'out' and r['value'] in node_dict and r['relation'] not in [':quote', ':modal-predicate']]
if var1 in children:
return True
for c in children:
if not c in tried and dominates(c, var1, node_dict, tried):
return True
return False
def validate_sentence_graph(sentence, node_dict, args):
"""
Verifies the second annotation block of a sentence: the sentence level graph.
"""
testlevel = 2
testclass = 'Sentence'
# Does the comment confirm that we are processing the sentence level graph?
if args.check_block_headers:
heading_found = False
if 'comments' in sentence[1]:
for c in sentence[1]['comments']:
if c == '# sentence level graph:':
heading_found = True
break
if not heading_found:
testid = 'missing-heading-sentence-level'
testmessage = "Missing heading comment '# sentence level graph:'."
warn(testmessage, testclass, testlevel, testid, lineno=sentence[1]['line0'])
# Besides the global node dictionary, we also need a temporary one for the
# current sentence because node references in the sentence level graph
# cannot lead to other sentences.
sentence[1]['nodes'] = set()
node_references = []
stack = []
# expecting_node_definition means we either just read ':something', which is
# a relation or an attribute, and we did not see a value (atom / number /
# string / node reference), or it is the beginning of the sentence. In both
# cases we are expecting a full node definition.
expecting_node_definition = True
# graph_ended makes sure that if there is premature topmost closing bracket,
# the following relation will be reported as error.
graph_ended = False
graph_ended_error_reported = False
iline = sentence[1]['line0'] + len(sentence[1]['comments']) - 1
for l in sentence[1]['lines']:
iline += 1
pline = l # processed line: we will remove stuff from pline but not from l
while pline:
if graph_ended:
testid = 'premature-closing-bracket'
testmessage = f"Not expecting further content after the topmost closing bracket, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
graph_ended_error_reported = True
break
# Remove leading whitespace.
pline = remove_leading_whitespace(pline)
if pline.startswith('('):
if not expecting_node_definition:
testid = 'extra-opening-bracket'
testmessage = f"Not expecting full node definition (opening bracket), found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
pline = remove_leading_whitespace(pline[1:])
# Now expecting variable identifier, e.g., 's15p'.
if variable_re.match(pline):
match = variable_re.match(pline)
variable = match.group(0)
# If this is not the root node (i.e., there is something on
# the stack), store this node as the child of the most recently
# added relation of the parent node. (There must be at least
# one relation and its type must be 'node'. Should we verify
# it?)
if stack:
node_dict[stack[-1]]['relations'][-1]['value'] = variable
pline = remove_leading_whitespace(variable_re.sub('', pline, 1))
# The variable serves as node id. It must be unique.
if variable in node_dict:
testid = 'non-unique-node-id'
testmessage = f"The node id (variable) '{variable}' is not unique. It was previously used on line {node_dict[variable]['line0']}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
# We have read the beginning of a node, including its
# variable. Now store it both globally and locally.
node_dict[variable] = {'variable': variable, 'line0': iline}
sentence[1]['nodes'].add(variable)
stack.append(variable)
# Now expecting the slash ('/').
if pline.startswith('/'):
pline = remove_leading_whitespace(pline[1:])
# Now expecting the concept string, e.g., 'have-quant-91'.
if concept_re.match(pline):
match = concept_re.match(pline)
concept = match.group(0)
node_dict[variable]['concept'] = concept
pline = remove_leading_whitespace(concept_re.sub('', pline, 1))
else:
testid = 'missing-concept-string'
testmessage = f"Expected concept string, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
testid = 'missing-slash'
testmessage = f"Expected slash and concept string, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
testid = 'missing-variable'
testmessage = f"Expected node variable id, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
expecting_node_definition = False
elif relation_re.match(pline):
if expecting_node_definition:
testid = 'missing-node-definition'
testmessage = f"Expected full node definition (opening bracket), found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
match = relation_re.match(pline)
relation = match.group(0)
# Save the outgoing relation at the parent node.
# The topmost node on the stack is the parent node for this relation.
# But beware that the stack may be empty if the relation occurred unexpectedly!
parent = {'relations': []}
if stack:
parent_id = stack[-1]
parent = node_dict[parent_id]
if not 'relations' in parent:
parent['relations'] = []
# Some relations, like ':ARG0', should occur at most once per parent node,
# but others, like ':mod', can occur multiple times, so we assume that
# multiple same relations are allowed in general and we will rule out
# specific cases at level 3.
parent['relations'].append({'relation': relation, 'dir': 'out', 'line0': iline})
pline = remove_leading_whitespace(relation_re.sub('', pline, 1))
# Besides a child node, there may be a numeric or string value.
expecting_node_definition = False
if string_re.match(pline):
match = string_re.match(pline)
string = match.group(1) # without the quotation marks
parent['relations'][-1]['type'] = 'string'
parent['relations'][-1]['value'] = string
pline = remove_leading_whitespace(string_re.sub('', pline, 1))
elif variable_re.match(pline):
match = variable_re.match(pline)
variable = match.group(0)
node_references.append({'variable': variable, 'line0': iline})
if args.check_forward_references and not variable in sentence[1]['nodes']:
if variable in node_dict:
testid = 'cross-sentence-reference'
testmessage = f"Sentence level graph cannot contain nodes from other sentences: '{variable}' was defined on line {node_dict[variable]['line0']}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
testid = 'unknown-node-id'
testmessage = f"The node id (variable) '{variable}' is unknown. No such node has been defined so far."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
parent['relations'][-1]['type'] = 'node'
parent['relations'][-1]['value'] = variable
if args.check_cycles and dominates(variable, variable, node_dict, {}):
testid = 'cycle'
testmessage = f"The node '{variable}', first defined on line {node_dict[variable]['line0']}, dominates itself. Use inverted relations to prevent cycles."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
pline = remove_leading_whitespace(variable_re.sub('', pline, 1))
elif atom_re.match(pline):
match = atom_re.match(pline)
atom = match.group(1)
parent['relations'][-1]['type'] = 'atom'
parent['relations'][-1]['value'] = atom
pline = remove_leading_whitespace(match.group(2)+atom_re.sub('', pline, 1))
# Integer numbers would be consumed as atoms. This is here because of decimal numbers.
elif number_re.match(pline):
match = number_re.match(pline)
number = match.group(1)
parent['relations'][-1]['type'] = 'atom'
parent['relations'][-1]['value'] = number
pline = remove_leading_whitespace(match.group(2)+number_re.sub('', pline, 1))
# Uppercase atoms are an error but we should recognize and report them now,
# otherwise there would be 'missing-node-deifnition' later, which would be
# a misleading message.
elif ucatom_re.match(pline):
match = ucatom_re.match(pline)
atom = match.group(1)
parent['relations'][-1]['type'] = 'atom'
parent['relations'][-1]['value'] = atom
pline = remove_leading_whitespace(match.group(2)+ucatom_re.sub('', pline, 1))
testid = 'value-wrong-chars'
testmessage = f"Atomic attribute value must contain neither uppercase letters nor underscores: '{atom}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
parent['relations'][-1]['type'] = 'node'
expecting_node_definition = True
elif pline.startswith(')'):
if expecting_node_definition:
testid = 'missing-node-definition'
testmessage = f"Expected full node definition (opening bracket), found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
# Check for the matching opening bracket and remove it from the stack.
if not stack:
testid = 'extra-closing-bracket'
testmessage = f"Found closing bracket but there was no matching opening bracket: '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
stack.pop()
# If we just popped the topmost node, the graph is over and it must not start again.
if not stack:
graph_ended = True
pline = remove_leading_whitespace(pline[1:])
expecting_node_definition = False
else:
if expecting_node_definition:
testid = 'missing-node-definition'
testmessage = f"Expected full node definition (opening bracket), found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
testid = 'invalid-sentence-level'
testmessage = f"Expected colon or closing bracket, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
pline = ''
# If there is extra content after the topmost closing bracket, do not complain about every line again.
if graph_ended_error_reported:
break
# The stack should be empty now. If not, then there were missing closing brackets!
if stack:
n = len(stack)
stacknodes = str(stack)
testid = 'missing-closing-bracket'
testmessage = f"Sentence graph ended without closing {n} nodes: {stacknodes}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
# If checking forward references is on, we know that all node references
# either lead to defined nodes or have been reported as errors. But if it is
# off, we must check for undefined nodes now.
if not args.check_forward_references:
for r in node_references:
# If the node exists elsewhere in the
if not r['variable'] in sentence[1]['nodes']:
if r['variable'] in node_dict:
testid = 'cross-sentence-reference'
testmessage = f"Sentence level graph cannot contain nodes from other sentences: '{r['variable']}' was defined on line {node_dict[r['variable']]['line0']}."
warn(testmessage, testclass, testlevel, testid, lineno=r['line0'])
else:
testid = 'unknown-node-id'
testmessage = f"The node id (variable) '{r['variable']}' is unknown. No such node is defined in this sentence."
warn(testmessage, testclass, testlevel, testid, lineno=r['line0'])
# Make sure that every node has the relation list, even if empty.
for nid in sentence[1]['nodes']:
node = node_dict[nid]
if not 'concept' in node:
node['concept'] = ''
if not 'relations' in node:
node['relations'] = []
# Make sure that every relation has the information we expect, even if empty.
for r in node['relations']:
if not 'value' in r:
r['value'] = ''
# So far we know for each node its outgoing relations.
# Store also the incoming relations at each node.
for nid in sentence[1]['nodes']:
node = node_dict[nid]
outrel = [r for r in node['relations'] if r['dir'] == 'out' and r['type'] == 'node']
for r in outrel:
if r['value'] in node_dict:
node_dict[r['value']]['relations'].append({'dir': 'in', 'type': 'node', 'value': nid, 'relation': r['relation'], 'line0': r['line0']})
def validate_alignment(sentence, node_dict, args):
"""
Verifies the third annotation block of a sentence: the alignment of the
concept nodes from the sentence level graph in the second block to the
tokens listed in the first block.
"""
testlevel = 2
testclass = 'Alignment'
global tokrng_re
global tokrngs_re
# UMR 1.0 occasionally has -1--1 instead of 0-0 and we can accept it on demand.
# Nevertheless, by default it is considered an error. See also
# https://github.com/ufal/UMR/issues/14
if not args.check_nonnegative_alignment:
tokrng_re = tokrng_neg_re
tokrngs_re = tokrngs_neg_re
# Does the comment confirm that we are processing the concept-token alignment?
if args.check_block_headers:
heading_found = False
if 'comments' in sentence[2]:
for c in sentence[2]['comments']:
if c == '# alignment:':
heading_found = True
break
if not heading_found:
testid = 'missing-heading-alignment'
testmessage = "Missing heading comment '# alignment:'."
warn(testmessage, testclass, testlevel, testid, lineno=sentence[2]['line0'])
iline = sentence[2]['line0'] + len(sentence[2]['comments']) - 1
for l in sentence[2]['lines']:
iline += 1
pline = l # processed line: we will remove stuff from pline but not from l
if variable_re.match(pline):
match = variable_re.match(pline)
variable = match.group(0)
if not variable in sentence[1]['nodes']:
testid = 'unknown-node-id'
testmessage = f"The node id (variable) '{variable}' is unknown. No such node is defined in this sentence."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
pline = remove_leading_whitespace(variable_re.sub('', pline, 1))
if pline.startswith(':'):
pline = remove_leading_whitespace(pline[1:])
if tokrngs_re.match(pline):
match = tokrngs_re.match(pline)
if match.group(3):
# The span is discontiguous and group(3) contains the tail.
spans = re.split(r",\s*", pline)
else:
spans = [pline]
t1 = -1
for s in spans:
# If we previously matched tokrngs_re, we must now match tokrng_re.
match = tokrng_re.match(s)
if match.group(0) == '0-0' or match.group(0) == '-1--1':
# The regular expression tokrngs_re excludes '0-0' combined with anything else,
# so we do not have to check it here.
t0 = 0
t1 = 0
else:
old_t1 = t1
t0 = int(match.group(1))
t1 = int(match.group(2))
if t0 <= old_t1 + 1:
testid = 'invalid-token-range'
testmessage = f"Index of the first token of segment '{s}' must be at least {old_t1+2} because the previous segment ended at {old_t1}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
if t1 < t0:
testid = 'invalid-token-range'
testmessage = f"Index of the first token '{t0}' is greater than the index of the second token '{t1}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
t1 = t0
tmax = len(sentence[0]['tokens'])
if t0 > tmax:
testid = 'invalid-token-index'
testmessage = f"Index of the first token '{t0}' is out of range: there are {tmax} tokens."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
t0 = tmax
if t1 > tmax:
testid = 'invalid-token-index'
testmessage = f"Index of the second token '{t1}' is out of range: there are {tmax} tokens."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
t1 = tmax
# The variable should be in node_dict. If it is not there,
# it has been already reported as error; but we must survive it here.
if variable in node_dict:
# If the variable is in node_dict, it also must be a variable defined in the current sentence.
if variable not in sentence[1]['nodes']:
testid = 'cross-sentence-alignment'
testmessage = f"Alignment cannot contain nodes from other sentences: '{variable}' was defined on line {node_dict[variable]['line0']}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
# There must not be multiple lines aligning the same node.
# However, there may be multiple alignment segments on one alignment line of the node.
elif 'alignment' in node_dict[variable]:
if node_dict[variable]['alignment']['line0'] != iline:
testid = 'duplicate-alignment'
testmessage = f"Repeated alignment of node '{variable}'. It was already specified as {str(node_dict[variable]['alignment']['tokids'])} on line {node_dict[variable]['alignment']['line0']}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
tokids = node_dict[variable]['alignment']['tokids']
tokids.extend(range(t0, t1+1))
tokens = [sentence[0]['tokens'][tokid-1] for tokid in tokids] if len(tokids) > 1 or tokids[0] != 0 else []
node_dict[variable]['alignment']['tokids'] = tokids
node_dict[variable]['alignment']['tokstr'] = ' '.join(tokens)
else:
tokids = []
tokids.extend(range(t0, t1+1))
tokens = [sentence[0]['tokens'][tokid-1] for tokid in tokids] if len(tokids) > 1 or tokids[0] != 0 else []
node_dict[variable]['alignment'] = {'tokids': tokids, 'tokstr': ' '.join(tokens), 'line0': iline}
else:
testid = 'invalid-token-range'
testmessage = f"Expected 1-based token index range, or multiple comma-separated ranges, or '0-0', found {pline}."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
testid = 'invalid-alignment'
testmessage = f"Expected colon, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
else:
testid = 'missing-variable'
testmessage = f"Expected node variable id, found '{pline}'."
warn(testmessage, testclass, testlevel, testid, lineno=iline)
# Check that all nodes in this sentence have an alignment.
# Even unaligned nodes should have alignment 0-0.
tokal = [False for x in sentence[0]['tokens']]
for n in sorted(sentence[1]['nodes']):
if not 'alignment' in node_dict[n]:
if args.check_complete_alignment:
testid = 'missing-alignment'
testmessage = f"Missing alignment of node '{n}'. Even unaligned nodes should be explicitly marked with '0-0'."
warn(testmessage, testclass, testlevel, testid, lineno=iline+1) # iline is now at the end of the alignment block
# We will later want to access the alignment, so set the default, i.e., unaligned.