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.

tag.py 4.6KB

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