/
framenet.py
3437 lines (2988 loc) · 128 KB
/
framenet.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
# Natural Language Toolkit: Framenet Corpus Reader
#
# Copyright (C) 2001-2021 NLTK Project
# Authors: Chuck Wooters <wooters@icsi.berkeley.edu>,
# Nathan Schneider <nathan.schneider@georgetown.edu>
# URL: <https://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
Corpus reader for the FrameNet 1.7 lexicon and corpus.
"""
import itertools
import os
import re
import sys
import textwrap
import types
from collections import OrderedDict, defaultdict
from itertools import zip_longest
from operator import itemgetter
from pprint import pprint
from nltk.corpus.reader import XMLCorpusReader, XMLCorpusView
from nltk.util import LazyConcatenation, LazyIteratorList, LazyMap
__docformat__ = "epytext en"
def mimic_wrap(lines, wrap_at=65, **kwargs):
"""
Wrap the first of 'lines' with textwrap and the remaining lines at exactly the same
positions as the first.
"""
l0 = textwrap.fill(lines[0], wrap_at, drop_whitespace=False).split("\n")
yield l0
def _(line):
il0 = 0
while line and il0 < len(l0) - 1:
yield line[: len(l0[il0])]
line = line[len(l0[il0]) :]
il0 += 1
if line: # Remaining stuff on this line past the end of the mimicked line.
# So just textwrap this line.
yield from textwrap.fill(line, wrap_at, drop_whitespace=False).split("\n")
for l in lines[1:]:
yield list(_(l))
def _pretty_longstring(defstr, prefix="", wrap_at=65):
"""
Helper function for pretty-printing a long string.
:param defstr: The string to be printed.
:type defstr: str
:return: A nicely formatted string representation of the long string.
:rtype: str
"""
outstr = ""
for line in textwrap.fill(defstr, wrap_at).split("\n"):
outstr += prefix + line + "\n"
return outstr
def _pretty_any(obj):
"""
Helper function for pretty-printing any AttrDict object.
:param obj: The obj to be printed.
:type obj: AttrDict
:return: A nicely formatted string representation of the AttrDict object.
:rtype: str
"""
outstr = ""
for k in obj:
if isinstance(obj[k], str) and len(obj[k]) > 65:
outstr += f"[{k}]\n"
outstr += "{}".format(_pretty_longstring(obj[k], prefix=" "))
outstr += "\n"
else:
outstr += f"[{k}] {obj[k]}\n"
return outstr
def _pretty_semtype(st):
"""
Helper function for pretty-printing a semantic type.
:param st: The semantic type to be printed.
:type st: AttrDict
:return: A nicely formatted string representation of the semantic type.
:rtype: str
"""
semkeys = st.keys()
if len(semkeys) == 1:
return "<None>"
outstr = ""
outstr += "semantic type ({0.ID}): {0.name}\n".format(st)
if "abbrev" in semkeys:
outstr += f"[abbrev] {st.abbrev}\n"
if "definition" in semkeys:
outstr += "[definition]\n"
outstr += _pretty_longstring(st.definition, " ")
outstr += f"[rootType] {st.rootType.name}({st.rootType.ID})\n"
if st.superType is None:
outstr += "[superType] <None>\n"
else:
outstr += f"[superType] {st.superType.name}({st.superType.ID})\n"
outstr += f"[subTypes] {len(st.subTypes)} subtypes\n"
outstr += (
" "
+ ", ".join(f"{x.name}({x.ID})" for x in st.subTypes)
+ "\n" * (len(st.subTypes) > 0)
)
return outstr
def _pretty_frame_relation_type(freltyp):
"""
Helper function for pretty-printing a frame relation type.
:param freltyp: The frame relation type to be printed.
:type freltyp: AttrDict
:return: A nicely formatted string representation of the frame relation type.
:rtype: str
"""
outstr = "<frame relation type ({0.ID}): {0.superFrameName} -- {0.name} -> {0.subFrameName}>".format(
freltyp
)
return outstr
def _pretty_frame_relation(frel):
"""
Helper function for pretty-printing a frame relation.
:param frel: The frame relation to be printed.
:type frel: AttrDict
:return: A nicely formatted string representation of the frame relation.
:rtype: str
"""
outstr = "<{0.type.superFrameName}={0.superFrameName} -- {0.type.name} -> {0.type.subFrameName}={0.subFrameName}>".format(
frel
)
return outstr
def _pretty_fe_relation(ferel):
"""
Helper function for pretty-printing an FE relation.
:param ferel: The FE relation to be printed.
:type ferel: AttrDict
:return: A nicely formatted string representation of the FE relation.
:rtype: str
"""
outstr = "<{0.type.superFrameName}={0.frameRelation.superFrameName}.{0.superFEName} -- {0.type.name} -> {0.type.subFrameName}={0.frameRelation.subFrameName}.{0.subFEName}>".format(
ferel
)
return outstr
def _pretty_lu(lu):
"""
Helper function for pretty-printing a lexical unit.
:param lu: The lu to be printed.
:type lu: AttrDict
:return: A nicely formatted string representation of the lexical unit.
:rtype: str
"""
lukeys = lu.keys()
outstr = ""
outstr += "lexical unit ({0.ID}): {0.name}\n\n".format(lu)
if "definition" in lukeys:
outstr += "[definition]\n"
outstr += _pretty_longstring(lu.definition, " ")
if "frame" in lukeys:
outstr += f"\n[frame] {lu.frame.name}({lu.frame.ID})\n"
if "incorporatedFE" in lukeys:
outstr += f"\n[incorporatedFE] {lu.incorporatedFE}\n"
if "POS" in lukeys:
outstr += f"\n[POS] {lu.POS}\n"
if "status" in lukeys:
outstr += f"\n[status] {lu.status}\n"
if "totalAnnotated" in lukeys:
outstr += f"\n[totalAnnotated] {lu.totalAnnotated} annotated examples\n"
if "lexemes" in lukeys:
outstr += "\n[lexemes] {}\n".format(
" ".join(f"{lex.name}/{lex.POS}" for lex in lu.lexemes)
)
if "semTypes" in lukeys:
outstr += f"\n[semTypes] {len(lu.semTypes)} semantic types\n"
outstr += (
" " * (len(lu.semTypes) > 0)
+ ", ".join(f"{x.name}({x.ID})" for x in lu.semTypes)
+ "\n" * (len(lu.semTypes) > 0)
)
if "URL" in lukeys:
outstr += f"\n[URL] {lu.URL}\n"
if "subCorpus" in lukeys:
subc = [x.name for x in lu.subCorpus]
outstr += f"\n[subCorpus] {len(lu.subCorpus)} subcorpora\n"
for line in textwrap.fill(", ".join(sorted(subc)), 60).split("\n"):
outstr += f" {line}\n"
if "exemplars" in lukeys:
outstr += "\n[exemplars] {} sentences across all subcorpora\n".format(
len(lu.exemplars)
)
return outstr
def _pretty_exemplars(exemplars, lu):
"""
Helper function for pretty-printing a list of exemplar sentences for a lexical unit.
:param sent: The list of exemplar sentences to be printed.
:type sent: list(AttrDict)
:return: An index of the text of the exemplar sentences.
:rtype: str
"""
outstr = ""
outstr += "exemplar sentences for {0.name} in {0.frame.name}:\n\n".format(lu)
for i, sent in enumerate(exemplars):
outstr += f"[{i}] {sent.text}\n"
outstr += "\n"
return outstr
def _pretty_fulltext_sentences(sents):
"""
Helper function for pretty-printing a list of annotated sentences for a full-text document.
:param sent: The list of sentences to be printed.
:type sent: list(AttrDict)
:return: An index of the text of the sentences.
:rtype: str
"""
outstr = ""
outstr += "full-text document ({0.ID}) {0.name}:\n\n".format(sents)
outstr += "[corpid] {0.corpid}\n[corpname] {0.corpname}\n[description] {0.description}\n[URL] {0.URL}\n\n".format(
sents
)
outstr += f"[sentence]\n"
for i, sent in enumerate(sents.sentence):
outstr += f"[{i}] {sent.text}\n"
outstr += "\n"
return outstr
def _pretty_fulltext_sentence(sent):
"""
Helper function for pretty-printing an annotated sentence from a full-text document.
:param sent: The sentence to be printed.
:type sent: list(AttrDict)
:return: The text of the sentence with annotation set indices on frame targets.
:rtype: str
"""
outstr = ""
outstr += "full-text sentence ({0.ID}) in {1}:\n\n".format(
sent, sent.doc.get("name", sent.doc.description)
)
outstr += f"\n[POS] {len(sent.POS)} tags\n"
outstr += f"\n[POS_tagset] {sent.POS_tagset}\n\n"
outstr += "[text] + [annotationSet]\n\n"
outstr += sent._ascii() # -> _annotation_ascii()
outstr += "\n"
return outstr
def _pretty_pos(aset):
"""
Helper function for pretty-printing a sentence with its POS tags.
:param aset: The POS annotation set of the sentence to be printed.
:type sent: list(AttrDict)
:return: The text of the sentence and its POS tags.
:rtype: str
"""
outstr = ""
outstr += "POS annotation set ({0.ID}) {0.POS_tagset} in sentence {0.sent.ID}:\n\n".format(
aset
)
# list the target spans and their associated aset index
overt = sorted(aset.POS)
sent = aset.sent
s0 = sent.text
s1 = ""
s2 = ""
i = 0
adjust = 0
for j, k, lbl in overt:
assert j >= i, ("Overlapping targets?", (j, k, lbl))
s1 += " " * (j - i) + "-" * (k - j)
if len(lbl) > (k - j):
# add space in the sentence to make room for the annotation index
amt = len(lbl) - (k - j)
s0 = (
s0[: k + adjust] + "~" * amt + s0[k + adjust :]
) # '~' to prevent line wrapping
s1 = s1[: k + adjust] + " " * amt + s1[k + adjust :]
adjust += amt
s2 += " " * (j - i) + lbl.ljust(k - j)
i = k
long_lines = [s0, s1, s2]
outstr += "\n\n".join(
map("\n".join, zip_longest(*mimic_wrap(long_lines), fillvalue=" "))
).replace("~", " ")
outstr += "\n"
return outstr
def _pretty_annotation(sent, aset_level=False):
"""
Helper function for pretty-printing an exemplar sentence for a lexical unit.
:param sent: An annotation set or exemplar sentence to be printed.
:param aset_level: If True, 'sent' is actually an annotation set within a sentence.
:type sent: AttrDict
:return: A nicely formatted string representation of the exemplar sentence
with its target, frame, and FE annotations.
:rtype: str
"""
sentkeys = sent.keys()
outstr = "annotation set" if aset_level else "exemplar sentence"
outstr += f" ({sent.ID}):\n"
if aset_level: # TODO: any UNANN exemplars?
outstr += f"\n[status] {sent.status}\n"
for k in ("corpID", "docID", "paragNo", "sentNo", "aPos"):
if k in sentkeys:
outstr += f"[{k}] {sent[k]}\n"
outstr += (
"\n[LU] ({0.ID}) {0.name} in {0.frame.name}\n".format(sent.LU)
if sent.LU
else "\n[LU] Not found!"
)
outstr += "\n[frame] ({0.ID}) {0.name}\n".format(
sent.frame
) # redundant with above, but .frame is convenient
if not aset_level:
outstr += "\n[annotationSet] {} annotation sets\n".format(
len(sent.annotationSet)
)
outstr += f"\n[POS] {len(sent.POS)} tags\n"
outstr += f"\n[POS_tagset] {sent.POS_tagset}\n"
outstr += "\n[GF] {} relation{}\n".format(
len(sent.GF), "s" if len(sent.GF) != 1 else ""
)
outstr += "\n[PT] {} phrase{}\n".format(
len(sent.PT), "s" if len(sent.PT) != 1 else ""
)
"""
Special Layers
--------------
The 'NER' layer contains, for some of the data, named entity labels.
The 'WSL' (word status layer) contains, for some of the data,
spans which should not in principle be considered targets (NT).
The 'Other' layer records relative clause constructions (Rel=relativizer, Ant=antecedent),
pleonastic 'it' (Null), and existential 'there' (Exist).
On occasion they are duplicated by accident (e.g., annotationSet 1467275 in lu6700.xml).
The 'Sent' layer appears to contain labels that the annotator has flagged the
sentence with for their convenience: values include
'sense1', 'sense2', 'sense3', etc.;
'Blend', 'Canonical', 'Idiom', 'Metaphor', 'Special-Sent',
'keepS', 'deleteS', 'reexamine'
(sometimes they are duplicated for no apparent reason).
The POS-specific layers may contain the following kinds of spans:
Asp (aspectual particle), Non-Asp (non-aspectual particle),
Cop (copula), Supp (support), Ctrlr (controller),
Gov (governor), X. Gov and X always cooccur.
>>> from nltk.corpus import framenet as fn
>>> def f(luRE, lyr, ignore=set()):
... for i,ex in enumerate(fn.exemplars(luRE)):
... if lyr in ex and ex[lyr] and set(zip(*ex[lyr])[2]) - ignore:
... print(i,ex[lyr])
- Verb: Asp, Non-Asp
- Noun: Cop, Supp, Ctrlr, Gov, X
- Adj: Cop, Supp, Ctrlr, Gov, X
- Prep: Cop, Supp, Ctrlr
- Adv: Ctrlr
- Scon: (none)
- Art: (none)
"""
for lyr in ("NER", "WSL", "Other", "Sent"):
if lyr in sent and sent[lyr]:
outstr += "\n[{}] {} entr{}\n".format(
lyr, len(sent[lyr]), "ies" if len(sent[lyr]) != 1 else "y"
)
outstr += "\n[text] + [Target] + [FE]"
# POS-specific layers: syntactically important words that are neither the target
# nor the FEs. Include these along with the first FE layer but with '^' underlining.
for lyr in ("Verb", "Noun", "Adj", "Adv", "Prep", "Scon", "Art"):
if lyr in sent and sent[lyr]:
outstr += f" + [{lyr}]"
if "FE2" in sentkeys:
outstr += " + [FE2]"
if "FE3" in sentkeys:
outstr += " + [FE3]"
outstr += "\n\n"
outstr += sent._ascii() # -> _annotation_ascii()
outstr += "\n"
return outstr
def _annotation_ascii(sent):
"""
Given a sentence or FE annotation set, construct the width-limited string showing
an ASCII visualization of the sentence's annotations, calling either
_annotation_ascii_frames() or _annotation_ascii_FEs() as appropriate.
This will be attached as a method to appropriate AttrDict instances
and called in the full pretty-printing of the instance.
"""
if sent._type == "fulltext_sentence" or (
"annotationSet" in sent and len(sent.annotationSet) > 2
):
# a full-text sentence OR sentence with multiple targets.
# (multiple targets = >2 annotation sets, because the first annotation set is POS.)
return _annotation_ascii_frames(sent)
else: # an FE annotation set, or an LU sentence with 1 target
return _annotation_ascii_FEs(sent)
def _annotation_ascii_frames(sent):
"""
ASCII string rendering of the sentence along with its targets and frame names.
Called for all full-text sentences, as well as the few LU sentences with multiple
targets (e.g., fn.lu(6412).exemplars[82] has two want.v targets).
Line-wrapped to limit the display width.
"""
# list the target spans and their associated aset index
overt = []
for a, aset in enumerate(sent.annotationSet[1:]):
for j, k in aset.Target:
indexS = f"[{a + 1}]"
if aset.status == "UNANN" or aset.LU.status == "Problem":
indexS += " "
if aset.status == "UNANN":
indexS += "!" # warning indicator that there is a frame annotation but no FE annotation
if aset.LU.status == "Problem":
indexS += "?" # warning indicator that there is a missing LU definition (because the LU has Problem status)
overt.append((j, k, aset.LU.frame.name, indexS))
overt = sorted(overt)
duplicates = set()
for o, (j, k, fname, asetIndex) in enumerate(overt):
if o > 0 and j <= overt[o - 1][1]:
# multiple annotation sets on the same target
# (e.g. due to a coordination construction or multiple annotators)
if (
overt[o - 1][:2] == (j, k) and overt[o - 1][2] == fname
): # same target, same frame
# splice indices together
combinedIndex = (
overt[o - 1][3] + asetIndex
) # e.g., '[1][2]', '[1]! [2]'
combinedIndex = combinedIndex.replace(" !", "! ").replace(" ?", "? ")
overt[o - 1] = overt[o - 1][:3] + (combinedIndex,)
duplicates.add(o)
else: # different frames, same or overlapping targets
s = sent.text
for j, k, fname, asetIndex in overt:
s += "\n" + asetIndex + " " + sent.text[j:k] + " :: " + fname
s += "\n(Unable to display sentence with targets marked inline due to overlap)"
return s
for o in reversed(sorted(duplicates)):
del overt[o]
s0 = sent.text
s1 = ""
s11 = ""
s2 = ""
i = 0
adjust = 0
fAbbrevs = OrderedDict()
for j, k, fname, asetIndex in overt:
if not j >= i:
assert j >= i, (
"Overlapping targets?"
+ (
" UNANN"
if any(aset.status == "UNANN" for aset in sent.annotationSet[1:])
else ""
),
(j, k, asetIndex),
)
s1 += " " * (j - i) + "*" * (k - j)
short = fname[: k - j]
if (k - j) < len(fname):
r = 0
while short in fAbbrevs:
if fAbbrevs[short] == fname:
break
r += 1
short = fname[: k - j - 1] + str(r)
else: # short not in fAbbrevs
fAbbrevs[short] = fname
s11 += " " * (j - i) + short.ljust(k - j)
if len(asetIndex) > (k - j):
# add space in the sentence to make room for the annotation index
amt = len(asetIndex) - (k - j)
s0 = (
s0[: k + adjust] + "~" * amt + s0[k + adjust :]
) # '~' to prevent line wrapping
s1 = s1[: k + adjust] + " " * amt + s1[k + adjust :]
s11 = s11[: k + adjust] + " " * amt + s11[k + adjust :]
adjust += amt
s2 += " " * (j - i) + asetIndex.ljust(k - j)
i = k
long_lines = [s0, s1, s11, s2]
outstr = "\n\n".join(
map("\n".join, zip_longest(*mimic_wrap(long_lines), fillvalue=" "))
).replace("~", " ")
outstr += "\n"
if fAbbrevs:
outstr += " (" + ", ".join("=".join(pair) for pair in fAbbrevs.items()) + ")"
assert len(fAbbrevs) == len(dict(fAbbrevs)), "Abbreviation clash"
return outstr
def _annotation_ascii_FE_layer(overt, ni, feAbbrevs):
"""Helper for _annotation_ascii_FEs()."""
s1 = ""
s2 = ""
i = 0
for j, k, fename in overt:
s1 += " " * (j - i) + ("^" if fename.islower() else "-") * (k - j)
short = fename[: k - j]
if len(fename) > len(short):
r = 0
while short in feAbbrevs:
if feAbbrevs[short] == fename:
break
r += 1
short = fename[: k - j - 1] + str(r)
else: # short not in feAbbrevs
feAbbrevs[short] = fename
s2 += " " * (j - i) + short.ljust(k - j)
i = k
sNI = ""
if ni:
sNI += " [" + ", ".join(":".join(x) for x in sorted(ni.items())) + "]"
return [s1, s2, sNI]
def _annotation_ascii_FEs(sent):
"""
ASCII string rendering of the sentence along with a single target and its FEs.
Secondary and tertiary FE layers are included if present.
'sent' can be an FE annotation set or an LU sentence with a single target.
Line-wrapped to limit the display width.
"""
feAbbrevs = OrderedDict()
posspec = [] # POS-specific layer spans (e.g., Supp[ort], Cop[ula])
posspec_separate = False
for lyr in ("Verb", "Noun", "Adj", "Adv", "Prep", "Scon", "Art"):
if lyr in sent and sent[lyr]:
for a, b, lbl in sent[lyr]:
if (
lbl == "X"
): # skip this, which covers an entire phrase typically containing the target and all its FEs
# (but do display the Gov)
continue
if any(1 for x, y, felbl in sent.FE[0] if x <= a < y or a <= x < b):
# overlap between one of the POS-specific layers and first FE layer
posspec_separate = (
True # show POS-specific layers on a separate line
)
posspec.append(
(a, b, lbl.lower().replace("-", ""))
) # lowercase Cop=>cop, Non-Asp=>nonasp, etc. to distinguish from FE names
if posspec_separate:
POSSPEC = _annotation_ascii_FE_layer(posspec, {}, feAbbrevs)
FE1 = _annotation_ascii_FE_layer(
sorted(sent.FE[0] + (posspec if not posspec_separate else [])),
sent.FE[1],
feAbbrevs,
)
FE2 = FE3 = None
if "FE2" in sent:
FE2 = _annotation_ascii_FE_layer(sent.FE2[0], sent.FE2[1], feAbbrevs)
if "FE3" in sent:
FE3 = _annotation_ascii_FE_layer(sent.FE3[0], sent.FE3[1], feAbbrevs)
for i, j in sent.Target:
FE1span, FE1name, FE1exp = FE1
if len(FE1span) < j:
FE1span += " " * (j - len(FE1span))
if len(FE1name) < j:
FE1name += " " * (j - len(FE1name))
FE1[1] = FE1name
FE1[0] = (
FE1span[:i] + FE1span[i:j].replace(" ", "*").replace("-", "=") + FE1span[j:]
)
long_lines = [sent.text]
if posspec_separate:
long_lines.extend(POSSPEC[:2])
long_lines.extend([FE1[0], FE1[1] + FE1[2]]) # lines with no length limit
if FE2:
long_lines.extend([FE2[0], FE2[1] + FE2[2]])
if FE3:
long_lines.extend([FE3[0], FE3[1] + FE3[2]])
long_lines.append("")
outstr = "\n".join(
map("\n".join, zip_longest(*mimic_wrap(long_lines), fillvalue=" "))
)
if feAbbrevs:
outstr += "(" + ", ".join("=".join(pair) for pair in feAbbrevs.items()) + ")"
assert len(feAbbrevs) == len(dict(feAbbrevs)), "Abbreviation clash"
outstr += "\n"
return outstr
def _pretty_fe(fe):
"""
Helper function for pretty-printing a frame element.
:param fe: The frame element to be printed.
:type fe: AttrDict
:return: A nicely formatted string representation of the frame element.
:rtype: str
"""
fekeys = fe.keys()
outstr = ""
outstr += "frame element ({0.ID}): {0.name}\n of {1.name}({1.ID})\n".format(
fe, fe.frame
)
if "definition" in fekeys:
outstr += "[definition]\n"
outstr += _pretty_longstring(fe.definition, " ")
if "abbrev" in fekeys:
outstr += f"[abbrev] {fe.abbrev}\n"
if "coreType" in fekeys:
outstr += f"[coreType] {fe.coreType}\n"
if "requiresFE" in fekeys:
outstr += "[requiresFE] "
if fe.requiresFE is None:
outstr += "<None>\n"
else:
outstr += f"{fe.requiresFE.name}({fe.requiresFE.ID})\n"
if "excludesFE" in fekeys:
outstr += "[excludesFE] "
if fe.excludesFE is None:
outstr += "<None>\n"
else:
outstr += f"{fe.excludesFE.name}({fe.excludesFE.ID})\n"
if "semType" in fekeys:
outstr += "[semType] "
if fe.semType is None:
outstr += "<None>\n"
else:
outstr += "\n " + f"{fe.semType.name}({fe.semType.ID})" + "\n"
return outstr
def _pretty_frame(frame):
"""
Helper function for pretty-printing a frame.
:param frame: The frame to be printed.
:type frame: AttrDict
:return: A nicely formatted string representation of the frame.
:rtype: str
"""
outstr = ""
outstr += "frame ({0.ID}): {0.name}\n\n".format(frame)
outstr += f"[URL] {frame.URL}\n\n"
outstr += "[definition]\n"
outstr += _pretty_longstring(frame.definition, " ") + "\n"
outstr += f"[semTypes] {len(frame.semTypes)} semantic types\n"
outstr += (
" " * (len(frame.semTypes) > 0)
+ ", ".join(f"{x.name}({x.ID})" for x in frame.semTypes)
+ "\n" * (len(frame.semTypes) > 0)
)
outstr += "\n[frameRelations] {} frame relations\n".format(
len(frame.frameRelations)
)
outstr += " " + "\n ".join(repr(frel) for frel in frame.frameRelations) + "\n"
outstr += f"\n[lexUnit] {len(frame.lexUnit)} lexical units\n"
lustrs = []
for luName, lu in sorted(frame.lexUnit.items()):
tmpstr = f"{luName} ({lu.ID})"
lustrs.append(tmpstr)
outstr += "{}\n".format(_pretty_longstring(", ".join(lustrs), prefix=" "))
outstr += f"\n[FE] {len(frame.FE)} frame elements\n"
fes = {}
for feName, fe in sorted(frame.FE.items()):
try:
fes[fe.coreType].append(f"{feName} ({fe.ID})")
except KeyError:
fes[fe.coreType] = []
fes[fe.coreType].append(f"{feName} ({fe.ID})")
for ct in sorted(
fes.keys(),
key=lambda ct2: [
"Core",
"Core-Unexpressed",
"Peripheral",
"Extra-Thematic",
].index(ct2),
):
outstr += "{:>16}: {}\n".format(ct, ", ".join(sorted(fes[ct])))
outstr += "\n[FEcoreSets] {} frame element core sets\n".format(
len(frame.FEcoreSets)
)
outstr += (
" "
+ "\n ".join(
", ".join([x.name for x in coreSet]) for coreSet in frame.FEcoreSets
)
+ "\n"
)
return outstr
class FramenetError(Exception):
"""An exception class for framenet-related errors."""
class AttrDict(dict):
"""A class that wraps a dict and allows accessing the keys of the
dict as if they were attributes. Taken from here:
https://stackoverflow.com/a/14620633/8879
>>> foo = {'a':1, 'b':2, 'c':3}
>>> bar = AttrDict(foo)
>>> pprint(dict(bar))
{'a': 1, 'b': 2, 'c': 3}
>>> bar.b
2
>>> bar.d = 4
>>> pprint(dict(bar))
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.__dict__ = self
def __setattr__(self, name, value):
self[name] = value
def __getattr__(self, name):
if name == "_short_repr":
return self._short_repr
return self[name]
def __getitem__(self, name):
v = super().__getitem__(name)
if isinstance(v, Future):
return v._data()
return v
def _short_repr(self):
if "_type" in self:
if self["_type"].endswith("relation"):
return self.__repr__()
try:
return "<{} ID={} name={}>".format(
self["_type"], self["ID"], self["name"]
)
except KeyError:
try: # no ID--e.g., for _type=lusubcorpus
return "<{} name={}>".format(self["_type"], self["name"])
except KeyError: # no name--e.g., for _type=lusentence
return "<{} ID={}>".format(self["_type"], self["ID"])
else:
return self.__repr__()
def _str(self):
outstr = ""
if "_type" not in self:
outstr = _pretty_any(self)
elif self["_type"] == "frame":
outstr = _pretty_frame(self)
elif self["_type"] == "fe":
outstr = _pretty_fe(self)
elif self["_type"] == "lu":
outstr = _pretty_lu(self)
elif self["_type"] == "luexemplars": # list of ALL exemplars for LU
outstr = _pretty_exemplars(self, self[0].LU)
elif (
self["_type"] == "fulltext_annotation"
): # list of all sentences for full-text doc
outstr = _pretty_fulltext_sentences(self)
elif self["_type"] == "lusentence":
outstr = _pretty_annotation(self)
elif self["_type"] == "fulltext_sentence":
outstr = _pretty_fulltext_sentence(self)
elif self["_type"] in ("luannotationset", "fulltext_annotationset"):
outstr = _pretty_annotation(self, aset_level=True)
elif self["_type"] == "posannotationset":
outstr = _pretty_pos(self)
elif self["_type"] == "semtype":
outstr = _pretty_semtype(self)
elif self["_type"] == "framerelationtype":
outstr = _pretty_frame_relation_type(self)
elif self["_type"] == "framerelation":
outstr = _pretty_frame_relation(self)
elif self["_type"] == "ferelation":
outstr = _pretty_fe_relation(self)
else:
outstr = _pretty_any(self)
# ensure result is unicode string prior to applying the
# decorator (because non-ASCII characters
# could in principle occur in the data and would trigger an encoding error when
# passed as arguments to str.format()).
# assert isinstance(outstr, unicode) # not in Python 3.2
return outstr
def __str__(self):
return self._str()
def __repr__(self):
return self.__str__()
class SpecialList(list):
"""
A list subclass which adds a '_type' attribute for special printing
(similar to an AttrDict, though this is NOT an AttrDict subclass).
"""
def __init__(self, typ, *args, **kwargs):
super().__init__(*args, **kwargs)
self._type = typ
def _str(self):
outstr = ""
assert self._type
if len(self) == 0:
outstr = "[]"
elif self._type == "luexemplars": # list of ALL exemplars for LU
outstr = _pretty_exemplars(self, self[0].LU)
else:
assert False, self._type
return outstr
def __str__(self):
return self._str()
def __repr__(self):
return self.__str__()
class Future:
"""
Wraps and acts as a proxy for a value to be loaded lazily (on demand).
Adapted from https://gist.github.com/sergey-miryanov/2935416
"""
def __init__(self, loader, *args, **kwargs):
"""
:param loader: when called with no arguments, returns the value to be stored
:type loader: callable
"""
super().__init__(*args, **kwargs)
self._loader = loader
self._d = None
def _data(self):
if callable(self._loader):
self._d = self._loader()
self._loader = None # the data is now cached
return self._d
def __nonzero__(self):
return bool(self._data())
def __len__(self):
return len(self._data())
def __setitem__(self, key, value):
return self._data().__setitem__(key, value)
def __getitem__(self, key):
return self._data().__getitem__(key)
def __getattr__(self, key):
return self._data().__getattr__(key)
def __str__(self):
return self._data().__str__()
def __repr__(self):
return self._data().__repr__()
class PrettyDict(AttrDict):
"""
Displays an abbreviated repr of values where possible.
Inherits from AttrDict, so a callable value will
be lazily converted to an actual value.
"""
def __init__(self, *args, **kwargs):
_BREAK_LINES = kwargs.pop("breakLines", False)
super().__init__(*args, **kwargs)
dict.__setattr__(self, "_BREAK_LINES", _BREAK_LINES)
def __repr__(self):
parts = []
for k, v in sorted(self.items()):
kv = repr(k) + ": "
try:
kv += v._short_repr()
except AttributeError:
kv += repr(v)
parts.append(kv)
return "{" + (",\n " if self._BREAK_LINES else ", ").join(parts) + "}"
class PrettyList(list):
"""
Displays an abbreviated repr of only the first several elements, not the whole list.
"""
# from nltk.util
def __init__(self, *args, **kwargs):
self._MAX_REPR_SIZE = kwargs.pop("maxReprSize", 60)
self._BREAK_LINES = kwargs.pop("breakLines", False)
super().__init__(*args, **kwargs)
def __repr__(self):
"""
Return a string representation for this corpus view that is
similar to a list's representation; but if it would be more
than 60 characters long, it is truncated.
"""
pieces = []
length = 5
for elt in self:
pieces.append(
elt._short_repr()
) # key difference from inherited version: call to _short_repr()
length += len(pieces[-1]) + 2
if self._MAX_REPR_SIZE and length > self._MAX_REPR_SIZE and len(pieces) > 2:
return "[%s, ...]" % str(",\n " if self._BREAK_LINES else ", ").join(
pieces[:-1]
)
return "[%s]" % str(",\n " if self._BREAK_LINES else ", ").join(pieces)
class PrettyLazyMap(LazyMap):