|
| 1 | +from __future__ import absolute_import |
| 2 | +from __future__ import division |
| 3 | +from __future__ import print_function |
| 4 | +from __future__ import unicode_literals |
| 5 | +from rasa_core.utils import EndpointConfig |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import requests |
| 9 | +from rasa_core import constants |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | +INTENT_MESSAGE_PREFIX = "/" |
| 13 | + |
| 14 | +from rasa_core.interpreter import NaturalLanguageInterpreter, RasaNLUHttpInterpreter |
| 15 | + |
| 16 | +class RasaMultiNLUHttpInterpreter(RasaNLUHttpInterpreter): |
| 17 | + def __init__(self, models=None, endpoint=None, project_name='default'): |
| 18 | + # type: (Text, EndpointConfig, Text) -> None |
| 19 | + |
| 20 | + self.models = models |
| 21 | + self.project_name = project_name |
| 22 | + |
| 23 | + if endpoint: |
| 24 | + self.endpoint = endpoint |
| 25 | + else: |
| 26 | + self.endpoint = EndpointConfig(constants.DEFAULT_SERVER_URL) |
| 27 | + |
| 28 | + def get_model(self, lang): |
| 29 | + return self.models.get(lang) |
| 30 | + |
| 31 | + def parse(self, text, lang): |
| 32 | + """Parse a text message. |
| 33 | +
|
| 34 | + Return a default value if the parsing of the text failed.""" |
| 35 | + |
| 36 | + default_return = {"intent": {"name": "", "confidence": 0.0}, |
| 37 | + "entities": [], "text": ""} |
| 38 | + result = self._rasa_http_parse(text, lang) |
| 39 | + |
| 40 | + return result if result is not None else default_return |
| 41 | + |
| 42 | + def _rasa_http_parse(self, text, lang): |
| 43 | + """Send a text message to a running rasa NLU http server. |
| 44 | +
|
| 45 | + Return `None` on failure.""" |
| 46 | + |
| 47 | + if not self.endpoint: |
| 48 | + logger.error( |
| 49 | + "Failed to parse text '{}' using rasa NLU over http. " |
| 50 | + "No rasa NLU server specified!".format(text)) |
| 51 | + return None |
| 52 | + |
| 53 | + params = { |
| 54 | + "token": self.endpoint.token, |
| 55 | + "model": self.get_model(lang), |
| 56 | + "project": self.project_name, |
| 57 | + "q": text |
| 58 | + } |
| 59 | + url = "{}/parse".format(self.endpoint.url) |
| 60 | + try: |
| 61 | + result = requests.get(url, params=params) |
| 62 | + if result.status_code == 200: |
| 63 | + return result.json() |
| 64 | + else: |
| 65 | + logger.error( |
| 66 | + "Failed to parse text '{}' using rasa NLU over http. " |
| 67 | + "Error: {}".format(text, result.text)) |
| 68 | + return None |
| 69 | + except Exception as e: |
| 70 | + logger.error( |
| 71 | + "Failed to parse text '{}' using rasa NLU over http. " |
| 72 | + "Error: {}".format(text, e)) |
| 73 | + return None |
0 commit comments