mirror of
https://github.com/PaddlePaddle/PaddleOCR.git
synced 2026-11-25 17:29:39 +08:00
[Feat] Refactor MCP server to use Python SDK (#18098)
* refactor(mcp): add Executor base class and module structure Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(code quality): rename TimeoutError and remove unnecessary pass statements - Rename TimeoutError to ExecutionTimeoutError to avoid shadowing built-in exception - Remove unnecessary pass statements from exception classes and abstract methods Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(mcp): add HTTPExecutor base class for synchronous HTTP APIs * feat(mcp): add AIStudioExecutor using AsyncPaddleOCRClient Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(mcp): add LocalExecutor for local inference - Add LocalExecutor class for local PaddleOCR inference - Add _EngineWrapper to run synchronous engine in async context - Support all pipeline types: OCR, PP-StructureV3, PaddleOCR-VL series - Handle file path, URL, and Base64 input formats Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(mcp): add QianfanExecutor and SelfHostedExecutor - QianfanExecutor: Bearer token authentication, "paddleocr" endpoint - SelfHostedExecutor: No authentication, "ocr"/"layout-parsing" endpoints - Both inherit HTTPExecutor with unified response parsing Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(mcp): add executor factory function Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(mcp): add capabilities module with OCR and layout parsing Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(mcp): fix type hints and remove pass statements in capabilities * refactor(mcp): update __main__.py to use new architecture * refactor(mcp): update copyright year to 2026 * refactor(mcp): add type hint to main() function * chore(mcp): bump version to 0.7.0 * refactor(mcp): remove old pipelines.py * docs(mcp): update docs for v0.7.0 SDK-based architecture - Remove PADDLEOCR_MCP_SERVER_URL for aistudio mode (SDK has built-in default) - Add optional PADDLEOCR_MCP_BASE_URL for custom AI Studio base URL - Update parameter reference table * Update code * fix(mcp): fix AIStudioExecutor SDK integration - Use PPStructureV3Options for PP-StructureV3 pipeline - Use PaddleOCRVLOptions for PaddleOCR-VL series - Fix DocParsingPage attribute names (markdown_text, markdown_images) * refactor(mcp): rename layout to doc_parsing - Rename layout.py to doc_parsing.py - Rename LayoutParsingCapability to DocParsingCapability - Rename _parse_layout_response_http to _parse_doc_parsing_response_http - Rename _parse_layout_result to _parse_doc_parsing_result - Remove file path comments from all Python files * docs(mcp): make DocParsingCapability docstring more generic - Change from listing specific pipelines to "e.g." style - Make tool_name description more generic for future extensibility * remove unused files * docs(mcp): update terminology and remove obsolete URL configuration - Change '工作模式' to '推理方式' / 'Inference methods' - Unify with SDK docs: use '官方 API' / 'Official API' - Update options: 本地推理、官方API、千帆API、自建API - Remove obsolete manual URL configuration (SDK has built-in defaults) - Update token acquisition instructions * docs(mcp): unify English doc terminology - working modes/mode → inference methods/method/API - Update TOC: 'Working Modes Explained' → 'Inference Methods' - Change 'Mode 1: Local Python Library' → 'Method 1: Local Inference' - Update parameter table: 'mode' → 'source', 'service' → 'API' - 'local Python library' → 'local inference' - 'PaddleOCR official service' → 'Official API' - 'Qianfan platform service' → 'Qianfan API' - 'self-hosted service' → 'Self-hosted API' - Update example command comments - Update 'Local mode' → 'Local Inference' in uvx section - Update Known Limitations section * fix(mcp): correct inaccuracies and unify terminology in docs and code - Remove incorrect Qianfan pipeline validation (OCR is supported) - Fix broken anchor link in Chinese doc 2.4 section - Unify Chinese doc terminology: - 千帆平台服务/自托管服务 → 千帆 API/自建 API - PaddleOCR 官方服务 → 官方 API - 本地 Python 库模式 → 本地推理 - 模式/方式 → 推理方式 - Fix Chinese doc numbered list error (5 → 4) - Remove incorrect Qianfan pipeline limitation note from English doc - Update example command comments to use consistent terminology * docs(mcp): simplify pipeline documentation and remove hardcoded lists - Replace Chinese docstrings with English in base.py - Remove hardcoded pipeline enumeration from AIStudioExecutor docstring - Simplify pipeline table: merge PaddleOCR-VL series into single entry - Add 'etc.' to parameter options to indicate extensibility * Fix bugs * refactor(mcp): let SDK use service-side defaults - Remove hardcoded parameter defaults (use_doc_orientation_classify=False, etc.) - Only set visualize=False (MCP tool never returns visualizations) - Pass-through all optional parameters from user options dict - This allows server-side optimizations and better future compatibility * feat(mcp): add reasonable default options - All pipelines: use_doc_orientation_classify=False, use_doc_unwarping=False - PP-StructureV3: use_chart_recognition=True - PaddleOCR-VL series: use_chart_recognition=True, use_seal_recognition=True - Users can override these defaults via options dict * refactor(mcp): move default options to MCPCapability - Move default options from AIStudioExecutor to MCPCapability._process - All executors now receive same default behavior via capability layer - User options override defaults - Add pipeline parameter to MCPCapability and subclasses * refactor(mcp): redesign capabilities as pipeline-level classes - MCPCapability: add PIPELINE class attribute, remove constructor param - BaseDocParsingCapability: new base class for doc parsing pipelines - PPStructureV3Capability: dedicated class for PP-StructureV3 - PaddleOCRVLCapability: handles PaddleOCR-VL series with pipeline param - OCRCapability: define PIPELINE as class attribute - Remove old DocParsingCapability (replaced by specific classes) - Factory simplified: no need to pass pipeline to constructors * refactor(mcp): use method for default options instead of hardcoded logic - MCPCapability: add DEFAULT_OPTIONS constant and get_default_options method - BaseDocParsingCapability: override get_default_options for chart recognition - PaddleOCRVLCapability: override get_default_options for seal recognition - Move default logic from hardcoded if/else to method inheritance - PaddleOCRVLCapability: set PIPELINE dynamically in __init__ * Big refactor * Fix bugs * Remove tests * Remove unused comments * Fix doc bugs --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
d4b5b09865
commit
1e5aa0ad31
54 files changed
+2586
-1411
No files matched your search
+5
-5
@@ -7,11 +7,11 @@ __pycache__/
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
inference/
|
||||
inference_results/
|
||||
output/
|
||||
train_data/
|
||||
log/
|
||||
/inference/
|
||||
/inference_results/
|
||||
/output/
|
||||
/train_data/
|
||||
/log/
|
||||
|
||||
*.DS_Store
|
||||
*.vs
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
|
||||
|
||||
|
||||
## 4、Inference and deployment Performance
|
||||
## 4、Inference and deployment Performance {#4-inference-and-deployment-performance}
|
||||
|
||||
|
||||
<div align="center">
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
|
||||
|
||||
|
||||
## 4、推理部署性能
|
||||
## 4、推理部署性能 {#4推理部署性能}
|
||||
|
||||
|
||||
<div align="center">
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
|
||||
## 4. Inference and Deployment Performance
|
||||
|
||||
PaddleOCR-VL-1.6 and PaddleOCR-VL-1.5 use exactly the same model architecture design, so they have identical inference speeds. For details about the inference speed of PaddleOCR-VL-1.5, refer to [PaddleOCR-VL-1.5 inference speed](./PaddleOCR-VL-1.5.md#4推理部署性能).
|
||||
PaddleOCR-VL-1.6 and PaddleOCR-VL-1.5 use exactly the same model architecture design, so they have identical inference speeds. For details about the inference speed of PaddleOCR-VL-1.5, refer to [PaddleOCR-VL-1.5 inference speed](./PaddleOCR-VL-1.5.md#4-inference-and-deployment-performance).
|
||||
|
||||
|
||||
## 5. Visualization
|
||||
@@ -144,4 +144,3 @@ PaddleOCR-VL-1.6 and PaddleOCR-VL-1.5 use exactly the same model architecture de
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr_vl_1_6/comparison/table3.png" width="800"/>
|
||||
</div>
|
||||
|
||||
@@ -144,4 +144,3 @@ PaddleOCR-VL-1.6 和 PaddleOCR-VL-1.5 采用完全相同的模型架构设计,
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr_vl_1_6/comparison/table3.png" width="800"/>
|
||||
</div>
|
||||
|
||||
@@ -61,8 +61,6 @@ The model constants in the table are type-safe aliases for the official API mode
|
||||
| OCR | `OCR`, `SubmitOCR`, `WaitOCRResult` | `PPOCRv5` | `PPOCRv5` | `*OCROptions` |
|
||||
| Document parsing | `ParseDocument`, `SubmitDocumentParsing`, `WaitDocumentParsingResult` | `PaddleOCRVL16` | `PPStructureV3`, `PaddleOCRVL`, `PaddleOCRVL15`, `PaddleOCRVL16` | Use `*PPStructureV3Options` with `PPStructureV3`, and `*PaddleOCRVLOptions` with PaddleOCR-VL models. |
|
||||
|
||||
Common mappings: `PPOCRv5` maps to `PP-OCRv5`, `PPStructureV3` maps to `PP-StructureV3`, `PaddleOCRVL` maps to `PaddleOCR-VL`, `PaddleOCRVL15` maps to `PaddleOCR-VL-1.5`, and `PaddleOCRVL16` maps to `PaddleOCR-VL-1.6`.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Client Configuration
|
||||
|
||||
@@ -61,8 +61,6 @@ Go SDK 常用公共方法包括:
|
||||
| OCR | `OCR`、`SubmitOCR`、`WaitOCRResult` | `PPOCRv5` | `PPOCRv5` | `*OCROptions` |
|
||||
| 文档解析 | `ParseDocument`、`SubmitDocumentParsing`、`WaitDocumentParsingResult` | `PaddleOCRVL16` | `PPStructureV3`、`PaddleOCRVL`、`PaddleOCRVL15`、`PaddleOCRVL16` | 选择 `PPStructureV3` 时传入 `*PPStructureV3Options`;选择 PaddleOCR-VL 系列模型时传入 `*PaddleOCRVLOptions`。 |
|
||||
|
||||
常用对应关系:`PPOCRv5` 对应 `PP-OCRv5`,`PPStructureV3` 对应 `PP-StructureV3`,`PaddleOCRVL` 对应 `PaddleOCR-VL`,`PaddleOCRVL15` 对应 `PaddleOCR-VL-1.5`,`PaddleOCRVL16` 对应 `PaddleOCR-VL-1.6`。
|
||||
|
||||
## 配置与参数
|
||||
|
||||
### 客户端配置
|
||||
@@ -94,7 +92,7 @@ client, err := paddleocr.NewClient(
|
||||
|
||||
### 请求参数
|
||||
|
||||
Go SDK 的 Options 结构体字段使用 PascalCase,序列化时自动转换为 camelCase。指针类型字段传 `nil` 表示不设置。完整字段定义见结构体源码或「官方 API 参考」。
|
||||
Go SDK 的 Options 结构体字段使用 PascalCase,序列化时自动转换为 camelCase。指针类型字段传 `nil` 表示不设置。完整字段定义见结构体源码或官方 API 参考。
|
||||
|
||||
#### OCROptions(常用字段)
|
||||
|
||||
|
||||
@@ -60,8 +60,6 @@ The `Model` enum values in the table are type-safe aliases for the official API
|
||||
| OCR | `ocr`, `submit_ocr`, `wait_ocr_result` | `Model.PP_OCRV5` | `Model.PP_OCRV5` | `OCROptions` |
|
||||
| Document parsing | `parse_document`, `submit_document_parsing`, `wait_document_parsing_result` | `Model.PADDLE_OCR_VL_16` | `Model.PP_STRUCTURE_V3`, `Model.PADDLE_OCR_VL`, `Model.PADDLE_OCR_VL_15`, `Model.PADDLE_OCR_VL_16` | Use `PPStructureV3Options` with `PP-StructureV3`, and `PaddleOCRVLOptions` with PaddleOCR-VL models. |
|
||||
|
||||
Common mappings: `Model.PP_OCRV5` maps to `PP-OCRv5`, `Model.PP_STRUCTURE_V3` maps to `PP-StructureV3`, `Model.PADDLE_OCR_VL` maps to `PaddleOCR-VL`, `Model.PADDLE_OCR_VL_15` maps to `PaddleOCR-VL-1.5`, and `Model.PADDLE_OCR_VL_16` maps to `PaddleOCR-VL-1.6`.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Client Configuration
|
||||
|
||||
@@ -60,8 +60,6 @@ Python SDK 常用公共方法包括:
|
||||
| OCR | `ocr`、`submit_ocr`、`wait_ocr_result` | `Model.PP_OCRV5` | `Model.PP_OCRV5` | `OCROptions` |
|
||||
| 文档解析 | `parse_document`、`submit_document_parsing`、`wait_document_parsing_result` | `Model.PADDLE_OCR_VL_16` | `Model.PP_STRUCTURE_V3`、`Model.PADDLE_OCR_VL`、`Model.PADDLE_OCR_VL_15`、`Model.PADDLE_OCR_VL_16` | 选择 `PP-StructureV3` 时传入 `PPStructureV3Options`;选择 `PaddleOCR-VL` 系列模型时传入 `PaddleOCRVLOptions`。 |
|
||||
|
||||
常用对应关系:`Model.PP_OCRV5` 对应 `PP-OCRv5`,`Model.PP_STRUCTURE_V3` 对应 `PP-StructureV3`,`Model.PADDLE_OCR_VL` 对应 `PaddleOCR-VL`,`Model.PADDLE_OCR_VL_15` 对应 `PaddleOCR-VL-1.5`,`Model.PADDLE_OCR_VL_16` 对应 `PaddleOCR-VL-1.6`。
|
||||
|
||||
## 配置与参数
|
||||
|
||||
### 客户端配置
|
||||
@@ -83,7 +81,7 @@ client = PaddleOCRClient(base_url="https://my-proxy.com/paddle")
|
||||
|
||||
### 请求参数
|
||||
|
||||
SDK 的参数名使用 Python 惯用的 snake_case,提交请求时自动转换为官方 API 的 camelCase。只需传入非 `None` 的字段,未设置的字段使用服务端默认值。完整字段定义见各 Options 类型源码或「官方 API 参考」。
|
||||
SDK 的参数名使用 Python 惯用的 snake_case,提交请求时自动转换为官方 API 的 camelCase。只需传入非 `None` 的字段,未设置的字段使用服务端默认值。完整字段定义见各 Options 类型源码或官方 API 参考。
|
||||
|
||||
#### OCROptions(常用字段)
|
||||
|
||||
|
||||
@@ -64,8 +64,6 @@ The `Model` enum values in the table are type-safe aliases for the official API
|
||||
| OCR | `ocr`, `submitOcr`, `waitOcrResult` | `Model.PPOCRv5` | `Model.PPOCRv5` | `OCROptions` |
|
||||
| Document parsing | `parseDocument`, `submitDocumentParsing`, `waitDocumentParsingResult` | `Model.PaddleOCRVL16` | `Model.PPStructureV3`, `Model.PaddleOCRVL`, `Model.PaddleOCRVL15`, `Model.PaddleOCRVL16` | Use `PPStructureV3Options` with `PPStructureV3`, and `PaddleOCRVLOptions` with PaddleOCR-VL models. |
|
||||
|
||||
Common mappings: `Model.PPOCRv5` maps to `PP-OCRv5`, `Model.PPStructureV3` maps to `PP-StructureV3`, `Model.PaddleOCRVL` maps to `PaddleOCR-VL`, `Model.PaddleOCRVL15` maps to `PaddleOCR-VL-1.5`, and `Model.PaddleOCRVL16` maps to `PaddleOCR-VL-1.6`.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Client Configuration
|
||||
|
||||
@@ -64,8 +64,6 @@ TypeScript SDK 常用公共方法包括:
|
||||
| OCR | `ocr`、`submitOcr`、`waitOcrResult` | `Model.PPOCRv5` | `Model.PPOCRv5` | `OCROptions` |
|
||||
| 文档解析 | `parseDocument`、`submitDocumentParsing`、`waitDocumentParsingResult` | `Model.PaddleOCRVL16` | `Model.PPStructureV3`、`Model.PaddleOCRVL`、`Model.PaddleOCRVL15`、`Model.PaddleOCRVL16` | 选择 `PPStructureV3` 时传入 `PPStructureV3Options`;选择 PaddleOCR-VL 系列模型时传入 `PaddleOCRVLOptions`。 |
|
||||
|
||||
常用对应关系:`Model.PPOCRv5` 对应 `PP-OCRv5`,`Model.PPStructureV3` 对应 `PP-StructureV3`,`Model.PaddleOCRVL` 对应 `PaddleOCR-VL`,`Model.PaddleOCRVL15` 对应 `PaddleOCR-VL-1.5`,`Model.PaddleOCRVL16` 对应 `PaddleOCR-VL-1.6`。
|
||||
|
||||
## 配置与参数
|
||||
|
||||
### 客户端配置
|
||||
@@ -97,7 +95,7 @@ const client = new PaddleOCRClient({
|
||||
|
||||
### 请求参数
|
||||
|
||||
TypeScript SDK 的参数名使用 camelCase,与官方 API 字段名一致。未设置的字段不会发送,使用服务端默认值。完整字段定义见接口源码或「官方 API 参考」。
|
||||
TypeScript SDK 的参数名使用 camelCase,与官方 API 字段名一致。未设置的字段不会发送,使用服务端默认值。完整字段定义见接口源码或官方 API 参考。
|
||||
|
||||
#### OCROptions(常用字段)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ comments: true
|
||||
|
||||
PaddleOCR provides a lightweight [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server designed to integrate PaddleOCR’s text recognition, layout parsing, and other capabilities into various large-model applications.
|
||||
|
||||
### Key Features
|
||||
### Key features include:
|
||||
|
||||
- **Currently Supported Pipelines**
|
||||
|
||||
@@ -17,24 +17,21 @@ PaddleOCR provides a lightweight [Model Context Protocol (MCP)](https://modelcon
|
||||
| --- | --- | --- |
|
||||
| `OCR` | `ocr` | Performs text detection and recognition on images and PDF files. |
|
||||
| `PP-StructureV3` | `pp_structurev3` | Identifies and extracts text blocks, titles, paragraphs, images, tables, and other layout elements from images or PDF files, converting the input into Markdown documents. |
|
||||
| `PaddleOCR-VL` | `paddleocr_vl` | Performs layout parsing with a VLM-based approach and converts the input into Markdown documents. |
|
||||
| `PaddleOCR-VL-1.5` | `paddleocr_vl` | An upgraded version of PaddleOCR-VL with improvements in both speed and accuracy. |
|
||||
| `PaddleOCR-VL-1.6` | `paddleocr_vl` | The latest version in the PaddleOCR-VL series, further upgrading the VLM component on top of PaddleOCR-VL-1.5. |
|
||||
| `PaddleOCR-VL Series` | `paddleocr_vl` | Performs layout parsing with a VLM-based approach and converts the input into Markdown documents. Includes versions: PaddleOCR-VL, PaddleOCR-VL-1.5, and PaddleOCR-VL-1.6. |
|
||||
|
||||
> Each MCP server instance exposes exactly one MCP tool.
|
||||
|
||||
- **Supported Working Modes**
|
||||
- **Local Python Library**: Runs PaddleOCR pipelines directly on the local machine. This mode requires a suitable local environment and hardware, and is ideal for offline use or privacy-sensitive scenarios.
|
||||
- **PaddleOCR Official Service**: Invokes services provided by the [PaddleOCR Official Website](https://aistudio.baidu.com/paddleocr?lang=en). This is suitable for quick testing, prototyping, or no-code scenarios.
|
||||
- **Qianfan Platform Service**: Calls the cloud services provided by Baidu AI Cloud's Qianfan large model platform.
|
||||
- **Self-hosted Service**: Invokes the user's self-hosted PaddleOCR services. This mode offers the advantages of serving and high flexibility. It is suitable for scenarios requiring customized service configurations, as well as those with strict data privacy requirements. **Currently, only the basic serving solution is supported.**
|
||||
- **Supported Inference Methods**
|
||||
- **Local Inference**: Runs PaddleOCR pipelines directly on the local machine. This method has certain requirements for the local environment and hardware performance, and is suitable for offline use and scenarios with strict data privacy requirements.
|
||||
- **Official API**: Invokes the PaddleOCR Official API. This method is suitable for quickly trying out features, validating solutions, and other no-code development scenarios.
|
||||
- **Qianfan API**: Calls the API provided by Baidu AI Cloud's Qianfan platform.
|
||||
- **Self-hosted API**: Invokes the user's self-hosted PaddleOCR inference service. This method offers serving advantages and high flexibility, suitable for scenarios requiring customized service configurations, as well as those with strict data privacy requirements. **Currently, only the basic serving solution is supported.**
|
||||
|
||||
## Examples:
|
||||
|
||||
The following showcases creative use cases built with the PaddleOCR MCP server combined with other tools:
|
||||
|
||||
### Demo 1
|
||||
|
||||
In Claude for Desktop, extract handwritten content from images and save to note-taking software Notion. The PaddleOCR MCP server extracts text, formulas and other information from images while preserving document structure.
|
||||
<div align="center">
|
||||
<img width="65%" src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/main/images/paddleocr/mcp_demo/note_to_notion.gif" alt="note_to_notion">
|
||||
@@ -46,7 +43,6 @@ In Claude for Desktop, extract handwritten content from images and save to note-
|
||||
---
|
||||
|
||||
### Demo 2
|
||||
|
||||
In VSCode, convert handwritten ideas or pseudocode into runnable Python scripts that comply with project coding standards with one click, and upload them to GitHub repositories. The PaddleOCR MCP server extracts explicitly handwritten code from images for subsequent processing.
|
||||
|
||||
<div align="center">
|
||||
@@ -88,7 +84,7 @@ Convert images containing formulas and tables to editable csv/Excel format:
|
||||
- [2. Using with Claude for Desktop](#2-using-with-claude-for-desktop)
|
||||
- [2.1 Quick Start](#21-quick-start)
|
||||
- [2.2 MCP Host Configuration Details](#22-mcp-host-configuration-details)
|
||||
- [2.3 Working Modes Explained](#23-working-modes-explained)
|
||||
- [2.3 Inference Methods](#23-inference-methods)
|
||||
- [2.4 Using `uvx`](#24-using-uvx)
|
||||
- [3. Running the Server](#3-running-the-server)
|
||||
- [4. Parameter Reference](#4-parameter-reference)
|
||||
@@ -98,36 +94,33 @@ Convert images containing formulas and tables to editable csv/Excel format:
|
||||
|
||||
This section explains how to install the `paddleocr-mcp` library via pip.
|
||||
|
||||
- For the local Python library mode, in addition to installing `paddleocr-mcp`, you also need to install the PaddlePaddle framework and PaddleOCR by referring to the [PaddleOCR installation guide](../installation.en.md).
|
||||
- For the local Python library mode, you may also consider installing the corresponding optional dependencies:
|
||||
- `paddleocr-mcp[local]`: includes PaddleOCR (without the PaddlePaddle framework).
|
||||
- `paddleocr-mcp[local-cpu]`: based on `local`, additionally includes the CPU version of the PaddlePaddle framework.
|
||||
- PaddleOCR also supports running the server without installation through methods like `uvx`. For details, please refer to the instructions in [2. Using with Claude for Desktop](#2-using-with-claude-for-desktop).
|
||||
`paddleocr-mcp` requires Python 3.10 or later.
|
||||
`paddleocr-mcp` depends on `paddleocr>=3.6.0` by default, so Official API, Qianfan API, and self-hosted API modes do not require installing PaddleOCR separately. Local inference additionally requires the document-parsing dependencies and an inference engine required to run PaddleOCR pipelines locally; see [Method 1: Local Inference](#method-1-local-inference) for details.
|
||||
|
||||
To install `paddleocr-mcp` using pip:
|
||||
Install from PyPI:
|
||||
|
||||
```bash
|
||||
# Install from PyPI
|
||||
pip install -U paddleocr-mcp
|
||||
```
|
||||
|
||||
# Install from source
|
||||
Install from source:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PaddlePaddle/PaddleOCR.git
|
||||
pip install -e mcp_server
|
||||
|
||||
# Install with optional extras (choose ONE of the following if you prefer convenience installs)
|
||||
# Install PaddleOCR together with the MCP server (framework not included):
|
||||
pip install "paddleocr-mcp[local]"
|
||||
# Install PaddleOCR and CPU PaddlePaddle framework together:
|
||||
pip install "paddleocr-mcp[local-cpu]"
|
||||
```
|
||||
|
||||
For local inference, install the optional extras described in [Method 1: Local Inference](#method-1-local-inference).
|
||||
|
||||
To verify successful installation:
|
||||
|
||||
```bash
|
||||
paddleocr_mcp --help
|
||||
```
|
||||
|
||||
If the help message is printed, the installation succeeded.
|
||||
If help information is printed after running the command above, the installation succeeded.
|
||||
|
||||
PaddleOCR also supports running the server without installation through methods like `uvx`; for details, see [2. Using with Claude for Desktop](#2-using-with-claude-for-desktop).
|
||||
|
||||
## 2. Using with Claude for Desktop
|
||||
|
||||
@@ -135,13 +128,15 @@ This section explains how to use the PaddleOCR MCP server within Claude for Desk
|
||||
|
||||
### 2.1 Quick Start
|
||||
|
||||
The following quick start uses **Official API** inference as an example to get you started.
|
||||
|
||||
1. **Install `paddleocr-mcp`**
|
||||
|
||||
Refer to [1. Installation](#1-installation). To avoid dependency conflicts, **it is strongly recommended to install in an isolated virtual environment**.
|
||||
Refer to [1. Installation](#1-installation).
|
||||
|
||||
2. **Install PaddleOCR**
|
||||
2. **Obtain an Access Token**
|
||||
|
||||
Install the PaddlePaddle framework and PaddleOCR, as per the [PaddleOCR installation documentation](../installation.en.md).
|
||||
Obtain your access token from the [AI Studio Access Token page](https://aistudio.baidu.com/account/accessToken).
|
||||
|
||||
3. **Add MCP Server Configuration**
|
||||
|
||||
@@ -151,7 +146,7 @@ This section explains how to use the PaddleOCR MCP server within Claude for Desk
|
||||
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
|
||||
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
|
||||
|
||||
Edit the file as follows:
|
||||
Open the `claude_desktop_config.json` file, adjust the configuration according to the example below, and fill it into `claude_desktop_config.json`.
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -161,7 +156,8 @@ This section explains how to use the PaddleOCR MCP server within Claude for Desk
|
||||
"args": [],
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "aistudio",
|
||||
"PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN": "<your-access-token>"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,48 +166,13 @@ This section explains how to use the PaddleOCR MCP server within Claude for Desk
|
||||
|
||||
**Notes**:
|
||||
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for more details.
|
||||
- `PADDLEOCR_MCP_PIPELINE_CONFIG` is optional; if not set, the default pipeline configuration will be used. If you need to adjust the configuration, such as changing the model, please refer to the [PaddleOCR documentation](../paddleocr_and_paddlex.md) to export the pipeline configuration file, and set `PADDLEOCR_MCP_PIPELINE_CONFIG` to the absolute path of this configuration file.
|
||||
- Replace `<your-access-token>` with your access token.
|
||||
- To use a custom service address, set the `PADDLEOCR_MCP_AISTUDIO_BASE_URL` environment variable.
|
||||
|
||||
- **Inference Performance Tips**:
|
||||
**Important**:
|
||||
|
||||
If you encounter issues such as long inference time or insufficient memory during use, you may consider adjusting the pipeline configuration according to the following recommendations.
|
||||
|
||||
- **OCR Pipeline**: It is recommended to switch to the `mobile` series models. For example, you can modify the pipeline configuration file to use `PP-OCRv5_mobile_det` for detection and `PP-OCRv5_mobile_rec` for recognition.
|
||||
|
||||
- **PP-StructureV3 Pipeline**:
|
||||
|
||||
- Disable unused features, e.g., set `use_formula_recognition` to `False` to disable formula recognition.
|
||||
- Use lightweight models, such as replacing the OCR model with the `mobile` version or switching to a lightweight formula recognition model like PP-FormulaNet-S.
|
||||
|
||||
The following sample code can be used to obtain the pipeline configuration file, in which most optional features of the PP-StructureV3 pipeline are disabled, and some key models are replaced with lightweight versions.
|
||||
|
||||
```python
|
||||
from paddleocr import PPStructureV3
|
||||
|
||||
pipeline = PPStructureV3(
|
||||
use_doc_orientation_classify=False, # Disable document image orientation classification
|
||||
use_doc_unwarping=False, # Disable text image unwarping
|
||||
use_textline_orientation=False, # Disable text line orientation classification
|
||||
use_formula_recognition=False, # Disable formula recognition
|
||||
use_seal_recognition=False, # Disable seal text recognition
|
||||
use_table_recognition=False, # Disable table recognition
|
||||
use_chart_recognition=False, # Disable chart parsing
|
||||
# Use lightweight models
|
||||
text_detection_model_name="PP-OCRv5_mobile_det",
|
||||
text_recognition_model_name="PP-OCRv5_mobile_rec",
|
||||
layout_detection_model_name="PP-DocLayout-S",
|
||||
)
|
||||
|
||||
# The configuration file is saved to `PP-StructureV3.yaml`
|
||||
pipeline.export_paddlex_config_to_yaml("PP-StructureV3.yaml")
|
||||
```
|
||||
|
||||
**For PaddleOCR-VL series, it is not recommended to use CPUs for inference.**
|
||||
|
||||
**Important**:
|
||||
|
||||
- If `paddleocr_mcp` is not in your system's `PATH`, set `command` to the absolute path of the executable.
|
||||
- Do not expose your **access token**.
|
||||
- If `paddleocr_mcp` is not in your system's `PATH`, set `command` to the absolute path of the executable.
|
||||
|
||||
4. **Restart the MCP Host**
|
||||
|
||||
@@ -225,23 +186,26 @@ In the configuration file for Claude for Desktop, you need to define how the MCP
|
||||
- `args`: Configurable command-line arguments, such as `["--verbose"]`. See [4. Parameter Reference](#4-parameter-reference) for details.
|
||||
- `env`: Configurable environment variables. See [4. Parameter Reference](#4-parameter-reference) for details.
|
||||
|
||||
### 2.3 Working Modes Explained
|
||||
### 2.3 Inference Methods
|
||||
|
||||
You can configure the MCP server according to your requirements to run in different working modes. The operational procedures vary for different modes, which will be explained in detail below.
|
||||
You can configure the MCP server according to your requirements to use different inference methods. The operational procedures vary for different methods, which will be explained in detail below.
|
||||
|
||||
#### Mode 1: Local Python Library
|
||||
#### Method 1: Local Inference {#method-1-local-inference}
|
||||
|
||||
See [2.1 Quick Start](#21-quick-start).
|
||||
1. Install `paddleocr-mcp` and the local inference dependencies. `paddleocr-mcp` already depends on PaddleOCR; local inference additionally requires the document-parsing dependencies and an inference engine. You can install them manually by referring to the [PaddleOCR installation guide](../installation.en.md), or use the corresponding optional dependencies:
|
||||
- `paddleocr-mcp[local]`: includes `paddleocr[doc-parser]>=3.6.0` (without the inference engine).
|
||||
- `paddleocr-mcp[local-cpu]`: based on `local`, additionally includes the CPU PaddlePaddle inference engine (`paddlepaddle>=3.2.1`).
|
||||
|
||||
#### Mode 2: PaddleOCR Official Service
|
||||
```bash
|
||||
# Install document-parsing dependencies for local inference (inference engine not included):
|
||||
pip install "paddleocr-mcp[local]"
|
||||
# Install the CPU PaddlePaddle framework in addition to local:
|
||||
pip install "paddleocr-mcp[local-cpu]"
|
||||
```
|
||||
|
||||
1. Install `paddleocr-mcp`.
|
||||
2. Obtain the service base URL and AI Studio Community access token.
|
||||
|
||||
On this page, click "API" in the upper-left corner. Copy the `API_URL` corresponding to "Text Recognition (PP-OCRv5)", and remove the trailing endpoint (`/ocr`) to get the base URL of the service (e.g., `https://xxxxxx.aistudio-app.com`). Also copy the `TOKEN`, which is your access token. You may need to register and log in to your PaddlePaddle AI Studio Community account.
|
||||
|
||||
3. Refer to the configuration example below to modify the contents of the `claude_desktop_config.json` file.
|
||||
4. Restart the MCP host.
|
||||
To avoid dependency conflicts, **it is strongly recommended to install in an isolated virtual environment**.
|
||||
2. Refer to the configuration example below to modify the `claude_desktop_config.json` file.
|
||||
3. Restart the MCP host.
|
||||
|
||||
Configuration example:
|
||||
|
||||
@@ -253,9 +217,7 @@ Configuration example:
|
||||
"args": [],
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "aistudio",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "<your-server-url>",
|
||||
"PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN": "<your-access-token>"
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,19 +226,54 @@ Configuration example:
|
||||
|
||||
**Notes**:
|
||||
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for more details.
|
||||
- Replace `<your-server-url>` with your service base URL.
|
||||
- Replace `<your-access-token>` with your access token.
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for details.
|
||||
- `PADDLEOCR_MCP_PIPELINE_CONFIG` is optional. If not set, the default pipeline configuration is used. To adjust the configuration, such as changing models, refer to the [PaddleOCR documentation](../paddleocr_and_paddlex.md) to export the pipeline configuration file, and set `PADDLEOCR_MCP_PIPELINE_CONFIG` to the absolute path of this file.
|
||||
- **Inference Performance Tips**:
|
||||
|
||||
**Important**:
|
||||
If you encounter long inference time or insufficient memory, consider adjusting the pipeline configuration:
|
||||
|
||||
- Do not expose your access token.
|
||||
- **OCR Pipeline**: It is recommended to switch to the `mobile` series models. For example, use `PP-OCRv5_mobile_det` for detection and `PP-OCRv5_mobile_rec` for recognition.
|
||||
- **PP-StructureV3 Pipeline**:
|
||||
|
||||
#### Mode 3: Qianfan Platform Services
|
||||
- Disable unused features, such as setting `use_formula_recognition` to `False` to disable formula recognition.
|
||||
- Use lightweight models, such as replacing the OCR model with the `mobile` version or switching to a lightweight formula recognition model like PP-FormulaNet-S.
|
||||
|
||||
The following sample code exports a PP-StructureV3 pipeline configuration with most optional features disabled and some key models replaced with lightweight versions.
|
||||
|
||||
```python
|
||||
from paddleocr import PPStructureV3
|
||||
|
||||
pipeline = PPStructureV3(
|
||||
use_doc_orientation_classify=False, # Disable document image orientation classification
|
||||
use_doc_unwarping=False, # Disable text image unwarping
|
||||
use_textline_orientation=False, # Disable text line orientation classification
|
||||
use_formula_recognition=False, # Disable formula recognition
|
||||
use_seal_recognition=False, # Disable seal text recognition
|
||||
use_table_recognition=False, # Disable table recognition
|
||||
use_chart_recognition=False, # Disable chart parsing
|
||||
# Use lightweight models
|
||||
text_detection_model_name="PP-OCRv5_mobile_det",
|
||||
text_recognition_model_name="PP-OCRv5_mobile_rec",
|
||||
layout_detection_model_name="PP-DocLayout-S",
|
||||
)
|
||||
|
||||
# The configuration file is saved to `PP-StructureV3.yaml`
|
||||
pipeline.export_paddlex_config_to_yaml("PP-StructureV3.yaml")
|
||||
```
|
||||
|
||||
**For PaddleOCR-VL series, CPU inference is not recommended.**
|
||||
|
||||
#### Method 2: Official API
|
||||
|
||||
Refer to [2.1 Quick Start](#21-quick-start).
|
||||
|
||||
For tasks other than text recognition, set `PADDLEOCR_MCP_PIPELINE` correctly (see Section 4 for parameter details).
|
||||
|
||||
#### Method 3: Qianfan API
|
||||
|
||||
1. Install `paddleocr-mcp`.
|
||||
2. Obtain an API key by referring to the [Qianfan Platform Official Documentation](https://cloud.baidu.com/doc/qianfan-api/s/ym9chdsy5).
|
||||
3. Modify the `claude_desktop_config.json` file according to the configuration example below. Set `PADDLEOCR_MCP_QIANFAN_API_KEY` to your Qianfan platform API key.
|
||||
3. Refer to the configuration example below to modify the `claude_desktop_config.json` file.
|
||||
4. Restart the MCP host.
|
||||
|
||||
Configuration example:
|
||||
@@ -290,7 +287,6 @@ Configuration example:
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "PaddleOCR-VL",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "qianfan",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "https://qianfan.baidubce.com/v2/ocr",
|
||||
"PADDLEOCR_MCP_QIANFAN_API_KEY": "<your-api-key>"
|
||||
}
|
||||
}
|
||||
@@ -298,15 +294,17 @@ Configuration example:
|
||||
}
|
||||
```
|
||||
|
||||
**Note**:
|
||||
**Notes**:
|
||||
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for more details. The Qianfan platform service currently only supports PP-StructureV3 and PaddleOCR-VL.
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. Qianfan supports only `PP-StructureV3` and `PaddleOCR-VL`.
|
||||
- `PADDLEOCR_MCP_QIANFAN_BASE_URL` is the Qianfan API base URL (optional).
|
||||
- `PADDLEOCR_MCP_QIANFAN_API_KEY` is your Qianfan API key for authentication.
|
||||
|
||||
#### Mode 4: Self-hosted Service
|
||||
#### Method 4: Self-hosted API
|
||||
|
||||
1. In the environment where you need to run the PaddleOCR inference server, run the inference server as per the [PaddleOCR serving documentation](../inference_deployment/serving/serving.en.md).
|
||||
2. Install `paddleocr-mcp` where the MCP server will run.
|
||||
3. Refer to the configuration example below to modify the contents of the `claude_desktop_config.json` file. Set `PADDLEOCR_MCP_SERVER_URL` (e.g., `"http://127.0.0.1:8000"`).
|
||||
1. In the environment where you need to run the PaddleOCR inference server, refer to the [PaddleOCR serving documentation](../inference_deployment/serving/serving.en.md) to run the inference server.
|
||||
2. Install `paddleocr-mcp` in the environment where you need to run the MCP server.
|
||||
3. Refer to the configuration example below to modify the `claude_desktop_config.json` file.
|
||||
4. Restart the MCP host.
|
||||
|
||||
Configuration example:
|
||||
@@ -320,17 +318,17 @@ Configuration example:
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "<your-server-url>"
|
||||
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note**:
|
||||
**Notes**:
|
||||
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for more details.
|
||||
- Replace `<your-server-url>` with your service’s base URL (e.g., `http://127.0.0.1:8000`).
|
||||
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for details.
|
||||
- Replace `<your-server-url>` with the underlying service base URL (e.g. `http://127.0.0.1:8080`, **without** path suffixes such as `/ocr` or `/layout-parsing`; MCP appends them by pipeline).
|
||||
|
||||
### 2.4 Using `uvx`
|
||||
|
||||
@@ -339,58 +337,58 @@ PaddleOCR also supports starting the MCP server via `uvx`. With this approach, m
|
||||
1. Install [uv](https://docs.astral.sh/uv/#installation).
|
||||
2. Modify `claude_desktop_config.json`. Examples:
|
||||
|
||||
Self-hosted mode:
|
||||
Self-hosted API inference example:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"paddleocr": {
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"--from",
|
||||
"paddleocr-mcp",
|
||||
"paddleocr_mcp"
|
||||
],
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "<your-server-url>"
|
||||
}
|
||||
}
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"paddleocr": {
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"--from",
|
||||
"paddleocr-mcp",
|
||||
"paddleocr_mcp"
|
||||
],
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
|
||||
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
}
|
||||
```
|
||||
|
||||
Local mode (inference on CPUs, using the `local-cpu` extra):
|
||||
Local inference (CPU inference, using the optional `local-cpu` extra) example:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"paddleocr": {
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"--from",
|
||||
"paddleocr_mcp[local-cpu]",
|
||||
"paddleocr_mcp"
|
||||
],
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
|
||||
}
|
||||
}
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"paddleocr": {
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"--from",
|
||||
"paddleocr-mcp[local-cpu]",
|
||||
"paddleocr_mcp"
|
||||
],
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
}
|
||||
```
|
||||
|
||||
For information on local mode dependencies, performance tuning, and production configuration, please refer to the [3.1 Quick Start](#21-quick-start) section.
|
||||
For local inference dependencies, performance tuning, and pipeline configuration, refer to [Method 1: Local Inference](#method-1-local-inference).
|
||||
|
||||
Due to the use of a different startup method, the `command` and `args` settings in the configuration file differ from the previously described approach. However, the command-line arguments and environment variables supported by the MCP service (such as `PADDLEOCR_MCP_SERVER_URL`) can still be set in the same way.
|
||||
Due to the use of a different startup method, the `command` and `args` settings in the configuration file differ from the previously described approach. However, the command-line arguments and environment variables supported by the MCP service (such as `PADDLEOCR_MCP_SELF_HOSTED_BASE_URL`) can still be set in the same way.
|
||||
|
||||
## 3. Running the Server
|
||||
|
||||
In addition to MCP hosts like Claude for Desktop, you can also run the PaddleOCR MCP server via the CLI.
|
||||
|
||||
To view help:
|
||||
Run the following command to print help information:
|
||||
|
||||
```bash
|
||||
paddleocr_mcp --help
|
||||
@@ -399,38 +397,41 @@ paddleocr_mcp --help
|
||||
Example commands:
|
||||
|
||||
```bash
|
||||
# OCR + PaddleOCR official service + stdio
|
||||
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --pipeline OCR --ppocr_source aistudio --server_url https://xxxxxx.aistudio-hub.baidu.com
|
||||
# OCR + Official API + stdio
|
||||
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --pipeline OCR --ppocr_source aistudio
|
||||
|
||||
# PP-StructureV3 + local Python library + stdio
|
||||
# PP-StructureV3 + Local Inference + stdio
|
||||
paddleocr_mcp --pipeline PP-StructureV3 --ppocr_source local
|
||||
|
||||
# OCR + self-hosted service + Streamable HTTP
|
||||
paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --server_url http://127.0.0.1:8080 --http
|
||||
# OCR + Self-hosted API + Streamable HTTP
|
||||
paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --self-hosted-base-url http://127.0.0.1:8080 --http
|
||||
```
|
||||
|
||||
You can find all the supported parameters of the PaddleOCR MCP server in [4. Parameter Reference](#4-parameter-reference).
|
||||
See [4. Parameter Reference](#4-parameter-reference) for all parameters supported by the PaddleOCR MCP server.
|
||||
|
||||
## 4. Parameter Reference
|
||||
|
||||
You can control the MCP server via environment variables or CLI arguments.
|
||||
|
||||
| Environment Variable | CLI Argument | Type | Description | Options | Default |
|
||||
| ------------------------------------- | ------------------------- | ------ | --------------------------------------------------------------------- | ---------------------------------------- | ------------- |
|
||||
| `PADDLEOCR_MCP_PIPELINE` | `--pipeline` | `str` | Pipeline to run. | `"OCR"`, `"PP-StructureV3"`, `"PaddleOCR-VL"`, `"PaddleOCR-VL-1.5"`, `"PaddleOCR-VL-1.6"` | `"OCR"` |
|
||||
| `PADDLEOCR_MCP_PPOCR_SOURCE` | `--ppocr_source` | `str` | Source of PaddleOCR capabilities. | `"local"` (local Python library), `"aistudio"` (PaddleOCR official service), `"qianfan"` (Qianfan platform service), `"self_hosted"` (self-hosted service) | `"local"` |
|
||||
| `PADDLEOCR_MCP_SERVER_URL` | `--server_url` | `str` | Base URL for the underlying service (required for `aistudio`, `qianfan`, or `self_hosted` modes). | - | `None` |
|
||||
| `PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN` | `--aistudio_access_token` | `str` | AI Studio access token (required for `aistudio` mode). | - | `None` |
|
||||
| `PADDLEOCR_MCP_TIMEOUT` | `--timeout` | `int` | Read timeout for the underlying requests (seconds). | - | `60` |
|
||||
| `PADDLEOCR_MCP_DEVICE` | `--device` | `str` | Device for inference (`local` mode only). | - | `None` |
|
||||
| `PADDLEOCR_MCP_PIPELINE_CONFIG` | `--pipeline_config` | `str` | Path to pipeline config file (`local` mode only). | - | `None` |
|
||||
| - | `--http` | `bool` | Use Streamable HTTP instead of stdio (for remote/multi-client use). | - | `False` |
|
||||
| - | `--host` | `str` | Host for the Streamable HTTP mode. | - | `"127.0.0.1"` |
|
||||
| - | `--port` | `int` | Port for the Streamable HTTP mode. | - | `8000` |
|
||||
| - | `--verbose` | `bool` | Enable verbose logging for debugging. | - | `False` |
|
||||
| Environment Variable | CLI Argument | Type | Description | Options | Default |
|
||||
|:---------|:-----------|:-----|:-----|:-------|:-------|
|
||||
| `PADDLEOCR_MCP_PIPELINE` | `--pipeline` | `str` | Pipeline to run. | `"OCR"`, `"PP-StructureV3"`, `"PaddleOCR-VL"`, `"PaddleOCR-VL-1.5"`, `"PaddleOCR-VL-1.6"` | `"OCR"` |
|
||||
| `PADDLEOCR_MCP_PPOCR_SOURCE` | `--ppocr_source` | `str` | Source of PaddleOCR capabilities. | `"local"` (local inference), `"aistudio"` (Official API), `"qianfan"` (Qianfan API), `"self_hosted"` (self-hosted API) | `"local"` |
|
||||
| `PADDLEOCR_MCP_AISTUDIO_BASE_URL` | `--aistudio-base-url` | `str` | AI Studio API base URL (optional for `aistudio` source). | - | `None` |
|
||||
| `PADDLEOCR_MCP_QIANFAN_BASE_URL` | `--qianfan-base-url` | `str` | Qianfan API base URL (optional for `qianfan` source). | - | `https://qianfan.baidubce.com/v2/ocr` |
|
||||
| `PADDLEOCR_MCP_SELF_HOSTED_BASE_URL` | `--self-hosted-base-url` | `str` | Self-hosted PaddleX serve base URL (required for `self_hosted` source). | - | `None` |
|
||||
| `PADDLEOCR_MCP_QIANFAN_API_KEY` | `--qianfan_api_key` | `str` | Qianfan API authentication key (required for `qianfan` source). | - | `None` |
|
||||
| `PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN` | `--aistudio_access_token` | `str` | AI Studio access token (required for `aistudio` source). | - | `None` |
|
||||
| `PADDLEOCR_MCP_TIMEOUT` | `--timeout` | `int` | Underlying request timeout in seconds. For `aistudio`, used as the per-request timeout; polling timeout is 10× this value. For `qianfan` and `self_hosted`, used as the HTTP read timeout. | - | `60` |
|
||||
| `PADDLEOCR_MCP_DEVICE` | `--device` | `str` | Device for inference (only effective for `local` source). | - | `None` |
|
||||
| `PADDLEOCR_MCP_PIPELINE_CONFIG` | `--pipeline_config` | `str` | PaddleOCR pipeline configuration file path (only effective for `local` source). | - | `None` |
|
||||
| - | `--http` | `bool` | Use Streamable HTTP transport instead of stdio (for remote deployment and multiple clients). | - | `False` |
|
||||
| - | `--host` | `str` | Host address for Streamable HTTP mode. | - | `"127.0.0.1"` |
|
||||
| - | `--port` | `int` | Port for Streamable HTTP mode. | - | `8000` |
|
||||
| - | `--verbose` | `bool` | Enable verbose logging for debugging. | - | `False` |
|
||||
|
||||
## 5. Known Limitations
|
||||
|
||||
- In the local Python library mode, the exposed MCP tool cannot process PDF document inputs that are Base64 encoded.
|
||||
- In the local Python library mode, the exposed MCP tool does not infer the file type based on the model's `file_type` prompt, and may fail to process some complex URLs.
|
||||
- Under local inference, the exposed MCP tool cannot process PDF document inputs that are Base64 encoded.
|
||||
- Under local inference, the exposed MCP tool does not infer file type from the model's `file_type` prompt; some complex URLs may fail to process.
|
||||
- For the PP-StructureV3 and PaddleOCR-VL series, if the input file contains images, the returned results may significantly increase token usage. If image content is not needed, you can explicitly exclude it through prompts to reduce resource consumption.
|
||||
@@ -17,17 +17,15 @@ PaddleOCR 提供轻量级的 [Model Context Protocol(MCP)](https://modelcont
|
||||
| --- | --- | --- |
|
||||
| `OCR` | `ocr` | 对图像和 PDF 文件进行文本检测与识别。 |
|
||||
| `PP-StructureV3` | `pp_structurev3` | 从图像或 PDF 文件中识别和提取文本块、标题、段落、图片、表格以及其他版面元素,将输入转换为 Markdown 文档。 |
|
||||
| `PaddleOCR-VL` | `paddleocr_vl` | 使用基于多模态大模型的方案进行版面解析,将输入转换为 Markdown 文档。 |
|
||||
| `PaddleOCR-VL-1.5` | `paddleocr_vl` | PaddleOCR-VL 的升级版,相较于 PaddleOCR-VL,在速度与准确率上均有提升。 |
|
||||
| `PaddleOCR-VL-1.6` | `paddleocr_vl` | PaddleOCR-VL 系列的最新版本,在 PaddleOCR-VL-1.5 的基础上进一步升级了 VLM 组件。 |
|
||||
| `PaddleOCR-VL 系列` | `paddleocr_vl` | 使用基于多模态大模型的方案进行版面解析,将输入转换为 Markdown 文档。包含版本:PaddleOCR-VL、PaddleOCR-VL-1.5、PaddleOCR-VL-1.6。 |
|
||||
|
||||
> 每个 MCP 服务器实例对外只暴露一个 MCP 工具。
|
||||
|
||||
- **支持运行在如下工作模式**
|
||||
- **本地 Python 库**:在本机直接运行 PaddleOCR 产线。此模式对本地环境与计算机性能有一定要求,适用于需要离线使用、对数据隐私有严格要求的场景。
|
||||
- **PaddleOCR 官方服务**:调用 [PaddleOCR 官网](https://aistudio.baidu.com/paddleocr) 提供的云服务。此模式适合快速体验功能、快速验证方案等,也适用于零代码开发场景。
|
||||
- **千帆平台服务**:调用百度智能云千帆大模型平台提供的云服务。
|
||||
- **自托管服务**:调用用户自托管的 PaddleOCR 服务。此模式具备服务化部署优势及高度灵活性,适用于需要自定义服务配置的场景,同时也适用于对数据隐私有严格要求的场景。**目前暂时只支持基础服务化部署方案。**
|
||||
- **支持的推理方式**
|
||||
- **本地推理**:在本机直接运行 PaddleOCR 产线。此方式对本地环境与计算机性能有一定要求,适用于需要离线使用、对数据隐私有严格要求的场景。
|
||||
- **官方 API**:调用 PaddleOCR 官方提供的 API。此方式适合快速体验功能、快速验证方案等,也适用于零代码开发场景。
|
||||
- **千帆 API**:调用百度智能云千帆大模型平台提供的 API。
|
||||
- **自建 API**:调用用户自建的 PaddleOCR 推理服务。此方式具备服务化部署优势及高度灵活性,适用于需要自定义服务配置的场景,同时也适用于对数据隐私有严格要求的场景。**目前暂时只支持基础服务化部署方案。**
|
||||
|
||||
## 示例:
|
||||
|
||||
@@ -87,7 +85,7 @@ PaddleOCR 提供轻量级的 [Model Context Protocol(MCP)](https://modelcont
|
||||
- [2. 在 Claude for Desktop 中使用](#2-claude-for-desktop)
|
||||
- [2.1 快速开始](#21)
|
||||
- [2.2 MCP 主机配置说明](#22-mcp)
|
||||
- [2.3 工作模式说明](#23)
|
||||
- [2.3 推理方式说明](#23)
|
||||
- [2.4 使用 `uvx`](#24-uvx)
|
||||
- [3. 运行服务器](#3)
|
||||
- [4. 参数说明](#4)
|
||||
@@ -97,29 +95,24 @@ PaddleOCR 提供轻量级的 [Model Context Protocol(MCP)](https://modelcont
|
||||
|
||||
本节将介绍如何通过 pip 安装 `paddleocr-mcp` 库。
|
||||
|
||||
- 对于本地 Python 库模式,除了安装 `paddleocr-mcp` 外,还需要参考 [PaddleOCR 安装文档](../installation.md) 安装飞桨框架和 PaddleOCR。
|
||||
- 对于本地 Python 库模式,也可以考虑选择安装相应的可选依赖:
|
||||
- `paddleocr-mcp[local]`:包含 PaddleOCR(不包含飞桨框架)。
|
||||
- `paddleocr-mcp[local-cpu]`:在 `local` 基础上额外包含 CPU 版本的飞桨框架。
|
||||
- PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器。详情请参考 [2. 在 Claude for Desktop 中使用](#2-claude-for-desktop) 中的说明。
|
||||
`paddleocr-mcp` 要求 Python 版本不低于 3.10。
|
||||
`paddleocr-mcp` 默认依赖 `paddleocr>=3.6.0`,因此官方 API、千帆 API 和自建 API 推理方式无需额外安装 PaddleOCR。如需使用本地推理,还需要安装本地运行产线所需的文档解析依赖和推理引擎,详情请参考 [方式一:本地推理](#方式一本地推理)。
|
||||
|
||||
使用 pip 安装 `paddleocr-mcp` 库的命令如下:
|
||||
从 PyPI 安装:
|
||||
|
||||
```bash
|
||||
# 从 PyPI 安装
|
||||
pip install -U paddleocr-mcp
|
||||
```
|
||||
|
||||
# 从项目源码安装
|
||||
从项目源码安装:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PaddlePaddle/PaddleOCR.git
|
||||
pip install -e mcp_server
|
||||
|
||||
# 通过指定 extra 安装可选依赖
|
||||
# 同时安装 PaddleOCR
|
||||
pip install "paddleocr-mcp[local]"
|
||||
# 同时安装 PaddleOCR 和 CPU 版本飞桨框架
|
||||
pip install "paddleocr-mcp[local-cpu]"
|
||||
```
|
||||
|
||||
如需使用本地推理,请安装 [方式一:本地推理](#方式一本地推理) 中说明的可选依赖。
|
||||
|
||||
可通过以下命令检查是否安装成功:
|
||||
|
||||
```bash
|
||||
@@ -128,21 +121,23 @@ paddleocr_mcp --help
|
||||
|
||||
如果执行上述命令后打印出了帮助信息,则说明安装成功。
|
||||
|
||||
PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参考 [2. 在 Claude for Desktop 中使用](#2-claude-for-desktop) 中的说明。
|
||||
|
||||
## 2. 在 Claude for Desktop 中使用
|
||||
|
||||
本节将介绍如何在 Claude for Desktop 中使用 PaddleOCR MCP 服务器。对于其他 MCP 主机,也可参照本节的步骤,并根据实际情况进行相应调整。
|
||||
|
||||
### 2.1 快速开始
|
||||
|
||||
接下来以 **PaddleOCR 官方服务** 工作模式为例,引导您快速上手。
|
||||
接下来以 **官方 API** 推理方式为例,引导您快速上手。
|
||||
|
||||
1. **安装 `paddleocr-mcp`**
|
||||
|
||||
请参考 [1. 安装](#1)。
|
||||
|
||||
2. **获取服务基础 URL 与星河社区访问令牌**
|
||||
2. **获取访问令牌**
|
||||
|
||||
在 [此页面](https://aistudio.baidu.com/paddleocr/task) 点击左上角的“API”,复制“文字识别(PP-OCRv5)”对应的 `API_URL` 去掉端点末尾(`/ocr`)的部分,即服务的基础 URL(如 `https://xxxxxx.aistudio-app.com`),以及 `TOKEN`,即您的访问令牌。您可能需要注册并登陆飞桨星河社区帐号。
|
||||
请先在 [AI Studio Access Token 页面](https://aistudio.baidu.com/account/accessToken) 获取访问令牌。
|
||||
|
||||
3. **添加 MCP 服务器配置**
|
||||
|
||||
@@ -163,7 +158,6 @@ paddleocr_mcp --help
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "aistudio",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "<your-server-url>",
|
||||
"PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN": "<your-access-token>"
|
||||
}
|
||||
}
|
||||
@@ -173,15 +167,15 @@ paddleocr_mcp --help
|
||||
|
||||
**说明**:
|
||||
|
||||
- 将 `<your-server-url>` 替换为上一步获取的服务基础 URL。
|
||||
- 将 `<your-access-token>` 替换为您的访问令牌。
|
||||
- 如需使用自定义服务地址,可设置 `PADDLEOCR_MCP_AISTUDIO_BASE_URL` 环境变量。
|
||||
|
||||
**注意**:
|
||||
|
||||
- 请勿泄漏您的 **访问令牌**。
|
||||
- 如果 `paddleocr_mcp` 无法在系统 `PATH` 中找到,请将 `command` 设置为可执行文件的绝对路径。
|
||||
|
||||
5. **重启 MCP 主机**
|
||||
4. **重启 MCP 主机**
|
||||
|
||||
重启 Claude for Desktop。新的 `paddleocr` 服务现在应该可以在应用中使用了。
|
||||
|
||||
@@ -193,13 +187,24 @@ paddleocr_mcp --help
|
||||
- `args`:可配置命令行参数,如 `["--verbose"]`。详见 [4. 参数说明](#4)。
|
||||
- `env`:可配置环境变量。详见 [4. 参数说明](#4)。
|
||||
|
||||
### 2.3 工作模式说明
|
||||
### 2.3 推理方式说明
|
||||
|
||||
您可以根据需求配置 MCP 服务器,使其运行在不同的工作模式。不同工作模式需要的操作流程有所不同,下面将详细介绍。
|
||||
您可以根据需求配置 MCP 服务器,使其使用不同的推理方式。不同推理方式需要的操作流程有所不同,下面将详细介绍。
|
||||
|
||||
#### 模式一:本地 Python 库
|
||||
#### 方式一:本地推理 {#方式一本地推理}
|
||||
|
||||
1. 安装 `paddleocr-mcp`、飞桨框架和 PaddleOCR。对于飞桨框架和 PaddleOCR,可以参考 [PaddleOCR 安装文档](../installation.md) 手动安装,也可以通过 `paddleocr-mcp[local]` 或 `paddleocr-mcp[local-cpu]` 方式于 `paddleocr-mcp` 一同安装。为避免依赖冲突,**强烈建议在独立的虚拟环境中安装**。
|
||||
1. 安装 `paddleocr-mcp` 及本地推理依赖。`paddleocr-mcp` 已默认依赖 PaddleOCR;本地推理还需要文档解析依赖和推理引擎。可以参考 [PaddleOCR 安装文档](../installation.md) 手动安装,也可以使用相应的可选依赖:
|
||||
- `paddleocr-mcp[local]`:包含 `paddleocr[doc-parser]>=3.6.0`(不包含推理引擎)。
|
||||
- `paddleocr-mcp[local-cpu]`:在 `local` 基础上额外包含 CPU 版本的 PaddlePaddle 推理引擎(`paddlepaddle>=3.2.1`)。
|
||||
|
||||
```bash
|
||||
# 安装本地推理所需的文档解析依赖(不包含推理引擎)
|
||||
pip install "paddleocr-mcp[local]"
|
||||
# 在 local 基础上额外安装 CPU 版本飞桨框架
|
||||
pip install "paddleocr-mcp[local-cpu]"
|
||||
```
|
||||
|
||||
为避免依赖冲突,**强烈建议在独立的虚拟环境中安装**。
|
||||
2. 参考下方的配置示例更改 `claude_desktop_config.json` 文件内容。
|
||||
3. 重启 MCP 主机。
|
||||
|
||||
@@ -259,17 +264,17 @@ paddleocr_mcp --help
|
||||
|
||||
**对于 PaddleOCR-VL 系列,不建议使用 CPU 推理。**
|
||||
|
||||
#### 模式二:PaddleOCR 官方服务
|
||||
#### 方式二:官方 API
|
||||
|
||||
请参考 [2.1 快速开始](#21)。
|
||||
|
||||
对于文字识别以外的任务,请在 PaddleOCR 官网获取任务对应的服务基础 URL,并正确设置 `PADDLEOCR_MCP_PIPELINE` 与 `PADDLEOCR_MCP_SERVER_URL`(参数说明详见第 4 节)。
|
||||
对于文字识别以外的任务,请正确设置 `PADDLEOCR_MCP_PIPELINE`(参数说明详见第 4 节)。
|
||||
|
||||
#### 模式三:千帆平台服务
|
||||
#### 方式三:千帆 API
|
||||
|
||||
1. 安装 `paddleocr-mcp`。
|
||||
2. 参考 [千帆平台官方文档](https://cloud.baidu.com/doc/qianfan-api/s/ym9chdsy5) 获取 API key。
|
||||
3. 参考下方的配置示例更改 `claude_desktop_config.json` 文件内容。将 `PADDLEOCR_MCP_QIANFAN_API_KEY` 设置为千帆平台的 API key。
|
||||
3. 参考下方的配置示例更改 `claude_desktop_config.json` 文件内容。
|
||||
4. 重启 MCP 主机。
|
||||
|
||||
配置示例:
|
||||
@@ -283,7 +288,6 @@ paddleocr_mcp --help
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "PaddleOCR-VL",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "qianfan",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "https://qianfan.baidubce.com/v2/ocr",
|
||||
"PADDLEOCR_MCP_QIANFAN_API_KEY": "<your-api-key>"
|
||||
}
|
||||
}
|
||||
@@ -293,13 +297,15 @@ paddleocr_mcp --help
|
||||
|
||||
**说明**:
|
||||
|
||||
- `PADDLEOCR_MCP_PIPELINE` 需要被设置为产线名称。详见第 4 节。千帆平台服务目前仅支持 PP-StructureV3 和 PaddleOCR-VL。
|
||||
- `PADDLEOCR_MCP_PIPELINE` 需设置为产线名称;千帆仅支持 `PP-StructureV3` 与 `PaddleOCR-VL`。
|
||||
- `PADDLEOCR_MCP_QIANFAN_BASE_URL` 为千帆 API 基础 URL(可选)。
|
||||
- `PADDLEOCR_MCP_QIANFAN_API_KEY` 是您的千帆 API key,用于认证。
|
||||
|
||||
#### 模式四:自托管服务
|
||||
#### 方式四:自建 API
|
||||
|
||||
1. 在需要运行 PaddleOCR 推理服务器的环境中,参考 [PaddleOCR 服务化部署文档](../inference_deployment/serving/serving.md) 运行推理服务器。
|
||||
2. 在需要运行 MCP 服务器的环境中安装 `paddleocr-mcp`。
|
||||
3. 参考下方的配置示例更改 `claude_desktop_config.json` 文件内容。将您的服务地址填入 `PADDLEOCR_MCP_SERVER_URL` (例如:`"http://127.0.0.1:8000"`)。
|
||||
3. 参考下方的配置示例更改 `claude_desktop_config.json` 文件内容。
|
||||
4. 重启 MCP 主机。
|
||||
|
||||
配置示例:
|
||||
@@ -313,7 +319,7 @@ paddleocr_mcp --help
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "<your-server-url>"
|
||||
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -323,7 +329,7 @@ paddleocr_mcp --help
|
||||
**说明**:
|
||||
|
||||
- `PADDLEOCR_MCP_PIPELINE` 需要被设置为产线名称。详见第 4 节。
|
||||
- 将 `<your-server-url>` 替换为底层服务的基础 URL(如:`http://127.0.0.1:8000`)。
|
||||
- 将 `<your-server-url>` 替换为底层服务的基础 URL(如:`http://127.0.0.1:8080`,**不要**包含 `/ocr`、`/layout-parsing` 等路径;MCP 会按产线自动拼接)。
|
||||
|
||||
### 2.4 使用 `uvx`
|
||||
|
||||
@@ -332,7 +338,7 @@ PaddleOCR 也支持通过 `uvx` 启动 MCP 服务器。这种方式不需要手
|
||||
1. 安装 [uv](https://docs.astral.sh/uv/#installation)。
|
||||
2. 修改 `claude_desktop_config.json` 文件。示例如下:
|
||||
|
||||
自托管服务模式示例:
|
||||
自建 API 推理示例:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -347,14 +353,14 @@ PaddleOCR 也支持通过 `uvx` 启动 MCP 服务器。这种方式不需要手
|
||||
"env": {
|
||||
"PADDLEOCR_MCP_PIPELINE": "OCR",
|
||||
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
|
||||
"PADDLEOCR_MCP_SERVER_URL": "<your-server-url>"
|
||||
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
本地模式(CPU 推理,使用可选依赖 `local-cpu`)示例:
|
||||
本地推理(CPU 推理,使用可选依赖 `local-cpu`)示例:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -363,7 +369,7 @@ PaddleOCR 也支持通过 `uvx` 启动 MCP 服务器。这种方式不需要手
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"--from",
|
||||
"paddleocr_mcp[local-cpu]",
|
||||
"paddleocr-mcp[local-cpu]",
|
||||
"paddleocr_mcp"
|
||||
],
|
||||
"env": {
|
||||
@@ -375,9 +381,9 @@ PaddleOCR 也支持通过 `uvx` 启动 MCP 服务器。这种方式不需要手
|
||||
}
|
||||
```
|
||||
|
||||
如需了解本地模式的依赖、性能调优及产线配置,请参考 [模式一:本地 Python 库](#python) 部分。
|
||||
如需了解本地推理的依赖、性能调优及产线配置,请参考 [方式一:本地推理](#方式一本地推理) 部分。
|
||||
|
||||
由于使用了不一样的启动方式,配置文件中 `command` 和 `args` 的设置都与前文介绍的方式存在不同,但 MCP 服务本身支持的命令行参数与环境变量(如 `PADDLEOCR_MCP_SERVER_URL`)仍然可以以相同的方式设置。
|
||||
由于使用了不一样的启动方式,配置文件中 `command` 和 `args` 的设置都与前文介绍的方式存在不同,但 MCP 服务本身支持的命令行参数与环境变量(如 `PADDLEOCR_MCP_SELF_HOSTED_BASE_URL`)仍然可以以相同的方式设置。
|
||||
|
||||
## 3. 运行服务器
|
||||
|
||||
@@ -392,14 +398,14 @@ paddleocr_mcp --help
|
||||
示例命令如下:
|
||||
|
||||
```bash
|
||||
# OCR + PaddleOCR 官方服务 + stdio
|
||||
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --pipeline OCR --ppocr_source aistudio --server_url https://xxxxxx.aistudio-hub.baidu.com
|
||||
# OCR + 官方 API + stdio
|
||||
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --pipeline OCR --ppocr_source aistudio
|
||||
|
||||
# PP-StructureV3 + 本地 Python 库 + stdio
|
||||
# PP-StructureV3 + 本地推理 + stdio
|
||||
paddleocr_mcp --pipeline PP-StructureV3 --ppocr_source local
|
||||
|
||||
# OCR + 本地服务 + Streamable HTTP
|
||||
paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --server_url http://127.0.0.1:8080 --http
|
||||
# OCR + 自建 API + Streamable HTTP
|
||||
paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --self-hosted-base-url http://127.0.0.1:8080 --http
|
||||
```
|
||||
|
||||
在 [4. 参数说明](#4) 中可以了解 PaddleOCR MCP 服务器支持的全部参数。
|
||||
@@ -411,12 +417,15 @@ paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --server_url http://127.
|
||||
| 环境变量 | 命令行参数 | 类型 | 描述 | 可选值 | 默认值 |
|
||||
|:---------|:-----------|:-----|:-----|:-------|:-------|
|
||||
| `PADDLEOCR_MCP_PIPELINE` | `--pipeline` | `str` | 要运行的产线。 | `"OCR"`,`"PP-StructureV3"`,`"PaddleOCR-VL"`,`"PaddleOCR-VL-1.5"`,`"PaddleOCR-VL-1.6"` | `"OCR"` |
|
||||
| `PADDLEOCR_MCP_PPOCR_SOURCE` | `--ppocr_source` | `str` | PaddleOCR 能力来源。 | `"local"`(本地 Python 库),`"aistudio"`(PaddleOCR 官方服务),`"qianfan"`(千帆平台服务),`"self_hosted"`(自托管服务) | `"local"` |
|
||||
| `PADDLEOCR_MCP_SERVER_URL` | `--server_url` | `str` | 底层服务基础 URL(`aistudio`、`qianfan`、`self_hosted` 模式下必需)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN` | `--aistudio_access_token` | `str` | AI Studio 访问令牌(`aistudio` 模式下必需)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_TIMEOUT` | `--timeout` | `int` | 底层服务请求的读取超时时间(秒)。 | - | `60` |
|
||||
| `PADDLEOCR_MCP_DEVICE` | `--device` | `str` | 指定运行推理的设备(仅在 `local` 模式下生效)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_PIPELINE_CONFIG` | `--pipeline_config` | `str` | PaddleOCR 产线配置文件路径(仅在 `local` 模式下生效)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_PPOCR_SOURCE` | `--ppocr_source` | `str` | PaddleOCR能力来源。 | `"local"`(本地推理),`"aistudio"`(官方 API),`"qianfan"`(千帆 API),`"self_hosted"`(自建 API) | `"local"` |
|
||||
| `PADDLEOCR_MCP_AISTUDIO_BASE_URL` | `--aistudio-base-url` | `str` | AI Studio API 基础 URL(`aistudio` 推理方式下可选)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_QIANFAN_BASE_URL` | `--qianfan-base-url` | `str` | 千帆 API 基础 URL(`qianfan` 推理方式下可选)。 | - | `https://qianfan.baidubce.com/v2/ocr` |
|
||||
| `PADDLEOCR_MCP_SELF_HOSTED_BASE_URL` | `--self-hosted-base-url` | `str` | 自建 PaddleX 服务基础 URL(`self_hosted` 推理方式下必需)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_QIANFAN_API_KEY` | `--qianfan_api_key` | `str` | 千帆 API 认证密钥(`qianfan` 推理方式下必需)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN` | `--aistudio_access_token` | `str` | AI Studio 访问令牌(`aistudio` 推理方式下必需)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_TIMEOUT` | `--timeout` | `int` | 底层服务请求超时时间(秒)。在 `aistudio` 推理方式下用作单次请求超时,轮询超时为该值的 10 倍;在 `qianfan` 和 `self_hosted` 推理方式下用作 HTTP 读取超时。 | - | `60` |
|
||||
| `PADDLEOCR_MCP_DEVICE` | `--device` | `str` | 指定运行推理的设备(仅在 `local` 推理方式下生效)。 | - | `None` |
|
||||
| `PADDLEOCR_MCP_PIPELINE_CONFIG` | `--pipeline_config` | `str` | PaddleOCR 产线配置文件路径(仅在 `local` 推理方式下生效)。 | - | `None` |
|
||||
| - | `--http` | `bool` | 使用 Streamable HTTP 传输而非 stdio(适用于远程部署和多客户端)。 | - | `False` |
|
||||
| - | `--host` | `str` | Streamable HTTP 模式的主机地址。 | - | `"127.0.0.1"` |
|
||||
| - | `--port` | `int` | Streamable HTTP 模式的端口。 | - | `8000` |
|
||||
@@ -424,6 +433,6 @@ paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --server_url http://127.
|
||||
|
||||
## 5. 已知局限性
|
||||
|
||||
- 在本地 Python 库模式下,对外暴露的 MCP 工具无法处理 Base64 编码的 PDF 文档输入。
|
||||
- 在本地 Python 库模式下,对外暴露的 MCP 工具不会根据模型提示的 `file_type` 推断文件类型,对于一些复杂 URL 可能处理失败。
|
||||
- 在本地推理方式下,对外暴露的 MCP 工具无法处理 Base64 编码的 PDF 文档输入。
|
||||
- 在本地推理方式下,对外暴露的 MCP 工具不会根据模型提示的 `file_type` 推断文件类型,对于一些复杂 URL 可能处理失败。
|
||||
- 对于 PP-StructureV3 和 PaddleOCR-VL 系列,若输入文件中包含图像,返回结果可能会显著增加 token 使用量。若无需图像内容,可通过提示词明确排除,以降低资源消耗。
|
||||
@@ -18,11 +18,6 @@ PaddleOCR provides official Agent Skills that package the routing rules, calling
|
||||
- `paddleocr-text-recognition`: extracts text from images, scans, and PDF files.
|
||||
- `paddleocr-doc-parsing`: parses complex document layouts and converts them to Markdown or structured output.
|
||||
|
||||
Each skill currently supports the following underlying models:
|
||||
|
||||
- `paddleocr-text-recognition`: `PP-OCRv5`
|
||||
- `paddleocr-doc-parsing`: `PP-StructureV3`, `PaddleOCR-VL`, `PaddleOCR-VL-1.5`, `PaddleOCR-VL-1.6`
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. Install Python 3.9 or later on the machine that runs the skill.
|
||||
@@ -75,12 +70,10 @@ The skill source code is located under `PaddleOCR/skills`. Refer to your AI app
|
||||
|
||||
## Configure Environment Variables
|
||||
|
||||
After installation, configure the required environment variables so the skills can work correctly:
|
||||
After installation, configure the following environment variables:
|
||||
|
||||
| Skill | Required | Optional |
|
||||
| --- | --- | --- |
|
||||
| `paddleocr-text-recognition` | `PADDLEOCR_ACCESS_TOKEN` (access token) | `PADDLEOCR_BASE_URL` (API base URL, defaults to official service) |
|
||||
| `paddleocr-doc-parsing` | `PADDLEOCR_ACCESS_TOKEN` (access token) | `PADDLEOCR_BASE_URL` (API base URL, defaults to official service) |
|
||||
- Required: `PADDLEOCR_ACCESS_TOKEN` (access token)
|
||||
- Optional: `PADDLEOCR_BASE_URL` (API base URL, defaults to official service)
|
||||
|
||||
Get access token: visit [AI Studio Access Token](https://aistudio.baidu.com/account/accessToken)
|
||||
|
||||
|
||||
@@ -18,11 +18,6 @@ PaddleOCR 提供官方 Agent Skills,将 OCR 与文档解析任务的触发规
|
||||
- `paddleocr-text-recognition`:用于识别图片、扫描件与 PDF 中的文字。
|
||||
- `paddleocr-doc-parsing`:用于解析复杂文档版面,并转换为 Markdown 或结构化结果。
|
||||
|
||||
当前各 Skill 支持的底层模型如下:
|
||||
|
||||
- `paddleocr-text-recognition`:`PP-OCRv5`
|
||||
- `paddleocr-doc-parsing`:`PP-StructureV3`、`PaddleOCR-VL`、`PaddleOCR-VL-1.5`、`PaddleOCR-VL-1.6`
|
||||
|
||||
## 安装前准备
|
||||
|
||||
1. 请确保执行 Skill 的设备已安装 Python 3.9 或以上版本。
|
||||
@@ -75,12 +70,10 @@ Skill 源码位于 `PaddleOCR/skills` 目录。请参考对应 AI 应用的安
|
||||
|
||||
## 配置环境变量 {#配置环境变量}
|
||||
|
||||
安装完成后,需要配置环境变量以便 Skill 正常工作:
|
||||
安装完成后,配置如下环境变量:
|
||||
|
||||
| Skill | 必填 | 可选 |
|
||||
| --- | --- | --- |
|
||||
| `paddleocr-text-recognition` | `PADDLEOCR_ACCESS_TOKEN`(access token) | `PADDLEOCR_BASE_URL`(API base URL,默认官方服务) |
|
||||
| `paddleocr-doc-parsing` | `PADDLEOCR_ACCESS_TOKEN`(access token) | `PADDLEOCR_BASE_URL`(API base URL,默认官方服务) |
|
||||
- 必填:`PADDLEOCR_ACCESS_TOKEN`(access token)
|
||||
- 可选:`PADDLEOCR_BASE_URL`(API base URL,默认官方服务)
|
||||
|
||||
获取 access token:访问 [AI Studio Access Token 页面](https://aistudio.baidu.com/account/accessToken)
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
@@ -14,6 +13,8 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
@@ -21,14 +22,15 @@ import sys
|
||||
|
||||
from fastmcp import FastMCP
|
||||
|
||||
from .pipelines import create_pipeline_handler
|
||||
from .inference import create_inference
|
||||
from .tasks import create_task
|
||||
|
||||
_QIANFAN_SUPPORTED_PIPELINES = frozenset({"PP-StructureV3", "PaddleOCR-VL"})
|
||||
|
||||
|
||||
def _parse_args() -> argparse.Namespace:
|
||||
"""Parse command line arguments."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="PaddleOCR MCP server - Supports local library, AI Studio service, and self-hosted servers."
|
||||
)
|
||||
parser = argparse.ArgumentParser(description="PaddleOCR MCP server.")
|
||||
|
||||
parser.add_argument(
|
||||
"--pipeline",
|
||||
@@ -40,71 +42,85 @@ def _parse_args() -> argparse.Namespace:
|
||||
"PaddleOCR-VL-1.6",
|
||||
],
|
||||
default=os.getenv("PADDLEOCR_MCP_PIPELINE", "OCR"),
|
||||
help="Pipeline name.",
|
||||
help="Pipeline to run. Env: PADDLEOCR_MCP_PIPELINE.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--ppocr_source",
|
||||
choices=["local", "aistudio", "qianfan", "self_hosted"],
|
||||
default=os.getenv("PADDLEOCR_MCP_PPOCR_SOURCE", "local"),
|
||||
help="Source of PaddleOCR functionality: local (local library), aistudio (AI Studio service), qianfan (Qianfan service), self_hosted (self-hosted server).",
|
||||
help="Inference backend. Env: PADDLEOCR_MCP_PPOCR_SOURCE.",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--http",
|
||||
action="store_true",
|
||||
help="Use HTTP transport instead of STDIO (suitable for remote deployment and multiple clients).",
|
||||
help="Use Streamable HTTP instead of stdio.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--host",
|
||||
default="127.0.0.1",
|
||||
help="Host address for HTTP mode (default: 127.0.0.1).",
|
||||
help="HTTP bind host (with --http). Default: 127.0.0.1.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port",
|
||||
type=int,
|
||||
default=8000,
|
||||
help="Port for HTTP mode (default: 8000).",
|
||||
help="HTTP bind port (with --http). Default: 8000.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--verbose", action="store_true", help="Enable verbose logging for debugging."
|
||||
"--verbose",
|
||||
action="store_true",
|
||||
help="Enable verbose logging.",
|
||||
)
|
||||
|
||||
# Local mode configuration
|
||||
parser.add_argument(
|
||||
"--pipeline_config",
|
||||
default=os.getenv("PADDLEOCR_MCP_PIPELINE_CONFIG"),
|
||||
help="PaddleOCR pipeline configuration file path (for local mode).",
|
||||
help="Pipeline config file path (local). Env: PADDLEOCR_MCP_PIPELINE_CONFIG.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--device",
|
||||
default=os.getenv("PADDLEOCR_MCP_DEVICE"),
|
||||
help="Device to run inference on.",
|
||||
help="Inference device (local). Env: PADDLEOCR_MCP_DEVICE.",
|
||||
)
|
||||
|
||||
# Service mode configuration
|
||||
parser.add_argument(
|
||||
"--server_url",
|
||||
default=os.getenv("PADDLEOCR_MCP_SERVER_URL"),
|
||||
help="Base URL of the underlying server (required in service mode).",
|
||||
"--aistudio-base-url",
|
||||
dest="aistudio_base_url",
|
||||
default=os.getenv("PADDLEOCR_MCP_AISTUDIO_BASE_URL"),
|
||||
help="AI Studio API base URL (aistudio). Env: PADDLEOCR_MCP_AISTUDIO_BASE_URL.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--qianfan-base-url",
|
||||
dest="qianfan_base_url",
|
||||
default=os.getenv("PADDLEOCR_MCP_QIANFAN_BASE_URL")
|
||||
or "https://qianfan.baidubce.com/v2/ocr",
|
||||
help="Qianfan API base URL (qianfan). Env: PADDLEOCR_MCP_QIANFAN_BASE_URL.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--self-hosted-base-url",
|
||||
dest="self_hosted_base_url",
|
||||
default=os.getenv("PADDLEOCR_MCP_SELF_HOSTED_BASE_URL"),
|
||||
help="Self-hosted service base URL (self_hosted). Env: PADDLEOCR_MCP_SELF_HOSTED_BASE_URL.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--aistudio_access_token",
|
||||
default=os.getenv("PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN"),
|
||||
help="AI Studio access token (required for AI Studio).",
|
||||
help="AI Studio access token (aistudio). Env: PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--qianfan_api_key",
|
||||
default=os.getenv("PADDLEOCR_MCP_QIANFAN_API_KEY"),
|
||||
help="Qianfan API key (required for Qianfan).",
|
||||
help="Qianfan API key (qianfan). Env: PADDLEOCR_MCP_QIANFAN_API_KEY.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--timeout",
|
||||
type=int,
|
||||
default=int(os.getenv("PADDLEOCR_MCP_TIMEOUT", "60")),
|
||||
help="HTTP read timeout in seconds for API requests to the underlying server.",
|
||||
help="Request timeout in seconds. Env: PADDLEOCR_MCP_TIMEOUT.",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def _validate_args(args: argparse.Namespace) -> None:
|
||||
@@ -116,17 +132,8 @@ def _validate_args(args: argparse.Namespace) -> None:
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
if args.ppocr_source in ["aistudio", "qianfan", "self_hosted"]:
|
||||
if not args.server_url:
|
||||
print("Error: The server base URL is required.", file=sys.stderr)
|
||||
print(
|
||||
"Please either set `--server_url` or set the environment variable "
|
||||
"`PADDLEOCR_MCP_SERVER_URL`.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
if args.ppocr_source == "aistudio" and not args.aistudio_access_token:
|
||||
if args.ppocr_source == "aistudio":
|
||||
if not args.aistudio_access_token:
|
||||
print("Error: The AI Studio access token is required.", file=sys.stderr)
|
||||
print(
|
||||
"Please either set `--aistudio_access_token` or set the environment variable "
|
||||
@@ -134,50 +141,85 @@ def _validate_args(args: argparse.Namespace) -> None:
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
elif args.ppocr_source == "qianfan":
|
||||
if not args.qianfan_api_key:
|
||||
print("Error: The Qianfan API key is required.", file=sys.stderr)
|
||||
print(
|
||||
"Please either set `--qianfan_api_key` or set the environment variable "
|
||||
"`PADDLEOCR_MCP_QIANFAN_API_KEY`.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
if args.pipeline not in ("PP-StructureV3", "PaddleOCR-VL"):
|
||||
print(
|
||||
f"{repr(args.pipeline)} is currently not supported when using the {repr(args.ppocr_source)} source.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
elif args.ppocr_source == "qianfan":
|
||||
if args.pipeline not in _QIANFAN_SUPPORTED_PIPELINES:
|
||||
supported = ", ".join(sorted(_QIANFAN_SUPPORTED_PIPELINES))
|
||||
print(
|
||||
f"Error: Pipeline {args.pipeline!r} is not supported with qianfan source. "
|
||||
f"Supported pipelines: {supported}. ",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
if not args.qianfan_api_key:
|
||||
print("Error: The Qianfan API key is required.", file=sys.stderr)
|
||||
print(
|
||||
"Please either set `--qianfan_api_key` or set the environment variable "
|
||||
"`PADDLEOCR_MCP_QIANFAN_API_KEY`.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
elif args.ppocr_source == "self_hosted":
|
||||
if not args.self_hosted_base_url:
|
||||
print(
|
||||
"Error: The self-hosted service base URL is required.", file=sys.stderr
|
||||
)
|
||||
print(
|
||||
f"Please set `--self-hosted-base-url` or the environment variable "
|
||||
"`PADDLEOCR_MCP_SELF_HOSTED_BASE_URL`.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def _create_inference_from_args(args: argparse.Namespace):
|
||||
source = args.ppocr_source
|
||||
|
||||
if source == "local":
|
||||
return create_inference(
|
||||
pipeline=args.pipeline,
|
||||
source=source,
|
||||
config=args.pipeline_config,
|
||||
device=args.device,
|
||||
)
|
||||
elif source == "aistudio":
|
||||
return create_inference(
|
||||
pipeline=args.pipeline,
|
||||
source=source,
|
||||
token=args.aistudio_access_token,
|
||||
base_url=args.aistudio_base_url,
|
||||
request_timeout=float(args.timeout),
|
||||
poll_timeout=float(args.timeout * 10),
|
||||
)
|
||||
elif source == "qianfan":
|
||||
return create_inference(
|
||||
pipeline=args.pipeline,
|
||||
source=source,
|
||||
base_url=args.qianfan_base_url,
|
||||
api_key=args.qianfan_api_key,
|
||||
timeout=args.timeout,
|
||||
)
|
||||
elif source == "self_hosted":
|
||||
return create_inference(
|
||||
pipeline=args.pipeline,
|
||||
source=source,
|
||||
base_url=args.self_hosted_base_url,
|
||||
timeout=args.timeout,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unknown source: {source}")
|
||||
|
||||
|
||||
async def async_main() -> None:
|
||||
"""Asynchronous main entry point."""
|
||||
args = _parse_args()
|
||||
|
||||
_validate_args(args)
|
||||
|
||||
try:
|
||||
pipeline_handler = create_pipeline_handler(
|
||||
args.pipeline,
|
||||
args.ppocr_source,
|
||||
pipeline_config=args.pipeline_config,
|
||||
device=args.device,
|
||||
server_url=args.server_url,
|
||||
aistudio_access_token=args.aistudio_access_token,
|
||||
qianfan_api_key=args.qianfan_api_key,
|
||||
timeout=args.timeout,
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"Failed to create the pipeline handler: {e}", file=sys.stderr)
|
||||
if args.verbose:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
sys.exit(1)
|
||||
inference = _create_inference_from_args(args)
|
||||
|
||||
try:
|
||||
await pipeline_handler.start()
|
||||
await inference.start()
|
||||
|
||||
task = create_task(args.pipeline, inference)
|
||||
|
||||
server_name = f"PaddleOCR {args.pipeline} MCP server"
|
||||
mcp = FastMCP(
|
||||
@@ -185,7 +227,7 @@ async def async_main() -> None:
|
||||
mask_error_details=True,
|
||||
)
|
||||
|
||||
pipeline_handler.register_tools(mcp)
|
||||
task.register_tools(mcp)
|
||||
|
||||
log_level = "INFO" if args.verbose else "WARNING"
|
||||
|
||||
@@ -208,10 +250,10 @@ async def async_main() -> None:
|
||||
sys.exit(1)
|
||||
|
||||
finally:
|
||||
await pipeline_handler.stop()
|
||||
await inference.stop()
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
"""Main entry point."""
|
||||
asyncio.run(async_main())
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from .base import Inference
|
||||
from .factory import InferenceFactory, create_inference
|
||||
|
||||
__all__ = [
|
||||
"Inference",
|
||||
"InferenceFactory",
|
||||
"create_inference",
|
||||
]
|
||||
@@ -0,0 +1,85 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import abc
|
||||
from typing import Any, Dict
|
||||
|
||||
from .types import InferenceRequest, InferenceResult
|
||||
|
||||
|
||||
class Inference(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def start(self) -> None:
|
||||
"""Initialize inference resources."""
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def stop(self) -> None:
|
||||
"""Clean up inference resources."""
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
async def predict(
|
||||
self,
|
||||
request: InferenceRequest,
|
||||
) -> InferenceResult:
|
||||
"""Run inference for the given request."""
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_valid_params(self) -> set[str]:
|
||||
"""Get valid runtime parameter names for this inference.
|
||||
|
||||
Returns:
|
||||
Set of valid parameter names.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_default_params(self) -> Dict[str, Any]:
|
||||
"""Get default runtime parameters for this inference.
|
||||
|
||||
Returns:
|
||||
Dictionary of default parameters.
|
||||
"""
|
||||
pass
|
||||
|
||||
def validate_params(self, params: Dict[str, Any]) -> None:
|
||||
"""Validate runtime parameters against allowed set.
|
||||
|
||||
Args:
|
||||
params: Runtime parameters dictionary.
|
||||
|
||||
Raises:
|
||||
ValueError: If any parameter is not in the valid set.
|
||||
"""
|
||||
valid_params = self.get_valid_params()
|
||||
invalid_params = set(params.keys()) - valid_params
|
||||
if invalid_params:
|
||||
raise ValueError(
|
||||
f"Invalid runtime parameters: {invalid_params}. "
|
||||
f"Valid parameters are: {sorted(valid_params)}"
|
||||
)
|
||||
|
||||
def get_final_params(self, runtime_params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Get final parameters with defaults merged.
|
||||
|
||||
Args:
|
||||
runtime_params: User-provided runtime parameters.
|
||||
|
||||
Returns:
|
||||
Dictionary with defaults overridden by user params.
|
||||
"""
|
||||
final_params = self.get_default_params()
|
||||
final_params.update(runtime_params)
|
||||
return final_params
|
||||
@@ -0,0 +1,30 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Inference-related exceptions."""
|
||||
|
||||
|
||||
class InferenceError(RuntimeError):
|
||||
"""Base class for inference errors."""
|
||||
|
||||
|
||||
class AuthenticationError(InferenceError):
|
||||
"""Authentication failed."""
|
||||
|
||||
|
||||
class ResourceUnavailableError(InferenceError):
|
||||
"""Service unavailable."""
|
||||
|
||||
|
||||
class ExecutionTimeoutError(InferenceError):
|
||||
"""Request timeout."""
|
||||
@@ -0,0 +1,108 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from .base import Inference
|
||||
from .ocr.aistudio import OCRAIStudioInference
|
||||
from .ocr.local import OCRLocalInference
|
||||
from .ocr.self_hosted import OCRSelfHostedInference
|
||||
from .paddleocr_vl.aistudio import PaddleOCRVLAIStudioInference
|
||||
from .paddleocr_vl.local import PaddleOCRVLLocalInference
|
||||
from .paddleocr_vl.qianfan import PaddleOCRVLQianfanInference
|
||||
from .paddleocr_vl.self_hosted import PaddleOCRVLSelfHostedInference
|
||||
from .pp_structurev3.aistudio import PPStructureV3AIStudioInference
|
||||
from .pp_structurev3.local import PPStructureV3LocalInference
|
||||
from .pp_structurev3.qianfan import PPStructureV3QianfanInference
|
||||
from .pp_structurev3.self_hosted import PPStructureV3SelfHostedInference
|
||||
|
||||
|
||||
class InferenceFactory:
|
||||
_registry: dict[tuple[str, str], Callable[..., Inference]] = {}
|
||||
|
||||
@classmethod
|
||||
def register(
|
||||
cls,
|
||||
pipeline: str,
|
||||
source: str,
|
||||
factory_fn: Callable[..., Inference],
|
||||
) -> None:
|
||||
cls._registry[(pipeline, source)] = factory_fn
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
cls,
|
||||
pipeline: str,
|
||||
source: str,
|
||||
**kwargs,
|
||||
) -> Inference:
|
||||
key = (pipeline, source)
|
||||
if key not in cls._registry:
|
||||
raise ValueError(
|
||||
f"Unsupported inference combination: {pipeline} + {source}. "
|
||||
f"Supported combinations: {sorted(cls._registry.keys())}"
|
||||
)
|
||||
factory_fn = cls._registry[key]
|
||||
return factory_fn(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def list_supported(cls) -> set[tuple[str, str]]:
|
||||
return set(cls._registry.keys())
|
||||
|
||||
|
||||
InferenceFactory.register("OCR", "local", OCRLocalInference)
|
||||
InferenceFactory.register("OCR", "aistudio", OCRAIStudioInference)
|
||||
InferenceFactory.register("OCR", "self_hosted", OCRSelfHostedInference)
|
||||
|
||||
InferenceFactory.register("PP-StructureV3", "local", PPStructureV3LocalInference)
|
||||
InferenceFactory.register("PP-StructureV3", "aistudio", PPStructureV3AIStudioInference)
|
||||
InferenceFactory.register("PP-StructureV3", "qianfan", PPStructureV3QianfanInference)
|
||||
InferenceFactory.register(
|
||||
"PP-StructureV3", "self_hosted", PPStructureV3SelfHostedInference
|
||||
)
|
||||
|
||||
|
||||
def _create_paddleocr_vl_local(version: str) -> Callable[..., Inference]:
|
||||
def _factory(**kwargs: Any) -> Inference:
|
||||
return PaddleOCRVLLocalInference(**kwargs, version=version)
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
def _create_paddleocr_vl_aistudio(version: str) -> Callable[..., Inference]:
|
||||
def _factory(**kwargs: Any) -> Inference:
|
||||
return PaddleOCRVLAIStudioInference(**kwargs, version=version)
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
for _pipeline, _version in {
|
||||
"PaddleOCR-VL": "v1",
|
||||
"PaddleOCR-VL-1.5": "v1.5",
|
||||
"PaddleOCR-VL-1.6": "v1.6",
|
||||
}.items():
|
||||
InferenceFactory.register(_pipeline, "local", _create_paddleocr_vl_local(_version))
|
||||
InferenceFactory.register(
|
||||
_pipeline, "aistudio", _create_paddleocr_vl_aistudio(_version)
|
||||
)
|
||||
InferenceFactory.register(_pipeline, "self_hosted", PaddleOCRVLSelfHostedInference)
|
||||
|
||||
InferenceFactory.register("PaddleOCR-VL", "qianfan", PaddleOCRVLQianfanInference)
|
||||
|
||||
|
||||
def create_inference(
|
||||
pipeline: str,
|
||||
source: str,
|
||||
**kwargs,
|
||||
) -> Inference:
|
||||
return InferenceFactory.create(pipeline, source, **kwargs)
|
||||
@@ -0,0 +1,128 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from ..shared.paddleocr_api_sdk import (
|
||||
AsyncPaddleOCRClient,
|
||||
APIError,
|
||||
AuthError,
|
||||
JobFailedError,
|
||||
RequestTimeoutError,
|
||||
ResponseFormatError,
|
||||
ResultParseError,
|
||||
ServiceUnavailableError,
|
||||
Model,
|
||||
OCROptions,
|
||||
)
|
||||
|
||||
from ..base import Inference
|
||||
from ..errors import (
|
||||
AuthenticationError,
|
||||
ExecutionTimeoutError,
|
||||
InferenceError,
|
||||
ResourceUnavailableError,
|
||||
)
|
||||
from ..types import InferenceRequest, OCRResult, TextLine
|
||||
from .params import OCR_DEFAULT_PARAMS, OCR_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class OCRAIStudioInference(Inference):
|
||||
def __init__(
|
||||
self,
|
||||
token: str,
|
||||
base_url: Optional[str] = None,
|
||||
request_timeout: float = 300.0,
|
||||
poll_timeout: float = 600.0,
|
||||
):
|
||||
self._token = token
|
||||
self._base_url = base_url
|
||||
self._request_timeout = request_timeout
|
||||
self._poll_timeout = poll_timeout
|
||||
self._client = None
|
||||
|
||||
async def start(self) -> None:
|
||||
try:
|
||||
self._client = AsyncPaddleOCRClient(
|
||||
token=self._token,
|
||||
base_url=self._base_url,
|
||||
request_timeout=self._request_timeout,
|
||||
poll_timeout=self._poll_timeout,
|
||||
)
|
||||
except AuthError as e:
|
||||
raise AuthenticationError(f"Authentication failed: {e}")
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._client:
|
||||
await self._client.close()
|
||||
self._client = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> OCRResult:
|
||||
if not self._client:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
try:
|
||||
input_source = self._resolve_input_source(request.input_data)
|
||||
options = OCROptions(**request.runtime_params, visualize=False)
|
||||
|
||||
result = await self._client.ocr(
|
||||
model=Model.PP_OCRV5, **input_source, options=options
|
||||
)
|
||||
|
||||
return self._parse_result(result)
|
||||
|
||||
except AuthError as e:
|
||||
raise AuthenticationError(f"Authentication failed: {e}")
|
||||
except ServiceUnavailableError as e:
|
||||
raise ResourceUnavailableError(f"Service unavailable: {e}")
|
||||
except (JobFailedError, APIError, ResponseFormatError, ResultParseError) as e:
|
||||
raise InferenceError(f"Execution failed: {e}")
|
||||
except RequestTimeoutError as e:
|
||||
raise ExecutionTimeoutError(f"Request timeout: {e}")
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
return set(OCR_RUNTIME_PARAMS.keys())
|
||||
|
||||
def get_default_params(self) -> dict[str, object]:
|
||||
return OCR_DEFAULT_PARAMS.copy()
|
||||
|
||||
def _resolve_input_source(self, input_data: str) -> dict[str, str]:
|
||||
if input_data.startswith("http://") or input_data.startswith("https://"):
|
||||
return {"file_url": input_data}
|
||||
return {"file_path": input_data}
|
||||
|
||||
def _parse_result(self, result) -> OCRResult:
|
||||
clean_texts, confidences, text_lines = [], [], []
|
||||
|
||||
for page_result in result.pages:
|
||||
pruned = page_result.pruned_result
|
||||
texts = pruned.get("rec_texts", [])
|
||||
scores = pruned.get("rec_scores", [])
|
||||
boxes = pruned.get("rec_boxes", [])
|
||||
|
||||
for i, text in enumerate(texts):
|
||||
if text and text.strip():
|
||||
conf = scores[i] if i < len(scores) else 0
|
||||
clean_texts.append(text.strip())
|
||||
confidences.append(conf)
|
||||
text_lines.append(
|
||||
TextLine(
|
||||
text=text.strip(), confidence=round(conf, 3), bbox=boxes[i]
|
||||
)
|
||||
)
|
||||
|
||||
return OCRResult(
|
||||
text="\n".join(clean_texts),
|
||||
confidence=sum(confidences) / len(confidences) if confidences else 0,
|
||||
text_lines=text_lines,
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import base64
|
||||
import io
|
||||
from typing import Any, Optional
|
||||
|
||||
from paddleocr import PaddleOCR
|
||||
|
||||
from ..base import Inference
|
||||
from ..shared.local_sync_runner import LocalSyncRunner
|
||||
from ..shared.local_input import LocalInputProcessor
|
||||
from ..types import InferenceRequest, OCRResult, TextLine
|
||||
from .params import OCR_DEFAULT_PARAMS, OCR_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class OCRLocalInference(Inference):
|
||||
def __init__(self, config: Optional[str] = None, device: Optional[str] = None):
|
||||
self._config = config
|
||||
self._device = device
|
||||
self._inference: Optional[Any] = None
|
||||
self._wrapper: Optional[LocalSyncRunner] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
try:
|
||||
self._inference = PaddleOCR(
|
||||
paddlex_config=self._config, device=self._device
|
||||
)
|
||||
self._wrapper = LocalSyncRunner(self._inference)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to create PaddleOCR inference: {str(e)}") from e
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._wrapper:
|
||||
await self._wrapper.close()
|
||||
self._wrapper = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> OCRResult:
|
||||
if not self._wrapper:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
processed_input = LocalInputProcessor.process_for_local(request.input_data)
|
||||
|
||||
result = await self._wrapper.call(
|
||||
self._wrapper.inference.predict, processed_input, **request.runtime_params
|
||||
)
|
||||
|
||||
return self._parse_result(result)
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
return set(OCR_RUNTIME_PARAMS.keys())
|
||||
|
||||
def get_default_params(self) -> dict[str, Any]:
|
||||
return OCR_DEFAULT_PARAMS.copy()
|
||||
|
||||
def _parse_result(self, result: Any) -> OCRResult:
|
||||
clean_texts, confidences, text_lines = [], [], []
|
||||
|
||||
for res in result:
|
||||
texts = res["rec_texts"]
|
||||
scores = res["rec_scores"]
|
||||
boxes = res["rec_boxes"]
|
||||
|
||||
for i, text in enumerate(texts):
|
||||
if text and text.strip():
|
||||
conf = scores[i] if i < len(scores) else 0
|
||||
clean_texts.append(text.strip())
|
||||
confidences.append(conf)
|
||||
text_lines.append(
|
||||
TextLine(
|
||||
text=text.strip(),
|
||||
confidence=round(conf, 3),
|
||||
bbox=boxes[i].tolist(),
|
||||
)
|
||||
)
|
||||
|
||||
return OCRResult(
|
||||
text="\n".join(clean_texts),
|
||||
confidence=sum(confidences) / len(confidences) if confidences else 0,
|
||||
text_lines=text_lines,
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
OCR_RUNTIME_PARAMS: dict[str, type] = {
|
||||
"use_doc_orientation_classify": bool,
|
||||
"use_doc_unwarping": bool,
|
||||
"use_textline_orientation": bool,
|
||||
"text_det_limit_side_len": int,
|
||||
"text_det_limit_type": str,
|
||||
"text_det_thresh": float,
|
||||
"text_det_box_thresh": float,
|
||||
"text_det_unclip_ratio": float,
|
||||
"text_rec_score_thresh": float,
|
||||
}
|
||||
|
||||
OCR_DEFAULT_PARAMS: dict[str, Any] = {
|
||||
"use_doc_orientation_classify": False,
|
||||
"use_doc_unwarping": False,
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
from typing_extensions import override
|
||||
|
||||
from ..shared.http_base import HTTPInferenceBase
|
||||
from ..types import InferenceResult
|
||||
from ..shared.http_result_parsers import parse_ocr_result
|
||||
from .params import OCR_DEFAULT_PARAMS, OCR_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class OCRSelfHostedInference(HTTPInferenceBase):
|
||||
def __init__(self, base_url: str, timeout: int = 60):
|
||||
super().__init__(base_url, timeout, api_key=None)
|
||||
|
||||
@override
|
||||
def _get_endpoint(self) -> str:
|
||||
return "ocr"
|
||||
|
||||
@override
|
||||
def _get_params(self) -> tuple[set[str], dict[str, Any]]:
|
||||
return set(OCR_RUNTIME_PARAMS.keys()), OCR_DEFAULT_PARAMS.copy()
|
||||
|
||||
@override
|
||||
def _parse_result(self, response: dict[str, Any]) -> InferenceResult:
|
||||
result_data = response.get("result", response)
|
||||
return parse_ocr_result(result_data)
|
||||
@@ -0,0 +1,115 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from ..shared.paddleocr_api_sdk import (
|
||||
AsyncPaddleOCRClient,
|
||||
APIError,
|
||||
AuthError,
|
||||
JobFailedError,
|
||||
RequestTimeoutError,
|
||||
ResponseFormatError,
|
||||
ResultParseError,
|
||||
ServiceUnavailableError,
|
||||
Model,
|
||||
PaddleOCRVLOptions,
|
||||
)
|
||||
|
||||
from ..base import Inference
|
||||
from ..errors import (
|
||||
AuthenticationError,
|
||||
ExecutionTimeoutError,
|
||||
InferenceError,
|
||||
ResourceUnavailableError,
|
||||
)
|
||||
from ..shared.doc_parsing_result_adapters import parse_aistudio_doc_parsing_result
|
||||
from ..types import DocParsingResult, InferenceRequest
|
||||
from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class PaddleOCRVLAIStudioInference(Inference):
|
||||
_MODEL_MAP = {
|
||||
"v1": Model.PADDLE_OCR_VL,
|
||||
"v1.5": Model.PADDLE_OCR_VL_15,
|
||||
"v1.6": Model.PADDLE_OCR_VL_16,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
token: str,
|
||||
base_url: Optional[str] = None,
|
||||
request_timeout: float = 300.0,
|
||||
poll_timeout: float = 600.0,
|
||||
version: str = "v1",
|
||||
):
|
||||
self._token = token
|
||||
self._base_url = base_url
|
||||
self._request_timeout = request_timeout
|
||||
self._poll_timeout = poll_timeout
|
||||
self._version = version
|
||||
self._client = None
|
||||
|
||||
async def start(self) -> None:
|
||||
try:
|
||||
self._client = AsyncPaddleOCRClient(
|
||||
token=self._token,
|
||||
base_url=self._base_url,
|
||||
request_timeout=self._request_timeout,
|
||||
poll_timeout=self._poll_timeout,
|
||||
)
|
||||
except AuthError as e:
|
||||
raise AuthenticationError(f"Authentication failed: {e}")
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._client:
|
||||
await self._client.close()
|
||||
self._client = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> DocParsingResult:
|
||||
if not self._client:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
try:
|
||||
input_source = self._resolve_input_source(request.input_data)
|
||||
options = PaddleOCRVLOptions(**request.runtime_params)
|
||||
|
||||
model = self._MODEL_MAP[self._version]
|
||||
result = await self._client.parse_document(
|
||||
model=model, **input_source, options=options
|
||||
)
|
||||
|
||||
return self._parse_result(result)
|
||||
|
||||
except AuthError as e:
|
||||
raise AuthenticationError(f"Authentication failed: {e}")
|
||||
except ServiceUnavailableError as e:
|
||||
raise ResourceUnavailableError(f"Service unavailable: {e}")
|
||||
except (JobFailedError, APIError, ResponseFormatError, ResultParseError) as e:
|
||||
raise InferenceError(f"Execution failed: {e}")
|
||||
except RequestTimeoutError as e:
|
||||
raise ExecutionTimeoutError(f"Request timeout: {e}")
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
return set(PADDLEOCR_VL_RUNTIME_PARAMS.keys())
|
||||
|
||||
def get_default_params(self) -> dict[str, object]:
|
||||
return PADDLEOCR_VL_DEFAULT_PARAMS.copy()
|
||||
|
||||
def _resolve_input_source(self, input_data: str) -> dict[str, str]:
|
||||
if input_data.startswith("http://") or input_data.startswith("https://"):
|
||||
return {"file_url": input_data}
|
||||
return {"file_path": input_data}
|
||||
|
||||
def _parse_result(self, result) -> DocParsingResult:
|
||||
return parse_aistudio_doc_parsing_result(result)
|
||||
@@ -0,0 +1,83 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from ..base import Inference
|
||||
from ..shared.doc_parsing_result_adapters import parse_local_doc_parsing_result
|
||||
from ..shared.local_sync_runner import LocalSyncRunner
|
||||
from ..shared.local_input import LocalInputProcessor
|
||||
from ..types import DocParsingResult, InferenceRequest
|
||||
from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
|
||||
|
||||
try:
|
||||
from paddleocr import PaddleOCRVL
|
||||
|
||||
LOCAL_VL_AVAILABLE = True
|
||||
except ImportError:
|
||||
LOCAL_VL_AVAILABLE = False
|
||||
|
||||
|
||||
class PaddleOCRVLLocalInference(Inference):
|
||||
def __init__(
|
||||
self,
|
||||
config: Optional[str] = None,
|
||||
device: Optional[str] = None,
|
||||
version: str = "v1",
|
||||
):
|
||||
self._config = config
|
||||
self._device = device
|
||||
self._version = version
|
||||
self._inference: Optional[Any] = None
|
||||
self._wrapper: Optional[LocalSyncRunner] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
if not LOCAL_VL_AVAILABLE:
|
||||
raise RuntimeError("PaddleOCRVL is not locally available")
|
||||
try:
|
||||
self._inference = PaddleOCRVL(
|
||||
pipeline_version=self._version,
|
||||
paddlex_config=self._config,
|
||||
device=self._device,
|
||||
)
|
||||
self._wrapper = LocalSyncRunner(self._inference)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"Failed to create PaddleOCRVL inference: {str(e)}"
|
||||
) from e
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._wrapper:
|
||||
await self._wrapper.close()
|
||||
self._wrapper = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> DocParsingResult:
|
||||
if not self._wrapper:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
processed_input = LocalInputProcessor.process_for_local(request.input_data)
|
||||
|
||||
result = await self._wrapper.call(
|
||||
self._wrapper.inference.predict, processed_input, **request.runtime_params
|
||||
)
|
||||
|
||||
return self._parse_result(result)
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
return set(PADDLEOCR_VL_RUNTIME_PARAMS.keys())
|
||||
|
||||
def get_default_params(self) -> dict[str, Any]:
|
||||
return PADDLEOCR_VL_DEFAULT_PARAMS.copy()
|
||||
|
||||
def _parse_result(self, result: Any) -> DocParsingResult:
|
||||
return parse_local_doc_parsing_result(result)
|
||||
@@ -0,0 +1,42 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
PADDLEOCR_VL_RUNTIME_PARAMS: dict[str, type] = {
|
||||
"use_doc_orientation_classify": bool,
|
||||
"use_doc_unwarping": bool,
|
||||
"use_layout_detection": bool,
|
||||
"use_chart_recognition": bool,
|
||||
"use_seal_recognition": bool,
|
||||
"layout_threshold": float,
|
||||
"layout_nms": bool,
|
||||
"layout_unclip_ratio": float,
|
||||
"layout_merge_bboxes_mode": int,
|
||||
"layout_shape_mode": str,
|
||||
"prompt_label": str,
|
||||
"repetition_penalty": float,
|
||||
"temperature": float,
|
||||
"top_p": float,
|
||||
"min_pixels": int,
|
||||
"max_pixels": int,
|
||||
"max_new_tokens": int,
|
||||
}
|
||||
|
||||
PADDLEOCR_VL_DEFAULT_PARAMS: dict[str, Any] = {
|
||||
"use_doc_orientation_classify": False,
|
||||
"use_doc_unwarping": False,
|
||||
"use_chart_recognition": True,
|
||||
"use_seal_recognition": True,
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
from typing_extensions import override
|
||||
|
||||
from ..shared.http_base import HTTPInferenceBase
|
||||
from ..types import InferenceResult
|
||||
from ..shared.http_result_parsers import parse_doc_parsing_result
|
||||
from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class PaddleOCRVLQianfanInference(HTTPInferenceBase):
|
||||
def __init__(self, base_url: str, api_key: str, timeout: int = 60):
|
||||
super().__init__(base_url, timeout, api_key)
|
||||
|
||||
@override
|
||||
def _get_endpoint(self) -> str:
|
||||
return "paddleocr"
|
||||
|
||||
@override
|
||||
def _get_params(self) -> tuple[set[str], dict[str, Any]]:
|
||||
return (
|
||||
set(PADDLEOCR_VL_RUNTIME_PARAMS.keys()),
|
||||
PADDLEOCR_VL_DEFAULT_PARAMS.copy(),
|
||||
)
|
||||
|
||||
@override
|
||||
def _parse_result(self, response: dict[str, Any]) -> InferenceResult:
|
||||
result_data = response.get("result", response)
|
||||
return parse_doc_parsing_result(result_data)
|
||||
@@ -0,0 +1,41 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
from typing_extensions import override
|
||||
|
||||
from ..shared.http_base import HTTPInferenceBase
|
||||
from ..types import InferenceResult
|
||||
from ..shared.http_result_parsers import parse_doc_parsing_result
|
||||
from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class PaddleOCRVLSelfHostedInference(HTTPInferenceBase):
|
||||
def __init__(self, base_url: str, timeout: int = 60):
|
||||
super().__init__(base_url, timeout, api_key=None)
|
||||
|
||||
@override
|
||||
def _get_endpoint(self) -> str:
|
||||
return "layout-parsing"
|
||||
|
||||
@override
|
||||
def _get_params(self) -> tuple[set[str], dict[str, Any]]:
|
||||
return (
|
||||
set(PADDLEOCR_VL_RUNTIME_PARAMS.keys()),
|
||||
PADDLEOCR_VL_DEFAULT_PARAMS.copy(),
|
||||
)
|
||||
|
||||
@override
|
||||
def _parse_result(self, response: dict[str, Any]) -> InferenceResult:
|
||||
result_data = response.get("result", response)
|
||||
return parse_doc_parsing_result(result_data)
|
||||
@@ -0,0 +1,106 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from ..shared.paddleocr_api_sdk import (
|
||||
AsyncPaddleOCRClient,
|
||||
APIError,
|
||||
AuthError,
|
||||
JobFailedError,
|
||||
RequestTimeoutError,
|
||||
ResponseFormatError,
|
||||
ResultParseError,
|
||||
ServiceUnavailableError,
|
||||
Model,
|
||||
PPStructureV3Options,
|
||||
)
|
||||
|
||||
from ..base import Inference
|
||||
from ..errors import (
|
||||
AuthenticationError,
|
||||
ExecutionTimeoutError,
|
||||
InferenceError,
|
||||
ResourceUnavailableError,
|
||||
)
|
||||
from ..shared.doc_parsing_result_adapters import parse_aistudio_doc_parsing_result
|
||||
from ..types import DocParsingResult, InferenceRequest
|
||||
from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class PPStructureV3AIStudioInference(Inference):
|
||||
def __init__(
|
||||
self,
|
||||
token: str,
|
||||
base_url: Optional[str] = None,
|
||||
request_timeout: float = 300.0,
|
||||
poll_timeout: float = 600.0,
|
||||
):
|
||||
self._token = token
|
||||
self._base_url = base_url
|
||||
self._request_timeout = request_timeout
|
||||
self._poll_timeout = poll_timeout
|
||||
self._client = None
|
||||
|
||||
async def start(self) -> None:
|
||||
try:
|
||||
self._client = AsyncPaddleOCRClient(
|
||||
token=self._token,
|
||||
base_url=self._base_url,
|
||||
request_timeout=self._request_timeout,
|
||||
poll_timeout=self._poll_timeout,
|
||||
)
|
||||
except AuthError as e:
|
||||
raise AuthenticationError(f"Authentication failed: {e}")
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._client:
|
||||
await self._client.close()
|
||||
self._client = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> DocParsingResult:
|
||||
if not self._client:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
try:
|
||||
input_source = self._resolve_input_source(request.input_data)
|
||||
options = PPStructureV3Options(**request.runtime_params, visualize=False)
|
||||
|
||||
result = await self._client.parse_document(
|
||||
model=Model.PP_STRUCTURE_V3, **input_source, options=options
|
||||
)
|
||||
|
||||
return self._parse_result(result)
|
||||
|
||||
except AuthError as e:
|
||||
raise AuthenticationError(f"Authentication failed: {e}")
|
||||
except ServiceUnavailableError as e:
|
||||
raise ResourceUnavailableError(f"Service unavailable: {e}")
|
||||
except (JobFailedError, APIError, ResponseFormatError, ResultParseError) as e:
|
||||
raise InferenceError(f"Execution failed: {e}")
|
||||
except RequestTimeoutError as e:
|
||||
raise ExecutionTimeoutError(f"Request timeout: {e}")
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
return set(PP_STRUCTUREV3_RUNTIME_PARAMS.keys())
|
||||
|
||||
def get_default_params(self) -> dict[str, object]:
|
||||
return PP_STRUCTUREV3_DEFAULT_PARAMS.copy()
|
||||
|
||||
def _resolve_input_source(self, input_data: str) -> dict[str, str]:
|
||||
if input_data.startswith("http://") or input_data.startswith("https://"):
|
||||
return {"file_url": input_data}
|
||||
return {"file_path": input_data}
|
||||
|
||||
def _parse_result(self, result) -> DocParsingResult:
|
||||
return parse_aistudio_doc_parsing_result(result)
|
||||
@@ -0,0 +1,75 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from ..base import Inference
|
||||
from ..shared.doc_parsing_result_adapters import parse_local_doc_parsing_result
|
||||
from ..shared.local_sync_runner import LocalSyncRunner
|
||||
from ..shared.local_input import LocalInputProcessor
|
||||
from ..types import DocParsingResult, InferenceRequest
|
||||
from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
|
||||
|
||||
try:
|
||||
from paddleocr import PPStructureV3
|
||||
|
||||
LOCAL_PPSTRUCTURE_AVAILABLE = True
|
||||
except ImportError:
|
||||
LOCAL_PPSTRUCTURE_AVAILABLE = False
|
||||
|
||||
|
||||
class PPStructureV3LocalInference(Inference):
|
||||
def __init__(self, config: Optional[str] = None, device: Optional[str] = None):
|
||||
self._config = config
|
||||
self._device = device
|
||||
self._inference: Optional[Any] = None
|
||||
self._wrapper: Optional[LocalSyncRunner] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
if not LOCAL_PPSTRUCTURE_AVAILABLE:
|
||||
raise RuntimeError("PPStructureV3 is not locally available")
|
||||
try:
|
||||
self._inference = PPStructureV3(
|
||||
paddlex_config=self._config, device=self._device
|
||||
)
|
||||
self._wrapper = LocalSyncRunner(self._inference)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"Failed to create PPStructureV3 inference: {str(e)}"
|
||||
) from e
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._wrapper:
|
||||
await self._wrapper.close()
|
||||
self._wrapper = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> DocParsingResult:
|
||||
if not self._wrapper:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
processed_input = LocalInputProcessor.process_for_local(request.input_data)
|
||||
|
||||
result = await self._wrapper.call(
|
||||
self._wrapper.inference.predict, processed_input, **request.runtime_params
|
||||
)
|
||||
|
||||
return self._parse_result(result)
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
return set(PP_STRUCTUREV3_RUNTIME_PARAMS.keys())
|
||||
|
||||
def get_default_params(self) -> dict[str, Any]:
|
||||
return PP_STRUCTUREV3_DEFAULT_PARAMS.copy()
|
||||
|
||||
def _parse_result(self, result: Any) -> DocParsingResult:
|
||||
return parse_local_doc_parsing_result(result)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
PP_STRUCTUREV3_RUNTIME_PARAMS: dict[str, type] = {
|
||||
"use_doc_orientation_classify": bool,
|
||||
"use_doc_unwarping": bool,
|
||||
"use_textline_orientation": bool,
|
||||
"use_seal_recognition": bool,
|
||||
"use_table_recognition": bool,
|
||||
"use_formula_recognition": bool,
|
||||
"use_chart_recognition": bool,
|
||||
"use_region_detection": bool,
|
||||
"layout_threshold": float,
|
||||
"layout_nms": bool,
|
||||
"layout_unclip_ratio": float,
|
||||
"layout_merge_bboxes_mode": int,
|
||||
"text_det_limit_side_len": int,
|
||||
"text_det_limit_type": str,
|
||||
"text_det_thresh": float,
|
||||
"text_det_box_thresh": float,
|
||||
"text_det_unclip_ratio": float,
|
||||
"text_rec_score_thresh": float,
|
||||
"seal_det_limit_side_len": int,
|
||||
"seal_det_limit_type": str,
|
||||
"seal_det_thresh": float,
|
||||
"seal_det_box_thresh": float,
|
||||
"seal_det_unclip_ratio": float,
|
||||
"seal_rec_score_thresh": float,
|
||||
"use_wired_table_cells_trans_to_html": bool,
|
||||
"use_wireless_table_cells_trans_to_html": bool,
|
||||
"use_table_orientation_classify": bool,
|
||||
"use_ocr_results_with_table_cells": bool,
|
||||
"use_e2e_wired_table_rec_model": bool,
|
||||
"use_e2e_wireless_table_rec_model": bool,
|
||||
}
|
||||
|
||||
PP_STRUCTUREV3_DEFAULT_PARAMS: dict[str, Any] = {
|
||||
"use_doc_orientation_classify": False,
|
||||
"use_doc_unwarping": False,
|
||||
"use_chart_recognition": True,
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
from typing_extensions import override
|
||||
|
||||
from ..shared.http_base import HTTPInferenceBase
|
||||
from ..types import InferenceResult
|
||||
from ..shared.http_result_parsers import parse_doc_parsing_result
|
||||
from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class PPStructureV3QianfanInference(HTTPInferenceBase):
|
||||
def __init__(self, base_url: str, api_key: str, timeout: int = 60):
|
||||
super().__init__(base_url, timeout, api_key)
|
||||
|
||||
@override
|
||||
def _get_endpoint(self) -> str:
|
||||
return "paddleocr"
|
||||
|
||||
@override
|
||||
def _get_params(self) -> tuple[set[str], dict[str, Any]]:
|
||||
return (
|
||||
set(PP_STRUCTUREV3_RUNTIME_PARAMS.keys()),
|
||||
PP_STRUCTUREV3_DEFAULT_PARAMS.copy(),
|
||||
)
|
||||
|
||||
@override
|
||||
def _parse_result(self, response: dict[str, Any]) -> InferenceResult:
|
||||
result_data = response.get("result", response)
|
||||
return parse_doc_parsing_result(result_data)
|
||||
@@ -0,0 +1,41 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
from typing_extensions import override
|
||||
|
||||
from ..shared.http_base import HTTPInferenceBase
|
||||
from ..types import InferenceResult
|
||||
from ..shared.http_result_parsers import parse_doc_parsing_result
|
||||
from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
|
||||
|
||||
|
||||
class PPStructureV3SelfHostedInference(HTTPInferenceBase):
|
||||
def __init__(self, base_url: str, timeout: int = 60):
|
||||
super().__init__(base_url, timeout, api_key=None)
|
||||
|
||||
@override
|
||||
def _get_endpoint(self) -> str:
|
||||
return "layout-parsing"
|
||||
|
||||
@override
|
||||
def _get_params(self) -> tuple[set[str], dict[str, Any]]:
|
||||
return (
|
||||
set(PP_STRUCTUREV3_RUNTIME_PARAMS.keys()),
|
||||
PP_STRUCTUREV3_DEFAULT_PARAMS.copy(),
|
||||
)
|
||||
|
||||
@override
|
||||
def _parse_result(self, response: dict[str, Any]) -> InferenceResult:
|
||||
result_data = response.get("result", response)
|
||||
return parse_doc_parsing_result(result_data)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
|
||||
|
||||
class AsyncHTTPClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
timeout: int = 60,
|
||||
headers: Optional[dict[str, str]] = None,
|
||||
):
|
||||
self._base_url = base_url
|
||||
self._timeout = timeout
|
||||
self._headers = headers or {}
|
||||
self._client: Optional[httpx.AsyncClient] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
timeout = httpx.Timeout(connect=30.0, read=self._timeout, write=30.0, pool=30.0)
|
||||
self._client = httpx.AsyncClient(timeout=timeout)
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._client:
|
||||
await self._client.aclose()
|
||||
self._client = None
|
||||
|
||||
async def post(
|
||||
self,
|
||||
endpoint: str,
|
||||
payload: dict[str, Any],
|
||||
headers: Optional[dict[str, str]] = None,
|
||||
) -> dict[str, Any]:
|
||||
if not self._client:
|
||||
raise RuntimeError("HTTP client not started")
|
||||
|
||||
url = f"{self._base_url.rstrip('/')}/{endpoint.lstrip('/')}"
|
||||
merged_headers = {**self._headers, **(headers or {})}
|
||||
|
||||
response = await self._client.post(url, json=payload, headers=merged_headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
@@ -0,0 +1,56 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import base64
|
||||
import io
|
||||
from typing import Any
|
||||
|
||||
from ..types import DocParsingResult
|
||||
|
||||
|
||||
def parse_local_doc_parsing_result(result: Any) -> DocParsingResult:
|
||||
markdown_parts: list[str] = []
|
||||
all_images_mapping: dict[str, str] = {}
|
||||
|
||||
for res in result:
|
||||
markdown = res.markdown
|
||||
markdown_parts.append(markdown["markdown_texts"])
|
||||
processed_images = {}
|
||||
for img_key, img_data in markdown["markdown_images"].items():
|
||||
with io.BytesIO() as buffer:
|
||||
img_data.save(buffer, format="JPEG")
|
||||
processed_images[img_key] = base64.b64encode(buffer.getvalue()).decode(
|
||||
"ascii"
|
||||
)
|
||||
all_images_mapping.update(processed_images)
|
||||
|
||||
return DocParsingResult(
|
||||
markdown="\n".join(markdown_parts),
|
||||
pages=len(result),
|
||||
images_mapping=all_images_mapping,
|
||||
)
|
||||
|
||||
|
||||
def parse_aistudio_doc_parsing_result(result: Any) -> DocParsingResult:
|
||||
markdown_parts: list[str] = []
|
||||
all_images_mapping: dict[str, str] = {}
|
||||
|
||||
for page in result.pages:
|
||||
markdown_parts.append(page.markdown_text)
|
||||
all_images_mapping.update(page.markdown_images)
|
||||
|
||||
return DocParsingResult(
|
||||
markdown="\n".join(markdown_parts),
|
||||
pages=len(result.pages),
|
||||
images_mapping=all_images_mapping,
|
||||
)
|
||||
@@ -0,0 +1,107 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import base64
|
||||
from abc import abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from ..base import Inference
|
||||
from ..errors import InferenceError
|
||||
from ..types import InferenceRequest, InferenceResult
|
||||
from .async_http_client import AsyncHTTPClient
|
||||
from .param_mapping import convert_params_to_camel
|
||||
|
||||
|
||||
class HTTPInferenceBase(Inference):
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
timeout: int = 60,
|
||||
api_key: Optional[str] = None,
|
||||
):
|
||||
self._base_url = base_url
|
||||
self._timeout = timeout
|
||||
self._api_key = api_key
|
||||
self._client: Optional[AsyncHTTPClient] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
headers = {}
|
||||
if self._api_key:
|
||||
headers["Authorization"] = f"Bearer {self._api_key}"
|
||||
self._client = AsyncHTTPClient(self._base_url, self._timeout, headers)
|
||||
await self._client.start()
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._client:
|
||||
await self._client.stop()
|
||||
self._client = None
|
||||
|
||||
async def predict(self, request: InferenceRequest) -> InferenceResult:
|
||||
if not self._client:
|
||||
raise RuntimeError("Inference not started")
|
||||
|
||||
payload = self._prepare_payload(
|
||||
request.input_data,
|
||||
request.file_type,
|
||||
**request.runtime_params,
|
||||
)
|
||||
|
||||
try:
|
||||
response = await self._client.post(self._get_endpoint(), payload)
|
||||
return self._parse_result(response)
|
||||
except Exception as e:
|
||||
raise InferenceError(f"HTTP request failed: {e}") from e
|
||||
|
||||
def _encode_file_field(self, input_data: str) -> str:
|
||||
"""Encode local paths to Base64; pass through URLs and raw payloads."""
|
||||
if input_data.startswith("http://") or input_data.startswith("https://"):
|
||||
return input_data
|
||||
from .local_input import LocalInputProcessor
|
||||
|
||||
if LocalInputProcessor.is_file_path(input_data):
|
||||
path = Path(input_data).expanduser()
|
||||
return base64.b64encode(path.read_bytes()).decode("ascii")
|
||||
return input_data
|
||||
|
||||
def _prepare_payload(
|
||||
self, input_data: str, file_type: Optional[str], **params
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {"file": self._encode_file_field(input_data)}
|
||||
if file_type == "image":
|
||||
payload["fileType"] = 1
|
||||
elif file_type == "pdf":
|
||||
payload["fileType"] = 0
|
||||
|
||||
payload.update(convert_params_to_camel({**params, "visualize": False}))
|
||||
return payload
|
||||
|
||||
@abstractmethod
|
||||
def _get_endpoint(self) -> str:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def _get_params(self) -> tuple[set[str], dict[str, Any]]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def _parse_result(self, response: dict[str, Any]) -> InferenceResult:
|
||||
pass
|
||||
|
||||
def get_valid_params(self) -> set[str]:
|
||||
valid_params, _ = self._get_params()
|
||||
return valid_params
|
||||
|
||||
def get_default_params(self) -> dict[str, Any]:
|
||||
_, defaults = self._get_params()
|
||||
return defaults
|
||||
@@ -0,0 +1,65 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
from ..types import DocParsingResult, OCRResult, TextLine
|
||||
|
||||
|
||||
def parse_ocr_result(result_data: dict[str, Any]) -> OCRResult:
|
||||
"""Parse OCR response payload."""
|
||||
ocr_results = result_data.get("ocrResults", [])
|
||||
all_texts, all_confidences, text_lines = [], [], []
|
||||
|
||||
for ocr_result in ocr_results:
|
||||
pruned = ocr_result["prunedResult"]
|
||||
texts = pruned["rec_texts"]
|
||||
scores = pruned["rec_scores"]
|
||||
boxes = pruned["rec_boxes"]
|
||||
|
||||
for i, text in enumerate(texts):
|
||||
if text and text.strip():
|
||||
conf = scores[i] if i < len(scores) else 0
|
||||
all_texts.append(text.strip())
|
||||
all_confidences.append(conf)
|
||||
text_lines.append(
|
||||
TextLine(
|
||||
text=text.strip(), confidence=round(conf, 3), bbox=boxes[i]
|
||||
)
|
||||
)
|
||||
|
||||
return OCRResult(
|
||||
text="\n".join(all_texts),
|
||||
confidence=(
|
||||
sum(all_confidences) / len(all_confidences) if all_confidences else 0
|
||||
),
|
||||
text_lines=text_lines,
|
||||
)
|
||||
|
||||
|
||||
def parse_doc_parsing_result(result_data: dict[str, Any]) -> DocParsingResult:
|
||||
"""Parse document parsing response payload."""
|
||||
doc_parsing_results = result_data.get("layoutParsingResults", [])
|
||||
markdown_parts = []
|
||||
all_images_mapping = {}
|
||||
|
||||
for res in doc_parsing_results:
|
||||
markdown_parts.append(res["markdown"]["text"])
|
||||
images = res["markdown"]["images"]
|
||||
all_images_mapping.update(images)
|
||||
|
||||
return DocParsingResult(
|
||||
markdown="\n".join(markdown_parts),
|
||||
pages=len(doc_parsing_results),
|
||||
images_mapping=all_images_mapping,
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import base64
|
||||
import io
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, Union
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
class LocalInputProcessor:
|
||||
@staticmethod
|
||||
def is_file_path(value: str) -> bool:
|
||||
return Path(value).expanduser().exists()
|
||||
|
||||
@staticmethod
|
||||
def is_url(value: str) -> bool:
|
||||
if not (value.startswith("http://") or value.startswith("https://")):
|
||||
return False
|
||||
|
||||
result = urlparse(value)
|
||||
return all([result.scheme, result.netloc]) and result.scheme in (
|
||||
"http",
|
||||
"https",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def is_base64(value: str) -> bool:
|
||||
if value.startswith("data:"):
|
||||
return "," in value and LocalInputProcessor.is_base64(
|
||||
value.split(",", 1)[1]
|
||||
)
|
||||
|
||||
pattern = r"^[A-Za-z0-9+/]+={0,2}$"
|
||||
return bool(re.fullmatch(pattern, value))
|
||||
|
||||
@staticmethod
|
||||
def infer_file_type_from_bytes(data: bytes) -> Optional[str]:
|
||||
import puremagic
|
||||
|
||||
mime = puremagic.from_string(data, mime=True)
|
||||
if mime.startswith("image/"):
|
||||
return "image"
|
||||
if mime == "application/pdf":
|
||||
return "pdf"
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def process_for_local(cls, input_data: str) -> Union[str, Any]:
|
||||
if cls.is_url(input_data) or cls.is_file_path(input_data):
|
||||
return input_data
|
||||
|
||||
if cls.is_base64(input_data):
|
||||
import numpy as np
|
||||
from PIL import Image as PILImage
|
||||
|
||||
base64_data = (
|
||||
input_data.split(",", 1)[1]
|
||||
if input_data.startswith("data:")
|
||||
else input_data
|
||||
)
|
||||
try:
|
||||
image_bytes = base64.b64decode(base64_data)
|
||||
file_type = cls.infer_file_type_from_bytes(image_bytes)
|
||||
if file_type != "image":
|
||||
raise ValueError("Currently, only images can be passed via Base64.")
|
||||
image_pil = PILImage.open(io.BytesIO(image_bytes))
|
||||
image_arr = np.array(image_pil.convert("RGB"))
|
||||
return np.ascontiguousarray(image_arr[..., ::-1])
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to decode Base64 image: {str(e)}") from e
|
||||
|
||||
raise ValueError("Invalid input data format")
|
||||
@@ -0,0 +1,58 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import asyncio
|
||||
from queue import Queue
|
||||
from threading import Thread
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
class LocalSyncRunner:
|
||||
def __init__(self, inference: Any) -> None:
|
||||
self._inference = inference
|
||||
self._queue: Queue = Queue()
|
||||
self._closed = False
|
||||
self._loop = asyncio.get_running_loop()
|
||||
self._thread = Thread(target=self._worker)
|
||||
self._thread.start()
|
||||
|
||||
@property
|
||||
def inference(self) -> Any:
|
||||
return self._inference
|
||||
|
||||
async def call(self, func: Callable, *args: Any, **kwargs: Any) -> Any:
|
||||
if self._closed:
|
||||
raise RuntimeError("Local sync runner has already been closed")
|
||||
fut = self._loop.create_future()
|
||||
self._queue.put((func, args, kwargs, fut))
|
||||
return await fut
|
||||
|
||||
async def close(self) -> None:
|
||||
if not self._closed:
|
||||
self._queue.put(None)
|
||||
await self._loop.run_in_executor(None, self._thread.join)
|
||||
self._closed = True
|
||||
|
||||
def _worker(self) -> None:
|
||||
while not self._closed:
|
||||
item = self._queue.get()
|
||||
if item is None:
|
||||
break
|
||||
func, args, kwargs, fut = item
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
self._loop.call_soon_threadsafe(fut.set_result, result)
|
||||
except Exception as e:
|
||||
self._loop.call_soon_threadsafe(fut.set_exception, e)
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
@@ -0,0 +1,181 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import importlib
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable, TypeAlias
|
||||
|
||||
|
||||
SDKObject: TypeAlias = Any
|
||||
SDKException: TypeAlias = type[BaseException]
|
||||
ImportModule: TypeAlias = Callable[[str], ModuleType]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PaddleOCRAPISDK:
|
||||
AsyncPaddleOCRClient: SDKObject
|
||||
Model: SDKObject
|
||||
OCROptions: SDKObject
|
||||
PPStructureV3Options: SDKObject
|
||||
PaddleOCRVLOptions: SDKObject
|
||||
APIError: SDKException
|
||||
AuthError: SDKException
|
||||
JobFailedError: SDKException
|
||||
RequestTimeoutError: SDKException
|
||||
ResponseFormatError: SDKException
|
||||
ResultParseError: SDKException
|
||||
ServiceUnavailableError: SDKException
|
||||
|
||||
|
||||
_NAMES = (
|
||||
"AsyncPaddleOCRClient",
|
||||
"Model",
|
||||
"OCROptions",
|
||||
"PPStructureV3Options",
|
||||
"PaddleOCRVLOptions",
|
||||
"APIError",
|
||||
"AuthError",
|
||||
"JobFailedError",
|
||||
"RequestTimeoutError",
|
||||
"ResponseFormatError",
|
||||
"ResultParseError",
|
||||
"ServiceUnavailableError",
|
||||
)
|
||||
|
||||
|
||||
def _sdk_object(module: ModuleType, name: str) -> SDKObject:
|
||||
return getattr(module, name)
|
||||
|
||||
|
||||
def _sdk_exception(module: ModuleType, name: str) -> SDKException:
|
||||
value = getattr(module, name)
|
||||
if not isinstance(value, type) or not issubclass(value, BaseException):
|
||||
raise TypeError(f"{module.__name__}.{name} must be an exception class")
|
||||
return value
|
||||
|
||||
|
||||
def _build_sdk_from_top_level(paddleocr: ModuleType) -> PaddleOCRAPISDK:
|
||||
missing = [name for name in _NAMES if not hasattr(paddleocr, name)]
|
||||
if missing:
|
||||
raise AttributeError(f"paddleocr is missing API SDK exports: {missing}")
|
||||
return PaddleOCRAPISDK(
|
||||
AsyncPaddleOCRClient=_sdk_object(paddleocr, "AsyncPaddleOCRClient"),
|
||||
Model=_sdk_object(paddleocr, "Model"),
|
||||
OCROptions=_sdk_object(paddleocr, "OCROptions"),
|
||||
PPStructureV3Options=_sdk_object(paddleocr, "PPStructureV3Options"),
|
||||
PaddleOCRVLOptions=_sdk_object(paddleocr, "PaddleOCRVLOptions"),
|
||||
APIError=_sdk_exception(paddleocr, "APIError"),
|
||||
AuthError=_sdk_exception(paddleocr, "AuthError"),
|
||||
JobFailedError=_sdk_exception(paddleocr, "JobFailedError"),
|
||||
RequestTimeoutError=_sdk_exception(paddleocr, "RequestTimeoutError"),
|
||||
ResponseFormatError=_sdk_exception(paddleocr, "ResponseFormatError"),
|
||||
ResultParseError=_sdk_exception(paddleocr, "ResultParseError"),
|
||||
ServiceUnavailableError=_sdk_exception(paddleocr, "ServiceUnavailableError"),
|
||||
)
|
||||
|
||||
|
||||
def _build_sdk_from_private_modules(import_module: ImportModule) -> PaddleOCRAPISDK:
|
||||
async_client = import_module("paddleocr._api_client.async_client")
|
||||
models = import_module("paddleocr._api_client.models")
|
||||
errors = import_module("paddleocr._api_client.errors")
|
||||
return PaddleOCRAPISDK(
|
||||
AsyncPaddleOCRClient=_sdk_object(async_client, "AsyncPaddleOCRClient"),
|
||||
Model=_sdk_object(models, "Model"),
|
||||
OCROptions=_sdk_object(models, "OCROptions"),
|
||||
PPStructureV3Options=_sdk_object(models, "PPStructureV3Options"),
|
||||
PaddleOCRVLOptions=_sdk_object(models, "PaddleOCRVLOptions"),
|
||||
APIError=_sdk_exception(errors, "APIError"),
|
||||
AuthError=_sdk_exception(errors, "AuthError"),
|
||||
JobFailedError=_sdk_exception(errors, "JobFailedError"),
|
||||
RequestTimeoutError=_sdk_exception(errors, "RequestTimeoutError"),
|
||||
ResponseFormatError=_sdk_exception(errors, "ResponseFormatError"),
|
||||
ResultParseError=_sdk_exception(errors, "ResultParseError"),
|
||||
ServiceUnavailableError=_sdk_exception(errors, "ServiceUnavailableError"),
|
||||
)
|
||||
|
||||
|
||||
def _find_paddleocr_package_dir() -> Path:
|
||||
spec = importlib.machinery.PathFinder.find_spec("paddleocr")
|
||||
if spec is None or spec.submodule_search_locations is None:
|
||||
raise ImportError("Cannot find paddleocr package")
|
||||
return Path(next(iter(spec.submodule_search_locations)))
|
||||
|
||||
|
||||
def _register_api_client_package_from_files() -> None:
|
||||
package_dir = _find_paddleocr_package_dir()
|
||||
api_client_dir = package_dir / "_api_client"
|
||||
init_file = api_client_dir / "__init__.py"
|
||||
if not init_file.exists():
|
||||
raise ImportError(f"Cannot find PaddleOCR API client at {init_file}")
|
||||
|
||||
if "paddleocr" not in sys.modules:
|
||||
parent = ModuleType("paddleocr")
|
||||
parent.__path__ = [str(package_dir)] # type: ignore[attr-defined]
|
||||
parent.__package__ = "paddleocr"
|
||||
parent.__spec__ = importlib.machinery.ModuleSpec(
|
||||
"paddleocr", loader=None, is_package=True
|
||||
)
|
||||
sys.modules["paddleocr"] = parent
|
||||
|
||||
if "paddleocr._api_client" in sys.modules:
|
||||
return
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"paddleocr._api_client",
|
||||
init_file,
|
||||
submodule_search_locations=[str(api_client_dir)],
|
||||
)
|
||||
if spec is None or spec.loader is None:
|
||||
raise ImportError(f"Cannot load PaddleOCR API client from {init_file}")
|
||||
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules["paddleocr._api_client"] = module
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
def _build_sdk_from_private_module_files() -> PaddleOCRAPISDK:
|
||||
_register_api_client_package_from_files()
|
||||
return _build_sdk_from_private_modules(importlib.import_module)
|
||||
|
||||
|
||||
def load_paddleocr_api_sdk(
|
||||
import_module: ImportModule = importlib.import_module,
|
||||
) -> PaddleOCRAPISDK:
|
||||
try:
|
||||
return _build_sdk_from_top_level(import_module("paddleocr"))
|
||||
except (AttributeError, ImportError):
|
||||
try:
|
||||
return _build_sdk_from_private_modules(import_module)
|
||||
except ImportError:
|
||||
return _build_sdk_from_private_module_files()
|
||||
|
||||
|
||||
_SDK = load_paddleocr_api_sdk()
|
||||
|
||||
AsyncPaddleOCRClient = _SDK.AsyncPaddleOCRClient
|
||||
Model = _SDK.Model
|
||||
OCROptions = _SDK.OCROptions
|
||||
PPStructureV3Options = _SDK.PPStructureV3Options
|
||||
PaddleOCRVLOptions = _SDK.PaddleOCRVLOptions
|
||||
APIError = _SDK.APIError
|
||||
AuthError = _SDK.AuthError
|
||||
JobFailedError = _SDK.JobFailedError
|
||||
RequestTimeoutError = _SDK.RequestTimeoutError
|
||||
ResponseFormatError = _SDK.ResponseFormatError
|
||||
ResultParseError = _SDK.ResultParseError
|
||||
ServiceUnavailableError = _SDK.ServiceUnavailableError
|
||||
@@ -0,0 +1,23 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def snake_to_camel(name: str) -> str:
|
||||
components = name.split("_")
|
||||
return components[0] + "".join(component.title() for component in components[1:])
|
||||
|
||||
|
||||
def convert_params_to_camel(params: dict[str, Any]) -> dict[str, Any]:
|
||||
return {snake_to_camel(key): value for key, value in params.items()}
|
||||
@@ -0,0 +1,60 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Mapping, Optional, Union
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InferenceRequest:
|
||||
"""Inference request payload."""
|
||||
|
||||
input_data: str
|
||||
file_type: Optional[str] = None
|
||||
runtime_params: Mapping[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TextLine:
|
||||
"""A single text line with its bounding box and confidence."""
|
||||
|
||||
text: str
|
||||
confidence: float
|
||||
bbox: Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OCRResult:
|
||||
"""OCR result."""
|
||||
|
||||
text: str
|
||||
confidence: float
|
||||
text_lines: list[TextLine]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DocParsingResult:
|
||||
"""Document parsing result."""
|
||||
|
||||
markdown: str
|
||||
pages: int
|
||||
images_mapping: dict[str, str]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
InferenceResult = Union[OCRResult, DocParsingResult]
|
||||
@@ -1,963 +0,0 @@
|
||||
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# TODO:
|
||||
# 1. Reuse `httpx` client.
|
||||
# 2. Use `contextvars` to manage MCP context objects.
|
||||
# 3. Implement structured logging, log stack traces, and log operation timing.
|
||||
# 4. Report progress for long-running operations.
|
||||
|
||||
import abc
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from pathlib import PurePath
|
||||
from queue import Queue
|
||||
from threading import Thread
|
||||
from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
import numpy as np
|
||||
import puremagic
|
||||
from fastmcp import Context, FastMCP
|
||||
from mcp.types import ImageContent, TextContent
|
||||
from PIL import Image as PILImage
|
||||
from typing_extensions import Literal, Self, assert_never
|
||||
|
||||
try:
|
||||
from paddleocr import PaddleOCR, PaddleOCRVL, PPStructureV3
|
||||
|
||||
LOCAL_OCR_AVAILABLE = True
|
||||
except ImportError:
|
||||
LOCAL_OCR_AVAILABLE = False
|
||||
|
||||
|
||||
OutputMode = Literal["simple", "detailed"]
|
||||
|
||||
|
||||
def _is_file_path(s: str) -> bool:
|
||||
try:
|
||||
PurePath(s)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_base64(s: str) -> bool:
|
||||
pattern = r"^[A-Za-z0-9+/]+={0,2}$"
|
||||
return bool(re.fullmatch(pattern, s))
|
||||
|
||||
|
||||
def _is_url(s: str) -> bool:
|
||||
if not (s.startswith("http://") or s.startswith("https://")):
|
||||
return False
|
||||
result = urlparse(s)
|
||||
return all([result.scheme, result.netloc]) and result.scheme in ("http", "https")
|
||||
|
||||
|
||||
def _infer_file_type_from_bytes(data: bytes) -> Optional[str]:
|
||||
mime = puremagic.from_string(data, mime=True)
|
||||
if mime.startswith("image/"):
|
||||
return "image"
|
||||
elif mime == "application/pdf":
|
||||
return "pdf"
|
||||
return None
|
||||
|
||||
|
||||
def get_str_with_max_len(obj: object, max_len: int) -> str:
|
||||
s = str(obj)
|
||||
if len(s) > max_len:
|
||||
return s[:max_len] + "..."
|
||||
else:
|
||||
return s
|
||||
|
||||
|
||||
class _EngineWrapper:
|
||||
def __init__(self, engine: Any) -> None:
|
||||
self._engine = engine
|
||||
self._queue: Queue = Queue()
|
||||
self._closed = False
|
||||
self._loop = asyncio.get_running_loop()
|
||||
self._thread = Thread(target=self._worker, daemon=False)
|
||||
self._thread.start()
|
||||
|
||||
@property
|
||||
def engine(self) -> Any:
|
||||
return self._engine
|
||||
|
||||
async def call(self, func: Callable, *args: Any, **kwargs: Any) -> Any:
|
||||
if self._closed:
|
||||
raise RuntimeError("Engine wrapper has already been closed")
|
||||
fut = self._loop.create_future()
|
||||
self._queue.put((func, args, kwargs, fut))
|
||||
return await fut
|
||||
|
||||
async def close(self) -> None:
|
||||
if not self._closed:
|
||||
self._queue.put(None)
|
||||
await self._loop.run_in_executor(None, self._thread.join)
|
||||
self._closed = True
|
||||
|
||||
def _worker(self) -> None:
|
||||
while not self._closed:
|
||||
item = self._queue.get()
|
||||
if item is None:
|
||||
break
|
||||
func, args, kwargs, fut = item
|
||||
try:
|
||||
result = func(*args, **kwargs)
|
||||
self._loop.call_soon_threadsafe(fut.set_result, result)
|
||||
except Exception as e:
|
||||
self._loop.call_soon_threadsafe(fut.set_exception, e)
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
|
||||
class PipelineHandler(abc.ABC):
|
||||
"""Abstract base class for pipeline handlers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pipeline: str,
|
||||
ppocr_source: str,
|
||||
pipeline_config: Optional[str],
|
||||
device: Optional[str],
|
||||
server_url: Optional[str],
|
||||
aistudio_access_token: Optional[str],
|
||||
qianfan_api_key: Optional[str],
|
||||
timeout: Optional[int],
|
||||
) -> None:
|
||||
"""Initialize the pipeline handler.
|
||||
|
||||
Args:
|
||||
pipeline: Pipeline name.
|
||||
ppocr_source: Source of PaddleOCR functionality.
|
||||
pipeline_config: Path to pipeline configuration.
|
||||
device: Device to run inference on.
|
||||
server_url: Base URL for service mode.
|
||||
aistudio_access_token: AI Studio access token.
|
||||
qianfan_api_key: Qianfan API key.
|
||||
timeout: Read timeout in seconds for HTTP requests.
|
||||
"""
|
||||
self._pipeline = pipeline
|
||||
if ppocr_source == "local":
|
||||
self._mode = "local"
|
||||
elif ppocr_source in ("aistudio", "qianfan", "self_hosted"):
|
||||
self._mode = "service"
|
||||
else:
|
||||
raise ValueError(f"Unknown PaddleOCR source {repr(ppocr_source)}")
|
||||
self._ppocr_source = ppocr_source
|
||||
self._pipeline_config = pipeline_config
|
||||
self._device = device
|
||||
self._server_url = server_url
|
||||
self._aistudio_access_token = aistudio_access_token
|
||||
self._qianfan_api_key = qianfan_api_key
|
||||
self._timeout = timeout or 60
|
||||
|
||||
if self._mode == "local":
|
||||
if not LOCAL_OCR_AVAILABLE:
|
||||
raise RuntimeError("PaddleOCR is not locally available")
|
||||
try:
|
||||
self._engine = self._create_local_engine()
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"Failed to create PaddleOCR engine: {str(e)}"
|
||||
) from e
|
||||
|
||||
self._status: Literal["initialized", "started", "stopped"] = "initialized"
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._status == "initialized":
|
||||
if self._mode == "local":
|
||||
self._engine_wrapper = _EngineWrapper(self._engine)
|
||||
self._status = "started"
|
||||
elif self._status == "started":
|
||||
pass
|
||||
elif self._status == "stopped":
|
||||
raise RuntimeError("Pipeline handler has already been stopped")
|
||||
else:
|
||||
assert_never(self._status)
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._status == "initialized":
|
||||
raise RuntimeError("Pipeline handler has not been started")
|
||||
elif self._status == "started":
|
||||
if self._mode == "local":
|
||||
await self._engine_wrapper.close()
|
||||
self._status = "stopped"
|
||||
elif self._status == "stopped":
|
||||
pass
|
||||
else:
|
||||
assert_never(self._status)
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
await self.start()
|
||||
return self
|
||||
|
||||
async def __aexit__(
|
||||
self,
|
||||
exc_type: Any,
|
||||
exc_val: Any,
|
||||
exc_tb: Any,
|
||||
) -> None:
|
||||
await self.stop()
|
||||
|
||||
@abc.abstractmethod
|
||||
def register_tools(self, mcp: FastMCP) -> None:
|
||||
"""Register tools with the MCP server.
|
||||
|
||||
Args:
|
||||
mcp: The `FastMCP` instance.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
def _create_local_engine(self) -> Any:
|
||||
"""Create the local OCR engine.
|
||||
|
||||
Returns:
|
||||
The OCR engine instance.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
def _get_service_endpoint(self) -> str:
|
||||
"""Get the service endpoint.
|
||||
|
||||
Returns:
|
||||
Service endpoint path.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
def _transform_local_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Transform keyword arguments for local execution.
|
||||
|
||||
Args:
|
||||
kwargs: Keyword arguments.
|
||||
|
||||
Returns:
|
||||
Transformed keyword arguments.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
def _transform_service_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Transform keyword arguments for service execution.
|
||||
|
||||
Args:
|
||||
kwargs: Keyword arguments.
|
||||
|
||||
Returns:
|
||||
Transformed keyword arguments.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _parse_local_result(
|
||||
self, local_result: Dict, ctx: Context
|
||||
) -> Dict[str, Any]:
|
||||
"""Parse raw result from local engine into a unified format.
|
||||
|
||||
Args:
|
||||
local_result: Raw result from local engine.
|
||||
ctx: MCP context.
|
||||
|
||||
Returns:
|
||||
Parsed result in unified format.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _parse_service_result(
|
||||
self, service_result: Dict[str, Any], ctx: Context
|
||||
) -> Dict[str, Any]:
|
||||
"""Parse raw result from the service into a unified format.
|
||||
|
||||
Args:
|
||||
service_result: Raw result from the service.
|
||||
ctx: MCP context.
|
||||
|
||||
Returns:
|
||||
Parsed result in unified format.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _log_completion_stats(self, result: Dict[str, Any], ctx: Context) -> None:
|
||||
"""Log statistics after processing completion.
|
||||
|
||||
Args:
|
||||
result: Processing result.
|
||||
ctx: MCP context.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _format_output(
|
||||
self,
|
||||
result: Dict[str, Any],
|
||||
detailed: bool,
|
||||
ctx: Context,
|
||||
**kwargs: Any,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
"""Format output into simple or detailed format.
|
||||
|
||||
Args:
|
||||
result: Processing result.
|
||||
detailed: Whether to use detailed format.
|
||||
ctx: MCP context.
|
||||
**kwargs: Additional arguments.
|
||||
|
||||
Returns:
|
||||
Formatted output in requested format.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def _predict_with_local_engine(
|
||||
self, processed_input: Union[str, np.ndarray], ctx: Context, **kwargs: Any
|
||||
) -> Dict:
|
||||
if not hasattr(self, "_engine_wrapper"):
|
||||
raise RuntimeError("Engine wrapper has not been initialized")
|
||||
return await self._engine_wrapper.call(
|
||||
self._engine_wrapper.engine.predict, processed_input, **kwargs
|
||||
)
|
||||
|
||||
|
||||
class SimpleInferencePipelineHandler(PipelineHandler):
|
||||
"""Base class for simple inference pipeline handlers."""
|
||||
|
||||
async def process(
|
||||
self,
|
||||
input_data: str,
|
||||
output_mode: OutputMode,
|
||||
ctx: Context,
|
||||
file_type: Optional[str] = None,
|
||||
infer_kwargs: Optional[Dict[str, Any]] = None,
|
||||
format_kwargs: Optional[Dict[str, Any]] = None,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
"""Process input data through the pipeline.
|
||||
|
||||
Args:
|
||||
input_data: Input data (file path, URL, or Base64).
|
||||
output_mode: Output mode ("simple" or "detailed").
|
||||
ctx: MCP context.
|
||||
file_type: File type for URLs ("image", "pdf", or None for auto-detection).
|
||||
infer_kwargs: Additional arguments for performing pipeline inference.
|
||||
format_kwargs: Additional arguments for formatting the output.
|
||||
|
||||
Returns:
|
||||
Processed result in the requested output format.
|
||||
"""
|
||||
infer_kwargs = infer_kwargs or {}
|
||||
format_kwargs = format_kwargs or {}
|
||||
try:
|
||||
await ctx.info(
|
||||
f"Starting {self._pipeline} processing (source: {self._ppocr_source})"
|
||||
)
|
||||
|
||||
if self._mode == "local":
|
||||
processed_input = self._process_input_for_local(input_data, file_type)
|
||||
infer_kwargs = self._transform_local_kwargs(infer_kwargs)
|
||||
raw_result = await self._predict_with_local_engine(
|
||||
processed_input, ctx, **infer_kwargs
|
||||
)
|
||||
result = await self._parse_local_result(raw_result, ctx)
|
||||
else:
|
||||
processed_input, inferred_file_type = self._process_input_for_service(
|
||||
input_data, file_type
|
||||
)
|
||||
infer_kwargs = self._transform_service_kwargs(infer_kwargs)
|
||||
raw_result = await self._call_service(
|
||||
processed_input, inferred_file_type, ctx, **infer_kwargs
|
||||
)
|
||||
result = await self._parse_service_result(raw_result, ctx)
|
||||
|
||||
await self._log_completion_stats(result, ctx)
|
||||
return await self._format_output(
|
||||
result, output_mode == "detailed", ctx, **format_kwargs
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
await ctx.error(f"{self._pipeline} processing failed: {str(e)}")
|
||||
self._handle_error(e, output_mode)
|
||||
|
||||
def _process_input_for_local(
|
||||
self, input_data: str, file_type: Optional[str]
|
||||
) -> Union[str, np.ndarray]:
|
||||
# TODO: Use `file_type` to handle more cases.
|
||||
if _is_base64(input_data):
|
||||
if input_data.startswith("data:"):
|
||||
base64_data = input_data.split(",", 1)[1]
|
||||
else:
|
||||
base64_data = input_data
|
||||
try:
|
||||
image_bytes = base64.b64decode(base64_data)
|
||||
file_type = _infer_file_type_from_bytes(image_bytes)
|
||||
if file_type != "image":
|
||||
raise ValueError("Currently, only images can be passed via Base64.")
|
||||
image_pil = PILImage.open(io.BytesIO(image_bytes))
|
||||
image_arr = np.array(image_pil.convert("RGB"))
|
||||
return np.ascontiguousarray(image_arr[..., ::-1])
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to decode Base64 image: {str(e)}") from e
|
||||
elif _is_file_path(input_data) or _is_url(input_data):
|
||||
return input_data
|
||||
else:
|
||||
raise ValueError("Invalid input data format")
|
||||
|
||||
def _process_input_for_service(
|
||||
self, input_data: str, file_type: Optional[str]
|
||||
) -> tuple[str, Optional[str]]:
|
||||
if _is_url(input_data):
|
||||
norm_ft = None
|
||||
if isinstance(file_type, str):
|
||||
if file_type.lower() in ("None", "none", "null", "unknown", ""):
|
||||
norm_ft = None
|
||||
else:
|
||||
norm_ft = file_type.lower()
|
||||
return input_data, norm_ft
|
||||
elif _is_base64(input_data):
|
||||
try:
|
||||
if input_data.startswith("data:"):
|
||||
base64_data = input_data.split(",", 1)[1]
|
||||
else:
|
||||
base64_data = input_data
|
||||
bytes_ = base64.b64decode(base64_data)
|
||||
file_type_str = _infer_file_type_from_bytes(bytes_)
|
||||
if file_type_str is None:
|
||||
raise ValueError(
|
||||
"Unsupported file type in Base64 data. "
|
||||
"Only images (JPEG, PNG, etc.) and PDF documents are supported."
|
||||
)
|
||||
return input_data, file_type_str
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to decode Base64 data: {str(e)}") from e
|
||||
elif _is_file_path(input_data):
|
||||
try:
|
||||
with open(input_data, "rb") as f:
|
||||
bytes_ = f.read()
|
||||
input_data = base64.b64encode(bytes_).decode("ascii")
|
||||
file_type_str = _infer_file_type_from_bytes(bytes_)
|
||||
if file_type_str is None:
|
||||
raise ValueError(
|
||||
f"Unsupported file type for '{input_data}'. "
|
||||
"Only images (JPEG, PNG, etc.) and PDF documents are supported."
|
||||
)
|
||||
return input_data, file_type_str
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to read file: {str(e)}") from e
|
||||
else:
|
||||
raise ValueError("Invalid input data format")
|
||||
|
||||
async def _call_service(
|
||||
self,
|
||||
processed_input: str,
|
||||
file_type: Optional[str],
|
||||
ctx: Context,
|
||||
**kwargs: Any,
|
||||
) -> Dict[str, Any]:
|
||||
if not self._server_url:
|
||||
raise RuntimeError("Server URL not configured")
|
||||
|
||||
endpoint = self._get_service_endpoint()
|
||||
if endpoint:
|
||||
endpoint = "/" + endpoint
|
||||
url = f"{self._server_url.rstrip('/')}{endpoint}"
|
||||
|
||||
payload = self._prepare_service_payload(processed_input, file_type, **kwargs)
|
||||
headers = {"Content-Type": "application/json"}
|
||||
|
||||
if self._ppocr_source == "aistudio":
|
||||
if not self._aistudio_access_token:
|
||||
raise RuntimeError("Missing AI Studio access token")
|
||||
headers["Authorization"] = f"token {self._aistudio_access_token}"
|
||||
elif self._ppocr_source == "qianfan":
|
||||
if not self._qianfan_api_key:
|
||||
raise RuntimeError("Missing Qianfan API key")
|
||||
headers["Authorization"] = f"Bearer {self._qianfan_api_key}"
|
||||
|
||||
try:
|
||||
timeout = httpx.Timeout(
|
||||
connect=30.0, read=self._timeout, write=30.0, pool=30.0
|
||||
)
|
||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||
response = await client.post(url, json=payload, headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except httpx.HTTPError as e:
|
||||
raise RuntimeError(f"HTTP request failed: {type(e).__name__}: {str(e)}")
|
||||
except json.JSONDecodeError as e:
|
||||
raise RuntimeError(f"Invalid service response: {str(e)}")
|
||||
|
||||
def _prepare_service_payload(
|
||||
self, processed_input: str, file_type: Optional[str], **kwargs: Any
|
||||
) -> Dict[str, Any]:
|
||||
payload: Dict[str, Any] = {"file": processed_input, **kwargs}
|
||||
if file_type == "image":
|
||||
payload["fileType"] = 1
|
||||
elif file_type == "pdf":
|
||||
payload["fileType"] = 0
|
||||
else:
|
||||
payload["fileType"] = None
|
||||
|
||||
return payload
|
||||
|
||||
def _handle_error(self, exc: Exception, output_mode: OutputMode) -> NoReturn:
|
||||
raise exc
|
||||
|
||||
|
||||
class OCRHandler(SimpleInferencePipelineHandler):
|
||||
def register_tools(self, mcp: FastMCP) -> None:
|
||||
@mcp.tool("ocr")
|
||||
async def _ocr(
|
||||
input_data: str,
|
||||
output_mode: OutputMode = "simple",
|
||||
file_type: Optional[str] = None,
|
||||
*,
|
||||
ctx: Context,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
"""Extracts text from images and PDFs. Accepts file path, URL, or Base64.
|
||||
|
||||
Args:
|
||||
input_data: The file to process (file path, URL, or Base64 string).
|
||||
output_mode: The desired output format.
|
||||
- "simple": (Default) Clean, readable text suitable for most use cases.
|
||||
- "detailed": A JSON output including text, confidence, and precise bounding box coordinates. Only use this when coordinates are specifically required.
|
||||
file_type: File type. This parameter is REQUIRED when `input_data` is a URL and should be omitted for other types.
|
||||
- "image": For image files
|
||||
- "pdf": For PDF documents
|
||||
- None: For unknown file types
|
||||
"""
|
||||
await ctx.info(
|
||||
f"--- OCR tool received `input_data`: {get_str_with_max_len(input_data, 50)} ---"
|
||||
)
|
||||
return await self.process(input_data, output_mode, ctx, file_type)
|
||||
|
||||
def _create_local_engine(self) -> Any:
|
||||
return PaddleOCR(
|
||||
paddlex_config=self._pipeline_config,
|
||||
device=self._device,
|
||||
)
|
||||
|
||||
def _get_service_endpoint(self) -> str:
|
||||
return "ocr"
|
||||
|
||||
def _transform_local_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"use_doc_unwarping": False,
|
||||
"use_doc_orientation_classify": False,
|
||||
}
|
||||
|
||||
def _transform_service_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"useDocUnwarping": False,
|
||||
"useDocOrientationClassify": False,
|
||||
}
|
||||
|
||||
async def _parse_local_result(self, local_result: Dict, ctx: Context) -> Dict:
|
||||
clean_texts, confidences, text_lines = [], [], []
|
||||
|
||||
for result in local_result:
|
||||
texts = result["rec_texts"]
|
||||
scores = result["rec_scores"]
|
||||
boxes = result["rec_boxes"]
|
||||
|
||||
for i, text in enumerate(texts):
|
||||
if text and text.strip():
|
||||
conf = scores[i] if i < len(scores) else 0
|
||||
clean_texts.append(text.strip())
|
||||
confidences.append(conf)
|
||||
instance = {
|
||||
"text": text.strip(),
|
||||
"confidence": round(conf, 3),
|
||||
"bbox": boxes[i].tolist(),
|
||||
}
|
||||
text_lines.append(instance)
|
||||
|
||||
return {
|
||||
"text": "\n".join(clean_texts),
|
||||
"confidence": sum(confidences) / len(confidences) if confidences else 0,
|
||||
"text_lines": text_lines,
|
||||
}
|
||||
|
||||
async def _parse_service_result(self, service_result: Dict, ctx: Context) -> Dict:
|
||||
result_data = service_result.get("result", service_result)
|
||||
ocr_results = result_data.get("ocrResults")
|
||||
|
||||
all_texts, all_confidences, text_lines = [], [], []
|
||||
|
||||
for ocr_result in ocr_results:
|
||||
pruned = ocr_result["prunedResult"]
|
||||
|
||||
texts = pruned["rec_texts"]
|
||||
scores = pruned["rec_scores"]
|
||||
boxes = pruned["rec_boxes"]
|
||||
|
||||
for i, text in enumerate(texts):
|
||||
if text and text.strip():
|
||||
conf = scores[i] if i < len(scores) else 0
|
||||
all_texts.append(text.strip())
|
||||
all_confidences.append(conf)
|
||||
instance = {
|
||||
"text": text.strip(),
|
||||
"confidence": round(conf, 3),
|
||||
"bbox": boxes[i],
|
||||
}
|
||||
text_lines.append(instance)
|
||||
|
||||
return {
|
||||
"text": "\n".join(all_texts),
|
||||
"confidence": (
|
||||
sum(all_confidences) / len(all_confidences) if all_confidences else 0
|
||||
),
|
||||
"text_lines": text_lines,
|
||||
}
|
||||
|
||||
async def _log_completion_stats(self, result: Dict, ctx: Context) -> None:
|
||||
text_length = len(result["text"])
|
||||
text_line_count = len(result["text_lines"])
|
||||
await ctx.info(
|
||||
f"OCR completed: {text_length} characters, {text_line_count} text lines"
|
||||
)
|
||||
|
||||
async def _format_output(
|
||||
self,
|
||||
result: Dict,
|
||||
detailed: bool,
|
||||
ctx: Context,
|
||||
**kwargs: Any,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
if not result["text"].strip():
|
||||
return (
|
||||
"❌ No text detected"
|
||||
if not detailed
|
||||
else json.dumps({"error": "No text detected"}, ensure_ascii=False)
|
||||
)
|
||||
|
||||
if detailed:
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
else:
|
||||
confidence = result["confidence"]
|
||||
text_line_count = len(result["text_lines"])
|
||||
|
||||
output = result["text"]
|
||||
if confidence > 0:
|
||||
output += f"\n\n📊 Confidence: {(confidence * 100):.1f}% | {text_line_count} text lines"
|
||||
|
||||
return output
|
||||
|
||||
|
||||
class _LayoutParsingHandler(SimpleInferencePipelineHandler):
|
||||
def _get_service_endpoint(self) -> str:
|
||||
return "layout-parsing" if self._ppocr_source != "qianfan" else "paddleocr"
|
||||
|
||||
def _transform_local_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"use_doc_unwarping": False,
|
||||
"use_doc_orientation_classify": False,
|
||||
}
|
||||
|
||||
def _transform_service_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"useDocUnwarping": False,
|
||||
"useDocOrientationClassify": False,
|
||||
}
|
||||
|
||||
async def _parse_local_result(self, local_result: Dict, ctx: Context) -> Dict:
|
||||
markdown_parts = []
|
||||
all_images_mapping = {}
|
||||
detailed_results = []
|
||||
|
||||
for result in local_result:
|
||||
markdown = result.markdown
|
||||
text = markdown["markdown_texts"]
|
||||
markdown_parts.append(text)
|
||||
images = markdown["markdown_images"]
|
||||
processed_images = {}
|
||||
for img_key, img_data in images.items():
|
||||
with io.BytesIO() as buffer:
|
||||
img_data.save(buffer, format="JPEG")
|
||||
processed_images[img_key] = base64.b64encode(buffer.getvalue())
|
||||
all_images_mapping.update(processed_images)
|
||||
detailed_results.append(result)
|
||||
|
||||
return {
|
||||
# TODO: Page concatenation can be done better via `pipeline.concatenate_markdown_pages`
|
||||
"markdown": "\n".join(markdown_parts),
|
||||
"pages": len(local_result),
|
||||
"images_mapping": all_images_mapping,
|
||||
"detailed_results": detailed_results,
|
||||
}
|
||||
|
||||
async def _parse_service_result(self, service_result: Dict, ctx: Context) -> Dict:
|
||||
result_data = service_result.get("result", service_result)
|
||||
layout_results = result_data.get("layoutParsingResults")
|
||||
|
||||
if not layout_results:
|
||||
return {
|
||||
"markdown": "",
|
||||
"pages": 0,
|
||||
"images_mapping": {},
|
||||
"detailed_results": [],
|
||||
}
|
||||
|
||||
markdown_parts = []
|
||||
all_images_mapping = {}
|
||||
detailed_results = []
|
||||
|
||||
for res in layout_results:
|
||||
markdown_parts.append(res["markdown"]["text"])
|
||||
images = res["markdown"]["images"]
|
||||
processed_images = {}
|
||||
for img_key, img_data in images.items():
|
||||
processed_images[img_key] = await self._process_image_data(
|
||||
img_data, ctx
|
||||
)
|
||||
all_images_mapping.update(processed_images)
|
||||
detailed_results.append(res["prunedResult"])
|
||||
|
||||
return {
|
||||
"markdown": "\n".join(markdown_parts),
|
||||
"pages": len(layout_results),
|
||||
"images_mapping": all_images_mapping,
|
||||
"detailed_results": detailed_results,
|
||||
}
|
||||
|
||||
async def _process_image_data(self, img_data: str, ctx: Context) -> str:
|
||||
if _is_url(img_data):
|
||||
try:
|
||||
timeout = httpx.Timeout(connect=30.0, read=30.0, write=30.0, pool=30.0)
|
||||
async with httpx.AsyncClient(timeout=timeout) as client:
|
||||
response = await client.get(img_data)
|
||||
response.raise_for_status()
|
||||
img_bytes = response.content
|
||||
return base64.b64encode(img_bytes).decode("ascii")
|
||||
except Exception as e:
|
||||
await ctx.error(
|
||||
f"Failed to download image from URL {img_data}: {str(e)}"
|
||||
)
|
||||
return img_data
|
||||
elif _is_base64(img_data):
|
||||
return img_data
|
||||
else:
|
||||
await ctx.error(
|
||||
f"Unknown image data format: {get_str_with_max_len(img_data, 50)}"
|
||||
)
|
||||
return img_data
|
||||
|
||||
async def _log_completion_stats(self, result: Dict, ctx: Context) -> None:
|
||||
page_count = result["pages"]
|
||||
await ctx.info(f"Layout parsing completed: {page_count} pages")
|
||||
|
||||
async def _format_output(
|
||||
self,
|
||||
result: Dict,
|
||||
detailed: bool,
|
||||
ctx: Context,
|
||||
**kwargs: Any,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
if not result["markdown"].strip():
|
||||
return (
|
||||
"❌ No document content detected"
|
||||
if not detailed
|
||||
else json.dumps({"error": "No content detected"}, ensure_ascii=False)
|
||||
)
|
||||
|
||||
markdown_text = result["markdown"]
|
||||
images_mapping = result.get("images_mapping", {})
|
||||
|
||||
if kwargs.get("return_images"):
|
||||
content_list = self._parse_markdown_with_images(
|
||||
markdown_text, images_mapping
|
||||
)
|
||||
else:
|
||||
content_list = [TextContent(type="text", text=markdown_text)]
|
||||
|
||||
if detailed:
|
||||
if "detailed_results" in result and result["detailed_results"]:
|
||||
for detailed_result in result["detailed_results"]:
|
||||
content_list.append(
|
||||
TextContent(
|
||||
type="text",
|
||||
text=json.dumps(
|
||||
detailed_result,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
default=str,
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
return content_list
|
||||
|
||||
def _parse_markdown_with_images(
|
||||
self, markdown_text: str, images_mapping: Dict[str, str]
|
||||
) -> List[Union[TextContent, ImageContent]]:
|
||||
"""Parse markdown text and return mixed list of text and images."""
|
||||
if not images_mapping:
|
||||
return [TextContent(type="text", text=markdown_text)]
|
||||
|
||||
content_list = []
|
||||
img_pattern = r'<img[^>]+src="([^"]+)"[^>]*>'
|
||||
last_pos = 0
|
||||
|
||||
for match in re.finditer(img_pattern, markdown_text):
|
||||
text_before = markdown_text[last_pos : match.start()]
|
||||
if text_before.strip():
|
||||
content_list.append(TextContent(type="text", text=text_before))
|
||||
|
||||
img_src = match.group(1)
|
||||
if img_src in images_mapping:
|
||||
content_list.append(
|
||||
ImageContent(
|
||||
type="image",
|
||||
data=images_mapping[img_src],
|
||||
mimeType="image/jpeg",
|
||||
)
|
||||
)
|
||||
|
||||
last_pos = match.end()
|
||||
|
||||
remaining_text = markdown_text[last_pos:]
|
||||
if remaining_text.strip():
|
||||
content_list.append(TextContent(type="text", text=remaining_text))
|
||||
|
||||
return content_list or [TextContent(type="text", text=markdown_text)]
|
||||
|
||||
|
||||
class PPStructureV3Handler(_LayoutParsingHandler):
|
||||
def register_tools(self, mcp: FastMCP) -> None:
|
||||
@mcp.tool("pp_structurev3")
|
||||
async def _pp_structurev3(
|
||||
input_data: str,
|
||||
output_mode: OutputMode = "simple",
|
||||
file_type: Optional[str] = None,
|
||||
return_images: bool = True,
|
||||
*,
|
||||
ctx: Context,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
"""Extracts structured markdown from complex documents (images/PDFs), including tables, formulas, etc. Accepts file path, URL, or Base64.
|
||||
|
||||
Args:
|
||||
input_data: The file to process (file path, URL, or Base64 string).
|
||||
output_mode: The desired output format.
|
||||
- "simple": (Default) Clean, readable markdown with embedded images. Best for most use cases.
|
||||
- "detailed": JSON data about document structure, plus markdown. Only use this when coordinates are specifically required.
|
||||
file_type: File type. This parameter is REQUIRED when `input_data` is a URL and should be omitted for other types.
|
||||
- "image": For image files
|
||||
- "pdf": For PDF documents
|
||||
- None: For unknown file types
|
||||
return_images: Whether to return the images extracted from the document.
|
||||
"""
|
||||
return await self.process(
|
||||
input_data,
|
||||
output_mode,
|
||||
ctx,
|
||||
file_type,
|
||||
format_kwargs={"return_images": return_images},
|
||||
)
|
||||
|
||||
def _create_local_engine(self) -> Any:
|
||||
return PPStructureV3(
|
||||
paddlex_config=self._pipeline_config,
|
||||
device=self._device,
|
||||
)
|
||||
|
||||
def _transform_service_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
kwargs = super()._transform_service_kwargs(kwargs)
|
||||
if self._ppocr_source == "qianfan":
|
||||
kwargs["model"] = "pp-structurev3"
|
||||
return kwargs
|
||||
|
||||
|
||||
class PaddleOCRVLHandler(_LayoutParsingHandler):
|
||||
def register_tools(self, mcp: FastMCP) -> None:
|
||||
@mcp.tool("paddleocr_vl")
|
||||
async def _paddleocr_vl(
|
||||
input_data: str,
|
||||
output_mode: OutputMode = "simple",
|
||||
file_type: Optional[str] = None,
|
||||
return_images: bool = True,
|
||||
*,
|
||||
ctx: Context,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
"""Extracts structured markdown from complex documents (images/PDFs) using a VLM-based approach. The extracted elements include tables, formulas, etc. Accepts file path, URL, or Base64.
|
||||
|
||||
Args:
|
||||
input_data: The file to process (file path, URL, or Base64 string).
|
||||
output_mode: The desired output format.
|
||||
- "simple": (Default) Clean, readable markdown with embedded images. Best for most use cases.
|
||||
- "detailed": JSON data about document structure, plus markdown. Only use this when coordinates are specifically required.
|
||||
file_type: File type. This parameter is REQUIRED when `input_data` is a URL and should be omitted for other types.
|
||||
- "image": For image files
|
||||
- "pdf": For PDF documents
|
||||
- None: For unknown file types
|
||||
return_images: Whether to return the images extracted from the document.
|
||||
"""
|
||||
return await self.process(
|
||||
input_data,
|
||||
output_mode,
|
||||
ctx,
|
||||
file_type,
|
||||
format_kwargs={"return_images": return_images},
|
||||
)
|
||||
|
||||
def _create_local_engine(self) -> Any:
|
||||
if self._pipeline == "PaddleOCR-VL":
|
||||
pipeline_version = "v1"
|
||||
elif self._pipeline == "PaddleOCR-VL-1.5":
|
||||
pipeline_version = "v1.5"
|
||||
elif self._pipeline == "PaddleOCR-VL-1.6":
|
||||
pipeline_version = "v1.6"
|
||||
else:
|
||||
raise RuntimeError(f"Unknown pipeline {repr(self._pipeline)}")
|
||||
return PaddleOCRVL(
|
||||
pipeline_version=pipeline_version,
|
||||
paddlex_config=self._pipeline_config,
|
||||
device=self._device,
|
||||
)
|
||||
|
||||
def _transform_service_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
|
||||
kwargs = super()._transform_service_kwargs(kwargs)
|
||||
if self._ppocr_source == "qianfan":
|
||||
if self._pipeline == "PaddleOCR-VL":
|
||||
kwargs["model"] = "paddleocr-vl-0.9b"
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"Unknown or unsupported pipeline {repr(self._pipeline)}"
|
||||
)
|
||||
return kwargs
|
||||
|
||||
|
||||
_PIPELINE_HANDLERS: Dict[str, Type[PipelineHandler]] = {
|
||||
"OCR": OCRHandler,
|
||||
"PP-StructureV3": PPStructureV3Handler,
|
||||
"PaddleOCR-VL": PaddleOCRVLHandler,
|
||||
"PaddleOCR-VL-1.5": PaddleOCRVLHandler,
|
||||
"PaddleOCR-VL-1.6": PaddleOCRVLHandler,
|
||||
}
|
||||
|
||||
|
||||
def create_pipeline_handler(
|
||||
pipeline: str, /, *args: Any, **kwargs: Any
|
||||
) -> PipelineHandler:
|
||||
if pipeline in _PIPELINE_HANDLERS:
|
||||
cls = _PIPELINE_HANDLERS[pipeline]
|
||||
return cls(pipeline, *args, **kwargs)
|
||||
else:
|
||||
raise ValueError(f"Unknown pipeline {repr(pipeline)}")
|
||||
@@ -0,0 +1,17 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from .base import Task
|
||||
from .factory import TaskFactory, create_task
|
||||
|
||||
__all__ = ["Task", "TaskFactory", "create_task"]
|
||||
@@ -0,0 +1,83 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import abc
|
||||
from typing import Any, List, Optional, Union
|
||||
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.server.dependencies import get_context
|
||||
from mcp.types import ImageContent, TextContent
|
||||
|
||||
from ..inference.base import Inference
|
||||
from ..inference.types import InferenceRequest, InferenceResult
|
||||
|
||||
ToolReturn = Union[str, List[Union[TextContent, ImageContent]]]
|
||||
|
||||
|
||||
class Task(abc.ABC):
|
||||
def __init__(self, inference: Inference):
|
||||
self._inference = inference
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def tool_name(self) -> str:
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def _format_result(
|
||||
self, result: InferenceResult, detailed: bool, **kwargs
|
||||
) -> ToolReturn:
|
||||
pass
|
||||
|
||||
def _tool_description(self) -> str:
|
||||
valid_params = sorted(self._inference.get_valid_params())
|
||||
params_hint = ", ".join(valid_params)
|
||||
return (
|
||||
f"PaddleOCR {self.tool_name} tool. "
|
||||
f"Optional runtime_params keys: {params_hint}."
|
||||
)
|
||||
|
||||
async def _invoke_tool(
|
||||
self,
|
||||
input_data: str,
|
||||
output_mode: str = "simple",
|
||||
file_type: Optional[str] = None,
|
||||
return_images: bool = True,
|
||||
runtime_params: Optional[dict[str, Any]] = None,
|
||||
) -> ToolReturn:
|
||||
ctx = get_context()
|
||||
await ctx.info(
|
||||
f"--- {self.tool_name} tool received input_data: {input_data[:50]} ---"
|
||||
)
|
||||
|
||||
final_params = self._inference.get_final_params(runtime_params or {})
|
||||
self._inference.validate_params(final_params)
|
||||
|
||||
request = InferenceRequest(
|
||||
input_data=input_data,
|
||||
file_type=file_type,
|
||||
runtime_params=final_params,
|
||||
)
|
||||
result = await self._inference.predict(request)
|
||||
|
||||
return self._format_result(
|
||||
result,
|
||||
detailed=(output_mode == "detailed"),
|
||||
return_images=return_images,
|
||||
)
|
||||
|
||||
def register_tools(self, mcp: FastMCP) -> None:
|
||||
mcp.tool(self.tool_name, description=self._tool_description())(
|
||||
self._invoke_tool
|
||||
)
|
||||
@@ -0,0 +1,112 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Dict, List, Union
|
||||
from typing_extensions import override
|
||||
|
||||
from mcp.types import ImageContent, TextContent
|
||||
|
||||
from ..inference.types import DocParsingResult, InferenceResult
|
||||
from .base import Task
|
||||
|
||||
|
||||
class DocParsingTask(Task):
|
||||
def _format_result(
|
||||
self,
|
||||
result: InferenceResult,
|
||||
detailed: bool,
|
||||
return_images: bool = True,
|
||||
**kwargs,
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
if not isinstance(result, DocParsingResult):
|
||||
raise TypeError(
|
||||
f"DocParsingTask expected DocParsingResult, got {type(result).__name__}"
|
||||
)
|
||||
|
||||
if not result.markdown.strip():
|
||||
return (
|
||||
"No document content detected"
|
||||
if not detailed
|
||||
else json.dumps({"error": "No content detected"}, ensure_ascii=False)
|
||||
)
|
||||
|
||||
markdown_text = result.markdown
|
||||
images_mapping = result.images_mapping
|
||||
|
||||
if return_images and images_mapping:
|
||||
content_list = self._parse_markdown_with_images(
|
||||
markdown_text, images_mapping
|
||||
)
|
||||
else:
|
||||
content_list = [TextContent(type="text", text=markdown_text)]
|
||||
|
||||
if detailed:
|
||||
content_list.append(
|
||||
TextContent(
|
||||
type="text",
|
||||
text=f"Pages: {result.pages}",
|
||||
)
|
||||
)
|
||||
|
||||
if len(content_list) == 1:
|
||||
return content_list[0]
|
||||
return content_list
|
||||
|
||||
def _parse_markdown_with_images(
|
||||
self, markdown_text: str, images_mapping: Dict[str, str]
|
||||
) -> List[Union[TextContent, ImageContent]]:
|
||||
if not images_mapping:
|
||||
return [TextContent(type="text", text=markdown_text)]
|
||||
|
||||
content_list = []
|
||||
img_pattern = r'<img[^>]+src="([^"]+)"[^>]*>'
|
||||
last_pos = 0
|
||||
|
||||
for match in re.finditer(img_pattern, markdown_text):
|
||||
text_before = markdown_text[last_pos : match.start()]
|
||||
if text_before.strip():
|
||||
content_list.append(TextContent(type="text", text=text_before))
|
||||
|
||||
img_src = match.group(1)
|
||||
if img_src in images_mapping:
|
||||
content_list.append(
|
||||
ImageContent(
|
||||
type="image",
|
||||
data=images_mapping[img_src],
|
||||
mimeType="image/jpeg",
|
||||
)
|
||||
)
|
||||
|
||||
last_pos = match.end()
|
||||
|
||||
remaining_text = markdown_text[last_pos:]
|
||||
if remaining_text.strip():
|
||||
content_list.append(TextContent(type="text", text=remaining_text))
|
||||
|
||||
return content_list or [TextContent(type="text", text=markdown_text)]
|
||||
|
||||
|
||||
class PPStructureV3Task(DocParsingTask):
|
||||
@property
|
||||
@override
|
||||
def tool_name(self) -> str:
|
||||
return "pp_structurev3"
|
||||
|
||||
|
||||
class PaddleOCRVLTask(DocParsingTask):
|
||||
@property
|
||||
@override
|
||||
def tool_name(self) -> str:
|
||||
return "paddleocr_vl"
|
||||
@@ -0,0 +1,52 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from ..inference.base import Inference
|
||||
from .base import Task
|
||||
|
||||
|
||||
class TaskFactory:
|
||||
_registry: Dict[str, type[Task]] = {}
|
||||
|
||||
@classmethod
|
||||
def register(cls, pipeline: str, task_class: type[Task]) -> None:
|
||||
cls._registry[pipeline] = task_class
|
||||
|
||||
@classmethod
|
||||
def create(cls, pipeline: str, inference: Inference) -> Task:
|
||||
if pipeline not in cls._registry:
|
||||
raise ValueError(
|
||||
f"Unknown pipeline: {pipeline}. Supported: {sorted(cls._registry.keys())}"
|
||||
)
|
||||
task_class = cls._registry[pipeline]
|
||||
return task_class(inference)
|
||||
|
||||
@classmethod
|
||||
def list_supported(cls) -> set[str]:
|
||||
return set(cls._registry.keys())
|
||||
|
||||
|
||||
from .ocr import OCRTask
|
||||
from .doc_parsing import PPStructureV3Task, PaddleOCRVLTask
|
||||
|
||||
TaskFactory.register("OCR", OCRTask)
|
||||
TaskFactory.register("PP-StructureV3", PPStructureV3Task)
|
||||
TaskFactory.register("PaddleOCR-VL", PaddleOCRVLTask)
|
||||
TaskFactory.register("PaddleOCR-VL-1.5", PaddleOCRVLTask)
|
||||
TaskFactory.register("PaddleOCR-VL-1.6", PaddleOCRVLTask)
|
||||
|
||||
|
||||
def create_task(pipeline: str, inference: Inference) -> Task:
|
||||
return TaskFactory.create(pipeline, inference)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import json
|
||||
from typing import List, Union
|
||||
from typing_extensions import override
|
||||
|
||||
from mcp.types import ImageContent, TextContent
|
||||
|
||||
from ..inference.types import InferenceResult, OCRResult
|
||||
from .base import Task
|
||||
|
||||
|
||||
class OCRTask(Task):
|
||||
@property
|
||||
@override
|
||||
def tool_name(self) -> str:
|
||||
return "ocr"
|
||||
|
||||
@override
|
||||
def _format_result(
|
||||
self, result: InferenceResult, detailed: bool, **kwargs
|
||||
) -> Union[str, List[Union[TextContent, ImageContent]]]:
|
||||
if not isinstance(result, OCRResult):
|
||||
raise TypeError(f"OCRTask expected OCRResult, got {type(result).__name__}")
|
||||
|
||||
if not result.text.strip():
|
||||
return (
|
||||
"No text detected"
|
||||
if not detailed
|
||||
else json.dumps({"error": "No text detected"}, ensure_ascii=False)
|
||||
)
|
||||
|
||||
if detailed:
|
||||
return json.dumps(result.to_dict(), ensure_ascii=False, indent=2)
|
||||
|
||||
confidence = result.confidence
|
||||
text_line_count = len(result.text_lines)
|
||||
|
||||
output = result.text
|
||||
if confidence > 0:
|
||||
output += f"\n\nConfidence: {(confidence * 100):.1f}% | {text_line_count} text lines"
|
||||
|
||||
return output
|
||||
@@ -4,13 +4,14 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "paddleocr_mcp"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"mcp>=1.5.0",
|
||||
"fastmcp>=2.0.0",
|
||||
"httpx>=0.24.0",
|
||||
"numpy>=1.24.0",
|
||||
"paddleocr>=3.6.0",
|
||||
"pillow>=9.0.0",
|
||||
"puremagic>=1.30.0",
|
||||
"typing-extensions>=4.0.0",
|
||||
@@ -18,10 +19,10 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
local = [
|
||||
"paddleocr[doc-parser]>=3.4",
|
||||
"paddleocr[doc-parser]>=3.6.0",
|
||||
]
|
||||
local-cpu = [
|
||||
"paddleocr[doc-parser]>=3.4",
|
||||
"paddleocr[doc-parser]>=3.6.0",
|
||||
"paddlepaddle>=3.2.1",
|
||||
]
|
||||
|
||||
|
||||
+16
-10
@@ -41,23 +41,27 @@ from ._pipelines import (
|
||||
SealRecognition,
|
||||
TableRecognitionPipelineV2,
|
||||
)
|
||||
from ._api_client import (
|
||||
AsyncPaddleOCRClient,
|
||||
PaddleOCRClient,
|
||||
PaddleOCRVLOptions,
|
||||
Model,
|
||||
OCROptions,
|
||||
PPStructureV3Options,
|
||||
PaddleOCRAPIError,
|
||||
from ._api_client.async_client import AsyncPaddleOCRClient
|
||||
from ._api_client.client import PaddleOCRClient
|
||||
from ._api_client.errors import (
|
||||
APIError,
|
||||
AuthError,
|
||||
InvalidRequestError,
|
||||
APIError,
|
||||
JobFailedError,
|
||||
NetworkError,
|
||||
PaddleOCRAPIError,
|
||||
PollTimeoutError,
|
||||
RateLimitError,
|
||||
RequestTimeoutError,
|
||||
ResponseFormatError,
|
||||
ResultParseError,
|
||||
NetworkError,
|
||||
ServiceUnavailableError,
|
||||
)
|
||||
from ._api_client.models import (
|
||||
Model,
|
||||
OCROptions,
|
||||
PaddleOCRVLOptions,
|
||||
PPStructureV3Options,
|
||||
)
|
||||
from ._utils.logging import logger
|
||||
from ._version import version as __version__
|
||||
@@ -115,10 +119,12 @@ __all__ = [
|
||||
"InvalidRequestError",
|
||||
"APIError",
|
||||
"JobFailedError",
|
||||
"RateLimitError",
|
||||
"RequestTimeoutError",
|
||||
"PollTimeoutError",
|
||||
"ResponseFormatError",
|
||||
"ResultParseError",
|
||||
"ServiceUnavailableError",
|
||||
"NetworkError",
|
||||
"logger",
|
||||
"__version__",
|
||||
|
||||
@@ -11,65 +11,3 @@
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from .client import PaddleOCRClient
|
||||
from .async_client import AsyncPaddleOCRClient
|
||||
from .models import (
|
||||
Model,
|
||||
OCROptions,
|
||||
PaddleOCRVLOptions,
|
||||
PPStructureV3Options,
|
||||
)
|
||||
from .results import (
|
||||
DocParsingPage,
|
||||
DocParsingResult,
|
||||
Job,
|
||||
JobStatus,
|
||||
BatchStatus,
|
||||
OCRPage,
|
||||
OCRResult,
|
||||
Progress,
|
||||
)
|
||||
from .errors import (
|
||||
APIError,
|
||||
AuthError,
|
||||
InvalidRequestError,
|
||||
JobFailedError,
|
||||
NetworkError,
|
||||
PaddleOCRAPIError,
|
||||
PollTimeoutError,
|
||||
RateLimitError,
|
||||
RequestTimeoutError,
|
||||
ResponseFormatError,
|
||||
ResultParseError,
|
||||
ServiceUnavailableError,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"PaddleOCRClient",
|
||||
"AsyncPaddleOCRClient",
|
||||
"Model",
|
||||
"OCROptions",
|
||||
"PPStructureV3Options",
|
||||
"PaddleOCRVLOptions",
|
||||
"OCRResult",
|
||||
"OCRPage",
|
||||
"DocParsingResult",
|
||||
"DocParsingPage",
|
||||
"Job",
|
||||
"JobStatus",
|
||||
"BatchStatus",
|
||||
"Progress",
|
||||
"PaddleOCRAPIError",
|
||||
"AuthError",
|
||||
"InvalidRequestError",
|
||||
"APIError",
|
||||
"RateLimitError",
|
||||
"ServiceUnavailableError",
|
||||
"JobFailedError",
|
||||
"RequestTimeoutError",
|
||||
"PollTimeoutError",
|
||||
"ResponseFormatError",
|
||||
"ResultParseError",
|
||||
"NetworkError",
|
||||
]
|
||||
@@ -8,7 +8,6 @@ description: >-
|
||||
发票, 财报, 复杂 PDF, PDF转Markdown, 图表, 阅读顺序; reading order, formula, LaTeX,
|
||||
layout parsing, structure extraction, PP-StructureV3, PaddleOCR-VL.
|
||||
license: Apache-2.0
|
||||
compatibility: Requires paddleocr>=3.6.0
|
||||
metadata:
|
||||
openclaw:
|
||||
requires:
|
||||
@@ -56,29 +55,22 @@ paddleocr api \
|
||||
--file_path "./document.pdf"
|
||||
```
|
||||
|
||||
### With Specific Model
|
||||
|
||||
PP-StructureV3:
|
||||
### Common Options
|
||||
|
||||
```bash
|
||||
# With specific model
|
||||
paddleocr api \
|
||||
--model_type doc_parsing \
|
||||
--model PP-StructureV3 \
|
||||
--file_path "./report.pdf"
|
||||
```
|
||||
|
||||
PaddleOCR-VL-1.6:
|
||||
|
||||
```bash
|
||||
# Disable preprocessing (faster, for flat/well-oriented images)
|
||||
paddleocr api \
|
||||
--model_type doc_parsing \
|
||||
--model PaddleOCR-VL-1.6 \
|
||||
--file_url "https://..."
|
||||
```
|
||||
--file_path "./document.pdf" \
|
||||
--use_doc_unwarping False \
|
||||
--use_doc_orientation_classify False
|
||||
|
||||
### Common Options
|
||||
|
||||
```bash
|
||||
# With page ranges
|
||||
paddleocr api \
|
||||
--model_type doc_parsing \
|
||||
@@ -92,12 +84,6 @@ paddleocr api \
|
||||
--output result.json \
|
||||
--save_resources ./resources
|
||||
|
||||
# With seal recognition
|
||||
paddleocr api \
|
||||
--model_type doc_parsing \
|
||||
--file_path "./document.pdf" \
|
||||
--use_seal_recognition True
|
||||
|
||||
# Prettify markdown output
|
||||
paddleocr api \
|
||||
--model_type doc_parsing \
|
||||
@@ -127,6 +113,17 @@ paddleocr api \
|
||||
|
||||
## Important Notes
|
||||
|
||||
**Preprocessing options**: For flat, well-oriented images (screenshots, properly scanned documents), you can disable preprocessing for faster results:
|
||||
|
||||
```bash
|
||||
paddleocr api --model_type doc_parsing --file_path "./document.pdf" --use_doc_unwarping False --use_doc_orientation_classify False
|
||||
```
|
||||
|
||||
Keep preprocessing enabled when:
|
||||
- The input is a photo of a curved or folded document
|
||||
- The document has significant perspective distortion
|
||||
- Orientation is uncertain (rotated 90/180/270 degrees)
|
||||
|
||||
**Display complete results**: Always show the full extracted content to users. Do not truncate with "..." unless content exceeds 10,000 characters. When multiple pages are processed, summarize if needed but provide complete results when explicitly requested.
|
||||
|
||||
**Handle errors gracefully**: When the CLI returns an error, inform the user of the specific issue rather than silently failing. Common errors:
|
||||
|
||||
@@ -8,7 +8,6 @@ description: >-
|
||||
plain text extraction, 坐标, 检测框, bbox, bounding box, image to text, screenshot, photo scan,
|
||||
recognize text.
|
||||
license: Apache-2.0
|
||||
compatibility: Requires paddleocr>=3.6.0
|
||||
metadata:
|
||||
openclaw:
|
||||
requires:
|
||||
@@ -58,20 +57,15 @@ paddleocr api \
|
||||
--file_path "./document.pdf"
|
||||
```
|
||||
|
||||
### With Specific Model
|
||||
|
||||
PP-OCRv5:
|
||||
### Common Options
|
||||
|
||||
```bash
|
||||
# With specific model
|
||||
paddleocr api \
|
||||
--model_type ocr \
|
||||
--model PP-OCRv5 \
|
||||
--file_path "./report.pdf"
|
||||
```
|
||||
|
||||
### Common Options
|
||||
|
||||
```bash
|
||||
# Disable preprocessing (faster, for flat/well-oriented images)
|
||||
paddleocr api \
|
||||
--model_type ocr \
|
||||
|
||||
Reference in new issue
Block a user