nlu_utils.py 2.1 KB

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