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.

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