pdf_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. """
  2. PDF处理工具模块(重构版)
  3. 提供PDF相关处理功能的统一入口:
  4. - PDF加载与分类
  5. - PDF文本提取(支持 pypdfium2 和 fitz)
  6. - PDF图像渲染(支持多种引擎)
  7. - 坐标转换(PDF坐标 ↔ 图像坐标)
  8. - 跨页表格合并
  9. - 页面范围解析与过滤
  10. 本模块已重构为多个子模块:
  11. - pdf_coordinate_transform: 坐标转换功能
  12. - pdf_text_extraction: 文本提取功能
  13. - pdf_image_rendering: 图像渲染功能
  14. - pdf_utils: 高级API和统一入口(本文件)
  15. 为保持向后兼容性,所有原有函数都从新模块重新导出。
  16. """
  17. from typing import Dict, List, Any, Optional, Tuple, Set
  18. from pathlib import Path
  19. from PIL import Image
  20. from loguru import logger
  21. # 导入页面范围解析函数(不依赖 MinerU)
  22. from .file_utils import parse_page_range
  23. # 从子模块导入功能
  24. from .pdf_coordinate_transform import (
  25. transform_bbox_for_rotation_fitz,
  26. transform_bbox_for_rotation_pypdfium2,
  27. pdf_rotation_to_image_rotation,
  28. )
  29. from .pdf_text_extraction import (
  30. detect_pdf_doc_type,
  31. bbox_overlap,
  32. extract_text_from_pdf,
  33. extract_text_from_pdf_pypdfium2,
  34. extract_text_from_pdf_fitz,
  35. extract_all_text_blocks,
  36. extract_all_text_blocks_pypdfium2,
  37. extract_all_text_blocks_fitz,
  38. detect_page_type,
  39. get_page_rotation,
  40. )
  41. from .pdf_image_rendering import (
  42. load_images_from_pdf_unified,
  43. load_images_pypdfium2,
  44. load_images_fitz,
  45. )
  46. # 导入 MinerU 组件
  47. try:
  48. from mineru.utils.pdf_classify import classify as pdf_classify
  49. from mineru.utils.enum_class import ImageType
  50. MINERU_AVAILABLE = True
  51. except ImportError:
  52. raise ImportError("MinerU components not available for PDF processing")
  53. class PDFUtils:
  54. """
  55. PDF处理工具类(重构版)
  56. 本类提供PDF处理的高级API,内部调用已重构的子模块功能。
  57. 保持原有接口不变,确保向后兼容性。
  58. 子模块:
  59. - pdf_coordinate_transform: 坐标转换
  60. - pdf_text_extraction: 文本提取
  61. - pdf_image_rendering: 图像渲染
  62. """
  63. @staticmethod
  64. def parse_page_range(page_range: Optional[str], total_pages: int) -> Set[int]:
  65. """
  66. 解析页面范围字符串(向后兼容包装函数)
  67. 此方法是对 file_utils.parse_page_range 的包装,保持向后兼容性。
  68. 新代码应直接使用 file_utils.parse_page_range。
  69. 支持格式:
  70. - "1-5" → {0, 1, 2, 3, 4}(页码从1开始,内部转为0-based索引)
  71. - "3" → {2}
  72. - "1-5,7,9-12" → {0, 1, 2, 3, 4, 6, 8, 9, 10, 11}
  73. - "1-" → 从第1页到最后
  74. - "-5" → 从第1页到第5页
  75. Args:
  76. page_range: 页面范围字符串(页码从1开始)
  77. total_pages: 总页数
  78. Returns:
  79. 页面索引集合(0-based)
  80. """
  81. return parse_page_range(page_range, total_pages)
  82. @staticmethod
  83. def _detect_pdf_doc_type(pdf_doc: Any) -> str:
  84. """
  85. 检测 PDF 文档对象类型(向后兼容包装)
  86. Args:
  87. pdf_doc: PDF 文档对象
  88. Returns:
  89. 'pypdfium2' 或 'fitz'
  90. """
  91. return detect_pdf_doc_type(pdf_doc)
  92. @staticmethod
  93. def load_and_classify_document(
  94. document_path: Path,
  95. dpi: int = 200,
  96. page_range: Optional[str] = None,
  97. renderer: str = "fitz"
  98. ) -> Tuple[List[Dict], str, Optional[Any], str]:
  99. """
  100. 加载文档并分类,支持页面范围过滤
  101. Args:
  102. document_path: 文档路径
  103. dpi: PDF渲染DPI
  104. page_range: 页面范围字符串,如 "1-5,7,9-12"
  105. - PDF:按页码(从1开始)
  106. - 图片目录:按文件名排序后的位置(从1开始)
  107. renderer: PDF渲染引擎,"fitz" 或 "pypdfium2"
  108. Returns:
  109. (images_list, pdf_type, pdf_doc, renderer_used)
  110. - images_list: 图像列表,每个元素包含 {'img_pil': PIL.Image, 'scale': float, 'page_idx': int}
  111. - pdf_type: 'ocr' 或 'txt'
  112. - pdf_doc: PDF文档对象(如果是PDF)
  113. - renderer_used: 实际使用的渲染器类型
  114. """
  115. pdf_doc = None
  116. pdf_type = 'ocr' # 默认使用OCR模式
  117. all_images = []
  118. if document_path.is_dir():
  119. # 处理目录:遍历所有图片
  120. image_extensions = {'.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.tif'}
  121. image_files = sorted([
  122. f for f in document_path.iterdir()
  123. if f.suffix.lower() in image_extensions
  124. ])
  125. # 解析页面范围
  126. total_pages = len(image_files)
  127. selected_pages = parse_page_range(page_range, total_pages)
  128. if page_range:
  129. logger.info(f"📋 图片目录共 {total_pages} 张,选择处理 {len(selected_pages)} 张")
  130. for idx, img_file in enumerate(image_files):
  131. if idx not in selected_pages:
  132. continue
  133. img = Image.open(img_file)
  134. if img.mode != 'RGB':
  135. img = img.convert('RGB')
  136. all_images.append({
  137. 'img_pil': img,
  138. 'scale': 1.0,
  139. 'source_path': str(img_file),
  140. 'page_idx': idx,
  141. 'page_name': img_file.stem
  142. })
  143. pdf_type = 'ocr'
  144. elif document_path.suffix.lower() == '.pdf':
  145. # 处理PDF文件
  146. if not MINERU_AVAILABLE:
  147. raise RuntimeError("MinerU components not available for PDF processing")
  148. with open(document_path, 'rb') as f:
  149. pdf_bytes = f.read()
  150. # PDF分类
  151. pdf_type = pdf_classify(pdf_bytes)
  152. logger.info(f"📋 PDF classified as: {pdf_type}")
  153. # 加载图像(使用重构后的函数)
  154. images_list, pdf_doc = load_images_from_pdf_unified(
  155. pdf_bytes,
  156. dpi=dpi,
  157. image_type=ImageType.PIL,
  158. renderer=renderer
  159. )
  160. # 解析页面范围
  161. total_pages = len(images_list)
  162. selected_pages = parse_page_range(page_range, total_pages)
  163. if page_range:
  164. logger.info(f"📋 PDF 共 {total_pages} 页,选择处理 {len(selected_pages)} 页")
  165. for idx, img_dict in enumerate(images_list):
  166. if idx not in selected_pages:
  167. continue
  168. all_images.append({
  169. 'img_pil': img_dict['img_pil'],
  170. 'scale': img_dict.get('scale', dpi / 72),
  171. 'source_path': str(document_path),
  172. 'page_idx': idx,
  173. 'page_name': f"{document_path.stem}_page_{idx + 1:03d}"
  174. })
  175. elif document_path.suffix.lower() in ['.png', '.jpg', '.jpeg', '.bmp', '.tiff', '.tif']:
  176. # 处理单个图片
  177. img = Image.open(document_path)
  178. if img.mode != 'RGB':
  179. img = img.convert('RGB')
  180. all_images.append({
  181. 'img_pil': img,
  182. 'scale': 1.0,
  183. 'source_path': str(document_path),
  184. 'page_idx': 0,
  185. 'page_name': document_path.stem
  186. })
  187. pdf_type = 'ocr'
  188. else:
  189. raise ValueError(f"Unsupported file format: {document_path.suffix}")
  190. return all_images, pdf_type, pdf_doc, renderer
  191. @staticmethod
  192. def _transform_bbox_for_rotation_fitz(
  193. bbox: List[float],
  194. rotation: int,
  195. pdf_width: float,
  196. pdf_height: float,
  197. scale: float
  198. ) -> List[float]:
  199. """向后兼容包装:fitz引擎坐标转换"""
  200. return transform_bbox_for_rotation_fitz(bbox, rotation, pdf_width, pdf_height, scale)
  201. @staticmethod
  202. def _transform_bbox_for_rotation_pypdfium2(
  203. bbox: List[float],
  204. rotation: int,
  205. pdf_width: float,
  206. pdf_height: float,
  207. scale: float
  208. ) -> List[float]:
  209. """向后兼容包装:pypdfium2引擎坐标转换"""
  210. return transform_bbox_for_rotation_pypdfium2(bbox, rotation, pdf_width, pdf_height, scale)
  211. # ========================================================================
  212. # 文本提取函数(向后兼容包装)
  213. # ========================================================================
  214. # ========================================================================
  215. # 文本提取函数(向后兼容包装)
  216. # ========================================================================
  217. @staticmethod
  218. def extract_text_from_pdf(
  219. pdf_doc: Any,
  220. page_idx: int,
  221. bbox: List[float],
  222. scale: float
  223. ) -> Tuple[str, bool]:
  224. """向后兼容包装:从PDF指定区域提取文本"""
  225. return extract_text_from_pdf(pdf_doc, page_idx, bbox, scale)
  226. @staticmethod
  227. def _extract_text_from_pdf_pypdfium2(
  228. pdf_doc: Any,
  229. page_idx: int,
  230. bbox: List[float],
  231. scale: float
  232. ) -> Tuple[str, bool]:
  233. """向后兼容包装:使用pypdfium2提取文本"""
  234. return extract_text_from_pdf_pypdfium2(pdf_doc, page_idx, bbox, scale)
  235. @staticmethod
  236. def _extract_text_from_pdf_fitz(
  237. pdf_doc: Any,
  238. page_idx: int,
  239. bbox: List[float],
  240. scale: float
  241. ) -> Tuple[str, bool]:
  242. """向后兼容包装:使用fitz提取文本"""
  243. return extract_text_from_pdf_fitz(pdf_doc, page_idx, bbox, scale)
  244. @staticmethod
  245. def extract_all_text_blocks(
  246. pdf_doc: Any,
  247. page_idx: int,
  248. scale: float,
  249. return_upright_coords: bool = True,
  250. ) -> Tuple[List[Dict[str, Any]], int]:
  251. """向后兼容包装:提取页面所有文本块
  252. Args:
  253. return_upright_coords: 是否返回正视坐标(True=正视,False=旋转后)
  254. """
  255. return extract_all_text_blocks(pdf_doc, page_idx, scale, return_upright_coords)
  256. @staticmethod
  257. def _extract_all_text_blocks_pypdfium2(
  258. pdf_doc: Any,
  259. page_idx: int,
  260. scale: float
  261. ) -> Tuple[List[Dict[str, Any]], int]:
  262. """向后兼容包装:使用pypdfium2提取所有文本块"""
  263. return extract_all_text_blocks_pypdfium2(pdf_doc, page_idx, scale)
  264. @staticmethod
  265. def _extract_all_text_blocks_fitz(
  266. pdf_doc: Any,
  267. page_idx: int,
  268. scale: float
  269. ) -> Tuple[List[Dict[str, Any]], int]:
  270. """向后兼容包装:使用fitz提取所有文本块"""
  271. return extract_all_text_blocks_fitz(pdf_doc, page_idx, scale)
  272. @staticmethod
  273. def _bbox_overlap(bbox1: List[float], bbox2: List[float]) -> bool:
  274. """向后兼容包装:检查两个bbox是否重叠"""
  275. return bbox_overlap(bbox1, bbox2)
  276. # ========================================================================
  277. # 图像渲染函数(向后兼容包装)
  278. # ========================================================================
  279. @staticmethod
  280. def load_images_from_pdf_unified(
  281. pdf_bytes: bytes,
  282. dpi: int = 200,
  283. start_page_id: int = 0,
  284. end_page_id: Optional[int] = None,
  285. image_type: str = "PIL",
  286. renderer: str = "pypdfium2",
  287. timeout: Optional[int] = None,
  288. threads: int = 4,
  289. ) -> Tuple[List[Dict[str, Any]], Any]:
  290. """向后兼容包装:统一的PDF图像加载接口"""
  291. return load_images_from_pdf_unified(
  292. pdf_bytes, dpi, start_page_id, end_page_id,
  293. image_type, renderer, timeout, threads
  294. )
  295. @staticmethod
  296. def _load_images_pypdfium2(
  297. pdf_bytes: bytes,
  298. dpi: int,
  299. start_page_id: int,
  300. end_page_id: Optional[int],
  301. image_type: str,
  302. timeout: Optional[int],
  303. threads: int
  304. ) -> Tuple[List[Dict[str, Any]], Any]:
  305. """向后兼容包装:使用pypdfium2渲染"""
  306. return load_images_pypdfium2(
  307. pdf_bytes, dpi, start_page_id, end_page_id,
  308. image_type, timeout, threads
  309. )
  310. @staticmethod
  311. def _load_images_fitz(
  312. pdf_bytes: bytes,
  313. dpi: int,
  314. start_page_id: int,
  315. end_page_id: Optional[int],
  316. image_type: str
  317. ) -> Tuple[List[Dict[str, Any]], Any]:
  318. """向后兼容包装:使用fitz渲染"""
  319. return load_images_fitz(
  320. pdf_bytes, dpi, start_page_id, end_page_id, image_type
  321. )
  322. @staticmethod
  323. def detect_page_type(
  324. pdf_doc: Any,
  325. page_idx: int,
  326. char_threshold: int = 50
  327. ) -> str:
  328. """
  329. 检测页面类型(文本PDF或扫描OCR)
  330. Returns:
  331. 页面类型:'txt' 或 'ocr'
  332. """
  333. return detect_page_type(pdf_doc, page_idx, char_threshold)
  334. @staticmethod
  335. def get_page_rotation(pdf_doc: Any, page_idx: int) -> int:
  336. """
  337. 获取PDF页面的旋转角度(逆时针定义,用于图像旋转)
  338. 返回的角度可直接用于PIL.rotate()等图像旋转函数。
  339. Args:
  340. pdf_doc: PDF文档对象 (pypdfium2.PdfDocument 或 fitz.Document)
  341. page_idx: 页码索引(0-based)
  342. Returns:
  343. 旋转角度:0/90/180/270(逆时针旋转角度)
  344. Examples:
  345. >>> rotate_angle = PDFUtils.get_page_rotation(pdf_doc, 0)
  346. >>> if rotate_angle != 0:
  347. >>> image = image.rotate(-rotate_angle, expand=True) # 旋转为正视
  348. """
  349. return get_page_rotation(pdf_doc, page_idx)
  350. # ========================================================================
  351. # 其他功能
  352. # ========================================================================
  353. @staticmethod
  354. def merge_cross_page_tables(results: Dict[str, Any]) -> Dict[str, Any]:
  355. """
  356. 合并跨页表格
  357. TODO: 实现跨页表格合并逻辑
  358. 可以参考 MinerU 的 cross_page_table_merge 实现
  359. Args:
  360. results: 处理结果字典
  361. Returns:
  362. 合并后的结果
  363. """
  364. # TODO: 实现跨页表格合并逻辑
  365. return results