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ů.

one.py 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. from io import BytesIO
  16. import re
  17. from deepdoc.parser.utils import get_text
  18. from rag.app import naive
  19. from rag.nlp import rag_tokenizer, tokenize
  20. from deepdoc.parser import PdfParser, ExcelParser, PlainParser, HtmlParser
  21. class Pdf(PdfParser):
  22. def __call__(self, filename, binary=None, from_page=0,
  23. to_page=100000, zoomin=3, callback=None):
  24. from timeit import default_timer as timer
  25. start = timer()
  26. callback(msg="OCR started")
  27. self.__images__(
  28. filename if not binary else binary,
  29. zoomin,
  30. from_page,
  31. to_page,
  32. callback
  33. )
  34. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  35. start = timer()
  36. self._layouts_rec(zoomin, drop=False)
  37. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  38. logging.debug("layouts cost: {}s".format(timer() - start))
  39. start = timer()
  40. self._table_transformer_job(zoomin)
  41. callback(0.65, "Table analysis ({:.2f}s)".format(timer() - start))
  42. start = timer()
  43. self._text_merge()
  44. callback(0.67, "Text merged ({:.2f}s)".format(timer() - start))
  45. tbls = self._extract_table_figure(True, zoomin, True, True)
  46. self._concat_downward()
  47. sections = [(b["text"], self.get_position(b, zoomin))
  48. for i, b in enumerate(self.boxes)]
  49. for (img, rows), poss in tbls:
  50. if not rows:
  51. continue
  52. sections.append((rows if isinstance(rows, str) else rows[0],
  53. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  54. return [(txt, "") for txt, _ in sorted(sections, key=lambda x: (
  55. x[-1][0][0], x[-1][0][3], x[-1][0][1]))], None
  56. def chunk(filename, binary=None, from_page=0, to_page=100000,
  57. lang="Chinese", callback=None, **kwargs):
  58. """
  59. Supported file formats are docx, pdf, excel, txt.
  60. One file forms a chunk which maintains original text order.
  61. """
  62. eng = lang.lower() == "english" # is_english(cks)
  63. if re.search(r"\.docx$", filename, re.IGNORECASE):
  64. callback(0.1, "Start to parse.")
  65. sections, tbls = naive.Docx()(filename, binary)
  66. sections = [s for s, _ in sections if s]
  67. for (_, html), _ in tbls:
  68. sections.append(html)
  69. callback(0.8, "Finish parsing.")
  70. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  71. pdf_parser = Pdf() if kwargs.get(
  72. "parser_config", {}).get(
  73. "layout_recognize", True) else PlainParser()
  74. sections, _ = pdf_parser(
  75. filename if not binary else binary, to_page=to_page, callback=callback)
  76. sections = [s for s, _ in sections if s]
  77. elif re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  78. callback(0.1, "Start to parse.")
  79. excel_parser = ExcelParser()
  80. sections = excel_parser.html(binary, 1000000000)
  81. elif re.search(r"\.(txt|md|markdown)$", filename, re.IGNORECASE):
  82. callback(0.1, "Start to parse.")
  83. txt = get_text(filename, binary)
  84. sections = txt.split("\n")
  85. sections = [s for s in sections if s]
  86. callback(0.8, "Finish parsing.")
  87. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  88. callback(0.1, "Start to parse.")
  89. sections = HtmlParser()(filename, binary)
  90. sections = [s for s in sections if s]
  91. callback(0.8, "Finish parsing.")
  92. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  93. callback(0.1, "Start to parse.")
  94. binary = BytesIO(binary)
  95. doc_parsed = parser.from_buffer(binary)
  96. sections = doc_parsed['content'].split('\n')
  97. sections = [s for s in sections if s]
  98. callback(0.8, "Finish parsing.")
  99. else:
  100. raise NotImplementedError(
  101. "file type not supported yet(doc, docx, pdf, txt supported)")
  102. doc = {
  103. "docnm_kwd": filename,
  104. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  105. }
  106. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  107. tokenize(doc, "\n".join(sections), eng)
  108. return [doc]
  109. if __name__ == "__main__":
  110. import sys
  111. def dummy(prog=None, msg=""):
  112. pass
  113. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)