PyPDFLoader和MinerU加载pdf文件

加载pdf

PDF存在多种来源格式,包括扫描版(图片PDF),电子文本版、混合版。并且布局格式也多种多样,包括单列布局,双列布局甚至竖排文本布局。并且包含段落、标题、页眉页脚、表格、数学公式、化学式、特殊符号、图片等各种元素

因此,PDF解析存在很多挑战。对于复杂PDF,需要进行文本提取,布局检测、表格解析、公式识别等处理

方式1:PyPDFLoader

LangChain加载PDF文件使用的是pypdf

除了本地文件,也支持在线文件

方式2:使用MinerU

MinerU提供了PDF、Word、PPT、图片等文件的解析,支持图像提取,OCR,公式,表格解析等功能。

调用在线服务:

bash 复制代码
https://mineru.net/apiManage/docs

可以从本地批量上传文件进行解析,并接收解析结果

登录之后点击api

在env文件中进行配置

bash 复制代码
import os
import time
import requests
from dotenv import load_dotenv

load_dotenv(override=True)

def upload_files(file_paths: list[str]) -> str:
    """批量上传文件"""
    url = "https://mineru.net/api/v4/file-urls/batch"
    api_token = os.getenv("MINERU_API_TOKEN")
    header = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_token}",
    }

    files_info = [
        {
            "name": os.path.basename(file_path),
            "is_ocr": True,
            "data_id": f"file_{i}",
        }
        for i, file_path in enumerate(file_paths)
    ]

    data = {
        "enable_formula": True,
        "enable_table": True,
        "language": "ch",
        "files": files_info,
    }

    try:
        response = requests.post(url, headers=header, json=data)
        if response.status_code == 200:
            result = response.json()
            print("response success. result:{}".format(result))

            if result["code"] == 0:
                batch_id = result["data"]["batch_id"]
                urls = result["data"]["file_urls"]
                print("batch_id:{}\nurls:{}".format(batch_id, urls))

                for i in range(0, len(urls)):
                    with open(file_paths[i], "rb") as f:
                        res_upload = requests.put(urls[i], data=f)
                        if res_upload.status_code == 200:
                            print(f"{urls[i]} upload success")
                        else:
                            print(f"{urls[i]} upload failed")
                            return None

                return batch_id
            else:
                print("apply upload url failed, reason: {}".format(result.get("msg")))
                return None
        else:
            print(
                "response not success. status:{} ,result:{}".format(
                    response.status_code, response.text
                )
            )
            return None

    except Exception as err:
        print(err)
        return None

def download_files(batch_id):
    """批量获取任务结果"""
    if not batch_id:
        print("batch_id为空,跳过下载")
        return

    os.makedirs("parsed_files", exist_ok=True)

    url = f"https://mineru.net/api/v4/extract-results/batch/{batch_id}"

    api_token = os.getenv("MINERU_API_TOKEN")
    header = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_token}",
    }

    failed_files = set()
    done_files = set()

    while True:
        res = requests.get(url, headers=header)
        result_json = res.json()

        if res.status_code != 200 or result_json.get("code") != 0:
            print("get result failed:", result_json)
            break

        extract_results = result_json["data"]["extract_result"]

        for result in extract_results:
            data_id = result["data_id"]

            if result["state"] == "failed":
                failed_files.add(data_id)

            elif result["state"] == "done" and data_id not in done_files:
                done_files.add(data_id)

                full_zip_url = result["full_zip_url"]
                res_download = requests.get(full_zip_url, stream=True)

                with open(
                    f"parsed_files/{result['file_name']}_{result['data_id']}.zip", "wb"
                ) as f:
                    for chunk in res_download.iter_content(chunk_size=1024):
                        if chunk:
                            f.write(chunk)

            if len(failed_files) + len(done_files) == len(extract_results):
                break

        time.sleep(5)

    for i in failed_files:
        print("failed:", i)

    for i in done_files:
        print("done:", i)

file_paths = ["../asset/load/04-sample.pdf"]
batch_id = upload_files(file_paths)

if batch_id:
    download_files(batch_id)

结果文件查看

相关推荐
泡海椒13 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf
开开心心就好14 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
前端fighter1 天前
2026年前端面试题总结(pdf版)
前端·pdf
科研邪修法6 天前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
ComPDFKit6 天前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
科研邪修法6 天前
固定列宽PDF表格改字:文本边界、单位字段与修改前后复核
pdf
Frag0ut6 天前
Chrome 2026打印与PDF处理全攻略:网页存证与文档输出实战进阶指南
chrome·pdf·批量打印·打印设置·网页存证·打印排版
开开心心就好8 天前
显示器关不掉怎么办,用小工具一键息屏
算法·智能手机·pdf·计算机外设·ocr·lua·1024程序员节
weixin_537217068 天前
2027年袁东申论万能素材(PDF)
经验分享·pdf
开开心心就好9 天前
PDF水印怎么去掉?勾选对象再点匹配
java·前端·mysql·支持向量机·pdf·音视频·模拟退火算法