-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathtextrazor.py
executable file
·1594 lines (1126 loc) · 65.8 KB
/
textrazor.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
"""
Copyright (c) 2023 TextRazor, https://www.textrazor.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
try:
from urllib2 import Request, urlopen, HTTPError
from urllib import urlencode
except ImportError:
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError
import warnings
try:
import simplejson as json
except ImportError:
import json
try:
import cStringIO.StringIO as IOStream
except ImportError:
try:
import StringIO.StringIO as IOStream
except ImportError:
from io import BytesIO as IOStream
import gzip
import zlib
# These options don't usually change much within a user's app,
# for convenience allow them to set global defaults for connection options.
api_key = None
do_compression = True
do_encryption = True
# Endpoints aren't usually changed by an end user, but helpful to
# have as an option for debug purposes.
_SECURE_TEXTRAZOR_ENDPOINT = "https://api.textrazor.com/"
_TEXTRAZOR_ENDPOINT = "http://api.textrazor.com/"
def _chunks(l, n):
n = max(1, n)
return (l[i:i + n] for i in range(0, len(l), n))
class proxy_response_json(object):
""" Helper class to provide a transparent proxy for python properties
with easy access to an underlying json document. This is to avoid unneccesary
copying of the response, while explictly exposing the expected response fields
and documentation."""
def __init__(self, attr_name, default=None, doc=None):
self.attr_name = attr_name
self.default = default
if doc:
self.__doc__ = doc
def __get__(self, instance, owner=None):
return instance.json.get(self.attr_name, self.default)
def __set__(self, instance, value):
instance.json[self.attr_name] = value
class proxy_member(object):
""" Slightly redundant given the property decorator, but saves some space
and makes non-json property access consistent with the above. """
def __init__(self, attr_name, doc=None):
self.attr_name = attr_name
if doc:
self.__doc__ = doc
def __get__(self, instance, owner=None):
return getattr(instance, self.attr_name)
def _generate_str(instance, banned_properties=[]):
out = ["TextRazor", type(instance).__name__]
try:
out.extend(["with id:", repr(instance.id), "\n"])
except AttributeError:
out.extend([":\n", ])
for prop in dir(instance):
if not prop.startswith("_") and prop != "id" and prop not in banned_properties:
out.extend([prop, ":", repr(getattr(instance, prop)), "\n"])
return " ".join(out)
class TextRazorConnection(object):
def __init__(self, local_api_key=None, local_do_compression=None, local_do_encryption=None):
global api_key, do_compression, do_encryption, _TEXTRAZOR_ENDPOINT, _SECURE_TEXTRAZOR_ENDPOINT
self.api_key = local_api_key
self.do_compression = local_do_compression
self.do_encryption = local_do_encryption
self.endpoint = _TEXTRAZOR_ENDPOINT
self.secure_endpoint = _SECURE_TEXTRAZOR_ENDPOINT
if self.api_key is None:
self.api_key = api_key
if self.do_compression is None:
self.do_compression = do_compression
if self.do_encryption is None:
self.do_encryption = do_encryption
def set_api_key(self, api_key):
"""Sets the TextRazor API key, required for all requests."""
self.api_key = api_key
def set_do_compression(self, do_compression):
"""When True, request gzipped responses from TextRazor. When expecting a large response this can
significantly reduce bandwidth. Defaults to True."""
self.do_compression = do_compression
def set_do_encryption(self, do_encryption):
"""When True, all communication to TextRazor will be sent over SSL, when handling sensitive
or private information this should be set to True. Defaults to False."""
self.do_encryption = do_encryption
def set_endpoint(self, endpoint):
self.endpoint = endpoint
def set_secure_endpoint(self, endpoint):
self.secure_endpoint = endpoint
def _build_request_headers(self, do_request_compression=False):
request_headers = {
'X-TextRazor-Key': self.api_key
}
if self.do_compression:
request_headers['Accept-Encoding'] = 'gzip'
if do_request_compression:
request_headers['Content-Encoding'] = 'gzip'
return request_headers
def do_request(self, path, post_data=None, content_type=None, method="GET"):
# Where compression is enabled, TextRazor supports compression of both request and response bodys.
# Request compression can result in a significant decrease in processing time, especially for
# larger documents.
do_request_compression = False
encoded_post_data = None
if post_data:
encoded_post_data = post_data.encode("utf-8")
# Don't do request compression for small/empty bodies
do_request_compression = self.do_compression and encoded_post_data and len(encoded_post_data) > 50
request_headers = self._build_request_headers(do_request_compression)
if content_type:
request_headers['Content-Type'] = content_type
if self.do_encryption:
endpoint = self.secure_endpoint
else:
endpoint = self.endpoint
url = "".join([endpoint, path])
if do_request_compression:
encoded_post_data = zlib.compress(encoded_post_data)
request = Request(url, headers=request_headers, data=encoded_post_data)
request.get_method = lambda: method
try:
response = urlopen(request)
except HTTPError as e:
raise TextRazorAnalysisException("TextRazor returned HTTP Code %d: %s" % (e.code, e.read()))
if response.info().get('Content-Encoding') == 'gzip':
buf = IOStream(response.read())
response = gzip.GzipFile(fileobj=buf)
response_text = response.read().decode("utf-8")
return json.loads(response_text)
class TextRazorAnalysisException(Exception):
pass
class Topic(object):
"""Represents a single abstract topic extracted from the input text.
Requires the "topics" extractor to be added to the TextRazor request.
"""
def __init__(self, topic_json, link_index):
self.json = topic_json
for callback, arg in link_index.get(("topic", self.id), []):
callback(arg, self)
id = proxy_response_json("id", None, """The unique id of this Topic within the result set.""")
label = proxy_response_json("label", None, """The label of this Topic.""")
wikipedia_link = proxy_response_json("wikiLink", None, """A link to Wikipedia for this topic, or None if this Topic couldn't be linked to a Wikipedia page.""")
wikidata_id = proxy_response_json("wikidataId", None, """A link to the Wikidata ID for this topic, or None if this Topic couldn't be linked to a Wikipedia page.""")
score = proxy_response_json("score", None, """The contextual relevance of this Topic to your document.""")
def __str__(self):
return _generate_str(self)
def __repr__(self):
return "TextRazor Topic %s with label %s" % (str(self.id), str(self.label))
class Entity(object):
"""Represents a single "Named Entity" extracted from the input text.
Requires the "entities" extractor to be added to the TextRazor request.
"""
def __init__(self, entity_json, link_index):
self.json = entity_json
self._matched_words = []
for callback, arg in link_index.get(("entity", self.document_id), []):
callback(arg, self)
for position in self.matched_positions:
try:
link_index[("word", position)].append((self._register_link, None))
except KeyError:
link_index[("word", position)] = [(self._register_link, None)]
def _register_link(self, dummy, word):
self._matched_words.append(word)
word._add_entity(self)
custom_entity_id = proxy_response_json("customEntityId", "", """
The custom entity DictionaryEntry id that matched this Entity,
if this entity was matched in a custom dictionary.""")
document_id = proxy_response_json("id", None)
id = proxy_response_json("entityId", None, "The disambiguated Wikipedia ID for this entity, or None if this entity could not be disambiguated.")
english_id = proxy_response_json("entityEnglishId", None, "The disambiguated entityId in the English Wikipedia, where a link between localized and English ID could be found. None if either the entity could not be linked, or where a language link did not exist.")
freebase_id = proxy_response_json("freebaseId", None, "The disambiguated Freebase ID for this entity, or None if either this entity could not be disambiguated, or has no Freebase link.")
wikidata_id = proxy_response_json("wikidataId", None, "The disambiguated Wikidata QID for this entity, or None if either this entity could not be disambiguated, or has no Freebase link.")
wikipedia_link = proxy_response_json("wikiLink", None, "Link to Wikipedia for this entity, or None if either this entity could not be disambiguated or a Wikipedia link doesn't exist.")
matched_text = proxy_response_json("matchedText", None, "The source text string that matched this entity")
starting_position = proxy_response_json("startingPos", None, "The character offset in the unicode source text that marks the start of this entity.")
ending_position = proxy_response_json("endingPos", None, "The character offset in the unicode source text that marks the end of this entity.")
matched_positions = proxy_response_json("matchingTokens", [], "List of the token positions in the current sentence that make up this entity.")
freebase_types = proxy_response_json("freebaseTypes", [], "List of Freebase types for this entity, or an empty list if there are none.")
dbpedia_types = proxy_response_json("type", [], "List of Dbpedia types for this entity, or an empty list if there are none.")
relevance_score = proxy_response_json("relevanceScore", None, """The relevance this entity has to the source text. This is a float on a scale of 0 to 1, with 1 being the most relevant.
Relevance is computed using a number contextual clues found in the entity context and facts in the TextRazor knowledgebase.""")
confidence_score = proxy_response_json("confidenceScore", None, """
The confidence that TextRazor is correct that this is a valid entity. TextRazor uses an ever increasing
number of signals to help spot valid entities, all of which contribute to this score. These include the contextual
agreement between the words in the source text and our knowledgebase, agreement between other entities in the text,
agreement between the expected entity type and context, and prior probabilities of having seen this entity across Wikipedia
and other web datasets. The score ranges from 0.5 to 10, with 10 representing the highest confidence that this is
a valid entity.""")
data = proxy_response_json("data", {}, """Dictionary containing enriched data found for this entity.
This is either as a result of an enrichment query, or as uploaded as part of a custom Entity Dictionary.""")
crunchbase_id = proxy_response_json("crunchbaseId", None, "The disambiguated Crunchbase ID for this entity. None if either the entity could not be linked, or the entity was not a Company type.")
lei = proxy_response_json("lei", None, "The disambiguated Legal Entity Identifier for this entity. None if either the entity could not be linked, or the entity was not a Company type.")
figi = proxy_response_json("figi", None, "The disambiguated Open FIGI for this entity. None if either the entity could not be linked, or the entity was not a Company type.")
permid = proxy_response_json("permid", None, "The disambiguated Thomson Reuters Open PermID for this entity. None if either the entity could not be linked, or the entity was not a Company type.")
@property
def matched_words(self):
"""Returns a list of :class:`Word` that make up this entity."""
return self._matched_words
def __repr__(self):
return "TextRazor Entity %s at positions %s" % (self.id.encode("utf-8"), str(self.matched_positions))
def __str__(self):
return _generate_str(self)
class Entailment(object):
"""Represents a single "entailment" derived from the source text.
Requires the "entailments" extractor to be added to the TextRazor request.
"""
def __init__(self, entailment_json, link_index):
self.json = entailment_json
self._matched_words = []
for callback, arg in link_index.get(("entailment", self.id), []):
callback(arg, self)
for position in self.matched_positions:
try:
link_index[("word", position)].append((self._register_link, None))
except KeyError:
link_index[("word", position)] = [(self._register_link, None)]
def _register_link(self, dummy, word):
self._matched_words.append(word)
word._add_entailment(self)
id = proxy_response_json("id", None, "The unique id of this Entailment within the result set.")
matched_positions = proxy_response_json("wordPositions", [], "The token positions in the current sentence that generated this entailment.")
prior_score = proxy_response_json("priorScore", None, "The score of this entailment independent of the context it is used in this sentence.")
context_score = proxy_response_json("contextScore", None, "Score of this entailment given the source word's usage in its sentence and the entailed word's usage in our knowledgebase")
score = proxy_response_json("score", None, "TextRazor's overall confidence that this is a valid entailment, a combination of the prior and context score")
@property
def matched_words(self):
"""The :class:`Word` in the current sentence that generated this entailment."""
return self._matched_words
@property
def entailed_word(self):
"""The word string that is entailed by the source words."""
entailed_tree = self.json.get("entailedTree")
if entailed_tree:
return entailed_tree.get("word")
def __repr__(self):
return "TextRazor Entailment:\"%s\" at positions %s" % (str(self.entailed_word), str(self.matched_positions))
def __str__(self):
return _generate_str(self)
class RelationParam(object):
"""Represents a Param to a specific :class:`Relation`.
Requires the "relations" extractor to be added to the TextRazor request."""
def __init__(self, param_json, relation_parent, link_index):
self.json = param_json
self._relation_parent = relation_parent
self._param_words = []
for position in self.param_positions:
try:
link_index[("word", position)].append((self._register_link, None))
except KeyError:
link_index[("word", position)] = [(self._register_link, None)]
def _register_link(self, dummy, word):
self._param_words.append(word)
word._add_relation_param(self)
@property
def relation_parent(self):
"""Returns the :class:`Relation` that owns this param."""
return self._relation_parent
relation = proxy_response_json("relation", None, """
The relation of this param to the predicate.
Possible values: SUBJECT, OBJECT, OTHER""")
param_positions = proxy_response_json("wordPositions", [], "List of the positions of the words in this param within their sentence.")
@property
def param_words(self):
"""Returns a list of all the :class:`Word` that make up this param."""
return self._param_words
def entities(self):
"""Returns a generator of all :class:`Entity` mentioned in this param."""
seen = set()
for word in self.param_words:
for entity in word.entities:
if entity not in seen:
seen.add(entity)
yield entity
def __repr__(self):
return "TextRazor RelationParam:\"%s\" at positions %s" % (str(self.relation), str(self.param_words))
def __str__(self):
return _generate_str(self)
class NounPhrase(object):
"""Represents a multi-word phrase extracted from a sentence.
Requires the "relations" extractor to be added to the TextRazor request."""
def __init__(self, noun_phrase_json, link_index):
self.json = noun_phrase_json
self._words = []
for callback, arg in link_index.get(("nounPhrase", self.id), []):
callback(arg, self)
for position in self.word_positions:
try:
link_index[("word", position)].append((self._register_link, None))
except KeyError:
link_index[("word", position)] = [(self._register_link, None)]
def _register_link(self, dummy, word):
self._words.append(word)
word._add_noun_phrase(self)
id = proxy_response_json("id", None, "The unique id of this NounPhrase within the result set.")
word_positions = proxy_response_json("wordPositions", None, "List of the positions of the words in this phrase.")
@property
def words(self):
"""Returns a list of :class:`Word` that make up this phrase."""
return self._words
def __repr__(self):
return "TextRazor NounPhrase at positions %s" % (str(self.words))
def __str__(self):
return _generate_str(self, banned_properties=["word_positions", ])
class Property(object):
"""Represents a property relation extracted from raw text. A property implies an "is-a" or "has-a" relationship
between the predicate (or focus) and its property.
Requires the "relations" extractor to be added to the TextRazor request.
"""
def __init__(self, property_json, link_index):
self.json = property_json
self._predicate_words = []
self._property_words = []
for callback, arg in link_index.get(("property", self.id), []):
callback(arg, self)
for position in self.predicate_positions:
try:
link_index[("word", position)].append((self._register_link, True))
except KeyError:
link_index[("word", position)] = [(self._register_link, True)]
for position in self.property_positions:
try:
link_index[("word", position)].append((self._register_link, False))
except KeyError:
link_index[("word", position)] = [(self._register_link, False)]
def _register_link(self, is_predicate, word):
if is_predicate:
self._predicate_words.append(word)
word._add_property_predicate(self)
else:
self._property_words.append(word)
word._add_property_properties(self)
id = proxy_response_json("id", None, "The unique id of this NounPhrase within the result set.")
predicate_positions = proxy_response_json("wordPositions", [], "List of the positions of the words in the predicate (or focus) of this property.")
predicate_words = proxy_member("_predicate_words", "List of TextRazor words that make up the predicate (or focus) of this property.")
property_positions = proxy_response_json("propertyPositions", [], "List of the positions of the words that modify the predicate of this property.")
property_words = proxy_member("_property_words", "List of :class:`Word` that modify the predicate of this property.")
def __repr__(self):
return "TextRazor Property at positions %s" % (str(self.predicate_positions))
def __str__(self):
return _generate_str(self, banned_properties=["predicate_positions", ])
class Relation(object):
"""Represents a grammatical relation between words. Typically owns a number of
:class:`RelationParam`, representing the SUBJECT and OBJECT of the relation.
Requires the "relations" extractor to be added to the TextRazor request."""
def __init__(self, relation_json, link_index):
self.json = relation_json
self._params = [RelationParam(param, self, link_index) for param in relation_json["params"]]
self._predicate_words = []
for callback, arg in link_index.get(("relation", self.id), []):
callback(arg, self)
for position in self.predicate_positions:
try:
link_index[("word", position)].append((self._register_link, None))
except KeyError:
link_index[("word", position)] = [(self._register_link, None)]
def _register_link(self, dummy, word):
self._predicate_words.append(word)
word._add_relation(self)
id = proxy_response_json("id", None, "The unique id of this Relation within the result set.")
predicate_positions = proxy_response_json("wordPositions", [], "List of the positions of the predicate words in this relation.")
predicate_words = proxy_member("_predicate_words", "List of the positions of the predicate words in this relation.")
params = proxy_member("_params", "List of the TextRazor RelationParam that are part of this relation.")
def __repr__(self):
return "TextRazor Relation at positions %s" % (str(self.predicate_words))
def __str__(self):
return _generate_str(self, banned_properties=["predicate_positions", ])
class Word(object):
"""Represents a single Word (token) extracted by TextRazor.
Requires the "words" extractor to be added to the TextRazor request."""
def __init__(self, response_word, link_index):
self.json = response_word
self._parent = None
self._children = []
self._entities = []
self._entailments = []
self._relations = []
self._relation_params = []
self._property_predicates = []
self._property_properties = []
self._noun_phrases = []
for callback, arg in link_index.get(("word", self.position), []):
callback(arg, self)
def _add_child(self, child):
self._children.append(child)
def _set_parent(self, parent):
self._parent = parent
parent._add_child(self)
def _add_entity(self, entity):
self._entities.append(entity)
def _add_entailment(self, entailment):
self._entailments.append(entailment)
def _add_relation(self, relation):
self._relations.append(relation)
def _add_relation_param(self, relation_param):
self._relation_params.append(relation_param)
def _add_property_predicate(self, property):
self._property_predicates.append(property)
def _add_property_properties(self, property):
self._property_properties.append(property)
def _add_noun_phrase(self, noun_phrase):
self._noun_phrases.append(noun_phrase)
parent_position = proxy_response_json("parentPosition", None, """
The position of the grammatical parent of this Word, or None if this Word is either at the root
of the sentence or the "dependency-trees" extractor was not requested.""")
parent = proxy_member("_parent", """
Link to the TextRazor Word that is parent of this Word, or None if this word is either at the root
of the sentence or the "dependency-trees" extractor was not requested.""")
relation_to_parent = proxy_response_json("relationToParent", None, """
Returns the grammatical relation between this word and its parent, or None if this Word is either at the root
of the sentence or the "dependency-trees" extractor was not requested.
TextRazor parses into the Stanford uncollapsed dependencies, as detailed at:
http://nlp.stanford.edu/software/dependencies_manual.pdf""")
children = proxy_member("_children", """
List of TextRazor words that make up the children of this word. Returns an empty list
for leaf words, or if the "dependency-trees" extractor was not requested.""")
position = proxy_response_json("position", None, "The position of this word in its sentence.")
stem = proxy_response_json("stem", None, "The stem of this word.")
lemma = proxy_response_json("lemma", None, "The morphological root of this word, see http://en.wikipedia.org/wiki/Lemma_(morphology) for details.")
token = proxy_response_json("token", None, "The raw token string that matched this word in the source text.")
part_of_speech = proxy_response_json("partOfSpeech", None, """
The Part of Speech that applies to this word. We use the Penn treebank tagset,
as detailed here:
http://www.comp.leeds.ac.uk/ccalas/tagsets/upenn.html""")
input_start_offset = proxy_response_json("startingPos", None, """
The start offset in the input text for this token. Note that this offset applies to the
original Unicode string passed in to the api, TextRazor treats multi byte utf8 charaters as a single position.""")
input_end_offset = proxy_response_json("endingPos", None, """
The end offset in the input text for this token. Note that this offset applies to the
original Unicode string passed in to the api, TextRazor treats multi byte utf8 charaters as a single position.""")
entailments = proxy_member("_entailments", "List of :class:`Entailment` that this word entails")
entities = proxy_member("_entities", "List of :class:`Entity` that this word is a part of.")
relations = proxy_member("_relations", "List of :class:`Relation` that this word is a predicate of.")
relation_params = proxy_member("_relation_params", "List of :class:`RelationParam` that this word is a member of.")
property_properties = proxy_member("_property_properties", "List of :class:`Property` that this word is a property member of.")
property_predicates = proxy_member("_property_predicates", "List of :class:`Property` that this word is a predicate (or focus) member of.")
noun_phrases = proxy_member("_noun_phrases", "List of :class:`NounPhrase` that this word is a member of.")
senses = proxy_response_json("senses", [], "List of {'sense', 'score'} dictionaries representing scores of each Wordnet sense this this word may be a part of.")
spelling_suggestions = proxy_response_json("spellingSuggestions", [], "List of {'suggestion', 'score'} dictionaries representing scores of each spelling suggestion that might replace this word. This property requires the \"spelling\" extractor to be sent with your request.")
def __repr__(self):
return "TextRazor Word:\"%s\" at position %s" % ((self.token).encode("utf-8"), str(self.position))
def __str__(self):
return _generate_str(self)
class Sentence(object):
"""Represents a single sentence extracted by TextRazor."""
def __init__(self, sentence_json, link_index):
if "words" in sentence_json:
self._words = [Word(word_json, link_index) for word_json in sentence_json["words"]]
else:
self._words = []
self._add_links(link_index)
def _add_links(self, link_index):
if not self._words:
return
self._root_word = None
# Add links between the parent/children of the dependency tree in this sentence.
word_positions = {}
for word in self._words:
word_positions[word.position] = word
for word in self._words:
parent_position = word.parent_position
if parent_position is not None and parent_position >= 0:
word._set_parent(word_positions[parent_position])
elif word.part_of_speech not in ("$", "``", "''", "(", ")", ",", "--", ".", ":"):
# Punctuation does not get attached to any parent, any non punctuation part of speech
# must be the root word.
self._root_word = word
root_word = proxy_member("_root_word", """The root word of this sentence if "dependency-trees" extractor was requested""")
words = proxy_member("_words", """List of all the :class:`Word` in this sentence""")
class CustomAnnotation(object):
def __init__(self, annotation_json, link_index):
self.json = annotation_json
for key_value in annotation_json.get("contents", []):
for link in key_value.get("links", []):
try:
link_index[(link["annotationName"], link["linkedId"])].append((self._register_link, link))
except Exception:
link_index[(link["annotationName"], link["linkedId"])] = [(self._register_link, link)]
def _register_link(self, link, annotation):
link["linked"] = annotation
new_custom_annotation_list = []
try:
new_custom_annotation_list = getattr(annotation, self.name())
except Exception:
pass
new_custom_annotation_list.append(self)
setattr(annotation, self.name(), new_custom_annotation_list)
def name(self):
return self.json["name"]
def __getattr__(self, attr):
exists = False
for key_value in self.json["contents"]:
if "key" in key_value and key_value["key"] == attr:
exists = True
for link in key_value.get("links", []):
try:
yield link["linked"]
except Exception:
yield link
for int_value in key_value.get("intValue", []):
yield int_value
for float_value in key_value.get("floatValue", []):
yield float_value
for str_value in key_value.get("stringValue", []):
yield str_value
for bytes_value in key_value.get("bytesValue", []):
yield bytes_value
if not exists:
raise AttributeError("%r annotation has no attribute %r" % (self.name(), attr))
def __repr__(self):
return "TextRazor CustomAnnotation:\"%s\"" % (self.json["name"])
def __str__(self):
out = ["TextRazor CustomAnnotation:", str(self.json["name"]), "\n"]
for key_value in self.json["contents"]:
try:
out.append("Param %s:" % key_value["key"])
except Exception:
out.append("Param (unlabelled):")
out.append("\n")
for link in self.__getattr__(key_value["key"]):
out.append(repr(link))
out.append("\n")
return " ".join(out)
class TextRazorResponse(object):
"""Represents a processed response from TextRazor."""
def __init__(self, response_json):
self.json = response_json
self._sentences = []
self._custom_annotations = []
self._topics = []
self._coarse_topics = []
self._entities = []
self._entailments = []
self._relations = []
self._properties = []
self._noun_phrases = []
self._categories = []
link_index = {}
if "response" in self.json:
# There's a bit of magic here. Each annotation registers a callback with the ids and types of annotation
# that it is linked to. When the linked annotation is later parsed it adds the link via the callback.
# This means that annotations must be added in order of the dependency between them.
if "customAnnotations" in self.json["response"]:
self._custom_annotations = [CustomAnnotation(json, link_index) for json in self.json["response"]["customAnnotations"]]
if "topics" in self.json["response"]:
self._topics = [Topic(topic_json, link_index) for topic_json in self.json["response"]["topics"]]
if "coarseTopics" in self.json["response"]:
self._coarse_topics = [Topic(topic_json, link_index) for topic_json in self.json["response"]["coarseTopics"]]
if "entities" in self.json["response"]:
self._entities = [Entity(entity_json, link_index) for entity_json in self.json["response"]["entities"]]
if "entailments" in self.json["response"]:
self._entailments = [Entailment(entailment_json, link_index) for entailment_json in self.json["response"]["entailments"]]
if "relations" in self.json["response"]:
self._relations = [Relation(relation_json, link_index) for relation_json in self.json["response"]["relations"]]
if "properties" in self.json["response"]:
self._properties = [Property(property_json, link_index) for property_json in self.json["response"]["properties"]]
if "nounPhrases" in self.json["response"]:
self._noun_phrases = [NounPhrase(phrase_json, link_index) for phrase_json in self.json["response"]["nounPhrases"]]
if "sentences" in self.json["response"]:
self._sentences = [Sentence(sentence_json, link_index) for sentence_json in self.json["response"]["sentences"]]
if "categories" in self.json["response"]:
self._categories = [ScoredCategory(category_json) for category_json in self.json["response"]["categories"]]
@property
def raw_text(self):
""""When the set_cleanup_return_raw option is enabled, contains the input text before any cleanup."""
return self.json["response"].get("rawText", "")
@property
def cleaned_text(self):
""""When the set_cleanup_return_cleaned option is enabled, contains the input text after any cleanup/article extraction."""
return self.json["response"].get("cleanedText", "")
@property
def language(self):
""""The ISO-639-2 language used to analyze this document, either explicitly provided as the languageOverride, or as detected by the language detector."""
return self.json["response"].get("language", "")
@property
def custom_annotation_output(self):
""""Any output generated while running the embedded Prolog engine on your rules."""
return self.json["response"].get("customAnnotationOutput", "")
ok = proxy_response_json("ok", False, """
True if TextRazor successfully analyzed your document, False if there was some error.
More detailed information about the error is available in the :meth:`error` property.
""")
error = proxy_response_json("error", "", """
Descriptive error message of any problems that may have occurred during analysis,
or an empty string if there was no error.
""")
message = proxy_response_json("message", "", """
Any warning or informational messages returned from the server.
""")
def coarse_topics(self):
"""Returns a list of all the coarse :class:`Topic` in the response. """
return self._coarse_topics
def topics(self):
"""Returns a list of all the :class:`Topic` in the response. """
return self._topics
def entities(self):
"""Returns a list of all the :class:`Entity` across all sentences in the response."""
return self._entities
def words(self):
"""Returns a generator of all :class:`Word` across all sentences in the response."""
for sentence in self._sentences:
for word in sentence.words:
yield word
def entailments(self):
"""Returns a list of all :class:`Entailment` across all sentences in the response."""
return self._entailments
def relations(self):
"""Returns a list of all :class:`Relation` across all sentences in the response."""
return self._relations
def properties(self):
"""Returns a list of all :class:`Property` across all sentences in the response."""
return self._properties
def noun_phrases(self):
"""Returns a list of all the :class:`NounPhrase` across all sentences in the response."""
return self._noun_phrases
def sentences(self):
"""Returns a list of all :class:`Sentence` in the response."""
return self._sentences
def categories(self):
"""List of all :class:`ScoredCategory` in the response."""
return self._categories
def matching_rules(self):
"""Returns a list of rule names that matched this document."""
return [custom_annotation.name() for custom_annotation in self._custom_annotations]
def summary(self):
return """Request processed in: %s seconds. Num Sentences:%s""" % (
self.json["time"], len(self.json["response"]["sentences"])
)
def __getattr__(self, attr):
exists = False
for custom_annotation in self._custom_annotations:
if custom_annotation.name() == attr:
exists = True
yield custom_annotation
if not exists:
raise AttributeError("TextRazor response has no annotation %r" % attr)
class AllDictionaryEntriesResponse(object):
def __init__(self, json):
self.json = json
self.entries = [DictionaryEntry(dictionary_json) for dictionary_json in json.get("entries", [])]
total = proxy_response_json("total", 0, """
The total number of DictionaryEntry in this Dictionary.
""")
limit = proxy_response_json("limit", 0, """
The maximium number of DictionaryEntry to be returned.
""")
offset = proxy_response_json("offset", 0, """
Offset into the full list of DictionaryEntry that this result set started from.
""")
class DictionaryManager(TextRazorConnection):
path = "entities/"
def __init__(self, api_key=None):
super(DictionaryManager, self).__init__(api_key)
def create_dictionary(self, dictionary_properties):
""" Creates a new dictionary using properties provided in the dict dictionary_properties.
See the properties of class Dictionary for valid options.
>>> import textrazor
>>> dictionary_manager = textrazor.DictionaryManager("YOUR_API_KEY_HERE")
>>>
>>> dictionary_manager.create_dictionary({"id":"UNIQUE_ID"})
"""
new_dictionary = Dictionary({})
for key, value in dictionary_properties.items():
if not hasattr(new_dictionary, key):
valid_options = ",".join(name for name, obj in Dictionary.__dict__.items() if isinstance(obj, proxy_response_json))
raise TextRazorAnalysisException("Cannot create dictionary, unexpected param: %s. Supported params: %s" % (key, valid_options))
setattr(new_dictionary, key, value)
# Check for the existence of a dictionary ID, without that
# we can't generate a URL and the server will return an unhelpful message.
if not new_dictionary.id:
raise TextRazorAnalysisException("Cannot create dictionary, dictionary id not provided.")
dictionary_path = "".join([self.path, new_dictionary.id])
self.do_request(dictionary_path, json.dumps(new_dictionary.json), method="PUT")
# The server may have added some optional fields so we want to force the user to "get" the new dictionary.
return self.get_dictionary(new_dictionary.id)
def all_dictionaries(self):
""" Returns a list of all Dictionary in your account.
>>> for dictionary in dictionary_manager.all_dictionaries():
>>> print dictionary.id
"""
response = self.do_request(self.path)
if "ok" in response and not response["ok"]:
raise TextRazorAnalysisException("TextRazor was unable to retrieve all dictionaries. Error: %s" % str(response))