Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 copy
  17. import re
  18. from io import BytesIO
  19. from xpinyin import Pinyin
  20. import numpy as np
  21. import pandas as pd
  22. # from openpyxl import load_workbook, Workbook
  23. from dateutil.parser import parse as datetime_parse
  24. from api.db.services.knowledgebase_service import KnowledgebaseService
  25. from deepdoc.parser.utils import get_text
  26. from rag.nlp import rag_tokenizer, tokenize
  27. from deepdoc.parser import ExcelParser
  28. class Excel(ExcelParser):
  29. def __call__(self, fnm, binary=None, from_page=0,
  30. to_page=10000000000, callback=None):
  31. if not binary:
  32. wb = Excel._load_excel_to_workbook(fnm)
  33. else:
  34. wb = Excel._load_excel_to_workbook(BytesIO(binary))
  35. total = 0
  36. for sheetname in wb.sheetnames:
  37. total += len(list(wb[sheetname].rows))
  38. res, fails, done = [], [], 0
  39. rn = 0
  40. for sheetname in wb.sheetnames:
  41. ws = wb[sheetname]
  42. rows = list(ws.rows)
  43. if not rows:
  44. continue
  45. headers = [cell.value for cell in rows[0]]
  46. missed = set([i for i, h in enumerate(headers) if h is None])
  47. headers = [
  48. cell.value for i,
  49. cell in enumerate(
  50. rows[0]) if i not in missed]
  51. if not headers:
  52. continue
  53. data = []
  54. for i, r in enumerate(rows[1:]):
  55. rn += 1
  56. if rn - 1 < from_page:
  57. continue
  58. if rn - 1 >= to_page:
  59. break
  60. row = [
  61. cell.value for ii,
  62. cell in enumerate(r) if ii not in missed]
  63. if len(row) != len(headers):
  64. fails.append(str(i))
  65. continue
  66. data.append(row)
  67. done += 1
  68. if np.array(data).size == 0:
  69. continue
  70. res.append(pd.DataFrame(np.array(data), columns=headers))
  71. callback(0.3, ("Extract records: {}~{}".format(from_page + 1, min(to_page, from_page + rn)) + (
  72. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  73. return res
  74. def trans_datatime(s):
  75. try:
  76. return datetime_parse(s.strip()).strftime("%Y-%m-%d %H:%M:%S")
  77. except Exception:
  78. pass
  79. def trans_bool(s):
  80. if re.match(r"(true|yes|是|\*|✓|✔|☑|✅|√)$",
  81. str(s).strip(), flags=re.IGNORECASE):
  82. return "yes"
  83. if re.match(r"(false|no|否|⍻|×)$", str(s).strip(), flags=re.IGNORECASE):
  84. return "no"
  85. def column_data_type(arr):
  86. arr = list(arr)
  87. counts = {"int": 0, "float": 0, "text": 0, "datetime": 0, "bool": 0}
  88. trans = {t: f for f, t in
  89. [(int, "int"), (float, "float"), (trans_datatime, "datetime"), (trans_bool, "bool"), (str, "text")]}
  90. for a in arr:
  91. if a is None:
  92. continue
  93. if re.match(r"[+-]?[0-9]{,19}(\.0+)?$", str(a).replace("%%", "")):
  94. counts["int"] += 1
  95. elif re.match(r"[+-]?[0-9.]{,19}$", str(a).replace("%%", "")):
  96. counts["float"] += 1
  97. elif re.match(r"(true|yes|是|\*|✓|✔|☑|✅|√|false|no|否|⍻|×)$", str(a), flags=re.IGNORECASE):
  98. counts["bool"] += 1
  99. elif trans_datatime(str(a)):
  100. counts["datetime"] += 1
  101. else:
  102. counts["text"] += 1
  103. counts = sorted(counts.items(), key=lambda x: x[1] * -1)
  104. ty = counts[0][0]
  105. for i in range(len(arr)):
  106. if arr[i] is None:
  107. continue
  108. try:
  109. arr[i] = trans[ty](str(arr[i]))
  110. except Exception:
  111. arr[i] = None
  112. # if ty == "text":
  113. # if len(arr) > 128 and uni / len(arr) < 0.1:
  114. # ty = "keyword"
  115. return arr, ty
  116. def chunk(filename, binary=None, from_page=0, to_page=10000000000,
  117. lang="Chinese", callback=None, **kwargs):
  118. """
  119. Excel and csv(txt) format files are supported.
  120. For csv or txt file, the delimiter between columns is TAB.
  121. The first line must be column headers.
  122. Column headers must be meaningful terms inorder to make our NLP model understanding.
  123. It's good to enumerate some synonyms using slash '/' to separate, and even better to
  124. enumerate values using brackets like 'gender/sex(male, female)'.
  125. Here are some examples for headers:
  126. 1. supplier/vendor\tcolor(yellow, red, brown)\tgender/sex(male, female)\tsize(M,L,XL,XXL)
  127. 2. 姓名/名字\t电话/手机/微信\t最高学历(高中,职高,硕士,本科,博士,初中,中技,中专,专科,专升本,MPA,MBA,EMBA)
  128. Every row in table will be treated as a chunk.
  129. """
  130. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  131. callback(0.1, "Start to parse.")
  132. excel_parser = Excel()
  133. dfs = excel_parser(
  134. filename,
  135. binary,
  136. from_page=from_page,
  137. to_page=to_page,
  138. callback=callback)
  139. elif re.search(r"\.(txt|csv)$", filename, re.IGNORECASE):
  140. callback(0.1, "Start to parse.")
  141. txt = get_text(filename, binary)
  142. lines = txt.split("\n")
  143. fails = []
  144. headers = lines[0].split(kwargs.get("delimiter", "\t"))
  145. rows = []
  146. for i, line in enumerate(lines[1:]):
  147. if i < from_page:
  148. continue
  149. if i >= to_page:
  150. break
  151. row = [field for field in line.split(kwargs.get("delimiter", "\t"))]
  152. if len(row) != len(headers):
  153. fails.append(str(i))
  154. continue
  155. rows.append(row)
  156. callback(0.3, ("Extract records: {}~{}".format(from_page, min(len(lines), to_page)) + (
  157. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  158. dfs = [pd.DataFrame(np.array(rows), columns=headers)]
  159. else:
  160. raise NotImplementedError(
  161. "file type not supported yet(excel, text, csv supported)")
  162. res = []
  163. PY = Pinyin()
  164. fieds_map = {
  165. "text": "_tks",
  166. "int": "_long",
  167. "keyword": "_kwd",
  168. "float": "_flt",
  169. "datetime": "_dt",
  170. "bool": "_kwd"}
  171. for df in dfs:
  172. for n in ["id", "_id", "index", "idx"]:
  173. if n in df.columns:
  174. del df[n]
  175. clmns = df.columns.values
  176. if len(clmns) != len(set(clmns)):
  177. duplicates = [col for col in clmns if list(clmns).count(col) > 1]
  178. raise ValueError(f"Duplicate column names detected: {set(duplicates)}")
  179. txts = list(copy.deepcopy(clmns))
  180. py_clmns = [
  181. PY.get_pinyins(
  182. re.sub(
  183. r"(/.*|([^()]+?)|\([^()]+?\))",
  184. "",
  185. str(n)),
  186. '_')[0] for n in clmns]
  187. clmn_tys = []
  188. for j in range(len(clmns)):
  189. cln, ty = column_data_type(df[clmns[j]])
  190. clmn_tys.append(ty)
  191. df[clmns[j]] = cln
  192. if ty == "text":
  193. txts.extend([str(c) for c in cln if c])
  194. clmns_map = [(py_clmns[i].lower() + fieds_map[clmn_tys[i]], str(clmns[i]).replace("_", " "))
  195. for i in range(len(clmns))]
  196. eng = lang.lower() == "english" # is_english(txts)
  197. for ii, row in df.iterrows():
  198. d = {
  199. "docnm_kwd": filename,
  200. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  201. }
  202. row_txt = []
  203. for j in range(len(clmns)):
  204. if row[clmns[j]] is None:
  205. continue
  206. if not str(row[clmns[j]]):
  207. continue
  208. if not isinstance(row[clmns[j]], pd.Series) and pd.isna(row[clmns[j]]):
  209. continue
  210. fld = clmns_map[j][0]
  211. d[fld] = row[clmns[j]] if clmn_tys[j] != "text" else rag_tokenizer.tokenize(
  212. row[clmns[j]])
  213. row_txt.append("{}:{}".format(clmns[j], row[clmns[j]]))
  214. if not row_txt:
  215. continue
  216. tokenize(d, "; ".join(row_txt), eng)
  217. res.append(d)
  218. KnowledgebaseService.update_parser_config(
  219. kwargs["kb_id"], {"field_map": {k: v for k, v in clmns_map}})
  220. callback(0.35, "")
  221. return res
  222. if __name__ == "__main__":
  223. import sys
  224. def dummy(prog=None, msg=""):
  225. pass
  226. chunk(sys.argv[1], callback=dummy)