high_level.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """Functions that can be used for the most common use-cases for pdf2zh.six"""
  2. import logging
  3. import sys
  4. from io import StringIO
  5. from typing import Any, BinaryIO, Container, Iterator, Optional, cast
  6. import torch
  7. import numpy as np
  8. import tqdm
  9. from pymupdf import Document
  10. from pdf2zh.converter import (
  11. HOCRConverter,
  12. HTMLConverter,
  13. PDFPageAggregator,
  14. TextConverter,
  15. XMLConverter,
  16. )
  17. from pdf2zh.image import ImageWriter
  18. from pdf2zh.layout import LAParams, LTPage
  19. from pdf2zh.pdfdevice import PDFDevice, TagExtractor
  20. from pdf2zh.pdfexceptions import PDFValueError
  21. from pdf2zh.pdfinterp import PDFPageInterpreter, PDFResourceManager
  22. from pdf2zh.pdfpage import PDFPage
  23. from pdf2zh.utils import AnyIO, FileOrName, open_filename
  24. def extract_text_to_fp(
  25. inf: BinaryIO,
  26. outfp: AnyIO,
  27. output_type: str = "text",
  28. codec: str = "utf-8",
  29. laparams: Optional[LAParams] = None,
  30. maxpages: int = 0,
  31. pages: Optional[Container[int]] = None,
  32. password: str = "",
  33. scale: float = 1.0,
  34. rotation: int = 0,
  35. layoutmode: str = "normal",
  36. output_dir: Optional[str] = None,
  37. strip_control: bool = False,
  38. debug: bool = False,
  39. disable_caching: bool = False,
  40. page_count: int = 0,
  41. vfont: str = "",
  42. vchar: str = "",
  43. thread: int = 0,
  44. doc_en: Document = None,
  45. model = None,
  46. lang_in: str = "",
  47. lang_out: str = "",
  48. service: str = "",
  49. **kwargs: Any,
  50. ) -> None:
  51. """Parses text from inf-file and writes to outfp file-like object.
  52. Takes loads of optional arguments but the defaults are somewhat sane.
  53. Beware laparams: Including an empty LAParams is not the same as passing
  54. None!
  55. :param inf: a file-like object to read PDF structure from, such as a
  56. file handler (using the builtin `open()` function) or a `BytesIO`.
  57. :param outfp: a file-like object to write the text to.
  58. :param output_type: May be 'text', 'xml', 'html', 'hocr', 'tag'.
  59. Only 'text' works properly.
  60. :param codec: Text decoding codec
  61. :param laparams: An LAParams object from pdf2zh.layout. Default is None
  62. but may not layout correctly.
  63. :param maxpages: How many pages to stop parsing after
  64. :param page_numbers: zero-indexed page numbers to operate on.
  65. :param password: For encrypted PDFs, the password to decrypt.
  66. :param scale: Scale factor
  67. :param rotation: Rotation factor
  68. :param layoutmode: Default is 'normal', see
  69. pdf2zh.converter.HTMLConverter
  70. :param output_dir: If given, creates an ImageWriter for extracted images.
  71. :param strip_control: Does what it says on the tin
  72. :param debug: Output more logging data
  73. :param disable_caching: Does what it says on the tin
  74. :param other:
  75. :return: nothing, acting as it does on two streams. Use StringIO to get
  76. strings.
  77. """
  78. if debug:
  79. logging.getLogger().setLevel(logging.DEBUG)
  80. imagewriter = None
  81. if output_dir:
  82. imagewriter = ImageWriter(output_dir)
  83. rsrcmgr = PDFResourceManager(caching=not disable_caching)
  84. device: Optional[PDFDevice] = None
  85. layout={}
  86. if output_type != "text" and outfp == sys.stdout:
  87. outfp = sys.stdout.buffer
  88. if output_type == "text":
  89. device = TextConverter(
  90. rsrcmgr,
  91. outfp,
  92. codec=codec,
  93. laparams=laparams,
  94. imagewriter=imagewriter,
  95. vfont=vfont,
  96. vchar=vchar,
  97. thread=thread,
  98. layout=layout,
  99. lang_in=lang_in,
  100. lang_out=lang_out,
  101. service=service,
  102. )
  103. elif output_type == "xml":
  104. device = XMLConverter(
  105. rsrcmgr,
  106. outfp,
  107. codec=codec,
  108. laparams=laparams,
  109. imagewriter=imagewriter,
  110. stripcontrol=strip_control,
  111. )
  112. elif output_type == "html":
  113. device = HTMLConverter(
  114. rsrcmgr,
  115. outfp,
  116. codec=codec,
  117. scale=scale,
  118. layoutmode=layoutmode,
  119. laparams=laparams,
  120. imagewriter=imagewriter,
  121. )
  122. elif output_type == "hocr":
  123. device = HOCRConverter(
  124. rsrcmgr,
  125. outfp,
  126. codec=codec,
  127. laparams=laparams,
  128. stripcontrol=strip_control,
  129. )
  130. elif output_type == "tag":
  131. # Binary I/O is required, but we have no good way to test it here.
  132. device = TagExtractor(rsrcmgr, cast(BinaryIO, outfp), codec=codec)
  133. else:
  134. msg = f"Output type can be text, html, xml or tag but is {output_type}"
  135. raise PDFValueError(msg)
  136. assert device is not None
  137. obj_patch={}
  138. interpreter = PDFPageInterpreter(rsrcmgr, device, obj_patch)
  139. if pages:
  140. total_pages=len(pages)
  141. else:
  142. total_pages=page_count
  143. for page in tqdm.tqdm(PDFPage.get_pages(
  144. inf,
  145. pages,
  146. maxpages=maxpages,
  147. password=password,
  148. caching=not disable_caching,
  149. ), total=total_pages, position=0):
  150. pix = doc_en[page.pageno].get_pixmap()
  151. image = np.fromstring(pix.samples, np.uint8).reshape(pix.height, pix.width, 3)[:, :, ::-1]
  152. page_layout=model.predict(
  153. image,
  154. imgsz=int(pix.height/32)*32,
  155. device="cuda:0" if torch.cuda.is_available() else "cpu", # Auto-select GPU if available
  156. )[0]
  157. # kdtree 是不可能 kdtree 的,不如直接渲染成图片,用空间换时间
  158. box=np.ones((pix.height, pix.width))
  159. h,w=box.shape
  160. vcls=['abandon','figure','table','isolate_formula','formula_caption']
  161. for i,d in enumerate(page_layout.boxes):
  162. if not page_layout.names[int(d.cls)] in vcls:
  163. x0,y0,x1,y1=d.xyxy.squeeze()
  164. x0,y0,x1,y1=np.clip(int(x0-1),0,w-1),np.clip(int(h-y1-1),0,h-1),np.clip(int(x1+1),0,w-1),np.clip(int(h-y0+1),0,h-1)
  165. box[y0:y1,x0:x1]=i+2
  166. for i,d in enumerate(page_layout.boxes):
  167. if page_layout.names[int(d.cls)] in vcls:
  168. x0,y0,x1,y1=d.xyxy.squeeze()
  169. x0,y0,x1,y1=np.clip(int(x0-1),0,w-1),np.clip(int(h-y1-1),0,h-1),np.clip(int(x1+1),0,w-1),np.clip(int(h-y0+1),0,h-1)
  170. box[y0:y1,x0:x1]=0
  171. layout[page.pageno]=box
  172. # print(page.number,page_layout)
  173. page.rotate = (page.rotate + rotation) % 360
  174. # 新建一个 xref 存放新指令流
  175. page.page_xref = doc_en.get_new_xref() # hack
  176. doc_en.update_object(page.page_xref, "<<>>")
  177. doc_en.update_stream(page.page_xref,b'')
  178. doc_en[page.pageno].set_contents(page.page_xref)
  179. interpreter.process_page(page)
  180. device.close()
  181. return obj_patch
  182. def extract_text(
  183. pdf_file: FileOrName,
  184. password: str = "",
  185. page_numbers: Optional[Container[int]] = None,
  186. maxpages: int = 0,
  187. caching: bool = True,
  188. codec: str = "utf-8",
  189. laparams: Optional[LAParams] = None,
  190. ) -> str:
  191. """Parse and return the text contained in a PDF file.
  192. :param pdf_file: Either a file path or a file-like object for the PDF file
  193. to be worked on.
  194. :param password: For encrypted PDFs, the password to decrypt.
  195. :param page_numbers: List of zero-indexed page numbers to extract.
  196. :param maxpages: The maximum number of pages to parse
  197. :param caching: If resources should be cached
  198. :param codec: Text decoding codec
  199. :param laparams: An LAParams object from pdf2zh.layout. If None, uses
  200. some default settings that often work well.
  201. :return: a string containing all of the text extracted.
  202. """
  203. if laparams is None:
  204. laparams = LAParams()
  205. with open_filename(pdf_file, "rb") as fp, StringIO() as output_string:
  206. fp = cast(BinaryIO, fp) # we opened in binary mode
  207. rsrcmgr = PDFResourceManager(caching=caching)
  208. device = TextConverter(rsrcmgr, output_string, codec=codec, laparams=laparams)
  209. interpreter = PDFPageInterpreter(rsrcmgr, device)
  210. for page in PDFPage.get_pages(
  211. fp,
  212. page_numbers,
  213. maxpages=maxpages,
  214. password=password,
  215. caching=caching,
  216. ):
  217. interpreter.process_page(page)
  218. return output_string.getvalue()
  219. def extract_pages(
  220. pdf_file: FileOrName,
  221. password: str = "",
  222. page_numbers: Optional[Container[int]] = None,
  223. maxpages: int = 0,
  224. caching: bool = True,
  225. laparams: Optional[LAParams] = None,
  226. ) -> Iterator[LTPage]:
  227. """Extract and yield LTPage objects
  228. :param pdf_file: Either a file path or a file-like object for the PDF file
  229. to be worked on.
  230. :param password: For encrypted PDFs, the password to decrypt.
  231. :param page_numbers: List of zero-indexed page numbers to extract.
  232. :param maxpages: The maximum number of pages to parse
  233. :param caching: If resources should be cached
  234. :param laparams: An LAParams object from pdf2zh.layout. If None, uses
  235. some default settings that often work well.
  236. :return: LTPage objects
  237. """
  238. if laparams is None:
  239. laparams = LAParams()
  240. with open_filename(pdf_file, "rb") as fp:
  241. fp = cast(BinaryIO, fp) # we opened in binary mode
  242. resource_manager = PDFResourceManager(caching=caching)
  243. device = PDFPageAggregator(resource_manager, laparams=laparams)
  244. interpreter = PDFPageInterpreter(resource_manager, device)
  245. for page in PDFPage.get_pages(
  246. fp,
  247. page_numbers,
  248. maxpages=maxpages,
  249. password=password,
  250. caching=caching,
  251. ):
  252. interpreter.process_page(page)
  253. layout = device.get_result()
  254. yield layout