You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

presentation.py 4.7KB

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