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

sentence_transformers_op.py 2.7 kB

10 months ago
10 months ago
10 months ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import os
  2. import sys
  3. import pyarrow as pa
  4. import torch
  5. from dora import DoraStatus
  6. from sentence_transformers import SentenceTransformer, util
  7. SHOULD_BE_INCLUDED = [
  8. "webcam.py",
  9. "object_detection.py",
  10. "plot.py",
  11. ]
  12. ## Get all python files path in given directory
  13. def get_all_functions(path):
  14. raw = []
  15. paths = []
  16. for root, dirs, files in os.walk(path):
  17. for file in files:
  18. if file.endswith(".py"):
  19. if file not in SHOULD_BE_INCLUDED:
  20. continue
  21. path = os.path.join(root, file)
  22. with open(path, encoding="utf8") as f:
  23. ## add file folder to system path
  24. sys.path.append(root)
  25. ## import module from path
  26. raw.append(f.read())
  27. paths.append(path)
  28. return raw, paths
  29. def search(query_embedding, corpus_embeddings, paths, raw, k=5, file_extension=None):
  30. cos_scores = util.cos_sim(query_embedding, corpus_embeddings)[0]
  31. top_results = torch.topk(cos_scores, k=min(k, len(cos_scores)), sorted=True)
  32. out = []
  33. for score, idx in zip(top_results[0], top_results[1]):
  34. out.extend([raw[idx], paths[idx], score])
  35. return out
  36. class Operator:
  37. """ """
  38. def __init__(self):
  39. ## TODO: Add a initialisation step
  40. self.model = SentenceTransformer("BAAI/bge-large-en-v1.5")
  41. self.encoding = []
  42. # file directory
  43. path = os.path.dirname(os.path.abspath(__file__))
  44. self.raw, self.path = get_all_functions(path)
  45. # Encode all files
  46. self.encoding = self.model.encode(self.raw)
  47. def on_event(
  48. self,
  49. dora_event,
  50. send_output,
  51. ) -> DoraStatus:
  52. if dora_event["type"] == "INPUT":
  53. if dora_event["id"] == "query":
  54. values = dora_event["value"].to_pylist()
  55. query_embeddings = self.model.encode(values)
  56. output = search(
  57. query_embeddings,
  58. self.encoding,
  59. self.path,
  60. self.raw,
  61. )
  62. [raw, path, score] = output[0:3]
  63. send_output(
  64. "raw_file",
  65. pa.array([{"raw": raw, "path": path, "user_message": values[0]}]),
  66. dora_event["metadata"],
  67. )
  68. else:
  69. input = dora_event["value"][0].as_py()
  70. index = self.path.index(input["path"])
  71. self.raw[index] = input["raw"]
  72. self.encoding[index] = self.model.encode([input["raw"]])[0]
  73. return DoraStatus.CONTINUE
  74. if __name__ == "__main__":
  75. operator = Operator()