Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

table.py 8.6KB

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