5分钟快速上手:Docling Serve 文档转换与OCR处理的终极解决方案
【免费下载链接】docling-serveRunning Docling as an API service项目地址: https://gitcode.com/gh_mirrors/do/docling-serve
在数字化时代,文档处理是企业和开发者面临的常见挑战。Docling Serve是一个强大的开源文档转换服务,通过RESTful API将PDF、Word、PPT等文档转换为Markdown、JSON、HTML等多种格式,同时提供智能OCR处理功能。这个免费的工具让文档转换变得简单快速,无论是学术研究、企业文档管理还是内容创作,都能获得高效的自动化处理体验。
🔥 为什么你需要Docling Serve?
传统文档处理面临诸多痛点:需要集成多个库处理不同格式、OCR配置复杂、批量处理效率低下、API开发周期长。Docling Serve通过统一的API接口解决了所有这些问题。
| 传统方案痛点 | Docling Serve解决方案 |
|---|---|
| 多格式支持需要多个库 | 统一API支持30+文档格式 |
| OCR配置复杂,精度不一 | 智能OCR引擎,支持多语言 |
| 批量处理效率低下 | 异步并行处理,支持大规模文档 |
| API开发周期长 | 开箱即用的RESTful API服务 |
| 格式转换质量差 | 保留原始布局和结构 |
🚀 快速开始指南
安装与启动
Docling Serve提供多种安装方式,满足不同场景需求:
Python包安装(推荐)
pip install "docling-serve[ui]" docling-serve run --enable-uiDocker容器部署
docker run -p 5001:5001 \ -e DOCLING_SERVE_ENABLE_UI=1 \ quay.io/docling-project/docling-serveGPU加速支持
# CUDA 12.6支持 pip install "docling-serve[ui,cu126]" # ROCm支持(AMD GPU) pip install "docling-serve[ui,rocm]"启动后,服务将在以下地址可用:
- API服务:http://127.0.0.1:5001
- API文档:http://127.0.0.1:5001/docs
- Web界面:http://127.0.0.1:5001/ui
Docling Serve提供的完整API文档界面,支持交互式测试和实时调用
📋 核心功能详解
1. 全面的文档格式支持
Docling Serve支持广泛的输入输出格式,满足各种文档处理需求:
支持的输入格式:
- 📄 PDF文档(扫描版和数字版)
- 📝 Word文档(DOCX/DOC)
- 🎨 PowerPoint演示文稿(PPTX/PPT)
- 🌐 HTML网页文件
- 🖼️ 图像文件(JPG、PNG、TIFF等)
- 📊 Excel表格(XLSX/XLS)
- 📈 CSV数据文件
- 📋 Markdown文件
- 📚 更多格式:AsciiDoc、XML、EPUB等
输出格式选择:
- ✅ Markdown(最常用)
- ✅ JSON结构化数据
- ✅ HTML网页格式
- ✅ 纯文本格式
- ✅ Doctags标记语言
- ✅ 分页HTML格式
2. 智能OCR处理能力
OCR功能是Docling Serve的亮点,支持多种OCR引擎和语言:
import httpx # 启用OCR处理 response = httpx.post( "http://localhost:5001/v1/convert/source", json={ "sources": [{"kind": "http", "url": "https://example.com/document.pdf"}], "to_formats": ["md", "json"], "do_ocr": True, "force_ocr": False, "ocr_engine": "easyocr", "ocr_lang": ["en", "zh", "ja"] } )支持的OCR引擎:
easyocr- 默认引擎,支持多语言tesserocr- Tesseract封装rapidocr- 快速OCR引擎tesseract- 传统OCR引擎ocrmac- macOS原生OCR
3. 高级处理选项
Docling Serve提供丰富的处理选项,满足专业需求:
table_mode: "accurate" # 表格识别模式 image_export_mode: "embedded" # 图片导出方式 pdf_backend: "dlparse_v2" # PDF处理后端 do_table_structure: true # 提取表格结构 do_code_enrichment: true # 代码块增强 do_formula_enrichment: true # 数学公式识别 page_range: [1, 10] # 只处理指定页面🛠️ 实战应用场景
场景一:学术论文批量处理
研究人员需要处理大量PDF论文,提取结构化信息用于分析:
# examples/split_processing.py import httpx import time def process_academic_papers(pdf_urls): """批量处理学术论文""" tasks = [] for url in pdf_urls: response = httpx.post( "http://localhost:5001/v1/convert/source", json={ "sources": [{"kind": "http", "url": url}], "to_formats": ["md", "json"], "do_ocr": True, "ocr_lang": ["en"], "table_mode": "accurate", "do_formula_enrichment": True, "do_code_enrichment": True }, timeout=300 ) tasks.append(response.json()["task_id"]) # 异步获取结果 results = [] for task_id in tasks: while True: status = httpx.get(f"http://localhost:5001/v1/status/poll/{task_id}").json() if status["task_status"] == "success": result = httpx.get(f"http://localhost:5001/v1/result/{task_id}").json() results.append(result) break elif status["task_status"] in ["failure", "revoked"]: print(f"任务失败: {task_id}") break time.sleep(2) return resultsDocling Serve的Web界面支持URL和文件上传,提供丰富的转换选项配置
场景二:企业文档数字化
企业需要将历史文档数字化并建立搜索索引:
# 批量处理企业文档 curl -X 'POST' \ 'http://localhost:5001/v1/convert/file' \ -H 'Content-Type: multipart/form-data' \ -F 'files=@document1.pdf' \ -F 'files=@document2.docx' \ -F 'to_formats=md' \ -F 'do_ocr=true' \ -F 'table_mode=accurate'场景三:内容管理系统集成
CMS系统需要支持多种文档格式上传和预览:
// 前端集成示例 async function uploadDocument(file) { const formData = new FormData(); formData.append('file', file); const response = await fetch('http://docling-server/v1/convert/file', { method: 'POST', body: formData }); const taskId = await response.json().task_id; // 使用WebSocket监控进度 const ws = new WebSocket(`ws://docling-server/v1/ws/${taskId}`); ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.kind === 'progress') { updateProgress(data.progress); } else if (data.kind === 'result') { displayResult(data.result); } }; }🏗️ 技术架构与核心模块
Docling Serve基于现代Python技术栈构建,采用模块化设计:
docling_serve/ ├── app.py # FastAPI主应用 ├── datamodel/ # 数据模型定义 ├── orchestrator_factory.py # 任务编排工厂 ├── response_preparation.py # 响应准备模块 ├── storage.py # 存储管理 └── websocket_notifier.py # WebSocket通知关键技术特性:
- 异步任务处理:支持长时间运行的文档转换任务
- WebSocket支持:实时进度通知和状态更新
- 队列管理:基于Redis的任务队列,支持高并发
- 多租户支持:企业级多租户架构
- OpenTelemetry:完整的监控和追踪
⚙️ 生产环境部署指南
Docker Compose部署
使用Docker Compose可以快速部署完整的生产环境:
# docs/deploy-examples/compose-amd.yaml version: '3.8' services: redis: image: redis:7-alpine ports: - "6379:6379" docling-serve: image: quay.io/docling-project/docling-serve ports: - "5001:5001" environment: - DOCLING_SERVE_ENABLE_UI=1 - DOCLING_SERVE_REDIS_URL=redis://redis:6379/0 - DOCLING_SERVE_MAX_WORKERS=4 depends_on: - redisKubernetes部署
对于大规模部署,Kubernetes提供了更好的扩展性:
# docs/deploy-examples/docling-serve-replicas-w-sticky-sessions.yaml apiVersion: apps/v1 kind: Deployment metadata: name: docling-serve spec: replicas: 3 selector: matchLabels: app: docling-serve template: metadata: labels: app: docling-serve spec: containers: - name: docling-serve image: quay.io/docling-project/docling-serve ports: - containerPort: 5001 env: - name: DOCLING_SERVE_ENABLE_UI value: "1" - name: DOCLING_SERVE_REDIS_URL value: "redis://redis-service:6379/0"性能优化配置
# 生产环境推荐配置 export DOCLING_SERVE_MAX_WORKERS=4 export DOCLING_SERVE_WORKER_TIMEOUT=600 export DOCLING_SERVE_RESULT_TTL=86400 export DOCLING_SERVE_LOG_FORMAT=json export DOCLING_SERVE_LOG_LEVEL=INFO📊 API使用详解
主要API端点
Docling Serve提供简洁的RESTful API:
POST /v1/convert/source # 处理URL源文档 POST /v1/convert/file # 处理文件上传 GET /v1/status/poll/{id} # 查询任务状态 GET /v1/result/{id} # 获取转换结果 GET /v1/health # 健康检查 WS /v1/ws/{id} # WebSocket进度通知异步处理流程
- 提交任务:客户端通过API提交转换请求
- 任务排队:任务进入Redis队列等待处理
- 工作器处理:RQ工作器处理文档转换
- 进度通知:通过WebSocket实时推送处理进度
- 结果获取:客户端轮询或回调获取最终结果
错误处理策略
from tenacity import retry, stop_after_attempt, wait_exponential @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10) ) def convert_document_with_retry(url: str): """带重试机制的文档转换""" try: response = httpx.post( "http://localhost:5001/v1/convert/source", json={"sources": [{"kind": "http", "url": url}]}, timeout=300 ) return response.json() except httpx.RequestError as e: print(f"请求失败: {e}") raise文档转换后的Markdown输出结果,展示结构化内容和格式保留效果
🎯 最佳实践建议
1. 配置优化技巧
# 内存管理配置 docling-serve run \ --enable-ui \ --workers 4 \ --worker-timeout 600 \ --result-ttl 172800 \ --max-queue-size 1000 \ --log-format json \ --log-level INFO2. 监控和告警
# Prometheus监控配置 scrape_configs: - job_name: 'docling-serve' static_configs: - targets: ['localhost:9464'] metrics_path: '/metrics' scrape_interval: 15s3. 安全配置
# 启用API密钥认证 export DOCLING_SERVE_API_KEYS=your-api-key-here # 启用HTTPS docling-serve run \ --ssl-certfile /path/to/cert.pem \ --ssl-keyfile /path/to/key.pem🔧 进阶功能探索
文档分块处理
对于大型文档,可以分块处理提高效率:
# 分块处理大型PDF def split_and_process_large_pdf(pdf_path, pages_per_chunk=10): """分块处理大型PDF文档""" from pypdf import PdfReader with open(pdf_path, "rb") as f: pdf_reader = PdfReader(f) total_pages = len(pdf_reader.pages) tasks = [] for start in range(0, total_pages, pages_per_chunk): end = min(start + pages_per_chunk, total_pages) response = httpx.post( "http://localhost:5001/v1/convert/file/async", files={"files": (pdf_path.name, open(pdf_path, "rb"), "application/pdf")}, data={ "to_formats": ["json"], "page_range": [start + 1, end], "image_export_mode": "placeholder" } ) tasks.append(response.json()["task_id"]) return tasks自定义处理管道
Docling Serve支持自定义处理管道:
# 自定义处理配置 custom_config = { "pipeline": "advanced", "do_table_structure": True, "do_formula_enrichment": True, "do_code_enrichment": True, "do_picture_description": True, "picture_description_preset": "default" }📚 学习资源与支持
官方文档资源
- 配置指南:docs/configuration.md - 详细配置选项说明
- 使用说明:docs/usage.md - API使用完整指南
- 部署示例:docs/deployment.md - 生产环境部署方案
- 开发指南:docs/development.md - 开发与贡献指南
示例代码
项目提供了丰富的示例代码:
- 异步处理示例:examples/split_processing.py
- 监控配置:examples/otel-collector-config.yaml
- Docker部署:docs/deploy-examples/
测试案例
完整的测试套件确保稳定性:
- 功能测试:tests/test_1-file-all-outputs.py
- 性能测试:tests/test_ray_metrics_collector.py
- 集成测试:tests/test_batch_endpoint.py
🚀 开始使用Docling Serve
现在就开始您的文档自动化之旅:
# 克隆仓库 git clone https://gitcode.com/gh_mirrors/do/docling-serve cd docling-serve # 安装依赖 pip install "docling-serve[ui]" # 启动服务 docling-serve run --enable-ui访问 http://localhost:5001/ui 即可体验强大的文档转换功能。Docling Serve让文档处理变得简单高效,无论是个人项目还是企业级应用,都能获得专业的文档转换体验。
通过Docling Serve,您可以轻松实现:
- 📄 多格式文档批量转换
- 🔍 智能OCR文字识别
- 🏢 企业级API服务集成
- 📊 结构化数据提取
- 🚀 高性能异步处理
立即开始,让文档处理变得前所未有的简单!
【免费下载链接】docling-serveRunning Docling as an API service项目地址: https://gitcode.com/gh_mirrors/do/docling-serve
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考