forked from rosette-api/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
877 lines (727 loc) · 31.7 KB
/
api.py
File metadata and controls
877 lines (727 loc) · 31.7 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
#!/usr/bin/env python
"""
Python client for the Rosette API.
Copyright (c) 2014-2015 Basis Technology Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from io import BytesIO
import gzip
import json
import logging
import sys
import time
import os
import requests
import re
import warnings
_BINDING_VERSION = '1.5.0'
_GZIP_BYTEARRAY = bytearray([0x1F, 0x8b, 0x08])
_IsPy3 = sys.version_info[0] == 3
if _IsPy3:
_GZIP_SIGNATURE = _GZIP_BYTEARRAY
else:
_GZIP_SIGNATURE = str(_GZIP_BYTEARRAY)
class _ReturnObject:
def __init__(self, js, code):
self._json = js
self.status_code = code
def json(self):
return self._json
def _my_loads(obj, response_headers):
if _IsPy3:
d1 = json.loads(obj.decode("utf-8")).copy()
d1.update(response_headers)
return d1 # if py3, need chars.
else:
d2 = json.loads(obj).copy()
d2.update(response_headers)
return d2
class RosetteException(Exception):
"""Exception thrown by all Rosette API operations for errors local and remote.
TBD. Right now, the only valid operation is conversion to __str__.
"""
def __init__(self, status, message, response_message):
self.status = status
self.message = message
self.response_message = response_message
def __str__(self):
sst = self.status
if not (isinstance(sst, str)):
sst = repr(sst)
return sst + ": " + self.message + ":\n " + self.response_message
class _PseudoEnum:
def __init__(self):
pass
@classmethod
def validate(cls, value, name):
values = []
for (k, v) in vars(cls).items():
if not k.startswith("__"):
values += [v]
# this is still needed to make sure that the parameter NAMES are known.
# If python didn't allow setting unknown values, this would be a
# language error.
if value not in values:
raise RosetteException(
"unknownVariable",
"The value supplied for " +
name +
" is not one of " +
", ".join(values) +
".",
repr(value))
class MorphologyOutput(_PseudoEnum):
LEMMAS = "lemmas"
PARTS_OF_SPEECH = "parts-of-speech"
COMPOUND_COMPONENTS = "compound-components"
HAN_READINGS = "han-readings"
COMPLETE = "complete"
class _DocumentParamSetBase(object):
def __init__(self, repertoire):
self.__params = {}
for k in repertoire:
self.__params[k] = None
def __setitem__(self, key, val):
if key not in self.__params:
raise RosetteException(
"badKey", "Unknown Rosette parameter key", repr(key))
self.__params[key] = val
def __getitem__(self, key):
if key not in self.__params:
raise RosetteException(
"badKey", "Unknown Rosette parameter key", repr(key))
return self.__params[key]
def validate(self):
pass
def serialize(self, options):
self.validate()
v = {}
for (key, val) in self.__params.items():
if val is None:
pass
else:
v[key] = val
if options is not None and len(options) > 0:
v['options'] = options
return v
def _byteify(s): # py 3 only
l = len(s)
b = bytearray(l)
for ix in range(l):
oc = ord(s[ix])
assert (oc < 256)
b[ix] = oc
return b
class DocumentParameters(_DocumentParamSetBase):
"""Parameter object for all operations requiring input other than
translated_name.
Two fields, C{content} and C{inputUri}, are set via
the subscript operator, e.g., C{params["content"]}, or the
convenience instance methods L{DocumentParameters.load_document_file}
and L{DocumentParameters.load_document_string}.
Using subscripts instead of instance variables facilitates diagnosis.
If the field C{contentUri} is set to the URL of a web page (only
protocols C{http, https, ftp, ftps} are accepted), the server will
fetch the content from that web page. In this case, C{content} may not be set.
"""
def __init__(self):
"""Create a L{DocumentParameters} object."""
_DocumentParamSetBase.__init__(
self, ("content", "contentUri", "language", "genre"))
self.file_name = ""
self.useMultipart = False
def validate(self):
"""Internal. Do not use."""
if self["content"] is None:
if self["contentUri"] is None:
raise RosetteException(
"badArgument",
"Must supply one of Content or ContentUri",
"bad arguments")
else: # self["content"] not None
if self["contentUri"] is not None:
raise RosetteException(
"badArgument",
"Cannot supply both Content and ContentUri",
"bad arguments")
def serialize(self, options):
"""Internal. Do not use."""
self.validate()
slz = super(DocumentParameters, self).serialize(options)
return slz
def load_document_file(self, path):
"""Loads a file into the object.
The file will be read as bytes; the appropriate conversion will
be determined by the server.
@parameter path: Pathname of a file acceptable to the C{open} function.
"""
self.useMultipart = True
self.file_name = path
self.load_document_string(open(path, "rb").read())
def load_document_string(self, s):
"""Loads a string into the object.
The string will be taken as bytes or as Unicode dependent upon
its native python type.
@parameter s: A string, possibly a unicode-string, to be loaded
for subsequent analysis.
"""
self["content"] = s
class NameTranslationParameters(_DocumentParamSetBase):
"""Parameter object for C{name-translation} endpoint.
The following values may be set by the indexing (i.e.,C{ parms["name"]}) operator. The values are all
strings (when not C{None}).
All are optional except C{name} and C{targetLanguage}. Scripts are in
ISO15924 codes, and languages in ISO639 (two- or three-letter) codes. See the Name Translation documentation for
more description of these terms, as well as the content of the return result.
C{name} The name to be translated.
C{targetLangauge} The language into which the name is to be translated.
C{entityType} The entity type (TBD) of the name.
C{sourceLanguageOfOrigin} The language of origin of the name.
C{sourceLanguageOfUse} The language of use of the name.
C{sourceScript} The script in which the name is supplied.
C{targetScript} The script into which the name should be translated.
C{targetScheme} The transliteration scheme by which the translated name should be rendered.
"""
def __init__(self):
self.useMultipart = False
_DocumentParamSetBase.__init__(
self,
("name",
"targetLanguage",
"entityType",
"sourceLanguageOfOrigin",
"sourceLanguageOfUse",
"sourceScript",
"targetScript",
"targetScheme",
"genre"))
def validate(self):
"""Internal. Do not use."""
for n in ("name", "targetLanguage"): # required
if self[n] is None:
raise RosetteException(
"missingParameter",
"Required Name Translation parameter not supplied",
repr(n))
class NameSimilarityParameters(_DocumentParamSetBase):
"""Parameter object for C{name-similarity} endpoint.
All are required.
C{name1} The name to be matched, a C{name} object.
C{name2} The name to be matched, a C{name} object.
The C{name} object contains these fields:
C{text} Text of the name, required.
C{language} Language of the name in ISO639 three-letter code, optional.
C{script} The ISO15924 code of the name, optional.
C{entityType} The entity type, can be "PERSON", "LOCATION" or "ORGANIZATION", optional.
"""
def __init__(self):
self.useMultipart = False
_DocumentParamSetBase.__init__(self, ("name1", "name2"))
def validate(self):
"""Internal. Do not use."""
for n in ("name1", "name2"): # required
if self[n] is None:
raise RosetteException(
"missingParameter",
"Required Name Similarity parameter not supplied",
repr(n))
class EndpointCaller:
"""L{EndpointCaller} objects are invoked via their instance methods to obtain results
from the Rosette server described by the L{API} object from which they
are created. Each L{EndpointCaller} object communicates with a specific endpoint
of the Rosette server, specified at its creation. Use the specific
instance methods of the L{API} object to create L{EndpointCaller} objects bound to
corresponding endpoints.
Use L{EndpointCaller.ping} to ping, and L{EndpointCaller.info} to retrieve server info.
For all other types of requests, use L{EndpointCaller.call}, which accepts
an argument specifying the data to be processed and certain metadata.
The results of all operations are returned as python dictionaries, whose
keys and values correspond exactly to those of the corresponding
JSON return value described in the Rosette web service documentation.
"""
def __init__(self, api, suburl):
"""This method should not be invoked by the user. Creation is reserved
for internal use by API objects."""
self.service_url = api.service_url
self.user_key = api.user_key
self.logger = api.logger
self.useMultipart = False
self.suburl = suburl
self.debug = api.debug
self.api = api
def __finish_result(self, r, ename):
code = r.status_code
the_json = r.json()
if code == 200:
return the_json
else:
if 'message' in the_json:
msg = the_json['message']
else:
msg = the_json['code'] # punt if can't get real message
if self.suburl is None:
complaint_url = "Top level info"
else:
complaint_url = ename + " " + self.suburl
raise RosetteException(code, complaint_url +
" : failed to communicate with Rosette", msg)
def info(self):
"""Issues an "info" request to the L{EndpointCaller}'s specific endpoint.
@return: A dictionary telling server version and other
identifying data."""
url = self.service_url + "info"
headers = {'Accept': 'application/json', 'X-RosetteAPI-Binding': 'python', 'X-RosetteAPI-Binding-Version': _BINDING_VERSION}
customHeaders = self.api.getCustomHeaders()
pattern = re.compile('^X-RosetteAPI-')
if customHeaders is not None:
for key in customHeaders.keys():
if pattern.match(key) is not None:
headers[key] = customHeaders[key]
else:
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key)
self.api.clearCustomHeaders()
if self.debug:
headers['X-RosetteAPI-Devel'] = 'true'
self.logger.info('info: ' + url)
if self.user_key is not None:
headers["X-RosetteAPI-Key"] = self.user_key
r = self.api._get_http(url, headers=headers)
return self.__finish_result(r, "info")
def ping(self):
"""Issues a "ping" request to the L{EndpointCaller}'s (server-wide) endpoint.
@return: A dictionary if OK. If the server cannot be reached,
or is not the right server or some other error occurs, it will be
signalled."""
url = self.service_url + 'ping'
headers = {'Accept': 'application/json', 'X-RosetteAPI-Binding': 'python', 'X-RosetteAPI-Binding-Version': _BINDING_VERSION}
customHeaders = self.api.getCustomHeaders()
pattern = re.compile('^X-RosetteAPI-')
if customHeaders is not None:
for key in customHeaders.keys():
if pattern.match(key) is not None:
headers[key] = customHeaders[key]
else:
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key)
self.api.clearCustomHeaders()
if self.debug:
headers['X-RosetteAPI-Devel'] = 'true'
self.logger.info('Ping: ' + url)
if self.user_key is not None:
headers["X-RosetteAPI-Key"] = self.user_key
r = self.api._get_http(url, headers=headers)
return self.__finish_result(r, "ping")
def call(self, parameters):
"""Invokes the endpoint to which this L{EndpointCaller} is bound.
Passes data and metadata specified by C{parameters} to the server
endpoint to which this L{EndpointCaller} object is bound. For all
endpoints except C{name-translation} and C{name-similarity}, it must be a L{DocumentParameters}
object or a string; for C{name-translation}, it must be an L{NameTranslationParameters} object;
for C{name-similarity}, it must be an L{NameSimilarityParameters} object. For relationships,
it may be an L(DocumentParameters).
In all cases, the result is returned as a python dictionary
conforming to the JSON object described in the endpoint's entry
in the Rosette web service documentation.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the endpoint. See the
details for those object types.
@type parameters: For C{name-translation}, L{NameTranslationParameters}, otherwise L{DocumentParameters} or L{str}
@return: A python dictionary expressing the result of the invocation.
"""
if not isinstance(parameters, _DocumentParamSetBase):
if self.suburl != "name-similarity" and self.suburl != "name-translation":
text = parameters
parameters = DocumentParameters()
parameters['content'] = text
else:
raise RosetteException(
"incompatible",
"Text-only input only works for DocumentParameter endpoints",
self.suburl)
self.useMultipart = parameters.useMultipart
url = self.service_url + self.suburl
params_to_serialize = parameters.serialize(self.api.options)
headers = {}
if self.user_key is not None:
customHeaders = self.api.getCustomHeaders()
pattern = re.compile('^X-RosetteAPI-')
if customHeaders is not None:
for key in customHeaders.keys():
if pattern.match(key) is not None:
headers[key] = customHeaders[key]
else:
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key)
self.api.clearCustomHeaders()
headers["X-RosetteAPI-Key"] = self.user_key
headers["X-RosetteAPI-Binding"] = "python"
headers["X-RosetteAPI-Binding-Version"] = _BINDING_VERSION
if self.useMultipart:
payload = None
if (self.api.urlParameters):
payload = self.api.urlParameters
params = dict(
(key,
value) for key,
value in params_to_serialize.iteritems() if key == 'language')
files = {
'content': (
os.path.basename(
parameters.file_name),
params_to_serialize["content"],
'text/plain'),
'request': (
'request_options',
json.dumps(params),
'application/json')}
request = requests.Request(
'POST', url, files=files, headers=headers, params=payload)
session = requests.Session()
prepared_request = session.prepare_request(request)
resp = session.send(prepared_request)
rdata = resp.content
response_headers = {"responseHeaders": dict(resp.headers)}
status = resp.status_code
r = _ReturnObject(_my_loads(rdata, response_headers), status)
else:
if self.debug:
headers['X-RosetteAPI-Devel'] = True
self.logger.info('operate: ' + url)
headers['Accept'] = "application/json"
headers['Accept-Encoding'] = "gzip"
headers['Content-Type'] = "application/json"
r = self.api._post_http(url, params_to_serialize, headers)
return self.__finish_result(r, "operate")
class API:
"""
Rosette Python Client Binding API; representation of a Rosette server.
Call instance methods upon this object to obtain L{EndpointCaller} objects
which can communicate with particular Rosette server endpoints.
"""
def __init__(
self,
user_key=None,
service_url='https://api.rosette.com/rest/v1/',
retries=5,
refresh_duration=0.5,
debug=False):
""" Create an L{API} object.
@param user_key: (Optional; required for servers requiring authentication.) An authentication string to be sent
as user_key with all requests. The default Rosette server requires authentication.
to the server.
"""
# logging.basicConfig(filename="binding.log", filemode="w", level=logging.DEBUG)
self.user_key = user_key
self.service_url = service_url if service_url.endswith(
'/') else service_url + '/'
self.logger = logging.getLogger('rosette.api')
self.logger.info('Initialized on ' + self.service_url)
self.debug = debug
if (retries < 1):
retries = 1
if (refresh_duration < 0):
refresh_duration = 0
self.connection_refresh_duration = refresh_duration
self.options = {}
self.customHeaders = {}
self.urlParameters = {}
self.maxPoolSize = 1
self.session = requests.Session()
def _set_pool_size(self):
adapter = requests.adapters.HTTPAdapter(pool_maxsize=self.maxPoolSize)
if 'https:' in self.service_url:
self.session.mount('https://', adapter)
else:
self.session.mount('http://', adapter)
def _make_request(self, op, url, data, headers):
"""
@param op: POST or GET
@param url: endpoing URL
@param data: request data
@param headers: request headers
"""
headers['User-Agent'] = "RosetteAPIPython/" + _BINDING_VERSION
message = None
code = "unknownError"
rdata = None
response_headers = {}
payload = None
if (self.urlParameters):
payload = self.urlParameters
request = requests.Request(op, url, data=data, headers=headers, params=payload)
session = requests.Session()
prepared_request = session.prepare_request(request)
try:
response = session.send(prepared_request)
status = response.status_code
rdata = response.content
dict_headers = dict(response.headers)
response_headers = {"responseHeaders": dict_headers}
if 'x-rosetteapi-concurrency' in dict_headers:
if dict_headers['x-rosetteapi-concurrency'] != self.maxPoolSize:
self.maxPoolSize = dict_headers['x-rosetteapi-concurrency']
self._set_pool_size()
if status == 200:
return rdata, status, response_headers
if rdata is not None:
try:
the_json = _my_loads(rdata, response_headers)
if 'message' in the_json:
message = the_json['message']
if "code" in the_json:
code = the_json['code']
else:
code = status
if not message:
message = rdata
raise RosetteException(code, message, url)
except:
raise
except requests.exceptions.RequestException as e:
raise RosetteException(
e.message,
"Unable to establish connection to the Rosette API server",
url)
raise RosetteException(code, message, url)
def _get_http(self, url, headers):
"""
Simple wrapper for the GET request
@param url: endpoint URL
@param headers: request headers
"""
(rdata, status, response_headers) = self._make_request(
"GET", url, None, headers)
return _ReturnObject(_my_loads(rdata, response_headers), status)
def _post_http(self, url, data, headers):
"""
Simple wrapper for the POST request
@param url: endpoint URL
@param data: request data
@param headers: request headers
"""
if data is None:
json_data = ""
else:
json_data = json.dumps(data)
(rdata, status, response_headers) = self._make_request(
"POST", url, json_data, headers)
if len(rdata) > 3 and rdata[0:3] == _GZIP_SIGNATURE:
buf = BytesIO(rdata)
rdata = gzip.GzipFile(fileobj=buf).read()
return _ReturnObject(_my_loads(rdata, response_headers), status)
def getPoolSize(self):
"""
Returns the maximum pool size, which is the returned x-rosetteapi-concurrency value
"""
return int(self.maxPoolSize)
def setOption(self, name, value):
"""
Sets an option
@param name: name of option
@param value: value of option
"""
if value is None:
self.options.pop(name, None)
else:
self.options[name] = value
def getOption(self, name):
"""
Gets an option
@param name: name of option
@return: value of option
"""
if name in self.options.keys():
return self.options[name]
else:
return None
def clearOptions(self):
"""
Clears all options
"""
self.options.clear()
def setUrlParameter(self, name, value):
"""
Sets a URL parameter
@param name: name of parameter
@param value: value of parameter
"""
if value is None:
self.urlParameters.pop(name, None)
else:
self.urlParameters[name] = value
def getUrlParameter(self, name):
"""
Gets a URL parameter
@param name: name of parameter
@return: value of parameter
"""
if name in self.urlParameters.keys():
return self.urlParameters[name]
else:
return None
def clearUrlParameters(self):
"""
Clears all options
"""
self.urlParameters.clear()
def setCustomHeaders(self, name, value):
"""
Sets custom headers
@param headers: array of custom headers to be set
"""
if value is None:
self.customHeaders.pop(name, None)
else:
self.customHeaders[name] = value
def getCustomHeaders(self):
"""
Get custom headers
"""
return self.customHeaders
def clearCustomHeaders(self):
"""
Clears custom headers
"""
self.customHeaders.clear()
def ping(self):
"""
Create a ping L{EndpointCaller} for the server and ping it.
@return: A python dictionary including the ping message of the L{API}
"""
return EndpointCaller(self, None).ping()
def info(self):
"""
Create a ping L{EndpointCaller} for the server and ping it.
@return: A python dictionary including the ping message of the L{API}
"""
return EndpointCaller(self, None).info()
def language(self, parameters):
"""
Create an L{EndpointCaller} for language identification and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the language identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of language
identification."""
return EndpointCaller(self, "language").call(parameters)
def sentences(self, parameters):
"""
Create an L{EndpointCaller} to break a text into sentences and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the sentence identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of sentence identification."""
return EndpointCaller(self, "sentences").call(parameters)
def tokens(self, parameters):
"""
Create an L{EndpointCaller} to break a text into tokens and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the tokens identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of tokenization."""
return EndpointCaller(self, "tokens").call(parameters)
def morphology(self, parameters, facet=MorphologyOutput.COMPLETE):
"""
Create an L{EndpointCaller} to returns a specific facet
of the morphological analyses of texts to which it is applied and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the morphology analyzer.
@type parameters: L{DocumentParameters} or L{str}
@param facet: The facet desired, to be returned by the created L{EndpointCaller}.
@type facet: An element of L{MorphologyOutput}.
@return: A python dictionary containing the results of morphological analysis."""
return EndpointCaller(self, "morphology/" + facet).call(parameters)
def entities(self, parameters):
"""
Create an L{EndpointCaller} to identify named entities found in the texts
to which it is applied and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the entity identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of entity extraction."""
return EndpointCaller(self, "entities").call(parameters)
def categories(self, parameters):
"""
Create an L{EndpointCaller} to identify the category of the text to which
it is applied and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the category identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of categorization."""
return EndpointCaller(self, "categories").call(parameters)
def sentiment(self, parameters):
"""
Create an L{EndpointCaller} to identify the sentiment of the text to
which it is applied and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the sentiment identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of sentiment identification."""
"""Create an L{EndpointCaller} to identify sentiments of the texts
to which is applied.
@return: An L{EndpointCaller} object which can return sentiments
of texts to which it is applied."""
return EndpointCaller(self, "sentiment").call(parameters)
def relationships(self, parameters):
"""
Create an L{EndpointCaller} to identify the relationships between entities in the text to
which it is applied and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the relationships identifier.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of relationship extraction."""
return EndpointCaller(self, "relationships").call(parameters)
def name_translation(self, parameters):
"""
Create an L{EndpointCaller} to perform name analysis and translation
upon the name to which it is applied and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the name translator.
@type parameters: L{NameTranslationParameters}
@return: A python dictionary containing the results of name translation."""
return EndpointCaller(self, "name-translation").call(parameters)
def translated_name(self, parameters):
""" deprecated
Call name_translation to perform name analysis and translation
upon the name to which it is applied.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the name translator.
@type parameters: L{NameTranslationParameters}
@return: A python dictionary containing the results of name translation."""
return self.name_translation(parameters)
def name_similarity(self, parameters):
"""
Create an L{EndpointCaller} to perform name similarity scoring and call it.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the name matcher.
@type parameters: L{NameSimilarityParameters}
@return: A python dictionary containing the results of name matching."""
return EndpointCaller(self, "name-similarity").call(parameters)
def matched_name(self, parameters):
""" deprecated
Call name_similarity to perform name matching.
@param parameters: An object specifying the data,
and possible metadata, to be processed by the name matcher.
@type parameters: L{NameSimilarityParameters}
@return: A python dictionary containing the results of name matching."""
return self.name_similarity(parameters)
def text_embedding(self, parameters):
"""
Create an L{EndpointCaller} to identify text vectors found in the texts
to which it is applied and call it.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of text embedding."""
return EndpointCaller(self, "text-embedding").call(parameters)
def syntax_dependencies(self, parameters):
"""
Create an L{EndpointCaller} to identify the syntactic dependencies in the texts
to which it is applied and call it.
@type parameters: L{DocumentParameters} or L{str}
@return: A python dictionary containing the results of syntactic dependencies identification"""
return EndpointCaller(self, "syntax/dependencies").call(parameters)