nlu_utils.py 2.6 KB

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