-
Notifications
You must be signed in to change notification settings - Fork 117
/
corenlp.py
46 lines (35 loc) · 1.59 KB
/
corenlp.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
import os
import sys
import corenlp
import requests
class CoreNLP:
def __init__(self):
if not os.environ.get('CORENLP_HOME'):
os.environ['CORENLP_HOME'] = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'../../third_party/stanford-corenlp-full-2018-10-05'))
if not os.path.exists(os.environ['CORENLP_HOME']):
raise Exception(
f'''Please install Stanford CoreNLP and put it at {os.environ['CORENLP_HOME']}.
Direct URL: http://nlp.stanford.edu/software/stanford-corenlp-full-2018-10-05.zip
Landing page: https://stanfordnlp.github.io/CoreNLP/''')
self.client = corenlp.CoreNLPClient()
def __del__(self):
self.client.stop()
def annotate(self, text, annotators=None, output_format=None, properties=None):
try:
result = self.client.annotate(text, annotators, output_format, properties)
except (corenlp.client.PermanentlyFailedException,
requests.exceptions.ConnectionError) as e:
print('\nWARNING: CoreNLP connection timeout. Recreating the server...', file=sys.stderr)
self.client.stop()
self.client.start()
result = self.client.annotate(text, annotators, output_format, properties)
return result
_singleton = None
def annotate(text, annotators=None, output_format=None, properties=None):
global _singleton
if not _singleton:
_singleton = CoreNLP()
return _singleton.annotate(text, annotators, output_format, properties)