選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

qa.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 re
  14. from copy import deepcopy
  15. from io import BytesIO
  16. from timeit import default_timer as timer
  17. from nltk import word_tokenize
  18. from openpyxl import load_workbook
  19. from rag.nlp import is_english, random_choices, find_codec, qbullets_category, add_positions, has_qbullet
  20. from rag.nlp import rag_tokenizer, tokenize_table
  21. from rag.settings import cron_logger
  22. from deepdoc.parser import PdfParser, ExcelParser
  23. class Excel(ExcelParser):
  24. def __call__(self, fnm, binary=None, callback=None):
  25. if not binary:
  26. wb = load_workbook(fnm)
  27. else:
  28. wb = load_workbook(BytesIO(binary))
  29. total = 0
  30. for sheetname in wb.sheetnames:
  31. total += len(list(wb[sheetname].rows))
  32. res, fails = [], []
  33. for sheetname in wb.sheetnames:
  34. ws = wb[sheetname]
  35. rows = list(ws.rows)
  36. for i, r in enumerate(rows):
  37. q, a = "", ""
  38. for cell in r:
  39. if not cell.value:
  40. continue
  41. if not q:
  42. q = str(cell.value)
  43. elif not a:
  44. a = str(cell.value)
  45. else:
  46. break
  47. if q and a:
  48. res.append((q, a))
  49. else:
  50. fails.append(str(i + 1))
  51. if len(res) % 999 == 0:
  52. callback(len(res) *
  53. 0.6 /
  54. total, ("Extract Q&A: {}".format(len(res)) +
  55. (f"{len(fails)} failure, line: %s..." %
  56. (",".join(fails[:3])) if fails else "")))
  57. callback(0.6, ("Extract Q&A: {}. ".format(len(res)) + (
  58. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  59. self.is_english = is_english(
  60. [rmPrefix(q) for q, _ in random_choices(res, k=30) if len(q) > 1])
  61. return res
  62. class Pdf(PdfParser):
  63. def __call__(self, filename, binary=None, from_page=0,
  64. to_page=100000, zoomin=3, callback=None):
  65. start = timer()
  66. callback(msg="OCR is running...")
  67. self.__images__(
  68. filename if not binary else binary,
  69. zoomin,
  70. from_page,
  71. to_page,
  72. callback
  73. )
  74. callback(msg="OCR finished")
  75. cron_logger.info("OCR({}~{}): {}".format(from_page, to_page, timer() - start))
  76. start = timer()
  77. self._layouts_rec(zoomin, drop=False)
  78. callback(0.63, "Layout analysis finished.")
  79. self._table_transformer_job(zoomin)
  80. callback(0.65, "Table analysis finished.")
  81. self._text_merge()
  82. callback(0.67, "Text merging finished")
  83. tbls = self._extract_table_figure(True, zoomin, True, True)
  84. #self._naive_vertical_merge()
  85. # self._concat_downward()
  86. #self._filter_forpages()
  87. cron_logger.info("layouts: {}".format(timer() - start))
  88. sections = [b["text"] for b in self.boxes]
  89. bull_x0_list = []
  90. q_bull, reg = qbullets_category(sections)
  91. if q_bull == -1:
  92. raise ValueError("Unable to recognize Q&A structure.")
  93. qai_list = []
  94. last_q, last_a, last_tag = '', '', ''
  95. last_index = -1
  96. last_box = {'text':''}
  97. last_bull = None
  98. for box in self.boxes:
  99. section, line_tag = box['text'], self._line_tag(box, zoomin)
  100. has_bull, index = has_qbullet(reg, box, last_box, last_index, last_bull, bull_x0_list)
  101. last_box, last_index, last_bull = box, index, has_bull
  102. if not has_bull: # No question bullet
  103. if not last_q:
  104. continue
  105. else:
  106. last_a = f'{last_a}{section}'
  107. last_tag = f'{last_tag}{line_tag}'
  108. else:
  109. if last_q:
  110. qai_list.append((last_q, last_a, *self.crop(last_tag, need_position=True)))
  111. last_q, last_a, last_tag = '', '', ''
  112. last_q = has_bull.group()
  113. _, end = has_bull.span()
  114. last_a = section[end:]
  115. last_tag = line_tag
  116. if last_q:
  117. qai_list.append((last_q, last_a, *self.crop(last_tag, need_position=True)))
  118. return qai_list, tbls
  119. def rmPrefix(txt):
  120. return re.sub(
  121. r"^(问题|答案|回答|user|assistant|Q|A|Question|Answer|问|答)[\t:: ]+", "", txt.strip(), flags=re.IGNORECASE)
  122. def beAdocPdf(d, q, a, eng, image, poss):
  123. qprefix = "Question: " if eng else "问题:"
  124. aprefix = "Answer: " if eng else "回答:"
  125. d["content_with_weight"] = "\t".join(
  126. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  127. d["content_ltks"] = rag_tokenizer.tokenize(q)
  128. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  129. d["image"] = image
  130. add_positions(d, poss)
  131. return d
  132. def beAdoc(d, q, a, eng):
  133. qprefix = "Question: " if eng else "问题:"
  134. aprefix = "Answer: " if eng else "回答:"
  135. d["content_with_weight"] = "\t".join(
  136. [qprefix + rmPrefix(q), aprefix + rmPrefix(a)])
  137. d["content_ltks"] = rag_tokenizer.tokenize(q)
  138. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  139. return d
  140. def mdQuestionLevel(s):
  141. match = re.match(r'#*', s)
  142. return (len(match.group(0)), s.lstrip('#').lstrip()) if match else (0, s)
  143. def chunk(filename, binary=None, lang="Chinese", callback=None, **kwargs):
  144. """
  145. Excel and csv(txt) format files are supported.
  146. If the file is in excel format, there should be 2 column question and answer without header.
  147. And question column is ahead of answer column.
  148. And it's O.K if it has multiple sheets as long as the columns are rightly composed.
  149. If it's in csv format, it should be UTF-8 encoded. Use TAB as delimiter to separate question and answer.
  150. All the deformed lines will be ignored.
  151. Every pair of Q&A will be treated as a chunk.
  152. """
  153. eng = lang.lower() == "english"
  154. res = []
  155. doc = {
  156. "docnm_kwd": filename,
  157. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  158. }
  159. if re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  160. callback(0.1, "Start to parse.")
  161. excel_parser = Excel()
  162. for q, a in excel_parser(filename, binary, callback):
  163. res.append(beAdoc(deepcopy(doc), q, a, eng))
  164. return res
  165. elif re.search(r"\.(txt|csv)$", filename, re.IGNORECASE):
  166. callback(0.1, "Start to parse.")
  167. txt = ""
  168. if binary:
  169. encoding = find_codec(binary)
  170. txt = binary.decode(encoding, errors="ignore")
  171. else:
  172. with open(filename, "r") as f:
  173. while True:
  174. l = f.readline()
  175. if not l:
  176. break
  177. txt += l
  178. lines = txt.split("\n")
  179. comma, tab = 0, 0
  180. for l in lines:
  181. if len(l.split(",")) == 2: comma += 1
  182. if len(l.split("\t")) == 2: tab += 1
  183. delimiter = "\t" if tab >= comma else ","
  184. fails = []
  185. question, answer = "", ""
  186. i = 0
  187. while i < len(lines):
  188. arr = lines[i].split(delimiter)
  189. if len(arr) != 2:
  190. if question: answer += "\n" + lines[i]
  191. else:
  192. fails.append(str(i+1))
  193. elif len(arr) == 2:
  194. if question and answer: res.append(beAdoc(deepcopy(doc), question, answer, eng))
  195. question, answer = arr
  196. i += 1
  197. if len(res) % 999 == 0:
  198. callback(len(res) * 0.6 / len(lines), ("Extract Q&A: {}".format(len(res)) + (
  199. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  200. if question: res.append(beAdoc(deepcopy(doc), question, answer, eng))
  201. callback(0.6, ("Extract Q&A: {}".format(len(res)) + (
  202. f"{len(fails)} failure, line: %s..." % (",".join(fails[:3])) if fails else "")))
  203. return res
  204. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  205. callback(0.1, "Start to parse.")
  206. pdf_parser = Pdf()
  207. count = 0
  208. qai_list, tbls = pdf_parser(filename if not binary else binary,
  209. from_page=0, to_page=10000, callback=callback)
  210. res = tokenize_table(tbls, doc, eng)
  211. for q, a, image, poss in qai_list:
  212. count += 1
  213. res.append(beAdocPdf(deepcopy(doc), q, a, eng, image, poss))
  214. return res
  215. elif re.search(r"\.(md|markdown)$", filename, re.IGNORECASE):
  216. callback(0.1, "Start to parse.")
  217. txt = ""
  218. if binary:
  219. encoding = find_codec(binary)
  220. txt = binary.decode(encoding, errors="ignore")
  221. else:
  222. with open(filename, "r") as f:
  223. while True:
  224. l = f.readline()
  225. if not l:
  226. break
  227. txt += l
  228. lines = txt.split("\n")
  229. last_question, last_answer = "", ""
  230. question_stack, level_stack = [], []
  231. code_block = False
  232. level_index = [-1] * 7
  233. for index, l in enumerate(lines):
  234. if not l.strip():
  235. continue
  236. if l.strip().startswith('```'):
  237. code_block = not code_block
  238. question_level, question = 0, ''
  239. if not code_block:
  240. question_level, question = mdQuestionLevel(l)
  241. if not question_level or question_level > 6: # not a question
  242. last_answer = f'{last_answer}\n{l}'
  243. else: # is a question
  244. if last_answer:
  245. sum_question = '\n'.join(question_stack)
  246. if sum_question:
  247. res.append(beAdoc(deepcopy(doc), sum_question, last_answer, eng))
  248. last_answer = ''
  249. i = question_level
  250. while question_stack and i <= level_stack[-1]:
  251. question_stack.pop()
  252. level_stack.pop()
  253. question_stack.append(question)
  254. level_stack.append(question_level)
  255. if last_answer:
  256. sum_question = '\n'.join(question_stack)
  257. if sum_question:
  258. res.append(beAdoc(deepcopy(doc), sum_question, last_answer, eng))
  259. return res
  260. raise NotImplementedError(
  261. "Excel, csv(txt), pdf and markdown format files are supported.")
  262. if __name__ == "__main__":
  263. import sys
  264. def dummy(prog=None, msg=""):
  265. pass
  266. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)