pdf_utils.py 13 KB

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