| 5 | import requests |
| 6 | |
| 7 | class CoreNLP: |
| 8 | def __init__(self): |
| 9 | if not os.environ.get('CORENLP_HOME'): |
| 10 | os.environ['CORENLP_HOME'] = os.path.abspath( |
| 11 | os.path.join( |
| 12 | os.path.dirname(__file__), |
| 13 | '../../third_party/stanford-corenlp-full-2018-10-05')) |
| 14 | if not os.path.exists(os.environ['CORENLP_HOME']): |
| 15 | raise Exception( |
| 16 | '''Please install Stanford CoreNLP and put it at {}. |
| 17 | |
| 18 | Direct URL: http://nlp.stanford.edu/software/stanford-corenlp-full-2018-10-05.zip |
| 19 | Landing page: https://stanfordnlp.github.io/CoreNLP/'''.format(os.environ['CORENLP_HOME'])) |
| 20 | self.client = corenlp.CoreNLPClient(endpoint="http://localhost:8999") |
| 21 | |
| 22 | def __del__(self): |
| 23 | self.client.stop() |
| 24 | |
| 25 | def annotate(self, text, annotators=None, output_format=None, properties=None): |
| 26 | try: |
| 27 | result = self.client.annotate(text, annotators, output_format, properties) |
| 28 | except (corenlp.client.PermanentlyFailedException, |
| 29 | requests.exceptions.ConnectionError) as e: |
| 30 | print('\nWARNING: CoreNLP connection timeout. Recreating the server...', file=sys.stderr) |
| 31 | self.client.stop() |
| 32 | self.client.start() |
| 33 | result = self.client.annotate(text, annotators, output_format, properties) |
| 34 | |
| 35 | return result |
| 36 | |
| 37 | |
| 38 | _singleton = None |