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

presentation.py 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 PIL import Image
  17. from rag.nlp import tokenize, is_english
  18. from rag.nlp import rag_tokenizer
  19. from deepdoc.parser import PdfParser, PptParser, PlainParser
  20. from PyPDF2 import PdfReader as pdf2_read
  21. class Ppt(PptParser):
  22. def __call__(self, fnm, from_page, to_page, callback=None):
  23. txts = super().__call__(fnm, from_page, to_page)
  24. callback(0.5, "Text extraction finished.")
  25. import aspose.slides as slides
  26. import aspose.pydrawing as drawing
  27. imgs = []
  28. with slides.Presentation(BytesIO(fnm)) as presentation:
  29. for i, slide in enumerate(presentation.slides[from_page: to_page]):
  30. buffered = BytesIO()
  31. slide.get_thumbnail(
  32. 0.5, 0.5).save(
  33. buffered, drawing.imaging.ImageFormat.jpeg)
  34. imgs.append(Image.open(buffered))
  35. assert len(imgs) == len(
  36. txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  37. callback(0.9, "Image extraction finished")
  38. self.is_english = is_english(txts)
  39. return [(txts[i], imgs[i]) for i in range(len(txts))]
  40. class Pdf(PdfParser):
  41. def __init__(self):
  42. super().__init__()
  43. def __garbage(self, txt):
  44. txt = txt.lower().strip()
  45. if re.match(r"[0-9\.,%/-]+$", txt):
  46. return True
  47. if len(txt) < 3:
  48. return True
  49. return False
  50. def __call__(self, filename, binary=None, from_page=0,
  51. to_page=100000, zoomin=3, callback=None):
  52. callback(msg="OCR is running...")
  53. self.__images__(filename if not binary else binary,
  54. zoomin, from_page, to_page, callback)
  55. callback(0.8, "Page {}~{}: OCR finished".format(
  56. from_page, min(to_page, self.total_page)))
  57. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(
  58. len(self.boxes), len(self.page_images))
  59. res = []
  60. for i in range(len(self.boxes)):
  61. lines = "\n".join([b["text"] for b in self.boxes[i]
  62. if not self.__garbage(b["text"])])
  63. res.append((lines, self.page_images[i]))
  64. callback(0.9, "Page {}~{}: Parsing finished".format(
  65. from_page, min(to_page, self.total_page)))
  66. return res
  67. class PlainPdf(PlainParser):
  68. def __call__(self, filename, binary=None, from_page=0,
  69. to_page=100000, callback=None, **kwargs):
  70. self.pdf = pdf2_read(filename if not binary else BytesIO(binary))
  71. page_txt = []
  72. for page in self.pdf.pages[from_page: to_page]:
  73. page_txt.append(page.extract_text())
  74. callback(0.9, "Parsing finished")
  75. return [(txt, None) for txt in page_txt]
  76. def chunk(filename, binary=None, from_page=0, to_page=100000,
  77. lang="Chinese", callback=None, **kwargs):
  78. """
  79. The supported file formats are pdf, pptx.
  80. Every page will be treated as a chunk. And the thumbnail of every page will be stored.
  81. PPT file will be parsed by using this method automatically, setting-up for every PPT file is not necessary.
  82. """
  83. eng = lang.lower() == "english"
  84. doc = {
  85. "docnm_kwd": filename,
  86. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  87. }
  88. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  89. res = []
  90. if re.search(r"\.pptx?$", filename, re.IGNORECASE):
  91. ppt_parser = Ppt()
  92. for pn, (txt, img) in enumerate(ppt_parser(
  93. filename if not binary else binary, from_page, 1000000, callback)):
  94. d = copy.deepcopy(doc)
  95. pn += from_page
  96. d["image"] = img
  97. d["page_num_int"] = [pn + 1]
  98. d["top_int"] = [0]
  99. d["position_int"] = [(pn + 1, 0, img.size[0], 0, img.size[1])]
  100. tokenize(d, txt, eng)
  101. res.append(d)
  102. return res
  103. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  104. pdf_parser = Pdf() if kwargs.get(
  105. "parser_config", {}).get(
  106. "layout_recognize", True) else PlainPdf()
  107. for pn, (txt, img) in enumerate(pdf_parser(filename, binary,
  108. from_page=from_page, to_page=to_page, callback=callback)):
  109. d = copy.deepcopy(doc)
  110. pn += from_page
  111. if img:
  112. d["image"] = img
  113. d["page_num_int"] = [pn + 1]
  114. d["top_int"] = [0]
  115. d["position_int"] = [
  116. (pn + 1, 0, img.size[0] if img else 0, 0, img.size[1] if img else 0)]
  117. tokenize(d, txt, eng)
  118. res.append(d)
  119. return res
  120. raise NotImplementedError(
  121. "file type not supported yet(pptx, pdf supported)")
  122. if __name__ == "__main__":
  123. import sys
  124. def dummy(a, b):
  125. pass
  126. chunk(sys.argv[1], callback=dummy)