Files
37duAutomation/app/utils/pdf.py
T
puddy 2daa1cd5a0 feat: 新增离职电子签流程审批功能,重构请假OCR业务逻辑
1.  新增离职电子签全流程校验:包括附件下载、PDF解析、表单与文书核验
2.  重构通用OCR模块,剥离业务逻辑到单独的请假附件检测模块
3.  新增PyMuPDF依赖用于PDF文本与扫描件OCR解析
4.  新增附件清单查询接口与离职附件检测工具类
2026-08-31 11:55:25 +08:00

71 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@Module: app.utils.pdf
@FileName: pdf.py
@Author: 小布丁
@Description: PDF 内容解析模块(PyMuPDF)。
1. 文本型 PDF:PyMuPDF 直接提取每页文本
2. 扫描型 PDF:PyMuPDF 逐页渲染为图像,复用 app.utils.ocr.recognize_image 做 OCR
@Version: 1.0.0
"""
import os
from PIL import Image
try:
import fitz # PyMuPDF
except ImportError:
fitz = None
from app.utils.ocr import recognize_image
# 扫描页渲染分辨率(dpi):越高识别越准但越耗时
SCAN_PAGE_DPI = 200
def parse_pdf(file_path: str, debug: bool = False) -> str:
"""解析 PDF 并返回全文。
逐页解析:
- 页面含可提取文本层 -> 直接取文本(文本型 PDF);
- 页面无可提取文本(扫描件/图片型)-> 渲染为图像后复用通用图像 OCR recognize_image。
Args:
file_path: PDF 文件路径
debug: 是否打印调试信息
Returns:
全文文本(各页用换行拼接);文件异常/解析失败抛异常
"""
if fitz is None:
raise RuntimeError("PyMuPDF 未安装,请执行: pip install pymupdf")
if not os.path.isfile(file_path):
raise FileNotFoundError(f"PDF 文件不存在: {file_path}")
doc = fitz.open(file_path)
try:
parts = []
for page_no, page in enumerate(doc, 1):
text = (page.get_text("text") or "").strip()
if text:
parts.append(text)
continue
# 扫描页:渲染为图像走通用 OCR
if debug:
print(f"【PDF】第 {page_no} 页无文本层,渲染为图像做 OCR ...")
pix = page.get_pixmap(dpi=SCAN_PAGE_DPI)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
page_text = recognize_image(img, debug=debug)
if page_text:
parts.append(page_text)
return "\n".join(parts)
finally:
doc.close()
if __name__ == "__main__":
# 简单自测入口
_path = r"D:\downloads\pdf_test_01.pdf"
print(parse_pdf(_path, debug=True))