-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathparsing.py
More file actions
2966 lines (2735 loc) · 132 KB
/
Copy pathparsing.py
File metadata and controls
2966 lines (2735 loc) · 132 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
from typing import List, Dict, Optional, Tuple, Generator, cast, Set, Union
import math
import pickle
import importlib
from abc import ABC, abstractmethod
from copy import copy
from functools import total_ordering
import srsly
import pkg_resources
from spacy.language import Language
from spacy.vocab import Vocab
from spacy.tokens import Token, Doc
from thinc.api import get_current_ops
from thinc.types import Floats1d
from holmes_extractor.ontology import Ontology
from .errors import (
DocumentTooBigError,
SearchPhraseContainsNegationError,
SearchPhraseContainsConjunctionError,
SearchPhraseWithoutMatchableWordsError,
SearchPhraseContainsMultipleClausesError,
SearchPhraseContainsCoreferringPronounError,
)
SERIALIZED_DOCUMENT_VERSION = "4.0"
class SemanticDependency:
"""A labelled semantic dependency between two tokens."""
def __init__(
self,
parent_index: int,
child_index: int,
label: str = None,
is_uncertain: bool = False,
) -> None:
"""Args:
parent_index -- the index of the parent token within the document.
child_index -- the index of the child token within the document, or one less than zero
minus the index of the child token within the document for a grammatical dependency. A
grammatical dependency is always in a non-final position within a chain of dependencies
ending in one or more non-grammatical (lexical / normal) dependencies. When creating
both Holmes semantic structures and search phrases, grammatical dependencies are
sometimes replaced by the lexical dependencies at the end of their chains.
label -- the label of the semantic dependency, which must be *None* for grammatical
dependencies.
is_uncertain -- if *True*, any match involving this dependency will itself be uncertain.
"""
if child_index < 0 and label is not None:
raise RuntimeError(
"Semantic dependency with negative child index may not have a label."
)
if parent_index == child_index:
raise RuntimeError(
" ".join(
(
"Attempt to create self-referring semantic dependency with index",
str(parent_index),
)
)
)
self.parent_index = parent_index
self.child_index = child_index
self.label = label
self.is_uncertain = is_uncertain
def parent_token(self, doc: Doc) -> Token:
"""Convenience method to return the parent token of this dependency.
doc -- the document containing the token.
"""
index = self.parent_index
if index < 0:
index = -1 - index
return doc[index]
def child_token(self, doc: Doc) -> Token:
"""Convenience method to return the child token of this dependency.
doc -- the document containing the token.
"""
index = self.child_index
if index < 0:
index = -1 - index
return doc[index]
def __str__(self) -> str:
"""e.g. *2:nsubj* or *2:nsubj(U)* to represent uncertainty."""
working_label = str(self.label)
if self.is_uncertain:
working_label = "".join((working_label, "(U)"))
return ":".join((str(self.child_index), working_label))
def __eq__(self, other) -> bool:
return (
isinstance(other, SemanticDependency)
and self.parent_index == other.parent_index
and self.child_index == other.child_index
and self.label == other.label
and self.is_uncertain == other.is_uncertain
)
def __hash__(self) -> int:
return hash(
(self.parent_index, self.child_index, self.label, self.is_uncertain)
)
class Mention:
"""Simplified information about a coreference mention with respect to a specific token."""
def __init__(self, root_index: int, indexes: List[int]) -> None:
"""
root_index -- the index of the member of *indexes* that forms the syntactic head of any
coordinated phrase, or *indexes[0]* if *len(indexes) == 1*.
indexes -- the indexes of the tokens that make up the mention. If there is more than one
token, they must form a coordinated phrase.
"""
self.root_index = root_index
self.indexes = indexes
def __str__(self) -> str:
return "".join(("[", str(self.root_index), "; ", str(self.indexes), "]"))
class Subword:
"""A semantically atomic part of a word. Currently only used for German.
containing_token_index -- the index of the containing token within the document.
index -- the index of the subword within the word.
text -- the original subword string.
lemma -- the model-normalized representation of the subword string.
derived_lemma -- where relevant, another lemma with which *lemma* is derivationally related
and which can also be useful for matching in some usecases; otherwise *None*
vector -- the vector representation of *lemma*, or *None* if there is none available.
char_start_index -- the character index of the subword within the containing word.
dependent_index -- the index of a subword that is dependent on this subword, or *None*
if there is no such subword.
dependency_label -- the label of the dependency between this subword and its dependent,
or *None* if it has no dependent.
governor_index -- the index of a subword on which this subword is dependent, or *None*
if there is no such subword.
governing_dependency_label -- the label of the dependency between this subword and its
governor, or *None* if it has no governor.
"""
def __init__(
self,
containing_token_index: int,
index: int,
text: str,
lemma: str,
derived_lemma: str,
vector: Floats1d,
char_start_index: int,
dependent_index: Optional[int],
dependency_label: Optional[str],
governor_index: Optional[int],
governing_dependency_label: Optional[str],
):
self.containing_token_index = containing_token_index
self.index = index
self.text = text
self.lemma = lemma
self.direct_matching_reprs = [lemma]
if text != lemma:
self.direct_matching_reprs.append(text)
self.derived_lemma = derived_lemma
if derived_lemma != lemma:
self.derivation_matching_reprs: Optional[List[str]] = [derived_lemma]
else:
self.derivation_matching_reprs = None
self.vector = vector
self.char_start_index = char_start_index
self.dependent_index = dependent_index
self.dependency_label = dependency_label
self.governor_index = governor_index
self.governing_dependency_label = governing_dependency_label
@property
def is_head(self) -> bool:
return self.governor_index is None
def __str__(self) -> str:
if self.derived_lemma is not None:
lemma_string = "".join((self.lemma, "(", self.derived_lemma, ")"))
else:
lemma_string = self.lemma
return "/".join((self.text, lemma_string))
@total_ordering
class Index:
"""The position of a multiword, word or subword within a document."""
def __init__(self, token_index: int, subword_index: Optional[int]) -> None:
self.token_index = token_index
self.subword_index = subword_index
def is_subword(self) -> bool:
return self.subword_index is not None
def __eq__(self, other) -> bool:
return (
isinstance(other, Index)
and self.token_index == other.token_index
and self.subword_index == other.subword_index
)
def __lt__(self, other) -> bool:
if not isinstance(other, Index):
raise RuntimeError("Comparison between Index and another type.")
if self.token_index < other.token_index:
return True
if not self.is_subword() and other.is_subword():
return True
if (
self.is_subword()
and other.is_subword()
and self.subword_index < other.subword_index # type:ignore[operator]
):
return True
return False
def __hash__(self) -> int:
return hash((self.token_index, self.subword_index))
class CorpusWordPosition:
"""A reference to a word or subword within a corpus of one or more documents."""
def __init__(self, document_label: str, index: Index) -> None:
if document_label is None:
raise RuntimeError("CorpusWordPosition.document_label must have a value.")
self.document_label = document_label
self.index = index
def __eq__(self, other) -> bool:
return (
isinstance(other, CorpusWordPosition)
and self.document_label == other.document_label
and self.index == other.index
)
def __hash__(self) -> int:
return hash((self.document_label, self.index))
def __str__(self) -> str:
return ":".join((self.document_label, str(self.index)))
class MultiwordSpan:
def __init__(
self,
text: str,
hyphen_normalized_lemma: Optional[str],
lemma: str,
derived_lemma: Optional[str],
token_indexes: List[int],
) -> None:
"""Args:
text -- the raw text representation of the multiword span
lemma - the lemma representation of the multiword span
hyphen_normalized_lemma -- a hyphen-normalized representation of *lemmaÜ
derived_lemma - the lemma representation with individual words that have derived
lemmas replaced by those derived lemmas
token_indexes -- a list of token indexes that make up the multiword span
"""
text = text
self.text = text
self.lemma = lemma
self.derived_lemma = derived_lemma
self.direct_matching_reprs = [lemma]
if hyphen_normalized_lemma != lemma and hyphen_normalized_lemma is not None:
self.direct_matching_reprs.append(hyphen_normalized_lemma)
if lemma != text.lower():
self.direct_matching_reprs.append(text.lower())
if derived_lemma != lemma and derived_lemma is not None:
self.derivation_matching_reprs: Optional[List[str]] = [derived_lemma]
else:
self.derivation_matching_reprs = None
self.token_indexes = token_indexes
class MatchImplication:
"""Entry describing which document dependencies match a given search phrase dependency.
Parameters:
search_phrase_dependency -- the search phrase dependency.
document_dependencies -- the matching document dependencies.
reverse_document_dependencies -- document dependencies that match when the polarity is
opposite to the polarity of *search_phrase_dependency*.
"""
def __init__(
self,
*,
search_phrase_dependency: str,
document_dependencies: List[str],
reverse_document_dependencies: Optional[List[str]] = None
):
self.search_phrase_dependency = search_phrase_dependency
self.document_dependencies = document_dependencies
if reverse_document_dependencies is None:
reverse_document_dependencies = []
self.reverse_document_dependencies: List[str] = reverse_document_dependencies
class HolmesDocumentInfo:
def __init__(self, semantic_analyzer: "SemanticAnalyzer"):
self.model = semantic_analyzer.get_model_name()
self.serialized_document_version = SERIALIZED_DOCUMENT_VERSION
@srsly.msgpack_encoders("holmes_document_info_holder")
def serialize_obj(obj, chain=None):
if isinstance(obj, HolmesDocumentInfo):
return {"__holmes_document_info_holder__": pickle.dumps(obj)}
return obj if chain is None else chain(obj)
@srsly.msgpack_decoders("holmes_document_info_holder")
def deserialize_obj(obj, chain=None):
if "__holmes_document_info_holder__" in obj:
return pickle.loads(obj["__holmes_document_info_holder__"])
return obj if chain is None else chain(obj)
class HolmesDictionary:
"""The holder object for token-level semantic information managed by Holmes
Holmes dictionaries are accessed using the syntax *token._.holmes*.
index -- the index of the token
lemma -- the value returned from *._.holmes.lemma* for the token.
hyphen_normalized_lemma -- a hyphen-normalized version of *lemma*.
derived_lemma -- the value returned from *._.holmes.derived_lemma for the token; where relevant,
another lemma with which *lemma* is derivationally related and which can also be useful for
matching in some usecases; otherwise the same value as *._.holmes.lemma*.
direct_matching_reprs -- a list of representations of the token that can be used for direct
matching, consisting of *token.text* and optionally a hyphen-normalized version of *token.text*
and *token.lemma_* if these are different from *token.text*.
derivation_matching_reprs -- if *lemma != derived_lemma*, a list of representations of the token
that can be used for derivation matching, consisting of *derived_lema*, *token.text*
and optionally a hyphen-normalized version of *token.text* and *token.lemma_* if these
are different from *token.text*; otherwise *None*.
vector -- the vector representation of *lemma*, unless *lemma* is a multiword, in which case
the vector representation of *token.lemma_* is used instead. *None* where there is no
vector for the lexeme.
multiword_spans -- where relevant, a list of multiword spans, otherwise *None*. Set after initialization.
"""
def __init__(
self,
index: int,
lemma: str,
hyphen_normalized_lemma: str,
derived_lemma: str,
direct_matching_reprs: List[str],
derivation_matching_reprs: Optional[List[str]],
vector: Floats1d,
):
self.index = index
self.lemma = lemma
self.hyphen_normalized_lemma = hyphen_normalized_lemma
self.derived_lemma = derived_lemma
self.direct_matching_reprs = direct_matching_reprs
self.derivation_matching_reprs = derivation_matching_reprs
self.multiword_spans: List[MultiwordSpan] = []
self.vector = vector
self.children: List[
SemanticDependency
] = [] # list of *SemanticDependency* objects where this token is the parent.
self.parents: List[
SemanticDependency
] = [] # list of *SemanticDependency* objects where this token is the child.
self.righthand_siblings: List[
Token
] = [] # list of tokens to the right of this token that stand in a
# conjunction relationship to this token and that share its semantic parents.
self.token_or_lefthand_sibling_index = (
None # the index of this token's lefthand sibling,
)
# or this token's own index if this token has no lefthand sibling.
self.is_involved_in_or_conjunction = False
self.is_negated: Optional[bool] = None
self.is_matchable: Optional[bool] = None
self.is_initial_question_word = False
self.has_initial_question_word_in_phrase = False
self.coreference_linked_child_dependencies: List[
Tuple[Index, str]
] = [] # list of [index, label] specifications of
# dependencies where this token is the parent, taking any coreference resolution into
# account. Used in topic matching.
self.coreference_linked_parent_dependencies: List[
Tuple[Index, str]
] = [] # list of [index, label] specifications of
# dependencies where this token is the child, taking any coreference resolution into
# account. Used in topic matching.
self.token_and_coreference_chain_indexes: Optional[
List[int]
] = None # where no coreference, only the token
# index; where coreference, the token index followed by the indexes of coreferring tokens
self.mentions: List[int] = []
self.subwords: List[int] = []
@property
def is_uncertain(self) -> bool:
"""if *True*, a match involving this token will itself be uncertain."""
return self.is_involved_in_or_conjunction
def loop_token_and_righthand_siblings(
self, doc: Doc
) -> Generator[Token, None, None]:
"""Convenience generator to loop through this token and any righthand siblings."""
indexes = [self.index]
indexes.extend(self.righthand_siblings)
indexes = sorted(
indexes
) # in rare cases involving truncated nouns in German, righthand
# siblings can actually end up to the left of the head word.
for index in indexes:
yield doc[index]
def get_sibling_indexes(self, doc: Doc) -> List[Token]:
"""Returns the indexes of this token and any siblings, ordered from left to right."""
# with truncated nouns in German, the righthand siblings may occasionally occur to the left
# of the head noun
head_sibling = doc[self.token_or_lefthand_sibling_index]
indexes = [self.token_or_lefthand_sibling_index]
indexes.extend(head_sibling._.holmes.righthand_siblings)
return sorted(indexes)
def has_dependency_with_child_index(self, index: int) -> bool:
for dependency in self.children:
if dependency.child_index == index:
return True
return False
def get_label_of_dependency_with_child_index(self, index: int) -> Optional[str]:
for dependency in self.children:
if dependency.child_index == index:
return dependency.label
return None
def has_dependency_with_label(self, label: str) -> bool:
for dependency in self.children:
if dependency.label == label:
return True
return False
def has_dependency_with_child_index_and_label(self, index: int, label: str) -> bool:
for dependency in self.children:
if dependency.child_index == index and dependency.label == label:
return True
return False
def remove_dependency_with_child_index(self, index: int) -> None:
self.children = [dep for dep in self.children if dep.child_index != index]
def string_representation_of_children(self) -> str:
children = sorted(self.children, key=lambda dependency: dependency.child_index)
return "; ".join(str(child) for child in children)
def string_representation_of_parents(self) -> str:
parents = sorted(self.parents, key=lambda dependency: dependency.parent_index)
return "; ".join(
":".join((str(parent.parent_index), cast(str, parent.label)))
for parent in parents
)
def is_involved_in_coreference(self) -> bool:
return len(self.mentions) > 0
@srsly.msgpack_encoders("holmes_dictionary_holder")
def serialize_obj(obj, chain=None):
if isinstance(obj, HolmesDictionary):
return {"__holmes_dictionary_holder__": pickle.dumps(obj)}
return obj if chain is None else chain(obj)
@srsly.msgpack_decoders("holmes_dictionary_holder")
def deserialize_obj(obj, chain=None):
if "__holmes_dictionary_holder__" in obj:
return pickle.loads(obj["__holmes_dictionary_holder__"])
return obj if chain is None else chain(obj)
class PhraseletTemplate:
"""A template for a phraselet used in topic matching.
Properties:
label -- a label for the relation which will be used to form part of the labels of phraselets
derived from this template.
template_sentence -- a sentence with the target grammatical structure for phraselets derived
from this template.
template_doc -- a spacy Doc representing *template_sentence* (set by the *Manager* object)
parent_index -- the index within *template_sentence* of the parent participant in the dependency
(for relation phraselets) or of the word (for single-word phraselets).
child_index -- the index within *template_sentence* of the child participant in the dependency
(for relation phraselets) or 'None' for single-word phraselets.
dependency_labels -- the labels of dependencies that match the template
(for relation phraselets) or 'None' for single-word phraselets.
parent_tags -- the tag_ values of parent participants in the dependency (for parent phraselets)
of of the word (for single-word phraselets) that match the template.
child_tags -- the tag_ values of child participants in the dependency (for parent phraselets)
that match the template, or 'None' for single-word phraselets.
reverse_only -- specifies that relation phraselets derived from this template should only be
reverse-matched, e.g. matching should only be attempted during topic matching when the
possible child token has already been matched to a single-word phraselet. This
is used for performance reasons when the parent tag belongs to a closed word class like
prepositions. Reverse-only phraselets are ignored in supervised document classification.
question -- a question template involves an interrogative pronoun in the child position and is
always matched regardless of corpus frequencies.
assigned_dependency_label -- if a value other than 'None', specifies a dependency label that
should be used to relabel the relationship between the parent and child participants.
Has no effect if child_index is None.
"""
def __init__(
self,
label: str,
template_sentence: str,
parent_index: int,
child_index: Optional[int],
dependency_labels: Optional[List[str]],
parent_tags: List[str],
child_tags: Optional[List[str]],
*,
reverse_only: bool,
question: bool,
assigned_dependency_label: Optional[str] = None
):
self.label = label
self.template_sentence = template_sentence
self.parent_index = parent_index
self.child_index = child_index
self.dependency_labels = dependency_labels
self.parent_tags = parent_tags
self.child_tags = child_tags
self.reverse_only = reverse_only
self.question = question
self.assigned_dependency_label = assigned_dependency_label
self.template_doc: Doc
def single_word(self) -> bool:
"""'True' if this is a template for single-word phraselets, otherwise 'False'."""
return self.child_index is None
class PhraseletInfo:
"""Information describing a topic matching phraselet.
Parameters:
label -- the phraselet label, e.g. 'predicate-patient: open-door'
template_label -- the value of 'PhraseletTemplate.label', e.g. 'predicate-patient'
parent_lemma -- the parent lemma, or the lemma for single-word phraselets.
parent_hyphen_normalized_lemma -- a hyphen-normalized version of *parent_lemma*-
parent_derived_lemma -- the parent derived lemma, or the derived lemma for single-word
phraselets.
parent_pos -- the part of speech tag of the token that supplied the parent word.
parent_ent_type -- the parent entity label, or the entity label for single-word
phraselets. '' if there is none.
parent_is_initial_question_word -- 'True' or 'False'
parent_has_initial_question_word_in_phrase -- 'True' or 'False'
child_lemma -- the child lemma, or 'None' for single-word phraselets.
child_hyphen_normalized_lemma -- a hyphen-normalized version of *child_lemma*-
child_derived_lemma -- the child derived lemma, or 'None' for single-word phraselets.
child_pos -- the part of speech tag of the token that supplied the child word, or 'None'
for single-word phraselets.
child_ent_type -- the child entity label. '' if there is none; 'None' for single-word
phraselets.
child_is_initial_question_word -- 'True' or 'False'
child_has_initial_question_word_in_phrase -- 'True' or 'False'
created_without_matching_tags -- 'True' if created without matching tags.
reverse_only_parent_lemma -- 'True' if the parent lemma is in the reverse matching list.
frequency_factor -- a multiplication factor between 0.0 and 1.0 which is lower the more
frequently words occur in the corpus, relating to the whole phraselet.
parent_frequency_factor -- a multiplication factor between 0.0 and 1.0 which is lower the
more frequently words occur in the corpus, relating to the parent token.
child_frequency_factor -- a multiplication factor between 0.0 and 1.0 which is lower the
more frequently words occur in the corpus, relating to the child token.
"""
def __init__(
self,
label: str,
template_label: str,
parent_lemma: str,
parent_hyphen_normalized_lemma: str,
parent_derived_lemma: str,
parent_pos: str,
parent_ent_type: str,
parent_is_initial_question_word: bool,
parent_has_initial_question_word_in_phrase: bool,
child_lemma: Optional[str],
child_hyphen_normalized_lemma: Optional[str],
child_derived_lemma: Optional[str],
child_pos: Optional[str],
child_ent_type: Optional[str],
child_is_initial_question_word: Optional[bool],
child_has_initial_question_word_in_phrase: Optional[bool],
created_without_matching_tags: bool,
reverse_only_parent_lemma: Optional[bool],
frequency_factor: Optional[float],
parent_frequency_factor: Optional[float],
child_frequency_factor: Optional[float],
):
self.label = label
self.template_label = template_label
self.parent_lemma = parent_lemma
self.parent_hyphen_normalized_lemma = parent_hyphen_normalized_lemma
self.parent_derived_lemma = parent_derived_lemma
self.parent_pos = parent_pos
self.parent_ent_type = parent_ent_type
self.parent_is_initial_question_word = parent_is_initial_question_word
self.parent_has_initial_question_word_in_phrase = (
parent_has_initial_question_word_in_phrase
)
self.child_lemma = child_lemma
self.child_hyphen_normalized_lemma = child_hyphen_normalized_lemma
self.child_derived_lemma = child_derived_lemma
self.child_pos = child_pos
self.child_ent_type = child_ent_type
self.child_is_initial_question_word = child_is_initial_question_word
self.child_has_initial_question_word_in_phrase = (
child_has_initial_question_word_in_phrase
)
self.created_without_matching_tags = created_without_matching_tags
self.reverse_only_parent_lemma = reverse_only_parent_lemma
self.frequency_factor = frequency_factor
self.parent_frequency_factor = parent_frequency_factor
self.child_frequency_factor = child_frequency_factor
self.set_parent_reprs()
self.set_child_reprs()
def set_parent_reprs(self) -> None:
self.parent_direct_matching_reprs = [self.parent_lemma]
if self.parent_lemma != self.parent_hyphen_normalized_lemma:
self.parent_direct_matching_reprs.append(
self.parent_hyphen_normalized_lemma
)
if self.parent_lemma != self.parent_derived_lemma:
self.parent_derivation_matching_reprs: Optional[List[str]] = [
self.parent_derived_lemma
]
else:
self.parent_derivation_matching_reprs = None
def set_child_reprs(self) -> None:
if self.child_lemma is not None:
self.child_direct_matching_reprs: Optional[List[str]] = [self.child_lemma]
if self.child_lemma != self.child_hyphen_normalized_lemma:
self.child_direct_matching_reprs.append(
cast(str, self.child_hyphen_normalized_lemma)
)
if self.child_lemma != self.child_derived_lemma:
self.child_derivation_matching_reprs: Optional[List[str]] = [
cast(str, self.child_derived_lemma)
]
else:
self.child_derivation_matching_reprs = None
else:
self.child_direct_matching_reprs = None
self.child_derivation_matching_reprs = None
def __eq__(self, other) -> bool:
return (
isinstance(other, PhraseletInfo)
and self.label == other.label
and self.template_label == other.template_label
and self.parent_lemma == other.parent_lemma
and self.parent_hyphen_normalized_lemma
== other.parent_hyphen_normalized_lemma
and self.parent_derived_lemma == other.parent_derived_lemma
and self.parent_pos == other.parent_pos
and self.parent_ent_type == other.parent_ent_type
and self.parent_is_initial_question_word
== other.parent_is_initial_question_word
and self.parent_has_initial_question_word_in_phrase
== other.parent_has_initial_question_word_in_phrase
and self.child_lemma == other.child_lemma
and self.child_hyphen_normalized_lemma
== other.child_hyphen_normalized_lemma
and self.child_derived_lemma == other.child_derived_lemma
and self.child_pos == other.child_pos
and self.child_ent_type == other.child_ent_type
and self.child_is_initial_question_word
== other.child_is_initial_question_word
and self.child_has_initial_question_word_in_phrase
== other.child_has_initial_question_word_in_phrase
and self.created_without_matching_tags
== other.created_without_matching_tags
and self.reverse_only_parent_lemma == other.reverse_only_parent_lemma
and str(self.frequency_factor) == str(other.frequency_factor)
and str(self.parent_frequency_factor) == str(other.parent_frequency_factor)
and str(self.child_frequency_factor) == str(other.child_frequency_factor)
)
def __hash__(self) -> int:
return hash(
(
self.label,
self.template_label,
self.parent_lemma,
self.parent_derived_lemma,
self.parent_hyphen_normalized_lemma,
self.parent_pos,
self.parent_ent_type,
self.parent_is_initial_question_word,
self.parent_has_initial_question_word_in_phrase,
self.child_lemma,
self.child_derived_lemma,
self.child_pos,
self.child_ent_type,
self.child_hyphen_normalized_lemma,
self.child_is_initial_question_word,
self.child_has_initial_question_word_in_phrase,
self.created_without_matching_tags,
self.reverse_only_parent_lemma,
str(self.frequency_factor),
str(self.parent_frequency_factor),
str(self.child_frequency_factor),
)
)
class SearchPhrase:
def __init__(
self,
doc: Doc,
matchable_token_indexes: List[int],
root_token_index: int,
matchable_non_entity_tokens_to_vectors: Dict[Token, Floats1d],
label: str,
topic_match_phraselet: bool,
topic_match_phraselet_created_without_matching_tags: bool,
question_phraselet: bool,
reverse_only: bool,
treat_as_reverse_only_during_initial_relation_matching: bool,
has_single_matchable_word: bool,
):
"""Args:
doc -- the Holmes document created for the search phrase
matchable_token_indexes -- a list of indexes of tokens all of which must have counterparts
in the document to produce a match
root_token_index -- the index of the token at which recursive matching starts
matchable_non_entity_tokens_to_vectors -- dictionary from token indexes to vectors.
Only used when embedding matching is active.
label -- a label for the search phrase.
topic_match_phraselet -- 'True' if a topic match phraselet, otherwise 'False'.
topic_match_phraselet_created_without_matching_tags -- 'True' if a topic match
phraselet created without matching tags (match_all_words), otherwise 'False'.
question_phraselet -- 'True' if a topic match phraselet where the child member is
an initial question word, otherwise 'False'
reverse_only -- 'True' if a phraselet that should only be reverse-matched.
treat_as_reverse_only_during_initial_relation_matching -- phraselets are
set to *True* in the context of topic matching to prevent them from being taken into
account during initial relation matching because the parent relation occurs too
frequently during the corpus. *reverse_only* cannot be used instead because it
has an effect on scoring.
has_single_matchable_word -- **True** or **False**.
"""
self.doc = doc
self.doc_text = doc.text
self.matchable_token_indexes = matchable_token_indexes
self.root_token_index = root_token_index
self.matchable_non_entity_tokens_to_vectors = (
matchable_non_entity_tokens_to_vectors
)
self.label = label
self.topic_match_phraselet = topic_match_phraselet
self.topic_match_phraselet_created_without_matching_tags = (
topic_match_phraselet_created_without_matching_tags
)
self.question_phraselet = question_phraselet
self.reverse_only = reverse_only
self.treat_as_reverse_only_during_initial_relation_matching = (
treat_as_reverse_only_during_initial_relation_matching
)
self.words_matching_root_token: List[str] = []
self.has_single_matchable_word = (
has_single_matchable_word # len(matchable_token_indexes) == 1
)
@property
def matchable_tokens(self) -> List[Token]:
return [self.doc[index] for index in self.matchable_token_indexes]
@property
def root_token(self) -> Token:
return self.doc[self.root_token_index]
def add_word_information(self, word: str) -> None:
if word not in self.words_matching_root_token:
self.words_matching_root_token.append(word)
def pack(self) -> None:
"""Prepares the search phrase for serialization."""
self.serialized_doc = self.doc.to_bytes()
self.doc = None
def unpack(self, vocab: Vocab) -> None:
"""Restores the search phrase following deserialization."""
self.doc = Doc(vocab).from_bytes(self.serialized_doc)
self.serialized_doc = None
class SemanticAnalyzerFactory:
"""Returns the correct *SemanticAnalyzer* for the model language.
This class must be added to if additional implementations are added for new languages.
"""
def semantic_analyzer(self, *, nlp: Language, vectors_nlp: Language):
language = nlp.meta["lang"]
try:
language_specific_rules_module = importlib.import_module(
".".join((".lang", language, "language_specific_rules")),
"holmes_extractor",
)
except ModuleNotFoundError:
raise ValueError(" ".join(("Language", language, "not supported")))
return language_specific_rules_module.LanguageSpecificSemanticAnalyzer(
nlp=nlp, vectors_nlp=vectors_nlp
)
class SemanticAnalyzer(ABC):
"""Abstract *SemanticAnalyzer* parent class. A *SemanticAnalyzer* is responsible for adding the
*token._.holmes* dictionaries to each token within a spaCy document. It requires full access to
the spaCy *Language* object, cannot be serialized and so may only be called within main
processes, not from worker processes.
Functionality is placed here that is common to all
current implementations. It follows that some functionality will probably have to be moved
out to specific implementations whenever an implementation for a new language is added.
For explanations of the abstract variables and methods, see the *EnglishSemanticAnalyzer*
implementation where they can be illustrated with direct examples.
"""
language_name: str = NotImplemented
noun_pos: List[str] = NotImplemented
predicate_head_pos: List[str] = NotImplemented
matchable_pos: List[str] = NotImplemented
adjectival_predicate_head_pos: List[str] = NotImplemented
adjectival_predicate_subject_pos: List[str] = NotImplemented
adjectival_predicate_subject_dep: str = NotImplemented
adjectival_predicate_predicate_dep: str = NotImplemented
adjectival_predicate_predicate_pos: str = NotImplemented
modifier_dep: str = NotImplemented
spacy_noun_to_preposition_dep: str = NotImplemented
spacy_verb_to_preposition_dep: str = NotImplemented
holmes_noun_to_preposition_dep: str = NotImplemented
holmes_verb_to_preposition_dep: str = NotImplemented
conjunction_deps: List[str] = NotImplemented
interrogative_pronoun_tags: List[str] = NotImplemented
semantic_dependency_excluded_tags: List[str] = NotImplemented
generic_pronoun_lemmas: List[str] = NotImplemented
or_lemma: str = NotImplemented
mark_child_dependencies_copied_to_siblings_as_uncertain: bool = NotImplemented
maximum_mentions_in_coreference_chain: int = NotImplemented
maximum_word_distance_in_coreference_chain: int = NotImplemented
sibling_marker_deps: List[str] = NotImplemented
entity_labels_to_corresponding_lexemes: Dict[str, str] = NotImplemented
whose_lemma: str = NotImplemented
@abstractmethod
def add_subwords(
self, token: Token, subword_cache: Dict[str, List[Subword]]
) -> None:
pass
@abstractmethod
def set_negation(self, token: Token) -> None:
pass
@abstractmethod
def correct_auxiliaries_and_passives(self, token: Token) -> None:
pass
@abstractmethod
def perform_language_specific_tasks(self, token: Token) -> None:
pass
@abstractmethod
def handle_relative_constructions(self, token: Token) -> None:
pass
@abstractmethod
def holmes_lemma(self, token: Token) -> str:
pass
@abstractmethod
def language_specific_derived_holmes_lemma(self, token: Token, lemma: str) -> str:
pass
def __init__(self, *, nlp: Language, vectors_nlp: Language) -> None:
"""Args:
nlp -- the spaCy model
vectors_nlp -- the spaCy model to use for vocabularies and vectors
"""
self.nlp = nlp
self.vectors_nlp = vectors_nlp
self.model = "_".join((self.nlp.meta["lang"], self.nlp.meta["name"]))
self.derivational_dictionary = self.load_derivational_dictionary()
self.serialized_document_version = SERIALIZED_DOCUMENT_VERSION
def load_derivational_dictionary(self) -> Dict[str, str]:
in_package_filename = "".join(
("lang/", self.nlp.meta["lang"], "/data/derivation.csv")
)
absolute_filename = pkg_resources.resource_filename(
__name__, in_package_filename
)
dictionary: Dict[str, str] = {}
with open(absolute_filename, "r", encoding="utf-8") as file:
for line in file.readlines():
words = [word.strip() for word in line.split(",")]
for index, _ in enumerate(words):
dictionary[words[index]] = words[0]
return dictionary
_maximum_document_size = 1000000
def spacy_parse_for_lemmas(self, text: str) -> Doc:
"""Performs a standard spaCy parse on a string in order to obtain lemmas. The 'parser' and 'ner' components
are disabled as they are not required to perform this task."""
if len(text) > self._maximum_document_size:
raise DocumentTooBigError(
" ".join(
("size:", str(len(text)), "max:", str(self._maximum_document_size))
)
)
return self.nlp(text, disable=["parser", "ner", "coreferee", "holmes"])
def parse(self, text: str) -> Doc:
return self.nlp(text)
def get_vector(self, lemma: str) -> Floats1d:
"""Returns a vector representation of *lemma*, or *None* if none is available."""
lexeme = self.vectors_nlp.vocab[lemma]
return lexeme.vector if lexeme.has_vector and lexeme.vector_norm > 0 else None
def holmes_parse(self, spacy_doc: Doc) -> Doc:
"""Adds the Holmes-specific information to each token within a spaCy document."""
spacy_doc._.set("holmes_document_info", HolmesDocumentInfo(self))
for token in spacy_doc:
lemma = self.holmes_lemma(token)
derived_lemma = self.derived_holmes_lemma(token, lemma)
direct_matching_reprs = [lemma]
hyphen_normalized_lemma = self.normalize_hyphens(lemma)
if lemma != hyphen_normalized_lemma:
direct_matching_reprs.append(hyphen_normalized_lemma)
if token.text.lower() != lemma:
direct_matching_reprs.append(token.text.lower())
if derived_lemma != lemma:
derivation_matching_reprs = [derived_lemma]
else:
derivation_matching_reprs = None
lexeme = self.vectors_nlp.vocab[
token.lemma_ if len(lemma.split()) > 1 else lemma
]
vector = (
lexeme.vector if lexeme.has_vector and lexeme.vector_norm > 0 else None
)
token._.set(
"holmes",
HolmesDictionary(
token.i,
lemma,