nlu_utils.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 : name -> a string usually reviewer name
  32. :return: Boolean -> true or false
  33. '''
  34. doc = ner_model(name)
  35. if doc.ents and doc.ents[0].label_ == 'PERSON':
  36. return True
  37. else:
  38. return False
  39. def analyze_inference(response):
  40. '''
  41. response has four property
  42. ['intent', 'entities', 'intent_ranking', 'text']
  43. we took all intents that has more than 10% of intent confident.
  44. all the intents that has bellow confidence has been omitted.
  45. :param response: JSON -> a json response that RASA NLU server respond.
  46. :return: DICT ->dictionary with key of intent and value of it's confident.
  47. '''
  48. res_intents = response.get('intent_ranking')
  49. intents = {}
  50. for intent in res_intents:
  51. key = intent.get('name')
  52. values = intent.get('confidence')
  53. if values > 0.1:
  54. intents[key] = int(values*100)
  55. return intents
  56. def name_entity_recognition(text):
  57. doc = ner_model(text)
  58. names = [n for n in doc.ents if n.label_ == 'PERSON']
  59. return names