Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. from copy import deepcopy
  18. import pandas as pd
  19. from rag.utils.doc_store_conn import OrderByExpr, FusionExpr
  20. from rag.nlp.search import Dealer
  21. class KGSearch(Dealer):
  22. def search(self, req, idxnm: str | list[str], kb_ids: list[str], emb_mdl=None, highlight=False):
  23. def merge_into_first(sres, title="") -> dict[str, str]:
  24. if not sres:
  25. return {}
  26. content_with_weight = ""
  27. df, texts = [],[]
  28. for d in sres.values():
  29. try:
  30. df.append(json.loads(d["content_with_weight"]))
  31. except Exception:
  32. texts.append(d["content_with_weight"])
  33. if df:
  34. content_with_weight = title + "\n" + pd.DataFrame(df).to_csv()
  35. else:
  36. content_with_weight = title + "\n" + "\n".join(texts)
  37. first_id = ""
  38. first_source = {}
  39. for k, v in sres.items():
  40. first_id = id
  41. first_source = deepcopy(v)
  42. break
  43. first_source["content_with_weight"] = content_with_weight
  44. first_id = next(iter(sres))
  45. return {first_id: first_source}
  46. qst = req.get("question", "")
  47. matchText, keywords = self.qryr.question(qst, min_match=0.05)
  48. condition = self.get_filters(req)
  49. ## Entity retrieval
  50. condition.update({"knowledge_graph_kwd": ["entity"]})
  51. assert emb_mdl, "No embedding model selected"
  52. matchDense = self.get_vector(qst, emb_mdl, 1024, req.get("similarity", 0.1))
  53. q_vec = matchDense.embedding_data
  54. src = req.get("fields", ["docnm_kwd", "content_ltks", "kb_id", "img_id", "title_tks", "important_kwd",
  55. "doc_id", f"q_{len(q_vec)}_vec", "position_int", "name_kwd",
  56. "available_int", "content_with_weight",
  57. "weight_int", "weight_flt"
  58. ])
  59. fusionExpr = FusionExpr("weighted_sum", 32, {"weights": "0.5, 0.5"})
  60. ent_res = self.dataStore.search(src, list(), condition, [matchText, matchDense, fusionExpr], OrderByExpr(), 0, 32, idxnm, kb_ids)
  61. ent_res_fields = self.dataStore.getFields(ent_res, src)
  62. entities = [d["name_kwd"] for d in ent_res_fields.values() if d.get("name_kwd")]
  63. ent_ids = self.dataStore.getChunkIds(ent_res)
  64. ent_content = merge_into_first(ent_res_fields, "-Entities-")
  65. if ent_content:
  66. ent_ids = list(ent_content.keys())
  67. ## Community retrieval
  68. condition = self.get_filters(req)
  69. condition.update({"entities_kwd": entities, "knowledge_graph_kwd": ["community_report"]})
  70. comm_res = self.dataStore.search(src, list(), condition, [matchText, matchDense, fusionExpr], OrderByExpr(), 0, 32, idxnm, kb_ids)
  71. comm_res_fields = self.dataStore.getFields(comm_res, src)
  72. comm_ids = self.dataStore.getChunkIds(comm_res)
  73. comm_content = merge_into_first(comm_res_fields, "-Community Report-")
  74. if comm_content:
  75. comm_ids = list(comm_content.keys())
  76. ## Text content retrieval
  77. condition = self.get_filters(req)
  78. condition.update({"knowledge_graph_kwd": ["text"]})
  79. txt_res = self.dataStore.search(src, list(), condition, [matchText, matchDense, fusionExpr], OrderByExpr(), 0, 6, idxnm, kb_ids)
  80. txt_res_fields = self.dataStore.getFields(txt_res, src)
  81. txt_ids = self.dataStore.getChunkIds(txt_res)
  82. txt_content = merge_into_first(txt_res_fields, "-Original Content-")
  83. if txt_content:
  84. txt_ids = list(txt_content.keys())
  85. return self.SearchResult(
  86. total=len(ent_ids) + len(comm_ids) + len(txt_ids),
  87. ids=[*ent_ids, *comm_ids, *txt_ids],
  88. query_vector=q_vec,
  89. highlight=None,
  90. field={**ent_content, **comm_content, **txt_content},
  91. keywords=[]
  92. )