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.

table.py 8.5KB

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