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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 logging
  14. from tika import parser
  15. import re
  16. from io import BytesIO
  17. from docx import Document
  18. from api.db import ParserType
  19. from deepdoc.parser.utils import get_text
  20. from rag.nlp import bullets_category, remove_contents_table, hierarchical_merge, \
  21. make_colon_as_title, tokenize_chunks, docx_question_level
  22. from rag.nlp import rag_tokenizer
  23. from deepdoc.parser import PdfParser, DocxParser, PlainParser, HtmlParser
  24. class Docx(DocxParser):
  25. def __init__(self):
  26. pass
  27. def __clean(self, line):
  28. line = re.sub(r"\u3000", " ", line).strip()
  29. return line
  30. def old_call(self, filename, binary=None, from_page=0, to_page=100000):
  31. self.doc = Document(
  32. filename) if not binary else Document(BytesIO(binary))
  33. pn = 0
  34. lines = []
  35. for p in self.doc.paragraphs:
  36. if pn > to_page:
  37. break
  38. if from_page <= pn < to_page and p.text.strip():
  39. lines.append(self.__clean(p.text))
  40. for run in p.runs:
  41. if 'lastRenderedPageBreak' in run._element.xml:
  42. pn += 1
  43. continue
  44. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  45. pn += 1
  46. return [line for line in lines if line]
  47. def __call__(self, filename, binary=None, from_page=0, to_page=100000):
  48. self.doc = Document(
  49. filename) if not binary else Document(BytesIO(binary))
  50. pn = 0
  51. lines = []
  52. bull = bullets_category([p.text for p in self.doc.paragraphs])
  53. for p in self.doc.paragraphs:
  54. if pn > to_page:
  55. break
  56. question_level, p_text = docx_question_level(p, bull)
  57. if not p_text.strip("\n"):
  58. continue
  59. lines.append((question_level, p_text))
  60. for run in p.runs:
  61. if 'lastRenderedPageBreak' in run._element.xml:
  62. pn += 1
  63. continue
  64. if 'w:br' in run._element.xml and 'type="page"' in run._element.xml:
  65. pn += 1
  66. visit = [False for _ in range(len(lines))]
  67. sections = []
  68. for s in range(len(lines)):
  69. e = s + 1
  70. while e < len(lines):
  71. if lines[e][0] <= lines[s][0]:
  72. break
  73. e += 1
  74. if e - s == 1 and visit[s]:
  75. continue
  76. sec = []
  77. next_level = lines[s][0] + 1
  78. while not sec and next_level < 22:
  79. for i in range(s+1, e):
  80. if lines[i][0] != next_level:
  81. continue
  82. sec.append(lines[i][1])
  83. visit[i] = True
  84. next_level += 1
  85. sec.insert(0, lines[s][1])
  86. sections.append("\n".join(sec))
  87. return [s for s in sections if s]
  88. def __str__(self) -> str:
  89. return f'''
  90. question:{self.question},
  91. answer:{self.answer},
  92. level:{self.level},
  93. childs:{self.childs}
  94. '''
  95. class Pdf(PdfParser):
  96. def __init__(self):
  97. self.model_speciess = ParserType.LAWS.value
  98. super().__init__()
  99. def __call__(self, filename, binary=None, from_page=0,
  100. to_page=100000, zoomin=3, callback=None):
  101. from timeit import default_timer as timer
  102. start = timer()
  103. callback(msg="OCR started")
  104. self.__images__(
  105. filename if not binary else binary,
  106. zoomin,
  107. from_page,
  108. to_page,
  109. callback
  110. )
  111. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  112. start = timer()
  113. self._layouts_rec(zoomin)
  114. callback(0.67, "Layout analysis ({:.2f}s)".format(timer() - start))
  115. logging.debug("layouts:".format(
  116. ))
  117. self._naive_vertical_merge()
  118. callback(0.8, "Text extraction ({:.2f}s)".format(timer() - start))
  119. return [(b["text"], self._line_tag(b, zoomin))
  120. for b in self.boxes], None
  121. def chunk(filename, binary=None, from_page=0, to_page=100000,
  122. lang="Chinese", callback=None, **kwargs):
  123. """
  124. Supported file formats are docx, pdf, txt.
  125. """
  126. doc = {
  127. "docnm_kwd": filename,
  128. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  129. }
  130. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  131. pdf_parser = None
  132. sections = []
  133. # is it English
  134. eng = lang.lower() == "english" # is_english(sections)
  135. if re.search(r"\.docx$", filename, re.IGNORECASE):
  136. callback(0.1, "Start to parse.")
  137. for txt in Docx()(filename, binary):
  138. sections.append(txt)
  139. callback(0.8, "Finish parsing.")
  140. chunks = sections
  141. return tokenize_chunks(chunks, doc, eng, pdf_parser)
  142. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  143. pdf_parser = Pdf() if kwargs.get(
  144. "parser_config", {}).get(
  145. "layout_recognize", True) else PlainParser()
  146. for txt, poss in pdf_parser(filename if not binary else binary,
  147. from_page=from_page, to_page=to_page, callback=callback)[0]:
  148. sections.append(txt + poss)
  149. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  150. callback(0.1, "Start to parse.")
  151. txt = get_text(filename, binary)
  152. sections = txt.split("\n")
  153. sections = [s for s in sections if s]
  154. callback(0.8, "Finish parsing.")
  155. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  156. callback(0.1, "Start to parse.")
  157. sections = HtmlParser()(filename, binary)
  158. sections = [s for s in sections if s]
  159. callback(0.8, "Finish parsing.")
  160. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  161. callback(0.1, "Start to parse.")
  162. binary = BytesIO(binary)
  163. doc_parsed = parser.from_buffer(binary)
  164. sections = doc_parsed['content'].split('\n')
  165. sections = [s for s in sections if s]
  166. callback(0.8, "Finish parsing.")
  167. else:
  168. raise NotImplementedError(
  169. "file type not supported yet(doc, docx, pdf, txt supported)")
  170. # Remove 'Contents' part
  171. remove_contents_table(sections, eng)
  172. make_colon_as_title(sections)
  173. bull = bullets_category(sections)
  174. chunks = hierarchical_merge(bull, sections, 5)
  175. if not chunks:
  176. callback(0.99, "No chunk parsed out.")
  177. return tokenize_chunks(["\n".join(ck)
  178. for ck in chunks], doc, eng, pdf_parser)
  179. if __name__ == "__main__":
  180. import sys
  181. def dummy(prog=None, msg=""):
  182. pass
  183. chunk(sys.argv[1], callback=dummy)