pdf2txt.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #!/home/modulos_llm/venv/bin/python3
  2. """A command line tool for extracting text and images from PDF and
  3. output it to plain text, html, xml or tags.
  4. """
  5. import argparse
  6. import logging
  7. import sys
  8. from typing import Any, Container, Iterable, List, Optional
  9. import pdfminer.high_level
  10. from pdfminer.layout import LAParams
  11. from pdfminer.pdfexceptions import PDFValueError
  12. from pdfminer.utils import AnyIO
  13. logging.basicConfig()
  14. OUTPUT_TYPES = ((".htm", "html"), (".html", "html"), (".xml", "xml"), (".tag", "tag"))
  15. def float_or_disabled(x: str) -> Optional[float]:
  16. if x.lower().strip() == "disabled":
  17. return None
  18. try:
  19. return float(x)
  20. except ValueError:
  21. raise argparse.ArgumentTypeError(f"invalid float value: {x}")
  22. def extract_text(
  23. files: Iterable[str] = [],
  24. outfile: str = "-",
  25. laparams: Optional[LAParams] = None,
  26. output_type: str = "text",
  27. codec: str = "utf-8",
  28. strip_control: bool = False,
  29. maxpages: int = 0,
  30. page_numbers: Optional[Container[int]] = None,
  31. password: str = "",
  32. scale: float = 1.0,
  33. rotation: int = 0,
  34. layoutmode: str = "normal",
  35. output_dir: Optional[str] = None,
  36. debug: bool = False,
  37. disable_caching: bool = False,
  38. **kwargs: Any,
  39. ) -> AnyIO:
  40. if not files:
  41. raise PDFValueError("Must provide files to work upon!")
  42. if output_type == "text" and outfile != "-":
  43. for override, alttype in OUTPUT_TYPES:
  44. if outfile.endswith(override):
  45. output_type = alttype
  46. if outfile == "-":
  47. outfp: AnyIO = sys.stdout
  48. if sys.stdout.encoding is not None:
  49. codec = "utf-8"
  50. else:
  51. outfp = open(outfile, "wb")
  52. for fname in files:
  53. with open(fname, "rb") as fp:
  54. pdfminer.high_level.extract_text_to_fp(fp, **locals())
  55. return outfp
  56. def create_parser() -> argparse.ArgumentParser:
  57. parser = argparse.ArgumentParser(description=__doc__, add_help=True)
  58. parser.add_argument(
  59. "files",
  60. type=str,
  61. default=None,
  62. nargs="+",
  63. help="One or more paths to PDF files.",
  64. )
  65. parser.add_argument(
  66. "--version",
  67. "-v",
  68. action="version",
  69. version=f"pdfminer.six v{pdfminer.__version__}",
  70. )
  71. parser.add_argument(
  72. "--debug",
  73. "-d",
  74. default=False,
  75. action="store_true",
  76. help="Use debug logging level.",
  77. )
  78. parser.add_argument(
  79. "--disable-caching",
  80. "-C",
  81. default=False,
  82. action="store_true",
  83. help="If caching or resources, such as fonts, should be disabled.",
  84. )
  85. parse_params = parser.add_argument_group(
  86. "Parser",
  87. description="Used during PDF parsing",
  88. )
  89. parse_params.add_argument(
  90. "--page-numbers",
  91. type=int,
  92. default=None,
  93. nargs="+",
  94. help="A space-seperated list of page numbers to parse.",
  95. )
  96. parse_params.add_argument(
  97. "--pagenos",
  98. "-p",
  99. type=str,
  100. help="A comma-separated list of page numbers to parse. "
  101. "Included for legacy applications, use --page-numbers "
  102. "for more idiomatic argument entry.",
  103. )
  104. parse_params.add_argument(
  105. "--maxpages",
  106. "-m",
  107. type=int,
  108. default=0,
  109. help="The maximum number of pages to parse.",
  110. )
  111. parse_params.add_argument(
  112. "--password",
  113. "-P",
  114. type=str,
  115. default="",
  116. help="The password to use for decrypting PDF file.",
  117. )
  118. parse_params.add_argument(
  119. "--rotation",
  120. "-R",
  121. default=0,
  122. type=int,
  123. help="The number of degrees to rotate the PDF "
  124. "before other types of processing.",
  125. )
  126. la_params = LAParams() # will be used for defaults
  127. la_param_group = parser.add_argument_group(
  128. "Layout analysis",
  129. description="Used during layout analysis.",
  130. )
  131. la_param_group.add_argument(
  132. "--no-laparams",
  133. "-n",
  134. default=False,
  135. action="store_true",
  136. help="If layout analysis parameters should be ignored.",
  137. )
  138. la_param_group.add_argument(
  139. "--detect-vertical",
  140. "-V",
  141. default=la_params.detect_vertical,
  142. action="store_true",
  143. help="If vertical text should be considered during layout analysis",
  144. )
  145. la_param_group.add_argument(
  146. "--line-overlap",
  147. type=float,
  148. default=la_params.line_overlap,
  149. help="If two characters have more overlap than this they "
  150. "are considered to be on the same line. The overlap is specified "
  151. "relative to the minimum height of both characters.",
  152. )
  153. la_param_group.add_argument(
  154. "--char-margin",
  155. "-M",
  156. type=float,
  157. default=la_params.char_margin,
  158. help="If two characters are closer together than this margin they "
  159. "are considered to be part of the same line. The margin is "
  160. "specified relative to the width of the character.",
  161. )
  162. la_param_group.add_argument(
  163. "--word-margin",
  164. "-W",
  165. type=float,
  166. default=la_params.word_margin,
  167. help="If two characters on the same line are further apart than this "
  168. "margin then they are considered to be two separate words, and "
  169. "an intermediate space will be added for readability. The margin "
  170. "is specified relative to the width of the character.",
  171. )
  172. la_param_group.add_argument(
  173. "--line-margin",
  174. "-L",
  175. type=float,
  176. default=la_params.line_margin,
  177. help="If two lines are close together they are considered to "
  178. "be part of the same paragraph. The margin is specified "
  179. "relative to the height of a line.",
  180. )
  181. la_param_group.add_argument(
  182. "--boxes-flow",
  183. "-F",
  184. type=float_or_disabled,
  185. default=la_params.boxes_flow,
  186. help="Specifies how much a horizontal and vertical position of a "
  187. "text matters when determining the order of lines. The value "
  188. "should be within the range of -1.0 (only horizontal position "
  189. "matters) to +1.0 (only vertical position matters). You can also "
  190. "pass `disabled` to disable advanced layout analysis, and "
  191. "instead return text based on the position of the bottom left "
  192. "corner of the text box.",
  193. )
  194. la_param_group.add_argument(
  195. "--all-texts",
  196. "-A",
  197. default=la_params.all_texts,
  198. action="store_true",
  199. help="If layout analysis should be performed on text in figures.",
  200. )
  201. output_params = parser.add_argument_group(
  202. "Output",
  203. description="Used during output generation.",
  204. )
  205. output_params.add_argument(
  206. "--outfile",
  207. "-o",
  208. type=str,
  209. default="-",
  210. help="Path to file where output is written. "
  211. 'Or "-" (default) to write to stdout.',
  212. )
  213. output_params.add_argument(
  214. "--output_type",
  215. "-t",
  216. type=str,
  217. default="text",
  218. help="Type of output to generate {text,html,xml,tag}.",
  219. )
  220. output_params.add_argument(
  221. "--codec",
  222. "-c",
  223. type=str,
  224. default="utf-8",
  225. help="Text encoding to use in output file.",
  226. )
  227. output_params.add_argument(
  228. "--output-dir",
  229. "-O",
  230. default=None,
  231. help="The output directory to put extracted images in. If not given, "
  232. "images are not extracted.",
  233. )
  234. output_params.add_argument(
  235. "--layoutmode",
  236. "-Y",
  237. default="normal",
  238. type=str,
  239. help="Type of layout to use when generating html "
  240. "{normal,exact,loose}. If normal,each line is"
  241. " positioned separately in the html. If exact"
  242. ", each character is positioned separately in"
  243. " the html. If loose, same result as normal "
  244. "but with an additional newline after each "
  245. "text line. Only used when output_type is html.",
  246. )
  247. output_params.add_argument(
  248. "--scale",
  249. "-s",
  250. type=float,
  251. default=1.0,
  252. help="The amount of zoom to use when generating html file. "
  253. "Only used when output_type is html.",
  254. )
  255. output_params.add_argument(
  256. "--strip-control",
  257. "-S",
  258. default=False,
  259. action="store_true",
  260. help="Remove control statement from text. "
  261. "Only used when output_type is xml.",
  262. )
  263. return parser
  264. def parse_args(args: Optional[List[str]]) -> argparse.Namespace:
  265. parsed_args = create_parser().parse_args(args=args)
  266. # Propagate parsed layout parameters to LAParams object
  267. if parsed_args.no_laparams:
  268. parsed_args.laparams = None
  269. else:
  270. parsed_args.laparams = LAParams(
  271. line_overlap=parsed_args.line_overlap,
  272. char_margin=parsed_args.char_margin,
  273. line_margin=parsed_args.line_margin,
  274. word_margin=parsed_args.word_margin,
  275. boxes_flow=parsed_args.boxes_flow,
  276. detect_vertical=parsed_args.detect_vertical,
  277. all_texts=parsed_args.all_texts,
  278. )
  279. if parsed_args.page_numbers:
  280. parsed_args.page_numbers = {x - 1 for x in parsed_args.page_numbers}
  281. if parsed_args.pagenos:
  282. parsed_args.page_numbers = {int(x) - 1 for x in parsed_args.pagenos.split(",")}
  283. if parsed_args.output_type == "text" and parsed_args.outfile != "-":
  284. for override, alttype in OUTPUT_TYPES:
  285. if parsed_args.outfile.endswith(override):
  286. parsed_args.output_type = alttype
  287. return parsed_args
  288. def main(args: Optional[List[str]] = None) -> int:
  289. parsed_args = parse_args(args)
  290. outfp = extract_text(**vars(parsed_args))
  291. outfp.close()
  292. return 0
  293. if __name__ == "__main__":
  294. sys.exit(main())