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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #
  2. # Copyright 2025 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 re
  18. import csv
  19. from copy import deepcopy
  20. from deepdoc.parser.utils import get_text
  21. from rag.app.qa import Excel
  22. from rag.nlp import rag_tokenizer
  23. def beAdoc(d, q, a, eng, row_num=-1):
  24. d["content_with_weight"] = q
  25. d["content_ltks"] = rag_tokenizer.tokenize(q)
  26. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  27. d["tag_kwd"] = [t.strip().replace(".", "_") for t in a.split(",") if t.strip()]
  28. if row_num >= 0:
  29. d["top_int"] = [row_num]
  30. return d
  31. def chunk(filename, binary=None, lang="Chinese", callback=None, **kwargs):
  32. """
  33. Excel and csv(txt) format files are supported.
  34. If the file is in excel format, there should be 2 column content and tags without header.
  35. And content column is ahead of tags column.
  36. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  37. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate content and tags.
  38. All the deformed lines will be ignored.
  39. Every pair will be treated as a chunk.
  40. """
  41. eng = lang.lower() == "english"
  42. res = []
  43. doc = {
  44. "docnm_kwd": filename,
  45. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  46. }
  47. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  48. callback(0.1, "Start to parse.")
  49. excel_parser = Excel()
  50. for ii, (q, a) in enumerate(excel_parser(filename, binary, callback)):
  51. res.append(beAdoc(deepcopy(doc), q, a, eng, ii))
  52. return res
  53. elif re.search(r"\.(txt)$", filename, re.IGNORECASE):
  54. callback(0.1, "Start to parse.")
  55. txt = get_text(filename, binary)
  56. lines = txt.split("\n")
  57. comma, tab = 0, 0
  58. for line in lines:
  59. if len(line.split(",")) == 2:
  60. comma += 1
  61. if len(line.split("\t")) == 2:
  62. tab += 1
  63. delimiter = "\t" if tab >= comma else ","
  64. fails = []
  65. content = ""
  66. i = 0
  67. while i < len(lines):
  68. arr = lines[i].split(delimiter)
  69. if len(arr) != 2:
  70. content += "\n" + lines[i]
  71. elif len(arr) == 2:
  72. content += "\n" + arr[0]
  73. res.append(beAdoc(deepcopy(doc), content, arr[1], eng, i))
  74. content = ""
  75. i += 1
  76. if len(res) % 999 == 0:
  77. callback(len(res) * 0.6 / len(lines), ("Extract TAG: {}".format(len(res)) + (
  78. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  79. callback(0.6, ("Extract TAG: {}".format(len(res)) + (
  80. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  81. return res
  82. elif re.search(r"\.(csv)$", filename, re.IGNORECASE):
  83. callback(0.1, "Start to parse.")
  84. txt = get_text(filename, binary)
  85. lines = txt.split("\n")
  86. fails = []
  87. content = ""
  88. res = []
  89. reader = csv.reader(lines)
  90. for i, row in enumerate(reader):
  91. row = [r.strip() for r in row if r.strip()]
  92. if len(row) != 2:
  93. content += "\n" + lines[i]
  94. elif len(row) == 2:
  95. content += "\n" + row[0]
  96. res.append(beAdoc(deepcopy(doc), content, row[1], eng, i))
  97. content = ""
  98. if len(res) % 999 == 0:
  99. callback(len(res) * 0.6 / len(lines), ("Extract Tags: {}".format(len(res)) + (
  100. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  101. callback(0.6, ("Extract TAG : {}".format(len(res)) + (
  102. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  103. return res
  104. raise NotImplementedError(
  105. "Excel, csv(txt) format files are supported.")
  106. def label_question(question, kbs):
  107. from api.db.services.knowledgebase_service import KnowledgebaseService
  108. from graphrag.utils import get_tags_from_cache, set_tags_to_cache
  109. from api import settings
  110. tags = None
  111. tag_kb_ids = []
  112. for kb in kbs:
  113. if kb.parser_config.get("tag_kb_ids"):
  114. tag_kb_ids.extend(kb.parser_config["tag_kb_ids"])
  115. if tag_kb_ids:
  116. all_tags = get_tags_from_cache(tag_kb_ids)
  117. if not all_tags:
  118. all_tags = settings.retrievaler.all_tags_in_portion(kb.tenant_id, tag_kb_ids)
  119. set_tags_to_cache(tags=all_tags, kb_ids=tag_kb_ids)
  120. else:
  121. all_tags = json.loads(all_tags)
  122. tag_kbs = KnowledgebaseService.get_by_ids(tag_kb_ids)
  123. tags = settings.retrievaler.tag_query(question,
  124. list(set([kb.tenant_id for kb in tag_kbs])),
  125. tag_kb_ids,
  126. all_tags,
  127. kb.parser_config.get("topn_tags", 3)
  128. )
  129. return tags
  130. if __name__ == "__main__":
  131. import sys
  132. def dummy(prog=None, msg=""):
  133. pass
  134. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)