def query(request): '''Gets NLP API response''' if request.method == 'POST': try: data = CamelCaseJSONParser().parse(request) text = data['nlp_text'] except KeyError: return HttpResponseBadRequest() text = check_text(text) if text is None: return JsonResponse(RESPONSE_EMPTY, status=200) client = LanguageServiceClient() # pylint: disable=no-member document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) # pylint: enable=no-member try: google_category_response = client.classify_text(document=document) google_analysis_response = client.analyze_entities(document=document) response = MessageToDict(google_category_response) analysis_response = MessageToDict(google_analysis_response) except InvalidArgument: return JsonResponse(RESPONSE_EMPTY, status=200) response = make_response(response, analysis_response) return JsonResponse(response, status=200) return HttpResponseNotAllowed(['POST'])
class GoogleNaturalLanguageNameParser(object): def __init__(self): if not settings.TEST: self.client = LanguageServiceClient() # pragma: no cover self.type = enums.Entity.Type.PERSON def parse(self, content): source, text = content document = types.Document(content=text, type=enums.Document.Type.PLAIN_TEXT) entities = self.client.analyze_entities(document=document).entities return [(source, e.name) for e in entities if e.type == self.type]
def analyze_entities(text): '''Returns a set of detected entities, and parameters associated with those entities, such as the entity's type, relevance of the entity to the overall text, and locations in the text that refer to the same entity. Entities are returned in the order (highest to lowest) of their salience scores, which reflect their relevance to the overall text. :param text: string :return: JSON ''' client = LanguageServiceClient() document = types.Document(content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 entities = client.analyze_entities(document=document, encoding_type=encoding_type) return entities