注册 登录
自由的生活_软路由 返回首页

心想事成的个人空间 https://www.routerclub.com/?681 [收藏] [复制] [分享] [RSS]

日志

PaddleOCRVL识别代码

已有 24 次阅读2026-5-8 15:05

from paddleocr import PaddleOCRVL
import os
import re
import glob
from datetime import datetime

# 定义输入和输出目录
input_dir = "/root/lanyun-tmp/image"
output_dir = "/root/lanyun-tmp/out"
os.makedirs(output_dir, exist_ok=True)

# vLLM 后端配置 (在循环外初始化,避免重复加载模型)
print("正在初始化 OCR pipeline...")
pipeline = PaddleOCRVL(
    vl_rec_backend="vllm-server",
    vl_rec_server_url="http://localhost:8118/v1",
    vl_rec_model_name="PaddleOCR-VL-1.5-0.9B",
    layout_detection_model_name="PP-DocLayoutV2",
    use_ocr_for_image_block=True,
    format_block_content=True,
    use_doc_orientation_classify=True,
    use_doc_unwarping=True,
    use_layout_detection=True,
    merge_layout_blocks=True
)

# 获取目录下所有的 PDF 文件
# 匹配 .pdf 后缀,忽略大小写的话可以使用通配符或后续加判断,这里默认标准 .pdf
pdf_files = glob.glob(os.path.join(input_dir, "*.pdf"))

if not pdf_files:
    print(f"在目录 {input_dir} 中没有找到任何 PDF 文件。")
else:
    print(f"共找到 {len(pdf_files)} 个 PDF 文件,开始批量处理...\n")
    
    # 遍历处理每个 PDF 文件
    for file_path in pdf_files:
        print(f"========== 正在处理: {file_path} ==========")
        try:
            # 执行预测
            output = pipeline.predict(file_path)

            # 生成输出文件名
            base_name = os.path.splitext(os.path.basename(file_path))[0]
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_file = os.path.join(output_dir, f"{base_name}_{timestamp}.md")

            # 保存为 Markdown 格式,只提取 content
            with open(output_file, "w", encoding="utf-8") as f:
                # 写入 Markdown 头部信息
                f.write(f"# OCR 识别结果\n\n")
                f.write(f"**原始文件**: `{file_path}`\n\n")
                f.write(f"**识别时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
                f.write("---\n\n")
                
                # 遍历识别结果
                for idx, res in enumerate(output):
                    # 将结果转换为字符串
                    res_str = str(res)
                    
                    # 使用正则表达式提取 content 字段的内容
                    # 匹配 content: 后面的内容,直到遇到下一个 ################# 或结束
                    pattern = r'content:\s+(.+?)(?=\n#################|$)'
                    matches = re.findall(pattern, res_str, re.DOTALL)
                    
                    if matches:
                        for match_idx, content in enumerate(matches):
                            # 清理内容,去除多余空白
                            content = content.strip()
                            if content:
                                f.write(content)
                                f.write("\n\n")
                                f.write("---\n\n")
                    else:
                        # 如果没有匹配到,尝试直接提取 parsing_res_list 中的内容
                        try:
                            if hasattr(res, 'parsing_res_list'):
                                for block in res.parsing_res_list:
                                    if hasattr(block, 'content'):
                                        f.write(block.content.strip())
                                        f.write("\n\n---\n\n")
                        except Exception as e_inner:
                            print(f"提取 parsing_res_list 时出现小错误: {e_inner}")
                    
                    # 同时在控制台打印
                    res.print()

            print(f"✅ 成功! 文件已保存为: {output_file}\n")
            
        except Exception as e:
            # 捕获异常,防止某一个损坏的PDF导致整个程序崩溃
            print(f"❌ 处理文件 {file_path} 时发生错误: {e}\n")
            continue

    print("所有 PDF 文件批量处理完成!")

路过

雷人

握手

鲜花

鸡蛋

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册

QQ|Archiver|手机版|小黑屋|软路由 ( 渝ICP备15001194号-1|渝公网安备 50011602500124号 )

GMT+8, 2026-5-13 13:34 , Processed in 0.093954 second(s), 5 queries , Gzip On, Redis On.

Powered by Discuz! X3.5 Licensed

© 2001-2026 Discuz! Team.

返回顶部