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.

presentation.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import copy
  2. import re
  3. from io import BytesIO
  4. from pptx import Presentation
  5. from rag.app import callback__
  6. from rag.nlp import huqie
  7. from rag.parser.pdf_parser import HuParser
  8. class Ppt(object):
  9. def __init__(self):
  10. super().__init__()
  11. def __extract(self, shape):
  12. if shape.shape_type == 19:
  13. tb = shape.table
  14. rows = []
  15. for i in range(1, len(tb.rows)):
  16. rows.append("; ".join([tb.cell(0, j).text + ": " + tb.cell(i, j).text for j in range(len(tb.columns)) if tb.cell(i, j)]))
  17. return "\n".join(rows)
  18. if shape.has_text_frame:
  19. return shape.text_frame.text
  20. if shape.shape_type == 6:
  21. texts = []
  22. for p in shape.shapes:
  23. t = self.__extract(p)
  24. if t: texts.append(t)
  25. return "\n".join(texts)
  26. def __call__(self, fnm, from_page, to_page, callback=None):
  27. ppt = Presentation(fnm) if isinstance(
  28. fnm, str) else Presentation(
  29. BytesIO(fnm))
  30. txts = []
  31. self.total_page = len(ppt.slides)
  32. for i, slide in enumerate(ppt.slides[from_page: to_page]):
  33. texts = []
  34. for shape in slide.shapes:
  35. txt = self.__extract(shape)
  36. if txt: texts.append(txt)
  37. txts.append("\n".join(texts))
  38. callback__((i+1)/self.total_page/2, "", callback)
  39. callback__((min(to_page, self.total_page) - from_page) / self.total_page,
  40. "Page {}~{}: Text extraction finished".format(from_page, min(to_page, self.total_page)), callback)
  41. import aspose.slides as slides
  42. import aspose.pydrawing as drawing
  43. imgs = []
  44. with slides.Presentation(BytesIO(fnm)) as presentation:
  45. for i, slide in enumerate(presentation.slides[from_page: to_page]):
  46. buffered = BytesIO()
  47. slide.get_thumbnail(0.5, 0.5).save(buffered, drawing.imaging.ImageFormat.jpeg)
  48. imgs.append(buffered.getvalue())
  49. assert len(imgs) == len(txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  50. callback__((min(to_page, self.total_page) - from_page) / self.total_page,
  51. "Page {}~{}: Image extraction finished".format(from_page, min(to_page, self.total_page)), callback)
  52. return [(txts[i], imgs[i]) for i in range(len(txts))]
  53. class Pdf(HuParser):
  54. def __init__(self):
  55. super().__init__()
  56. def __garbage(self, txt):
  57. txt = txt.lower().strip()
  58. if re.match(r"[0-9\.,%/-]+$", txt): return True
  59. if len(txt) < 3:return True
  60. return False
  61. def __call__(self, filename, binary=None, from_page=0, to_page=100000, zoomin=3, callback=None):
  62. self.__images__(filename if not binary else binary, zoomin, from_page, to_page)
  63. callback__((min(to_page, self.total_page)-from_page) / self.total_page, "Page {}~{}: OCR finished".format(from_page, min(to_page, self.total_page)), callback)
  64. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(len(self.boxes), len(self.page_images))
  65. res = []
  66. #################### More precisely ###################
  67. # self._layouts_paddle(zoomin)
  68. # self._text_merge()
  69. # pages = {}
  70. # for b in self.boxes:
  71. # if self.__garbage(b["text"]):continue
  72. # if b["page_number"] not in pages: pages[b["page_number"]] = []
  73. # pages[b["page_number"]].append(b["text"])
  74. # for i, lines in pages.items():
  75. # res.append(("\n".join(lines), self.page_images[i-1]))
  76. # return res
  77. ########################################
  78. for i in range(len(self.boxes)):
  79. lines = "\n".join([b["text"] for b in self.boxes[i] if not self.__garbage(b["text"])])
  80. res.append((lines, self.page_images[i]))
  81. return res
  82. def chunk(filename, binary=None, from_page=0, to_page=100000, callback=None):
  83. doc = {
  84. "docnm_kwd": filename,
  85. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  86. }
  87. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  88. res = []
  89. if re.search(r"\.pptx?$", filename, re.IGNORECASE):
  90. for txt,img in Ppt()(filename if not binary else binary, from_page, to_page, callback):
  91. d = copy.deepcopy(doc)
  92. d["content_ltks"] = huqie.qie(txt)
  93. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  94. d["image"] = img
  95. res.append(d)
  96. return res
  97. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  98. for txt,img in Pdf()(filename if not binary else binary, from_page=from_page, to_page=to_page, callback=callback):
  99. d = copy.deepcopy(doc)
  100. d["content_ltks"] = huqie.qie(txt)
  101. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  102. d["image"] = img
  103. res.append(d)
  104. return res
  105. callback__(-1, "This kind of presentation document did not support yet!", callback)
  106. if __name__== "__main__":
  107. import sys
  108. print(chunk(sys.argv[1]))