nlu_utils.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from django.conf import settings
  2. from requests import post
  3. import json
  4. from difflib import SequenceMatcher
  5. from review.models import Review
  6. nlu_server_url = settings.NLU_SERVER_URI
  7. ner_model = settings.MODEL
  8. def filter_with_last_ten_reviews(location_id, replies):
  9. replies = list(replies)
  10. revs = Review.objects.filter(location_id=location_id).exclude(reply=None).order_by('-update_time')[:10]
  11. for r in revs:
  12. s1 = r.reply.replied_text
  13. for rep in replies:
  14. s2 = rep.reply
  15. similarity = SequenceMatcher(None, s1, s2).ratio()
  16. if similarity > 0.7:
  17. replies.remove(rep)
  18. print('%.2f'%similarity, ' -------------- ', rep.reply_category)
  19. return replies
  20. def model_inference(text):
  21. url = nlu_server_url + '/model/parse'
  22. payload = {'text': text}
  23. headers = {'content-type': 'application/json'}
  24. response = post(url, data=json.dumps(payload), headers=headers)
  25. if response.status_code == 200:
  26. return response.json()
  27. return response
  28. def is_a_name(name):
  29. '''
  30. function that decide whether it is a person name or not
  31. :param -> a string usually reviewer name:
  32. :return -> a boolean True/False:
  33. '''
  34. response = model_inference(name.title())
  35. entities = response.get('entities')
  36. if not entities:
  37. return False
  38. entity = entities[0]
  39. if entity.get('entity') == 'PERSON':
  40. return True
  41. else:
  42. return False
  43. def analyze_inference(response):
  44. '''
  45. response has four property
  46. ['intent', 'entities', 'intent_ranking', 'text']
  47. we took all intents that has more than 10% of intent confident.
  48. all the intents that has bellow confidence has been omitted.
  49. :param response: JSON -> a json response that RASA NLU server respond.
  50. :return: DICT ->dictionary with key of intent and value of it's confident.
  51. '''
  52. res_intents = response.get('intent_ranking')
  53. intents = {}
  54. for intent in res_intents:
  55. key = intent.get('name')
  56. values = intent.get('confidence')
  57. if values > 0.1:
  58. intents[key] = int(values*100)
  59. return intents
  60. def name_entity_recognition(text):
  61. doc = ner_model(text)
  62. names = [n for n in doc.ents if n.label_ == 'PERSON']
  63. return names