You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import json
  17. import os
  18. import time
  19. import logging
  20. import re
  21. from api.utils.file_utils import get_project_base_directory
  22. class Dealer:
  23. def __init__(self, redis=None):
  24. self.lookup_num = 100000000
  25. self.load_tm = time.time() - 1000000
  26. self.dictionary = None
  27. path = os.path.join(get_project_base_directory(), "rag/res", "synonym.json")
  28. try:
  29. self.dictionary = json.load(open(path, 'r'))
  30. except Exception as e:
  31. logging.warn("Missing synonym.json")
  32. self.dictionary = {}
  33. if not redis:
  34. logging.warning(
  35. "Realtime synonym is disabled, since no redis connection.")
  36. if not len(self.dictionary.keys()):
  37. logging.warning(f"Fail to load synonym")
  38. self.redis = redis
  39. self.load()
  40. def load(self):
  41. if not self.redis:
  42. return
  43. if self.lookup_num < 100:
  44. return
  45. tm = time.time()
  46. if tm - self.load_tm < 3600:
  47. return
  48. self.load_tm = time.time()
  49. self.lookup_num = 0
  50. d = self.redis.get("kevin_synonyms")
  51. if not d:
  52. return
  53. try:
  54. d = json.loads(d)
  55. self.dictionary = d
  56. except Exception as e:
  57. logging.error("Fail to load synonym!" + str(e))
  58. def lookup(self, tk):
  59. self.lookup_num += 1
  60. self.load()
  61. res = self.dictionary.get(re.sub(r"[ \t]+", " ", tk.lower()), [])
  62. if isinstance(res, str):
  63. res = [res]
  64. return res
  65. if __name__ == '__main__':
  66. dl = Dealer()
  67. print(dl.dictionary)