Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

one.py 4.2KB

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