您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

synonym.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import json
  2. import os
  3. import time
  4. import logging
  5. import re
  6. from api.utils.file_utils import get_project_base_directory
  7. class Dealer:
  8. def __init__(self, redis=None):
  9. self.lookup_num = 100000000
  10. self.load_tm = time.time() - 1000000
  11. self.dictionary = None
  12. path = os.path.join(get_project_base_directory(), "rag/res", "synonym.json")
  13. try:
  14. self.dictionary = json.load(open(path, 'r'))
  15. except Exception as e:
  16. logging.warn("Miss synonym.json")
  17. self.dictionary = {}
  18. if not redis:
  19. logging.warning(
  20. "Realtime synonym is disabled, since no redis connection.")
  21. if not len(self.dictionary.keys()):
  22. logging.warning(f"Fail to load synonym")
  23. self.redis = redis
  24. self.load()
  25. def load(self):
  26. if not self.redis:
  27. return
  28. if self.lookup_num < 100:
  29. return
  30. tm = time.time()
  31. if tm - self.load_tm < 3600:
  32. return
  33. self.load_tm = time.time()
  34. self.lookup_num = 0
  35. d = self.redis.get("kevin_synonyms")
  36. if not d:
  37. return
  38. try:
  39. d = json.loads(d)
  40. self.dictionary = d
  41. except Exception as e:
  42. logging.error("Fail to load synonym!" + str(e))
  43. def lookup(self, tk):
  44. self.lookup_num += 1
  45. self.load()
  46. res = self.dictionary.get(re.sub(r"[ \t]+", " ", tk.lower()), [])
  47. if isinstance(res, str):
  48. res = [res]
  49. return res
  50. if __name__ == '__main__':
  51. dl = Dealer()
  52. print(dl.dictionary)