pdf_utils.py 13 KB

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