refactor(skills): simplify skills to use PaddleOCR CLI directly (#18090)

* refactor(skills): simplify skills to use PaddleOCR CLI directly

Simplify PaddleOCR Skills by removing custom scripts and using the
official `paddleocr api` CLI directly. This reduces maintenance burden
and aligns with the 3.6.0 release which includes async API support.

**Changes:**
- Remove scripts/ and references/ directories from both skills
- Rewrite SKILL.md files to document CLI usage
- Update environment variables from PADDLEOCR_OCR_API_URL /
  PADDLEOCR_DOC_PARSING_API_URL to PADDLEOCR_BASE_URL (optional)
- Update skills.md and skills.en.md documentation

**Environment Variables:**
- Required: PADDLEOCR_ACCESS_TOKEN
- Optional: PADDLEOCR_BASE_URL (defaults to official service)

**Installation:**
Users now install PaddleOCR 3.6.0+ and use the CLI directly:
  pip install "paddleocr>=3.6.0"
  paddleocr api --model_type ocr --file_url "..."

* fix: add missing newline at end of SKILL.md

* Fix and polish

---------

Co-authored-by: Bobholamovic <bob1998425@hotmail.com>
This commit is contained in:
RanderandBobholamovic authored and GitHub committed 2026-06-03 15:24:50 +08:00
1 parent 4205657795
commit 9f704bc6ab
21 files changed
+602 -2683

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
# PaddleOCR API SDK 集成测试报告
**测试分支**: feature/api-sdk (PR #18049)
**测试环境**: macOS Darwin 24.3.0, Python 3.9.6, requests 2.32.5
**API Endpoint**: https://paddleocr.aistudio-app.com/api/v2/ocr/jobs
---
## 测试结果总览
| # | 测试项                | 结果  | 耗时 | 说明                       |
| -----| ---------------------------------------| --------| ------| ---------------------------------------------------|
| 1 | OCR URL (PP-OCRv5)          | ✅ PASS | 3.6s | URL 输入,默认参数                |
| 2 | OCR URL + 自定义 Options       | ✅ PASS | 3.6s | 设置 use_doc_orientation_classify=True      |
| 3 | Doc Parsing URL (PP-StructureV3)   | ✅ PASS | 3.7s | 文档版面解析                   |
| 4 | Submit + Poll 分步调用        | ✅ PASS | 3.7s | 非阻塞 API:submit → get_result → wait_for_result |
| 5 | OCR 本地文件上传           | ✅ PASS | 4.3s | file_path 模式                  |
| 6 | 错误处理 (无效 token)         | ✅ PASS | 0.2s | 正确抛出 AuthError                |
| 7 | 输入校验               | ✅ PASS | 0.0s | 缺少输入 / 互斥参数均正确拦截           |
| 8 | Context Manager (with)        | ✅ PASS | 3.6s | with 语句正常工作                 |
| 9 | PaddleOCR-VL 模型           | ✅ PASS | 3.6s | VL 模型正常返回 markdown             |
| 10 | PaddleOCR-VL-1.5 模型         | ✅ PASS | 3.6s | VL-1.5 模型正常返回 markdown           |
| 11 | Doc Parsing 文件上传 (PP-StructureV3) | ✅ PASS | 4.3s | 本地文件上传 + 文档解析              |
**总计: 11 passed, 0 failed**
---
## 发现的 Bug(已修复验证)
### 🔴 阻塞性 Bug: `fetch_jsonl` 请求 BOS 签名 URL 时携带了多余的 Authorization header
**文件**: `paddleocr/_api_client/_http.py` (同步) + `async_client.py` (异步)
**现象**: 任务提交和轮询均成功,但在最后一步下载 JSONL 结果文件时,SDK 使用带有 `Authorization: bearer <paddle_token>` 的 session 去请求百度 BOS 对象存储的预签名 URL。BOS 不认识这个 header,返回 400 Bad Request。
**根因**: `HTTPClient.fetch_jsonl()` 使用 `self._session.get(url)` 发起请求,而 session 在初始化时设置了 `Authorization` header。BOS 的预签名 URL 已经包含了自己的鉴权参数(`authorization=bce-auth-v1/...`),额外的 Authorization header 导致冲突。
**修复**: `fetch_jsonl` 应使用不带 auth header 的独立请求:
```python
# 修复前
resp = self._session.get(url, timeout=self._timeout)
# 修复后
resp = requests.get(url, timeout=self._timeout)
```
**影响范围**: 所有实际 API 调用(OCR、Doc Parsing、所有模型)在修复前均无法获取结果。这是一个 **必须在合入前修复的阻塞性 bug**。
---
## 其他已知问题(非阻塞,可后续迭代)
| 严重度 | 语言 | 问题 |
|--------|------|------|
| 中 | Python | AsyncAPIClient._poll_until_done 使用硬编码 DEFAULT_MAX_WAIT_TIME,忽略用户设置的 timeout |
| 中 | Go | submitURL/submitFile/getJobStatus 未使用 http.NewRequestWithContext,context 取消无法中断 HTTP 请求 |
| 中 | TypeScript | poller.ts 的 sleep 方法 abort listener 未设置 `{ once: true }`,长轮询会泄漏 listener |
| 中 | TypeScript | http.ts 的 fetchJsonl 未检查 resp.ok(同样的 BOS auth 问题可能也存在于 TS SDK) |
| 低 | 全部 | 轮询循环先 sleep 再 check,对已完成任务多等 3 秒 |
| 低 | Python | CLI argparse 的 store_true 传 False 而非 None,导致多余字段发送给 API |
---
## 结论
**修复 `fetch_jsonl` 的 auth header 问题后,Python SDK 的核心功能全部正常工作。** 4 个模型(PP-OCRv5、PP-StructureV3、PaddleOCR-VL、PaddleOCR-VL-1.5)均可正常调用,URL 输入和文件上传两种模式均可用,错误处理和输入校验逻辑正确。
**建议**:
1. ⚠️ **合入前必须修复** `fetch_jsonl` 的 BOS auth header bug(Python 同步 + 异步,以及 Go/TypeScript SDK 中的同类问题)
2. 其他问题可以合入后迭代修复
@@ -43,19 +43,19 @@ paddleocr api \
- `--save_resources`: directory for saving resources referenced by the result object.
- `--overwrite_resources`: overwrite existing files when saving resources.
- `--page_ranges`: page ranges such as `2,4-6`.
- `--use_doc_orientation_classify` / `--no-use_doc_orientation_classify`: enable or disable document orientation classification.
- `--use_doc_unwarping` / `--no-use_doc_unwarping`: enable or disable document unwarping.
- `--use_textline_orientation` / `--no-use_textline_orientation`: enable or disable textline orientation detection.
- `--use_doc_orientation_classify`: document orientation classification, `True` or `False`.
- `--use_doc_unwarping`: document unwarping, `True` or `False`.
- `--use_textline_orientation`: textline orientation detection, `True` or `False`.
- `--text_det_limit_side_len`: image side length limit for text detection.
- `--text_det_limit_type`: side length limit type, `min` or `max`.
- `--text_rec_score_thresh`: score threshold for text recognition results.
- `--use_layout_detection` / `--no-use_layout_detection`: enable or disable layout detection.
- `--use_seal_recognition` / `--no-use_seal_recognition`: enable or disable seal recognition.
- `--use_table_recognition` / `--no-use_table_recognition`: enable or disable table recognition.
- `--use_formula_recognition` / `--no-use_formula_recognition`: enable or disable formula recognition.
- `--use_chart_recognition` / `--no-use_chart_recognition`: enable or disable chart recognition.
- `--visualize` / `--no-visualize`: enable or disable result visualization images.
- `--prettify_markdown` / `--no-prettify_markdown`: enable or disable markdown prettification.
- `--use_layout_detection`: layout detection, `True` or `False`.
- `--use_seal_recognition`: seal recognition, `True` or `False`.
- `--use_table_recognition`: table recognition, `True` or `False`.
- `--use_formula_recognition`: formula recognition, `True` or `False`.
- `--use_chart_recognition`: chart recognition, `True` or `False`.
- `--visualize`: result visualization images, `True` or `False`.
- `--prettify_markdown`: markdown prettification, `True` or `False`.
## OCR Example
@@ -75,7 +75,7 @@ paddleocr api \
paddleocr api \
--model_type doc_parsing \
--file_url https://example.com/report.pdf \
--use_chart_recognition \
--use_chart_recognition True \
--save_resources ./doc-assets \
--output doc-result.json
```
@@ -43,19 +43,19 @@ paddleocr api \
- `--save_resources`:保存结果对象引用资源的目录。
- `--overwrite_resources`:保存资源时覆盖已有文件。
- `--page_ranges`:页码范围,例如 `2,4-6`。
- `--use_doc_orientation_classify` / `--no-use_doc_orientation_classify`:启用或禁用文档方向分类。
- `--use_doc_unwarping` / `--no-use_doc_unwarping`:启用或禁用文档扭曲矫正。
- `--use_textline_orientation` / `--no-use_textline_orientation`:启用或禁用文本行方向检测。
- `--use_doc_orientation_classify`:文档方向分类,`True` 或 `False`。
- `--use_doc_unwarping`:文档扭曲矫正,`True` 或 `False`。
- `--use_textline_orientation`:文本行方向检测,`True` 或 `False`。
- `--text_det_limit_side_len`:文本检测图像边长限制。
- `--text_det_limit_type`:边长限制类型,`min` 或 `max`。
- `--text_rec_score_thresh`:文本识别置信度阈值。
- `--use_layout_detection` / `--no-use_layout_detection`:启用或禁用版面检测。
- `--use_seal_recognition` / `--no-use_seal_recognition`:启用或禁用印章识别。
- `--use_table_recognition` / `--no-use_table_recognition`:启用或禁用表格识别。
- `--use_formula_recognition` / `--no-use_formula_recognition`:启用或禁用公式识别。
- `--use_chart_recognition` / `--no-use_chart_recognition`:启用或禁用图表识别。
- `--visualize` / `--no-visualize`:启用或禁用可视化结果图。
- `--prettify_markdown` / `--no-prettify_markdown`:启用或禁用 markdown 美化。
- `--use_layout_detection`:版面检测,`True` 或 `False`。
- `--use_seal_recognition`:印章识别,`True` 或 `False`。
- `--use_table_recognition`:表格识别,`True` 或 `False`。
- `--use_formula_recognition`:公式识别,`True` 或 `False`。
- `--use_chart_recognition`:图表识别,`True` 或 `False`。
- `--visualize`:可视化结果图,`True` 或 `False`。
- `--prettify_markdown`:markdown 美化,`True` 或 `False`。
## OCR 示例
@@ -75,7 +75,7 @@ paddleocr api \
paddleocr api \
--model_type doc_parsing \
--file_url https://example.com/report.pdf \
--use_chart_recognition \
--use_chart_recognition True \
--save_resources ./doc-assets \
--output doc-result.json
```
+9 -36
View File
@@ -10,7 +10,7 @@ PaddleOCR provides official Agent Skills that package the routing rules, calling
| Need | Recommended Skill | Output |
| --- | --- | --- |
| Extract plain text from images or PDFs | `paddleocr-text-recognition` | Plain text |
| Extract plain text from images or PDFs | `paddleocr-text-recognition` | line-level text with bounding boxes and confidence scores |
| Preserve headings, paragraphs, tables, formulas, and layout structure | `paddleocr-doc-parsing` | Markdown / structured output |
## Included Skills
@@ -25,9 +25,9 @@ Each skill currently supports the following underlying models:
## Prerequisites
1. Install Python 3.9 or later and [uv](https://docs.astral.sh/uv/) on the machine that runs the skill.
2. All scripts declare dependencies inline with [PEP 723](https://peps.python.org/pep-0723/), so `uv run` resolves them automatically.
3. The skills rely on PaddleOCR official APIs. Visit the [PaddleOCR website](https://www.paddleocr.com), click **API**, choose the model you need, and copy the `API_URL` and `Token`.
1. Install Python 3.9 or later on the machine that runs the skill.
2. Install PaddleOCR 3.6.0+: `pip install "paddleocr>=3.6.0"`
3. Get access token from [AI Studio](https://aistudio.baidu.com/account/accessToken)
## Install into AI Apps
@@ -79,8 +79,10 @@ After installation, configure the required environment variables so the skills c
| Skill | Required | Optional |
| --- | --- | --- |
| `paddleocr-text-recognition` | `PADDLEOCR_OCR_API_URL` (full endpoint URL ending with `/ocr`), `PADDLEOCR_ACCESS_TOKEN` (access token) | `PADDLEOCR_OCR_TIMEOUT` (API request timeout) |
| `paddleocr-doc-parsing` | `PADDLEOCR_DOC_PARSING_API_URL` (full endpoint URL ending with `/layout-parsing`), `PADDLEOCR_ACCESS_TOKEN` (access token) | `PADDLEOCR_DOC_PARSING_TIMEOUT` (API request timeout) |
| `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) |
Get access token: visit [AI Studio Access Token](https://aistudio.baidu.com/account/accessToken)
Examples for some AI apps:
@@ -89,9 +91,7 @@ Examples for some AI apps:
```json
{
"env": {
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>",
"PADDLEOCR_OCR_API_URL": "<OCR_API_URL>",
"PADDLEOCR_DOC_PARSING_API_URL": "<DOC_PARSING_API_URL>"
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>"
}
}
```
@@ -105,14 +105,12 @@ Examples for some AI apps:
"paddleocr-text-recognition": {
"enabled": true,
"env": {
"PADDLEOCR_OCR_API_URL": "<OCR_API_URL>",
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>"
}
},
"paddleocr-doc-parsing": {
"enabled": true,
"env": {
"PADDLEOCR_DOC_PARSING_API_URL": "<DOC_PARSING_API_URL>",
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>"
}
}
@@ -152,28 +150,3 @@ Local file example:
```text
Parse local file C:\docs\report.pdf and return complete structured output.
```
## Local Verification
This section shows how to run smoke tests locally to verify that the skill configuration works as expected.
> The examples below cover both skills. If you only need one, run only the corresponding commands.
Before running the commands, make sure your working directory is the directory that contains this document. All scripts declare inline dependencies, so `uv` resolves them automatically.
1. Configure environment variables as described in [Configure Environment Variables](#configure-environment-variables).
```shell
export PADDLEOCR_OCR_API_URL="<OCR_API_URL>"
export PADDLEOCR_ACCESS_TOKEN="<ACCESS_TOKEN>"
export PADDLEOCR_DOC_PARSING_API_URL="<DOC_PARSING_API_URL>"
```
2. Run the smoke test scripts.
```shell
cd paddleocr-text-recognition && uv run scripts/smoke_test.py && cd ..
cd paddleocr-doc-parsing && uv run scripts/smoke_test.py && cd ..
```
Use `--skip-api-test` to verify configuration only without making network requests. Use `--test-url "https://..."` to override the default sample document or image URL.
+9 -36
View File
@@ -10,7 +10,7 @@ PaddleOCR 提供官方 Agent Skills,将 OCR 与文档解析任务的触发规
| 需求 | 推荐 Skill | 输出 |
| --- | --- | --- |
| 只想提取图片或 PDF 中的纯文本 | `paddleocr-text-recognition` | 纯文本 |
| 只想提取图片或 PDF 中的纯文本 | `paddleocr-text-recognition` | 行级文本及对应边界框和置信度分数 |
| 需要保留标题、段落、表格、公式等文档结构 | `paddleocr-doc-parsing` | Markdown / 结构化结果 |
## 包含的 Skills
@@ -25,9 +25,9 @@ PaddleOCR 提供官方 Agent Skills,将 OCR 与文档解析任务的触发规
## 安装前准备
1. 请确保执行 Skill 的设备已安装 Python 3.9 或以上版本,以及 [uv](https://docs.astral.sh/uv/)。
2. 所有脚本均以 [PEP 723](https://peps.python.org/pep-0723/) 格式内联声明依赖,`uv run` 会自动解析依赖。
3. Skills 依赖 PaddleOCR 官方 API。请前往 [PaddleOCR 官网](https://www.paddleocr.com) 点击 **API**,选择对应模型后复制 `API_URL` 和 `Token`。
1. 请确保执行 Skill 的设备已安装 Python 3.9 或以上版本。
2. Skills 依赖 PaddleOCR 3.6.0+。请安装:`pip install "paddleocr>=3.6.0"`
3. 获取 access token:访问 [AI Studio Access Token 页面](https://aistudio.baidu.com/account/accessToken)
## 安装到 AI 应用
@@ -79,8 +79,10 @@ Skill 源码位于 `PaddleOCR/skills` 目录。请参考对应 AI 应用的安
| Skill | 必填 | 可选 |
| --- | --- | --- |
| `paddleocr-text-recognition` | `PADDLEOCR_OCR_API_URL`(完整端点 URL,须以 `/ocr` 结尾)、`PADDLEOCR_ACCESS_TOKEN`(access token) | `PADDLEOCR_OCR_TIMEOUT`(API 请求超时时间) |
| `paddleocr-doc-parsing` | `PADDLEOCR_DOC_PARSING_API_URL`(完整端点 URL,须以 `/layout-parsing` 结尾)、`PADDLEOCR_ACCESS_TOKEN`(access token) | `PADDLEOCR_DOC_PARSING_TIMEOUT`(API 请求超时时间) |
| `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,默认官方服务) |
获取 access token:访问 [AI Studio Access Token 页面](https://aistudio.baidu.com/account/accessToken)
部分 AI 应用的配置方式如下:
@@ -89,9 +91,7 @@ Skill 源码位于 `PaddleOCR/skills` 目录。请参考对应 AI 应用的安
```json
{
"env": {
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>",
"PADDLEOCR_OCR_API_URL": "<OCR_API_URL>",
"PADDLEOCR_DOC_PARSING_API_URL": "<DOC_PARSING_API_URL>"
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>"
}
}
```
@@ -105,14 +105,12 @@ Skill 源码位于 `PaddleOCR/skills` 目录。请参考对应 AI 应用的安
"paddleocr-text-recognition": {
"enabled": true,
"env": {
"PADDLEOCR_OCR_API_URL": "<OCR_API_URL>",
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>"
}
},
"paddleocr-doc-parsing": {
"enabled": true,
"env": {
"PADDLEOCR_DOC_PARSING_API_URL": "<DOC_PARSING_API_URL>",
"PADDLEOCR_ACCESS_TOKEN": "<ACCESS_TOKEN>"
}
}
@@ -152,28 +150,3 @@ Skill 源码位于 `PaddleOCR/skills` 目录。请参考对应 AI 应用的安
```text
解析本地文件 C:\docs\report.pdf,并返回完整结构化结果。
```
## 本地验证
本节介绍如何在本地运行冒烟测试,以验证 Skill 配置是否正常。
> 以下示例覆盖两个 Skill。如果只需使用其中一个,只执行对应命令即可。
执行前,请确保工作目录位于本文档所在目录。所有脚本均以内联依赖声明,`uv` 会自动解析,无需单独安装依赖。
1. 配置环境变量(见上文 [配置环境变量](#配置环境变量))。
```shell
export PADDLEOCR_OCR_API_URL="<OCR_API_URL>"
export PADDLEOCR_ACCESS_TOKEN="<ACCESS_TOKEN>"
export PADDLEOCR_DOC_PARSING_API_URL="<DOC_PARSING_API_URL>"
```
2. 运行冒烟测试脚本。
```shell
cd paddleocr-text-recognition && uv run scripts/smoke_test.py && cd ..
cd paddleocr-doc-parsing && uv run scripts/smoke_test.py && cd ..
```
使用 `--skip-api-test` 可只做配置检查(不发网络请求)。使用 `--test-url "https://..."` 可指定自定义测试文档或图片 URL。
+188
View File
@@ -0,0 +1,188 @@
# 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 json
import os
from typing import Any, Dict, Optional
import aiohttp
from ._core import (
extract_api_message_from_payload,
extract_job_id,
raise_for_status,
unwrap_api_response,
)
from .errors import (
NetworkError,
RequestTimeoutError,
ResponseFormatError,
ResultParseError,
)
from ._http import API_PATH, DEFAULT_BASE_URL
class AsyncHTTPClient:
def __init__(
self,
token: str,
base_url: str,
timeout: float,
client_platform: Optional[str] = None,
):
self._token = token
self._base_url = base_url.rstrip("/")
self._jobs_url = f"{self._base_url}{API_PATH}"
self._timeout = timeout
self._client_platform = client_platform
self._session = None
@property
def timeout(self) -> float:
return self._timeout
async def __aenter__(self):
await self._ensure_session()
return self
async def __aexit__(self, *args):
await self.close()
async def _ensure_session(self):
if self._session is None:
self._session = aiohttp.ClientSession(
headers=self._api_headers(),
timeout=aiohttp.ClientTimeout(total=self._timeout),
)
async def close(self):
if self._session:
await self._session.close()
self._session = None
def _api_headers(self) -> dict:
headers = {"Authorization": f"Bearer {self._token}"}
if self._client_platform:
headers["Client-Platform"] = self._client_platform
return headers
async def submit_url(
self,
model: str,
file_url: str,
optional_payload: dict,
page_ranges: Optional[str] = None,
batch_id: Optional[str] = None,
) -> str:
body = {
"fileUrl": file_url,
"model": model,
"optionalPayload": optional_payload,
}
if page_ranges is not None:
body["pageRanges"] = page_ranges
if batch_id is not None:
body["batchId"] = batch_id
await self._ensure_session()
async with self._session.post(
self._jobs_url,
json=body,
headers={"Content-Type": "application/json"},
) as resp:
await self._raise_for_response(resp)
data = await self._response_data(resp)
return extract_job_id(data)
async def submit_file(
self,
model: str,
file_path: str,
optional_payload: dict,
page_ranges: Optional[str] = None,
batch_id: Optional[str] = None,
) -> str:
if not os.path.exists(file_path):
raise FileNotFoundError(file_path)
form = aiohttp.FormData()
form.add_field("model", model)
form.add_field("optionalPayload", json.dumps(optional_payload))
if page_ranges is not None:
form.add_field("pageRanges", page_ranges)
if batch_id is not None:
form.add_field("batchId", batch_id)
with open(file_path, "rb") as f:
file_data = f.read()
form.add_field(
"file",
file_data,
filename=os.path.basename(file_path),
)
await self._ensure_session()
async with self._session.post(self._jobs_url, data=form) as resp:
await self._raise_for_response(resp)
data = await self._response_data(resp)
return extract_job_id(data)
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
await self._ensure_session()
async with self._session.get(f"{self._jobs_url}/{job_id}") as resp:
await self._raise_for_response(resp)
return await self._response_data(resp)
async def get_batch_status(self, batch_id: str) -> Dict[str, Any]:
await self._ensure_session()
async with self._session.get(f"{self._jobs_url}/batch/{batch_id}") as resp:
await self._raise_for_response(resp)
return await self._response_data(resp)
async def fetch_jsonl(self, url: str) -> list:
timeout = aiohttp.ClientTimeout(total=self._timeout)
async with aiohttp.ClientSession(timeout=timeout) as bare_session:
async with bare_session.get(url) as resp:
await self._raise_for_response(resp)
text = await resp.text()
try:
lines = text.strip().split("\n")
return [json.loads(line) for line in lines if line.strip()]
except json.JSONDecodeError as e:
raise ResultParseError(
f"Malformed JSONL result payload: {e}"
) from e
async def _raise_for_response(self, resp) -> None:
if 200 <= resp.status < 300:
return
try:
body = await resp.json()
msg = (
extract_api_message_from_payload(body)
if isinstance(body, dict)
else None
)
if not msg:
msg = await resp.text()
except Exception:
msg = await resp.text()
raise_for_status(resp.status, msg)
async def _response_data(self, resp) -> Dict[str, Any]:
try:
payload = await resp.json()
except Exception as e:
raise ResponseFormatError(f"Response body is not valid JSON: {e}") from e
return unwrap_api_response(payload, resp.status)
+86
View File
@@ -0,0 +1,86 @@
# 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 asyncio
from typing import Any
from ._core import (
job_status_from_data,
parse_batch_status,
validate_result_json_url,
validate_state,
)
from .errors import (
JobFailedError,
PollTimeoutError,
)
from .results import BatchStatus, JobStatus
DEFAULT_INITIAL_INTERVAL = 3.0
DEFAULT_MULTIPLIER = 1.5
DEFAULT_MAX_INTERVAL = 15.0
DEFAULT_MAX_WAIT_TIME = 600.0
class AsyncPoller:
def __init__(
self,
http_client,
initial_interval: float = DEFAULT_INITIAL_INTERVAL,
multiplier: float = DEFAULT_MULTIPLIER,
max_interval: float = DEFAULT_MAX_INTERVAL,
max_wait_time: float = DEFAULT_MAX_WAIT_TIME,
):
self._http = http_client
self._initial_interval = initial_interval
self._multiplier = multiplier
self._max_interval = max_interval
self._max_wait_time = max_wait_time
async def poll_until_done(self, job_id: str) -> Any:
interval = self._initial_interval
loop = asyncio.get_running_loop()
start = loop.time()
deadline = start + self._max_wait_time
while True:
now = loop.time()
if now >= deadline:
raise PollTimeoutError(job_id, now - start)
data = await self._http.get_job_status(job_id)
state = validate_state(data)
if state == "done":
json_url = validate_result_json_url(data)
jsonl_data = await self._http.fetch_jsonl(json_url)
return jsonl_data, data
if state == "failed":
error_msg = data.get("errorMsg", "Unknown error")
raise JobFailedError(job_id, error_msg)
remaining = deadline - loop.time()
if remaining <= 0:
raise PollTimeoutError(job_id, loop.time() - start)
await asyncio.sleep(min(interval, remaining))
interval = min(interval * self._multiplier, self._max_interval)
async def get_status(self, job_id: str) -> JobStatus:
data = await self._http.get_job_status(job_id)
return job_status_from_data(job_id, data)
async def get_batch_status(self, batch_id: str) -> BatchStatus:
data = await self._http.get_batch_status(batch_id)
return parse_batch_status(batch_id, data)
+42 -249
View File
@@ -13,63 +13,37 @@
# limitations under the License.
import asyncio
import contextlib
import json
import os
from typing import Optional, Union
import aiohttp
from ._core import (
default_payload,
extract_api_message_from_payload,
extract_job_id,
job_id_for_task,
job_status_from_data,
parse_batch_status,
raise_for_status,
resolve_document_model,
resolve_document_options,
resolve_ocr_model,
unwrap_api_response,
validate_input_source,
validate_result_json_url,
validate_state,
)
from .errors import (
APIError,
AuthError,
InvalidRequestError,
JobFailedError,
NetworkError,
PollTimeoutError,
RequestTimeoutError,
ResponseFormatError,
ResultParseError,
)
from .models import (
DocParsingOptions,
Model,
OCROptions,
)
from ._async_http import AsyncHTTPClient
from ._http import DEFAULT_BASE_URL
from ._async_poller import AsyncPoller
from ._poller import parse_doc_parsing_result, parse_ocr_result
from ._resources import (
save_document_parsing_result_resources,
save_ocr_result_resources,
save_resource,
)
from .results import BatchStatus, DocParsingResult, Job, JobStatus, OCRResult
from ._http import API_PATH, DEFAULT_BASE_URL
from ._poller import (
DEFAULT_INITIAL_INTERVAL,
DEFAULT_MAX_INTERVAL,
DEFAULT_MULTIPLIER,
parse_doc_parsing_result,
parse_ocr_result,
from .errors import AuthError
from .models import (
DocParsingOptions,
Model,
OCROptions,
)
from .results import BatchStatus, DocParsingResult, Job, JobStatus, OCRResult
class AsyncPaddleOCRClient:
"""Async client for PaddleOCR API using aiohttp.
"""Async client for PaddleOCR API.
Supports asyncio.gather for concurrent job submission and polling.
"""
@@ -91,66 +65,26 @@ class AsyncPaddleOCRClient:
resolved_base_url = (
base_url or os.environ.get("PADDLEOCR_BASE_URL") or DEFAULT_BASE_URL
)
self._base_url = resolved_base_url.rstrip("/")
self._jobs_url = f"{self._base_url}{API_PATH}"
if timeout is not None:
request_timeout = timeout
poll_timeout = timeout
self._request_timeout = request_timeout
self._poll_timeout = poll_timeout
self._client_platform = client_platform
self._session = None
self._http = AsyncHTTPClient(
self._token,
resolved_base_url,
request_timeout,
client_platform=client_platform,
)
self._poller = AsyncPoller(self._http, max_wait_time=poll_timeout)
async def __aenter__(self):
await self._ensure_session()
await self._http.__aenter__()
return self
async def __aexit__(self, *args):
await self.close()
async def _ensure_session(self):
if self._session is None:
self._session = aiohttp.ClientSession(
headers=self._api_headers(),
timeout=aiohttp.ClientTimeout(total=self._request_timeout),
)
await self._http.close()
async def close(self):
if self._session:
await self._session.close()
self._session = None
def _api_headers(self) -> dict:
headers = {"Authorization": f"Bearer {self._token}"}
if self._client_platform:
headers["Client-Platform"] = self._client_platform
return headers
@contextlib.asynccontextmanager
async def _request_scope(self):
"""Wraps an async block with unified error classification."""
try:
yield
except asyncio.TimeoutError as e:
raise RequestTimeoutError(f"Request timed out: {e}") from e
except Exception as e:
if isinstance(
e,
(
AuthError,
InvalidRequestError,
APIError,
FileNotFoundError,
RequestTimeoutError,
ResponseFormatError,
ResultParseError,
PollTimeoutError,
JobFailedError,
NetworkError,
),
):
raise
raise NetworkError(f"Connection failed: {e}") from e
await self._http.close()
async def ocr(
self,
@@ -170,7 +104,7 @@ class AsyncPaddleOCRClient:
page_ranges,
batch_id,
)
jsonl_data = await self._poll_until_done(job_id)
jsonl_data, _ = await self._poller.poll_until_done(job_id)
return parse_ocr_result(job_id, jsonl_data)
async def parse_document(
@@ -187,7 +121,7 @@ class AsyncPaddleOCRClient:
job_id = await self._submit(
model, file_url, file_path, options, page_ranges, batch_id
)
jsonl_data = await self._poll_until_done(job_id)
jsonl_data, _ = await self._poller.poll_until_done(job_id)
return parse_doc_parsing_result(job_id, jsonl_data)
async def submit_ocr(
@@ -226,15 +160,23 @@ class AsyncPaddleOCRClient:
)
return Job(job_id=job_id, model=model.value, task="document_parsing")
async def wait_ocr_result(self, job: Union[Job, str]) -> OCRResult:
job_id = job_id_for_task(job, "ocr")
jsonl_data, _ = await self._poller.poll_until_done(job_id)
return parse_ocr_result(job_id, jsonl_data)
async def wait_document_parsing_result(
self, job: Union[Job, str]
) -> DocParsingResult:
job_id = job_id_for_task(job, "document_parsing")
jsonl_data, _ = await self._poller.poll_until_done(job_id)
return parse_doc_parsing_result(job_id, jsonl_data)
async def get_status(self, job_id: str) -> JobStatus:
await self._ensure_session()
data = await self._get_job_status(job_id)
return job_status_from_data(job_id, data)
return await self._poller.get_status(job_id)
async def get_batch_status(self, batch_id: str) -> BatchStatus:
await self._ensure_session()
data = await self._get_batch_status(batch_id)
return parse_batch_status(batch_id, data)
return await self._poller.get_batch_status(batch_id)
async def save_resource(
self,
@@ -250,7 +192,7 @@ class AsyncPaddleOCRClient:
destination,
overwrite=overwrite,
filename=filename,
timeout=self._request_timeout,
timeout=self._http.timeout,
)
async def save_ocr_result_resources(
@@ -265,7 +207,7 @@ class AsyncPaddleOCRClient:
result,
destination,
overwrite=overwrite,
timeout=self._request_timeout,
timeout=self._http.timeout,
)
async def save_document_parsing_result_resources(
@@ -280,21 +222,9 @@ class AsyncPaddleOCRClient:
result,
destination,
overwrite=overwrite,
timeout=self._request_timeout,
timeout=self._http.timeout,
)
async def wait_ocr_result(self, job: Union[Job, str]) -> OCRResult:
job_id = job_id_for_task(job, "ocr")
jsonl_data = await self._poll_until_done(job_id)
return parse_ocr_result(job_id, jsonl_data)
async def wait_document_parsing_result(
self, job: Union[Job, str]
) -> DocParsingResult:
job_id = job_id_for_task(job, "document_parsing")
jsonl_data = await self._poll_until_done(job_id)
return parse_doc_parsing_result(job_id, jsonl_data)
async def _submit(
self,
model: Model,
@@ -305,156 +235,19 @@ class AsyncPaddleOCRClient:
batch_id: Optional[str],
) -> str:
validate_input_source(file_url, file_path)
await self._ensure_session()
payload = options.to_payload() if options else default_payload(model)
if file_url:
return await self._submit_url(
return await self._http.submit_url(
model.value,
file_url,
payload,
page_ranges=page_ranges,
batch_id=batch_id,
)
return await self._submit_file(
return await self._http.submit_file(
model.value,
file_path,
payload,
page_ranges=page_ranges,
batch_id=batch_id,
)
async def _submit_url(
self,
model: str,
file_url: str,
payload: dict,
page_ranges: Optional[str] = None,
batch_id: Optional[str] = None,
) -> str:
body = {
"fileUrl": file_url,
"model": model,
"optionalPayload": payload,
}
if page_ranges is not None:
body["pageRanges"] = page_ranges
if batch_id is not None:
body["batchId"] = batch_id
async with self._request_scope():
async with self._session.post(
self._jobs_url,
json=body,
headers={"Content-Type": "application/json"},
) as resp:
await self._raise_for_response(resp)
data = await self._response_data(resp)
return extract_job_id(data)
async def _submit_file(
self,
model: str,
file_path: str,
payload: dict,
page_ranges: Optional[str] = None,
batch_id: Optional[str] = None,
) -> str:
if not os.path.exists(file_path):
raise FileNotFoundError(file_path)
form = aiohttp.FormData()
form.add_field("model", model)
form.add_field("optionalPayload", json.dumps(payload))
if page_ranges is not None:
form.add_field("pageRanges", page_ranges)
if batch_id is not None:
form.add_field("batchId", batch_id)
with open(file_path, "rb") as f:
file_data = f.read()
form.add_field(
"file",
file_data,
filename=os.path.basename(file_path),
)
async with self._request_scope():
async with self._session.post(self._jobs_url, data=form) as resp:
await self._raise_for_response(resp)
data = await self._response_data(resp)
return extract_job_id(data)
async def _get_job_status(self, job_id: str) -> dict:
async with self._request_scope():
async with self._session.get(f"{self._jobs_url}/{job_id}") as resp:
await self._raise_for_response(resp)
return await self._response_data(resp)
async def _get_batch_status(self, batch_id: str) -> dict:
async with self._request_scope():
async with self._session.get(f"{self._jobs_url}/batch/{batch_id}") as resp:
await self._raise_for_response(resp)
return await self._response_data(resp)
async def _fetch_jsonl(self, url: str) -> list:
async with self._request_scope():
timeout = aiohttp.ClientTimeout(total=self._request_timeout)
async with aiohttp.ClientSession(timeout=timeout) as bare_session:
async with bare_session.get(url) as resp:
await self._raise_for_response(resp)
text = await resp.text()
try:
lines = text.strip().split("\n")
return [json.loads(line) for line in lines if line.strip()]
except json.JSONDecodeError as e:
raise ResultParseError(
f"Malformed JSONL result payload: {e}"
) from e
async def _poll_until_done(self, job_id: str) -> list:
interval = DEFAULT_INITIAL_INTERVAL
loop = asyncio.get_running_loop()
start = loop.time()
deadline = start + self._poll_timeout
while True:
now = loop.time()
if now >= deadline:
raise PollTimeoutError(job_id, now - start)
data = await self._get_job_status(job_id)
state = validate_state(data)
if state == "done":
json_url = validate_result_json_url(data)
return await self._fetch_jsonl(json_url)
if state == "failed":
error_msg = data.get("errorMsg", "Unknown error")
raise JobFailedError(job_id, error_msg)
remaining = deadline - loop.time()
if remaining <= 0:
raise PollTimeoutError(job_id, loop.time() - start)
await asyncio.sleep(min(interval, remaining))
interval = min(interval * DEFAULT_MULTIPLIER, DEFAULT_MAX_INTERVAL)
async def _raise_for_response(self, resp) -> None:
if 200 <= resp.status < 300:
return
try:
body = await resp.json()
msg = (
extract_api_message_from_payload(body)
if isinstance(body, dict)
else None
)
if not msg:
msg = await resp.text()
except Exception:
msg = await resp.text()
raise_for_status(resp.status, msg)
async def _response_data(self, resp) -> dict:
try:
payload = await resp.json()
except Exception as e:
raise ResponseFormatError(f"Response body is not valid JSON: {e}") from e
return unwrap_api_response(payload, resp.status)
+21 -21
View File
@@ -12,10 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import sys
from .._utils.cli import str2bool
from .client import PaddleOCRClient
from .models import (
Model,
@@ -121,22 +121,22 @@ def register_api_command(subparsers):
# --- Preprocessing ---
subparser.add_argument(
"--use_doc_orientation_classify",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable document orientation classification",
help="Enable document orientation classification (True/False)",
)
subparser.add_argument(
"--use_doc_unwarping",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable document unwarping",
help="Enable document unwarping (True/False)",
)
# --- Text detection ---
subparser.add_argument(
"--use_textline_orientation",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable textline orientation detection (OCR only)",
help="Enable textline orientation detection for OCR (True/False)",
)
subparser.add_argument(
"--text_det_limit_side_len",
@@ -161,46 +161,46 @@ def register_api_command(subparsers):
# --- Layout and feature toggles (doc_parsing only) ---
subparser.add_argument(
"--use_layout_detection",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable layout detection (doc_parsing only)",
help="Enable layout detection for document parsing (True/False)",
)
subparser.add_argument(
"--use_seal_recognition",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable seal recognition (doc_parsing only)",
help="Enable seal recognition for document parsing (True/False)",
)
subparser.add_argument(
"--use_table_recognition",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable table recognition (PP-StructureV3 only)",
help="Enable table recognition for PP-StructureV3 (True/False)",
)
subparser.add_argument(
"--use_formula_recognition",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable formula recognition (PP-StructureV3 only)",
help="Enable formula recognition for PP-StructureV3 (True/False)",
)
subparser.add_argument(
"--use_chart_recognition",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable chart recognition (doc_parsing only)",
help="Enable chart recognition for document parsing (True/False)",
)
# --- Output ---
subparser.add_argument(
"--visualize",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable result visualization images",
help="Enable result visualization images (True/False)",
)
subparser.add_argument(
"--prettify_markdown",
action=argparse.BooleanOptionalAction,
type=str2bool,
default=None,
help="Enable/disable markdown prettification (doc_parsing only)",
help="Enable markdown prettification for document parsing (True/False)",
)
subparser.set_defaults(executor=_execute_api)
+78 -252
View File
@@ -8,26 +8,26 @@ description: >-
发票, 财报, 复杂 PDF, PDF转Markdown, 图表, 阅读顺序; reading order, formula, LaTeX,
layout parsing, structure extraction, PP-StructureV3, PaddleOCR-VL.
license: Apache-2.0
compatibility: Requires uv and internet access.
compatibility: Requires paddleocr>=3.6.0
metadata:
openclaw:
requires:
env:
- PADDLEOCR_DOC_PARSING_API_URL
- PADDLEOCR_ACCESS_TOKEN
bins:
- uv
- paddleocr
primaryEnv: PADDLEOCR_ACCESS_TOKEN
emoji: "📄"
homepage: https://github.com/PaddlePaddle/PaddleOCR/tree/main/skills/paddleocr-doc-parsing
install:
- kind: uv
package: paddleocr
bins: [paddleocr]
---
# PaddleOCR Document Parsing Skill
# PaddleOCR Document Parsing
## When to Use This Skill
**Trigger keywords (routing)**: Bilingual trigger terms (Chinese and English) are listed in the YAML `description` above—use that field for discovery and routing.
**Use this skill for**:
- Documents with tables (invoices, financial reports, spreadsheets)
@@ -35,281 +35,107 @@ metadata:
- Documents with charts and diagrams
- Multi-column layouts (newspapers, magazines, brochures)
- Complex document structures requiring layout analysis
- Any document requiring structured understanding
**Do not use for**:
## Usage
- Simple text-only extraction
- Quick OCR tasks where speed is critical
- Screenshots or simple images with clear text
### Basic Document Parsing
## Installation
Scripts declare their dependencies inline ([PEP 723](https://peps.python.org/pep-0723/)). No separate install step is needed — [uv](https://docs.astral.sh/uv/) resolves dependencies automatically:
From URL:
```bash
uv run scripts/layout_caller.py --help
paddleocr api \
--model_type doc_parsing \
--file_url "https://example.com/report.pdf"
```
## How to Use This Skill
> **Working directory**: All `uv run scripts/...` commands below should be run from this skill's root directory (the directory containing this SKILL.md file).
### Basic Workflow
1. **Identify the input source**:
- User provides URL: Use the `--file-url` parameter
- User provides local file path: Use the `--file-path` parameter
2. **Execute document parsing**:
```bash
uv run scripts/layout_caller.py --file-url "URL provided by user" --pretty
```
Or for local files:
```bash
uv run scripts/layout_caller.py --file-path "file path" --pretty
```
**Optional: explicitly set file type**:
```bash
uv run scripts/layout_caller.py --file-url "URL provided by user" --file-type 0 --pretty
```
- `--file-type 0`: PDF
- `--file-type 1`: image
- If omitted, the type is auto-detected from the file extension. For local files, a recognized extension (`.pdf`, `.png`, `.jpg`, `.jpeg`, `.bmp`, `.tiff`, `.tif`, `.webp`) is required; otherwise pass `--file-type` explicitly. For URLs with unrecognized extensions, the service attempts inference.
> **Performance note**: Parsing time scales with document complexity. Single-page images typically complete in 1-5 seconds; large PDFs (50+ pages) may take several minutes. Allow adequate time before assuming a timeout.
**Default behavior: save raw JSON to a temp file**:
- If `--output` is omitted, the script saves automatically under the system temp directory
- Default path pattern: `<system-temp>/paddleocr/doc-parsing/results/result_<timestamp>_<id>.json`
- If `--output` is provided, it overrides the default temp-file destination
- If `--stdout` is provided, JSON is printed to stdout and no file is saved
- In save mode, the script prints the absolute saved path on stderr: `Result saved to: /absolute/path/...`
- In default/custom save mode, read and parse the saved JSON file before responding
- Use `--stdout` only when you explicitly want to skip file persistence
3. **Parse JSON response**:
- Check the `ok` field: `true` means success, `false` means error
- The output contains complete document data: text, tables, formulas (LaTeX), figures, seals, headers/footers, and reading order
- Use the appropriate field based on what the user needs:
- `text` — full document text across all pages
- `result.result.layoutParsingResults[n].markdown.text` — page-level markdown
- `result.result.layoutParsingResults[n].prunedResult` — structured layout data with positions and confidence
- Handle errors: If `ok` is false, display `error.message`
4. **Present results to user**:
- Display content based on what the user requested (see "Complete Output Display" below)
- If the content is empty, the document may contain no extractable text
- In save mode, always tell the user the saved file path and that full raw JSON is available there
### What to Do After Parsing
Common next steps once you have the structured output:
- **Save as Markdown**: Write the `text` field to a `.md` file — tables, headings, and formulas are preserved
- **Extract specific tables**: Navigate `result.result.layoutParsingResults[n].prunedResult` to access individual layout elements with position and confidence data
- **Feed to RAG / search pipeline**: The `text` field is structured markdown, ready for chunking and indexing
- **Poor results**: See "Tips for Better Results" below before retrying
### Complete Output Display
Display the COMPLETE extracted content based on what the user asked for. The parsed output is only useful if the user receives all of it — truncation silently drops data.
- If user asks for "all text", show the entire `text` field
- If user asks for "tables", show ALL tables in the document
- If user asks for "main content", filter out headers/footers but show ALL body text
- Do not truncate with "..." unless content is excessively long (>10,000 chars)
- Do not say "Here's a preview" when user expects complete output
**Example - Correct**:
```
User: "Extract all the text from this document"
Agent: I've parsed the complete document. Here's all the extracted text:
[Display entire text field or concatenated regions in reading order]
Document Statistics:
- Total regions: 25
- Text blocks: 15
- Tables: 3
- Formulas: 2
Quality: Excellent (confidence: 0.92)
```
**Example - Incorrect**:
```
User: "Extract all the text"
Agent: "I found a document with multiple sections. Here's the beginning:
'Introduction...' (content truncated for brevity)"
```
### Understanding the Output
The script returns an envelope with `ok`, `text`, `result`, and `error`. Use `text` for the full document content; navigate `result.result.layoutParsingResults[n]` for per-page structured data.
For the complete schema and field-level details, see `references/output_schema.md`.
> Raw result location (default): the temp-file path printed by the script on stderr
### Usage Examples
**Example 1: Extract Full Document Text**
From local file:
```bash
uv run scripts/layout_caller.py \
--file-url "https://example.com/paper.pdf" \
--pretty
paddleocr api \
--model_type doc_parsing \
--file_path "./document.pdf"
```
Then use:
### With Specific Model
- Top-level `text` for quick full-text output
- `result.result.layoutParsingResults[n].markdown` when page-level output is needed
**Example 2: Extract Structured Page Data**
PP-StructureV3:
```bash
uv run scripts/layout_caller.py \
--file-path "./financial_report.pdf" \
--pretty
paddleocr api \
--model_type doc_parsing \
--model PP-StructureV3 \
--file_path "./report.pdf"
```
Then use:
- `result.result.layoutParsingResults[n].prunedResult` for structured parsing data (layout/content/confidence)
**Example 3: Print JSON to stdout (without saving to file)**
PaddleOCR-VL-1.6:
```bash
uv run scripts/layout_caller.py \
--file-url "URL" \
--stdout \
--pretty
paddleocr api \
--model_type doc_parsing \
--model PaddleOCR-VL-1.6 \
--file_url "https://..."
```
By default the script writes JSON to a temp file and prints the path to stderr. Add `--stdout` to print the full JSON directly to stdout instead. Use this when you need to inspect the result inline or pipe it to another tool.
### Common Options
### First-Time Configuration
```bash
# With page ranges
paddleocr api \
--model_type doc_parsing \
--file_path "./large.pdf" \
--page_ranges "1-5,10,15-20"
**When API is not configured**, the script outputs:
# Save result and resources
paddleocr api \
--model_type doc_parsing \
--file_url "https://..." \
--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 \
--file_path "./document.pdf" \
--prettify_markdown True
```
### Output Format
```json
{
"ok": false,
"text": "",
"result": null,
"error": {
"code": "CONFIG_ERROR",
"message": "PADDLEOCR_DOC_PARSING_API_URL not configured. Get your API at: https://paddleocr.com"
}
"jobId": "job-xxx",
"pages": [
{
"markdownText": "# Title\n\nContent...",
"markdownImages": {
"img1": "https://...",
"img2": "https://..."
},
"outputImages": {
"layout1": "https://..."
}
}
]
}
```
**Configuration workflow**:
## Important Notes
1. **Show the exact error message** to the user.
**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.
2. **Guide the user to obtain credentials**: Visit the [PaddleOCR website](https://www.paddleocr.com), click **API**, select a model (`PP-StructureV3`, or `PaddleOCR-VL` series models), then copy the `API_URL` and `Token`. They map to these environment variables:
- `PADDLEOCR_DOC_PARSING_API_URL` — full endpoint URL ending with `/layout-parsing`
- `PADDLEOCR_ACCESS_TOKEN` — 40-character alphanumeric string
**Handle errors gracefully**: When the CLI returns an error, inform the user of the specific issue rather than silently failing. Common errors:
- Authentication: `PADDLEOCR_ACCESS_TOKEN` invalid or missing
- Quota: API rate limit exceeded
- No content detected: Document may be blank or contain no extractable text
Optionally configure `PADDLEOCR_DOC_PARSING_TIMEOUT` for request timeout. Recommend using the host application's standard configuration method rather than pasting credentials in chat.
## CLI Reference
3. **Apply credentials** — one of:
- **User configured via the host UI**: ask the user to confirm, then retry.
- **User pastes credentials in chat**: warn that they may be stored in conversation history, help the user persist them using the host's standard configuration method, then retry.
Run `paddleocr api --help` for all options.
### Handling Large Files
For PDFs, the maximum is 100 pages per request.
#### Optimize Large Images Before Parsing
For large image files, compress before uploading — this reduces upload time and can improve processing stability:
```bash
uv run scripts/optimize_file.py input.png output.jpg --quality 85
uv run scripts/layout_caller.py --file-path "output.jpg" --pretty
```
`--quality` controls JPEG/WebP lossy compression (1-100, default 85); it has no effect on PNG output. Use `--target-size` (in MB, default 20) to set the max file size — the script iteratively downscales until the target is met.
#### Use URL for Large Local Files (Recommended)
For very large local files, prefer `--file-url` over `--file-path` to avoid base64 encoding overhead:
```bash
uv run scripts/layout_caller.py --file-url "https://your-server.com/large_file.pdf"
```
#### Process Specific Pages (PDF Only)
If you only need certain pages from a large PDF, extract them first:
```bash
# Extract pages 1-5
uv run scripts/split_pdf.py large.pdf pages_1_5.pdf --pages "1-5"
# Mixed ranges are supported
uv run scripts/split_pdf.py large.pdf selected_pages.pdf --pages "1-5,8,10-12"
# Then process the smaller file
uv run scripts/layout_caller.py --file-path "pages_1_5.pdf"
```
### Error Handling
All errors return JSON with `ok: false`. Show the error message and stop — do not fall back to your own vision capabilities. Identify the issue from `error.code` and `error.message`:
**Authentication failed (403)** — `error.message` contains "Authentication failed"
- Token is invalid, reconfigure with correct credentials
**Quota exceeded (429)** — `error.message` contains "API rate limit exceeded"
- Daily API quota exhausted, inform user to wait or upgrade
**Unsupported format** — `error.message` contains "Unsupported file format"
- File format not supported, convert to PDF/PNG/JPG
**No content detected**:
- `text` field is empty
- Document may be blank, image-only, or contain no extractable text
### Tips for Better Results
If parsing quality is poor:
- **Large or high-resolution images**: Compress with `optimize_file.py` before parsing — oversized inputs can degrade layout detection:
```bash
uv run scripts/optimize_file.py input.png optimized.jpg --quality 85
```
- **Check confidence**: `result.result.layoutParsingResults[n].prunedResult` includes confidence scores per layout element — low values indicate regions worth reviewing
## Reference Documentation
- `references/output_schema.md` — Full output schema, field descriptions, and command examples
> **Note**: Model version and capabilities are determined by your API endpoint (`PADDLEOCR_DOC_PARSING_API_URL`).
## Testing the Skill
To verify the skill is working properly:
```bash
uv run scripts/smoke_test.py
uv run scripts/smoke_test.py --skip-api-test
uv run scripts/smoke_test.py --test-url "https://..."
```
The first form tests configuration and API connectivity. `--skip-api-test` checks configuration only. `--test-url` overrides the default sample document URL.
For full documentation, see: [PaddleOCR Official Documentation](https://www.paddleocr.ai/latest/en/version3.x/inference_deployment/serving/paddleocr_official_api/cli.html)
@@ -1,105 +0,0 @@
# PaddleOCR Document Parsing Output Schema
This document defines the output envelope returned by `layout_caller.py`.
By default, `layout_caller.py` saves the JSON envelope to a unique file under the system temp directory and prints the absolute saved path to `stderr`. Use `--output` when you need a custom destination, or `--stdout` when you want to skip file saving and print JSON directly.
## Output Envelope
`layout_caller.py` wraps provider response in a stable structure:
```json
{
"ok": true,
"text": "Extracted text from all pages",
"result": { ... }, // raw provider response
"error": null
}
```
On error:
```json
{
"ok": false,
"text": "",
"result": null,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable message"
}
}
```
## Error Codes
| Code | Description |
| -------------- | --------------------------------------------------------------------------- |
| `INPUT_ERROR` | Invalid or unusable input (arguments, file source, format, types). |
| `CONFIG_ERROR` | Missing or invalid API / client configuration. |
| `API_ERROR` | Request or response handling failed (network, HTTP, body parsing, schema). |
## Raw Result Notes
The `result` field contains raw provider output.
Raw fields may vary by model version and endpoint.
## Raw Result Example
```json
{
"logId": "request-uuid",
"errorCode": 0,
"errorMsg": "Success",
"result": {
"layoutParsingResults": [
{
"prunedResult": { ... }, // layout elements with position/content/confidence information
"markdown": {
"text": "Full page content in markdown/HTML format",
"images": {
"imgs/filename.jpg": "https://..."
},
"...": "other model-specific fields"
}
}
]
}
}
```
## Important Fields
Paths are relative to the output envelope root.
- `result.result.layoutParsingResults[n].prunedResult`
Structured parsing data for page `n` (layout elements, locations, content, confidence, and related metadata).
- `result.result.layoutParsingResults[n].markdown`
Rendered output for page `n`.
- `result.result.layoutParsingResults[n].markdown.text`
Full page markdown text.
## Text Extraction
`layout_caller.py` extracts top-level `text` from `result.result.layoutParsingResults[n].markdown.text` and joins pages with `\n\n`.
## Command Examples
```bash
# Parse document from URL (result auto-saves to the system temp directory)
uv run scripts/layout_caller.py --file-url "URL" --pretty
# Parse local file (result auto-saves to the system temp directory)
uv run scripts/layout_caller.py --file-path "doc.pdf" --pretty
# Parse with explicit file type
uv run scripts/layout_caller.py --file-url "URL" --file-type 1 --pretty
# Save result to a custom file path
uv run scripts/layout_caller.py --file-url "URL" --output "./result.json" --pretty
# Print JSON to stdout without saving a file
uv run scripts/layout_caller.py --file-url "URL" --stdout --pretty
```
@@ -1,150 +0,0 @@
"""
PaddleOCR Document Parser
Simple CLI wrapper for the PaddleOCR document parsing library.
Usage:
uv run scripts/layout_caller.py --file-url "URL"
uv run scripts/layout_caller.py --file-path "document.pdf"
uv run scripts/layout_caller.py --file-path "doc.pdf" --pretty
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "httpx>=0.24.0",
# ]
# ///
import argparse
import io
import json
import sys
import tempfile
import uuid
from datetime import datetime
from pathlib import Path
from typing import Optional
# Fix Windows console encoding
if sys.platform == "win32":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
# Add scripts dir to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from lib import parse_document
def get_default_output_path() -> Path:
"""Build a unique result path under the OS temp directory."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
short_id = uuid.uuid4().hex[:8]
return (
Path(tempfile.gettempdir())
/ "paddleocr"
/ "doc-parsing"
/ "results"
/ f"result_{timestamp}_{short_id}.json"
)
def resolve_output_path(output_arg: Optional[str]) -> Path:
if output_arg:
return Path(output_arg).expanduser().resolve()
return get_default_output_path().resolve()
def main() -> None:
parser = argparse.ArgumentParser(
description="PaddleOCR Document Parsing - with layout analysis",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Parse document from URL (result is auto-saved to the system temp directory)
uv run scripts/layout_caller.py --file-url "https://example.com/document.pdf"
# Parse local file (result is auto-saved to the system temp directory)
uv run scripts/layout_caller.py --file-path "./invoice.pdf"
# Save result to a custom file path
uv run scripts/layout_caller.py --file-url "URL" --output "./result.json" --pretty
# Print JSON to stdout without saving a file
uv run scripts/layout_caller.py --file-url "URL" --stdout --pretty
Exit codes:
0 Success (ok=true in JSON output)
1 Parse or API error (ok=false in JSON output; see error.code and error.message)
5 Cannot write result to output file
Configuration:
Set environment variables: PADDLEOCR_DOC_PARSING_API_URL, PADDLEOCR_ACCESS_TOKEN
Optional: PADDLEOCR_DOC_PARSING_TIMEOUT
""",
)
input_group = parser.add_mutually_exclusive_group(required=True)
input_group.add_argument("--file-url", help="URL to document (PDF, PNG, JPG, etc.)")
input_group.add_argument("--file-path", help="Local file path")
# Optional input options
parser.add_argument(
"--file-type",
type=int,
choices=[0, 1],
help="Optional file type override (0=PDF, 1=Image)",
)
# Output options
parser.add_argument(
"--pretty", action="store_true", help="Pretty-print JSON output"
)
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument(
"--output",
"-o",
metavar="FILE",
help="Save result to JSON file (default: auto-save to system temp directory)",
)
output_group.add_argument(
"--stdout",
action="store_true",
help="Print JSON to stdout instead of saving to a file",
)
args = parser.parse_args()
# Unwarping and orientation classification are off to cover common scenarios
# with faster response times; visualize is off to reduce response payload.
result = parse_document(
file_path=args.file_path,
file_url=args.file_url,
file_type=args.file_type,
useDocUnwarping=False,
useDocOrientationClassify=False,
visualize=False,
)
indent = 2 if args.pretty else None
json_output = json.dumps(result, indent=indent, ensure_ascii=False)
if args.stdout:
print(json_output)
else:
output_path = resolve_output_path(args.output)
try:
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json_output, encoding="utf-8")
print(f"Result saved to: {output_path}", file=sys.stderr)
except (PermissionError, OSError) as e:
print(f"Error: Cannot write to {output_path}: {e}", file=sys.stderr)
sys.exit(5)
sys.exit(0 if result.get("ok") else 1)
if __name__ == "__main__":
main()
-387
View File
@@ -1,387 +0,0 @@
"""
PaddleOCR Document Parsing Library
Simple document parsing API wrapper for PaddleOCR.
"""
import base64
import logging
import math
import os
from pathlib import Path
from typing import Any, Optional
from urllib.parse import unquote, urlparse
import httpx
logger = logging.getLogger(__name__)
# =============================================================================
# Constants
# =============================================================================
DEFAULT_TIMEOUT = 600 # seconds (10 minutes)
API_GUIDE_URL = "https://paddleocr.com"
FILE_TYPE_PDF = 0
FILE_TYPE_IMAGE = 1
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif", ".webp")
# =============================================================================
# Environment
# =============================================================================
def _get_env(key: str) -> str:
"""Get environment variable, defaulting to empty string with whitespace stripped."""
return os.getenv(key, "").strip()
def _http_timeout_from_env(env_key: str, default_seconds: float) -> float:
"""
Read HTTP client timeout in seconds from the environment.
Returns a positive finite float. If the variable is missing, empty,
unparsable, non-finite, or not greater than zero, logs a warning and uses the
default_seconds argument value.
"""
raw = os.getenv(env_key)
if raw is None:
return float(default_seconds)
stripped = raw.strip()
if not stripped:
return float(default_seconds)
try:
timeout = float(stripped)
except (ValueError, TypeError):
logger.warning(
"Invalid %s value %r; using default %ss",
env_key,
raw,
default_seconds,
)
return float(default_seconds)
if not math.isfinite(timeout) or timeout <= 0:
logger.warning(
"%s must be a finite number > 0 (got %r); using default %ss",
env_key,
raw,
default_seconds,
)
return float(default_seconds)
return timeout
def _resolve_api_url(api_url: str, env_var: str) -> str:
"""Require https; allow host-only values by prepending https://."""
if api_url.startswith("http://"):
raise ValueError(f"{env_var} must use https://; http:// is not allowed.")
if not api_url.startswith("https://"):
return f"https://{api_url}"
return api_url
def get_config() -> tuple[str, str]:
"""
Get API URL and token from environment.
Returns:
tuple of (api_url, token)
Raises:
ValueError: If required env vars are missing, API URL uses http://,
or URL path doesn't end with /layout-parsing
"""
api_url = _get_env("PADDLEOCR_DOC_PARSING_API_URL")
token = _get_env("PADDLEOCR_ACCESS_TOKEN")
if not api_url:
raise ValueError(
f"PADDLEOCR_DOC_PARSING_API_URL not configured. Get your API at: {API_GUIDE_URL}"
)
if not token:
raise ValueError(
f"PADDLEOCR_ACCESS_TOKEN not configured. Get your API at: {API_GUIDE_URL}"
)
api_url = _resolve_api_url(api_url, "PADDLEOCR_DOC_PARSING_API_URL")
api_path = urlparse(api_url).path.rstrip("/")
if not api_path.endswith("/layout-parsing"):
raise ValueError(
"PADDLEOCR_DOC_PARSING_API_URL must be a full endpoint ending with "
"/layout-parsing. "
"Example: https://your-service.paddleocr.com/layout-parsing"
)
return api_url, token
# =============================================================================
# File Utilities
# =============================================================================
def _detect_file_type(path_or_url: str) -> int:
"""Detect file type: 0=PDF, 1=Image."""
path = path_or_url.lower()
if path.startswith(("http://", "https://")):
path = unquote(urlparse(path).path)
if path.endswith(".pdf"):
return FILE_TYPE_PDF
elif path.endswith(IMAGE_EXTENSIONS):
return FILE_TYPE_IMAGE
else:
raise ValueError(f"Unsupported file format: {path_or_url}")
def _load_file_as_base64(file_path: str) -> str:
"""Load local file and encode as base64."""
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
if path.stat().st_size == 0:
raise ValueError(f"File is empty (0 bytes): {file_path}")
return base64.b64encode(path.read_bytes()).decode("utf-8")
# =============================================================================
# API Request
# =============================================================================
def _make_api_request(
api_url: str, token: str, params: dict[str, Any]
) -> dict[str, Any]:
"""
Make PaddleOCR document parsing API request.
Args:
api_url: API endpoint URL
token: Access token
params: Request parameters
Returns:
API response dict
Raises:
RuntimeError: On API errors
"""
headers = {
"Authorization": f"token {token}",
"Content-Type": "application/json",
"Client-Platform": "official-skill",
}
timeout = _http_timeout_from_env(
"PADDLEOCR_DOC_PARSING_TIMEOUT", float(DEFAULT_TIMEOUT)
)
try:
with httpx.Client(timeout=timeout) as client:
try:
resp = client.post(api_url, json=params, headers=headers)
except TypeError as e:
raise RuntimeError(
"Request parameters cannot be JSON-encoded; use only JSON-serializable "
f"option values ({e})"
) from e
except httpx.TimeoutException:
raise RuntimeError(f"API request timed out after {timeout}s")
except httpx.RequestError as e:
raise RuntimeError(f"API request failed: {e}")
if resp.status_code != 200:
error_detail = ""
try:
error_body = resp.json()
if isinstance(error_body, dict):
error_detail = str(error_body.get("errorMsg", "")).strip()
except Exception:
pass
if not error_detail:
error_detail = (resp.text[:200] or "No response body").strip()
if resp.status_code == 403:
raise RuntimeError(f"Authentication failed (403): {error_detail}")
elif resp.status_code == 429:
raise RuntimeError(f"API rate limit exceeded (429): {error_detail}")
elif resp.status_code >= 500:
raise RuntimeError(
f"API service error ({resp.status_code}): {error_detail}"
)
else:
raise RuntimeError(f"API error ({resp.status_code}): {error_detail}")
try:
result = resp.json()
except Exception:
raise RuntimeError(f"Invalid JSON response: {resp.text[:200]}")
if not isinstance(result, dict):
raise RuntimeError(
f"Unexpected JSON shape (expected object): {resp.text[:200]}"
)
if result.get("errorCode", 0) != 0:
msg = result.get("errorMsg", "Unknown error")
raise RuntimeError(f"API error: {msg}")
return result
# =============================================================================
# Main API
# =============================================================================
def parse_document(
file_path: Optional[str] = None,
file_url: Optional[str] = None,
file_type: Optional[int] = None,
**options: Any,
) -> dict[str, Any]:
"""
Parse document with PaddleOCR.
Args:
file_path: Local file path (mutually exclusive with file_url)
file_url: URL to file (mutually exclusive with file_path)
file_type: Optional file type override (0=PDF, 1=Image)
**options: Additional API options
Returns:
{
"ok": True,
"text": "extracted text...",
"result": { raw API result },
"error": None
}
or on error:
{
"ok": False,
"text": "",
"result": None,
"error": {"code": "...", "message": "..."}
}
"""
if file_path is not None and not isinstance(file_path, str):
return _error("INPUT_ERROR", "file_path must be a string or None")
if file_url is not None and not isinstance(file_url, str):
return _error("INPUT_ERROR", "file_url must be a string or None")
fp = file_path.strip() if file_path else ""
fu = file_url.strip() if file_url else ""
if fp and fu:
return _error(
"INPUT_ERROR",
"Provide only one of file_path or file_url, not both",
)
if not fp and not fu:
return _error("INPUT_ERROR", "file_path or file_url required")
if file_type is not None and file_type not in (FILE_TYPE_PDF, FILE_TYPE_IMAGE):
return _error("INPUT_ERROR", "file_type must be 0 (PDF) or 1 (Image)")
try:
api_url, token = get_config()
except ValueError as e:
return _error("CONFIG_ERROR", str(e))
# Build request params
try:
resolved_file_type: Optional[int] = None
if fu:
params = {"file": fu}
if file_type is not None:
resolved_file_type = file_type
else:
try:
resolved_file_type = _detect_file_type(fu)
except ValueError:
resolved_file_type = None
else:
resolved_file_type = (
file_type if file_type is not None else _detect_file_type(fp)
)
params = {
"file": _load_file_as_base64(fp),
}
params["visualize"] = (
False # reduce response payload; callers can override via options
)
params.update(options)
if resolved_file_type is not None:
params["fileType"] = resolved_file_type
else:
params.pop("fileType", None)
except (ValueError, OSError, MemoryError) as e:
return _error("INPUT_ERROR", str(e))
try:
result = _make_api_request(api_url, token, params)
except RuntimeError as e:
return _error("API_ERROR", str(e))
try:
text = _extract_text(result)
except ValueError as e:
return _error("API_ERROR", str(e))
return {
"ok": True,
"text": text,
"result": result,
"error": None,
}
def _extract_text(result: dict[str, Any]) -> str:
"""Extract text from document parsing result."""
if not isinstance(result, dict):
raise ValueError("Invalid API response: top-level response must be an object")
raw_result = result.get("result")
if not isinstance(raw_result, dict):
raise ValueError("Invalid API response: missing 'result' object")
pages = raw_result.get("layoutParsingResults")
if not isinstance(pages, list):
raise ValueError(
"Invalid API response: result.layoutParsingResults must be an array"
)
texts = []
for i, page in enumerate(pages):
if not isinstance(page, dict):
raise ValueError(
f"Invalid API response: result.layoutParsingResults[{i}] must be an object"
)
markdown = page.get("markdown")
if not isinstance(markdown, dict):
raise ValueError(
f"Invalid API response: result.layoutParsingResults[{i}].markdown must be an object"
)
text = markdown.get("text")
if not isinstance(text, str):
raise ValueError(
f"Invalid API response: result.layoutParsingResults[{i}].markdown.text must be a string"
)
texts.append(text)
return "\n\n".join(texts)
def _error(code: str, message: str) -> dict[str, Any]:
"""Create error response."""
return {
"ok": False,
"text": "",
"result": None,
"error": {"code": code, "message": message},
}
@@ -1,179 +0,0 @@
"""
File Optimizer for PaddleOCR Document Parsing
Compresses and optimizes large files to meet size requirements.
Supports image files only.
Usage:
uv run scripts/optimize_file.py input.png output.png
uv run scripts/optimize_file.py input.png output.jpg --quality 70
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "Pillow>=10.0.0",
# ]
# ///
import argparse
import math
import sys
from pathlib import Path
DEFAULT_QUALITY = 85
DEFAULT_TARGET_SIZE_MB = 20
SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif", ".webp")
SUPPORTED_FORMATS_DISPLAY = ", ".join(
e.lstrip(".").upper() for e in SUPPORTED_EXTENSIONS
)
def _arg_quality(value: str) -> int:
q = int(value)
if q < 1 or q > 100:
raise argparse.ArgumentTypeError("quality must be between 1 and 100 inclusive")
return q
def _arg_positive_mb(value: str) -> float:
v = float(value)
if not math.isfinite(v) or v <= 0:
raise argparse.ArgumentTypeError(
"target size must be a finite number greater than 0"
)
return v
def optimize_image(
input_path: Path,
output_path: Path,
quality: int = DEFAULT_QUALITY,
max_size_mb: float = DEFAULT_TARGET_SIZE_MB,
) -> None:
"""Optimize image file by reducing quality and/or resolution."""
from PIL import Image
if input_path.stat().st_size == 0:
raise ValueError("Input file is empty (0 bytes); nothing to optimize")
print(f"Optimizing image: {input_path}")
img = Image.open(input_path)
original_size = input_path.stat().st_size / 1024 / 1024
print(f"Original size: {original_size:.2f}MB")
print(f"Original dimensions: {img.size[0]}x{img.size[1]}")
is_jpeg = output_path.suffix.lower() in (".jpg", ".jpeg")
if is_jpeg and img.mode in ("RGBA", "LA", "P"):
background = Image.new("RGB", img.size, (255, 255, 255))
if img.mode == "P":
img = img.convert("RGBA")
background.paste(
img, mask=img.split()[-1] if img.mode in ("RGBA", "LA") else None
)
img = background
save_kwargs = {"optimize": True}
if is_jpeg or output_path.suffix.lower() == ".webp":
save_kwargs["quality"] = quality
def _save(image):
image.save(output_path, **save_kwargs)
return output_path.stat().st_size / 1024 / 1024
new_size = _save(img)
scale_factor = 0.9
while new_size > max_size_mb and scale_factor >= 0.4:
new_width = int(img.size[0] * scale_factor)
new_height = int(img.size[1] * scale_factor)
if new_width < 1 or new_height < 1:
print(
f"Cannot shrink to valid dimensions at scale {scale_factor:.2f} "
f"(would be {new_width}x{new_height}); stopping resize loop."
)
break
print(f"Resizing to {new_width}x{new_height} (scale: {scale_factor:.2f})")
resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
new_size = _save(resized)
scale_factor -= 0.1
print(f"Optimized size: {new_size:.2f}MB")
pct = (original_size - new_size) / original_size * 100
print(f"Reduction: {pct:.1f}%")
if new_size > max_size_mb:
print(f"\nWARNING: File still larger than {max_size_mb}MB")
print("Consider:")
print(" - Lower quality (--quality 70)")
print(" - Use --file-url instead of local file")
print(" - Use a smaller or resized image")
def main() -> None:
parser = argparse.ArgumentParser(
description="Optimize files for PaddleOCR document parsing",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=f"""
Examples:
# Optimize image with default quality
uv run scripts/optimize_file.py input.png output.png
# Optimize with specific quality
uv run scripts/optimize_file.py input.jpg output.jpg --quality 70
Supported formats:
- Images: {SUPPORTED_FORMATS_DISPLAY}
""",
)
parser.add_argument("input", help="Input file path")
parser.add_argument("output", help="Output file path")
parser.add_argument(
"--quality",
type=_arg_quality,
default=DEFAULT_QUALITY,
help="JPEG/WebP quality (1-100, default: %(default)s)",
)
parser.add_argument(
"--target-size",
type=_arg_positive_mb,
default=DEFAULT_TARGET_SIZE_MB,
help="Target maximum size in MB (default: %(default)s)",
)
args = parser.parse_args()
input_path = Path(args.input)
output_path = Path(args.output)
if not input_path.exists():
print(f"ERROR: Input file not found: {input_path}")
sys.exit(1)
ext = input_path.suffix.lower()
if ext in SUPPORTED_EXTENSIONS:
try:
optimize_image(input_path, output_path, args.quality, args.target_size)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
else:
print(f"ERROR: Unsupported file format: {ext}")
print(f"Supported: {SUPPORTED_FORMATS_DISPLAY}")
sys.exit(1)
print(f"\nOptimized file saved to: {output_path}")
print("\nYou can now process with:")
print(f' uv run scripts/layout_caller.py --file-path "{output_path}" --pretty')
if __name__ == "__main__":
main()
@@ -1,149 +0,0 @@
"""
Smoke Test for PaddleOCR Document Parsing Skill
Verifies configuration and API connectivity.
Usage:
uv run scripts/smoke_test.py
uv run scripts/smoke_test.py --skip-api-test
uv run scripts/smoke_test.py --test-url "https://example.com/test.pdf"
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "httpx>=0.24.0",
# ]
# ///
import argparse
import sys
from pathlib import Path
# Add scripts dir to path for imports
sys.path.insert(0, str(Path(__file__).parent))
def print_config_guide() -> None:
"""Print friendly configuration guide."""
from lib import DEFAULT_TIMEOUT
print(
f"""
============================================================
HOW TO GET YOUR API CREDENTIALS
============================================================
1. Visit: https://www.paddleocr.com
2. Open your model's API page and sign in
3. Open your model's Example Code section
4. In Example Code, copy the API URL value
5. In Example Code, copy the Access Token value
Set environment variables:
export PADDLEOCR_DOC_PARSING_API_URL=https://your-api-url.paddleocr.com/layout-parsing
export PADDLEOCR_ACCESS_TOKEN=your_token_here
export PADDLEOCR_DOC_PARSING_TIMEOUT={DEFAULT_TIMEOUT} # optional
============================================================
"""
)
def main() -> int:
parser = argparse.ArgumentParser(
description="PaddleOCR Document Parsing smoke test"
)
parser.add_argument("--test-url", help="Optional: Custom document URL for testing")
parser.add_argument(
"--skip-api-test",
action="store_true",
help="Skip API connectivity test, only check configuration",
)
args = parser.parse_args()
print("=" * 60)
print("PaddleOCR Document Parsing - Smoke Test")
print("=" * 60)
print("\n[1/3] Checking dependencies...")
try:
import httpx
print(f" + httpx: {httpx.__version__}")
except ImportError:
print(" X httpx not installed")
print("\nRun this script with uv to auto-resolve dependencies:")
print(" uv run scripts/smoke_test.py")
print("\nOr install manually:")
print(" pip install httpx")
return 1
print("\n[2/3] Checking configuration...")
from lib import get_config
try:
api_url, token = get_config()
print(f" + PADDLEOCR_DOC_PARSING_API_URL: {api_url}")
masked_token = token[:8] + "..." + token[-4:] if len(token) > 12 else "***"
print(f" + PADDLEOCR_ACCESS_TOKEN: {masked_token}")
except ValueError as e:
print(f" X {e}")
print_config_guide()
return 1
if args.skip_api_test:
print("\n[3/3] Skipping API connectivity test (--skip-api-test)")
print("\n" + "=" * 60)
print("Configuration Check Complete!")
print("=" * 60)
return 0
print("\n[3/3] Testing API connectivity...")
test_url = (
args.test_url
or "https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/pp_structure_v3_demo.png"
)
print(f" Test document: {test_url}")
from lib import parse_document
result = parse_document(file_url=test_url)
if not result.get("ok"):
error = result.get("error", {})
print(f"\n X API call failed: {error.get('message')}")
if "Authentication" in error.get("message", ""):
print("\n Hint: Check if your token is correct and not expired.")
print(
" Get a new token from the PaddleOCR page example code section."
)
return 1
print(" + API call successful!")
text = result.get("text", "")
if text:
preview = text[:200].replace("\n", " ")
if len(text) > 200:
preview += "..."
print(f"\n Preview: {preview}")
print("\n" + "=" * 60)
print("Smoke Test PASSED")
print("=" * 60)
print("\nNext steps:")
print(' uv run scripts/layout_caller.py --file-url "URL" --pretty')
print(' uv run scripts/layout_caller.py --file-path "doc.pdf" --pretty')
print(
" Results are auto-saved to the system temp directory; the caller prints the saved path."
)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,119 +0,0 @@
"""
Split a PDF by page ranges.
Usage:
uv run scripts/split_pdf.py input.pdf output.pdf --pages "1-5,8,10-12"
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "pypdfium2>=4.0.0",
# ]
# ///
import argparse
import sys
from pathlib import Path
def parse_pages(pages_spec: str, total_pages: int) -> list[int]:
"""Parse 1-based page ranges into 0-based unique page indices."""
if not pages_spec or not pages_spec.strip():
raise ValueError("Page ranges are required. Example: 1-5,8,10-12")
selected_pages = []
seen_pages = set()
def add_page(page_number: int):
if page_number < 1 or page_number > total_pages:
raise ValueError(
f"Page {page_number} is out of range. Valid range: 1-{total_pages}"
)
page_index = page_number - 1
if page_index not in seen_pages:
seen_pages.add(page_index)
selected_pages.append(page_index)
for token in [part.strip() for part in pages_spec.split(",") if part.strip()]:
if "-" in token:
start_str, end_str = token.split("-", 1)
if not start_str.isdigit() or not end_str.isdigit():
raise ValueError(f"Invalid page range: {token}")
start_page, end_page = int(start_str), int(end_str)
if start_page > end_page:
raise ValueError(
f"Invalid page range: {token} (start cannot be greater than end)"
)
for page_number in range(start_page, end_page + 1):
add_page(page_number)
else:
if not token.isdigit():
raise ValueError(f"Invalid page value: {token}")
add_page(int(token))
if not selected_pages:
raise ValueError("No valid pages selected")
return selected_pages
def split_pdf(input_path: Path, output_path: Path, pages_spec: str) -> tuple[int, int]:
"""Create a new PDF containing selected pages from the input PDF."""
import pypdfium2 as pdfium
source_pdf = pdfium.PdfDocument(str(input_path))
try:
total_pages = len(source_pdf)
page_indices = parse_pages(pages_spec, total_pages)
output_pdf = pdfium.PdfDocument.new()
try:
output_pdf.import_pages(source_pdf, page_indices)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_pdf.save(str(output_path))
finally:
output_pdf.close()
finally:
source_pdf.close()
return total_pages, len(page_indices)
def main() -> int:
parser = argparse.ArgumentParser(description="Split PDF by page ranges")
parser.add_argument("input_pdf", help="Input PDF file")
parser.add_argument("output_pdf", help="Output PDF file")
parser.add_argument(
"--pages",
required=True,
help='Page ranges, e.g. "1-5,8,10-12"',
)
args = parser.parse_args()
input_path = Path(args.input_pdf)
output_path = Path(args.output_pdf)
if not input_path.exists():
print(f"ERROR: Input file not found: {input_path}")
return 1
if input_path.suffix.lower() != ".pdf":
print(f"ERROR: Input must be a PDF file: {input_path}")
return 1
if output_path.suffix.lower() != ".pdf":
print(f"ERROR: Output must be a PDF file: {output_path}")
return 1
try:
total_pages, kept_pages = split_pdf(input_path, output_path, args.pages)
except Exception as e:
print(f"ERROR: {e}")
return 1
print(f"Split complete: {output_path}")
print(f"Selected {kept_pages} page(s) from {total_pages} total page(s)")
return 0
if __name__ == "__main__":
sys.exit(main())
+76 -183
View File
@@ -8,236 +8,129 @@ description: >-
plain text extraction, 坐标, 检测框, bbox, bounding box, image to text, screenshot, photo scan,
recognize text.
license: Apache-2.0
compatibility: Requires uv and internet access.
compatibility: Requires paddleocr>=3.6.0
metadata:
openclaw:
requires:
env:
- PADDLEOCR_OCR_API_URL
- PADDLEOCR_ACCESS_TOKEN
bins:
- uv
- paddleocr
primaryEnv: PADDLEOCR_ACCESS_TOKEN
emoji: "🔤"
homepage: https://github.com/PaddlePaddle/PaddleOCR/tree/main/skills/paddleocr-text-recognition
install:
- kind: uv
package: paddleocr
bins: [paddleocr]
---
# PaddleOCR Text Recognition Skill
# PaddleOCR Text Recognition
## When to Use This Skill
**Trigger keywords (routing)**: Bilingual trigger terms (Chinese and English) are listed in the YAML `description` above—use that field for discovery and routing.
**Use this skill for**:
- Extract text from images (screenshots, photos, scans)
- Extract text from PDFs or document images when the goal is **line/box-level text**, not recovering table grids, formulas, or full reading-order layout
- Extract text from PDFs or document images when the goal is **line/box-level text**
- Extract text from URLs or local files that point to images/PDFs
**Do not use for**:
- Plain text files, code files, or markdown documents that can be read directly as text
- Documents with tables, formulas, charts, or complex layouts — use Document Parsing instead
- Tasks that do not involve image-to-text conversion
## Installation
## Usage
Scripts declare their dependencies inline ([PEP 723](https://peps.python.org/pep-0723/)). No separate install step is needed — [uv](https://docs.astral.sh/uv/) resolves dependencies automatically:
### Basic OCR
From URL:
```bash
uv run scripts/ocr_caller.py --help
paddleocr api \
--model_type ocr \
--file_url "https://example.com/image.png"
```
## How to Use This Skill
> **Working directory**: All `uv run scripts/...` commands below should be run from this skill's root directory (the directory containing this SKILL.md file).
### Basic Workflow
1. **Identify the input source**:
- User provides URL: Use the `--file-url` parameter
- User provides local file path: Use the `--file-path` parameter
2. **Execute OCR**:
```bash
uv run scripts/ocr_caller.py --file-url "URL provided by user" --pretty
```
Or for local files:
```bash
uv run scripts/ocr_caller.py --file-path "file path" --pretty
```
> **Performance note**: Parsing time scales with document complexity. Single-page images typically complete in 1-3 seconds; large PDFs (50+ pages) may take several minutes. Allow adequate time before assuming a timeout.
**Default behavior: save raw JSON to a temp file**:
- If `--output` is omitted, the script saves automatically under the system temp directory
- Default path pattern: `<system-temp>/paddleocr/text-recognition/results/result_<timestamp>_<id>.json`
- If `--output` is provided, it overrides the default temp-file destination
- If `--stdout` is provided, JSON is printed to stdout and no file is saved
- In save mode, the script prints the absolute saved path on stderr: `Result saved to: /absolute/path/...`
- In default/custom save mode, read and parse the saved JSON file before responding
- Use `--stdout` only when you explicitly want to skip file persistence
3. **Parse JSON response**:
- In default/custom save mode, load JSON from the saved file path shown by the script
- Check the `ok` field: `true` means success, `false` means error
- Extract text: `text` field contains all recognized text
- If `--stdout` is used, parse the stdout JSON directly
- Handle errors: If `ok` is false, display `error.message`
4. **Present results to user**:
- Display extracted text in a readable format
- If the text is empty, the image may contain no text
- In save mode, always tell the user the saved file path and that full raw JSON is available there
### What to Do After Extraction
Common next steps once you have the recognized text:
- **Save to file**: Write the `text` field to a `.txt` or `.md` file
- **Search the content**: Search the saved output file for keywords
- **Feed to another pipeline**: The `text` field is clean plain text, ready for downstream processing
- **Poor results**: See "Tips for Better Results" below before retrying
### Complete Output Display
Always display the COMPLETE recognized text to the user. The user typically needs the full content for downstream use — truncation silently loses data they may not notice is missing.
- Display the entire `text` field, no matter how long
- Do not use phrases like "Here's a summary" or "The text begins with..."
- Do not truncate with "..." unless the text truly exceeds reasonable display limits (>10,000 chars)
**Example - Correct**:
```
User: "Extract the text from this image"
Agent: I've extracted the text from the image. Here's the complete content:
[Display the entire text here]
```
**Example - Incorrect**:
```
User: "Extract the text from this image"
Agent: I found some text in the image. Here's a preview:
"The quick brown fox..." (truncated)
```
### Understanding the Output
The script returns a JSON envelope with `ok`, `text`, `result`, and `error` fields. Use `text` for the recognized content; `result` contains the raw API response for debugging.
For the full schema and field-level details, see `references/output_schema.md`.
> Raw result location (default): the temp-file path printed by the script on stderr
### Usage Examples
**Example 1: URL OCR**
From local file:
```bash
uv run scripts/ocr_caller.py --file-url "https://example.com/invoice.jpg" --pretty
paddleocr api \
--model_type ocr \
--file_path "./document.pdf"
```
**Example 2: Local File OCR**
### With Specific Model
PP-OCRv5:
```bash
uv run scripts/ocr_caller.py --file-path "./document.pdf" --pretty
paddleocr api \
--model_type ocr \
--model PP-OCRv5 \
--file_path "./report.pdf"
```
**Example 3: OCR With Explicit File Type**
### Common Options
```bash
uv run scripts/ocr_caller.py --file-url "https://example.com/input" --file-type 1 --pretty
# Disable preprocessing (faster, for flat/well-oriented images)
paddleocr api \
--model_type ocr \
--file_path "./document.pdf" \
--use_doc_unwarping False \
--use_doc_orientation_classify False
# Save result to file
paddleocr api \
--model_type ocr \
--file_url "https://..." \
--output result.json
# Page ranges
paddleocr api \
--model_type ocr \
--file_path "./large.pdf" \
--page_ranges "1-5,10,15-20"
```
- `--file-type 0`: PDF
- `--file-type 1`: image
- If omitted, the type is auto-detected from the file extension. For local files, a recognized extension (`.pdf`, `.png`, `.jpg`, `.jpeg`, `.bmp`, `.tiff`, `.tif`, `.webp`) is required; otherwise pass `--file-type` explicitly. For URLs with unrecognized extensions, the service attempts inference.
**Example 4: Print JSON Without Saving**
```bash
uv run scripts/ocr_caller.py --file-url "https://example.com/input" --stdout --pretty
```
### First-Time Configuration
**When API is not configured**, the script outputs:
### Output Format
```json
{
"ok": false,
"text": "",
"result": null,
"error": {
"code": "CONFIG_ERROR",
"message": "PADDLEOCR_OCR_API_URL not configured. Get your API at: https://paddleocr.com"
}
"jobId": "job-xxx",
"pages": [
{
"prunedResult": {
"rec_texts": ["Line 1", "Line 2"],
"rec_scores": [0.98, 0.95]
},
"ocrImageUrl": "https://..."
}
]
}
```
**Configuration workflow**:
## Important Notes
1. **Show the exact error message** to the user.
2. **Guide the user to obtain credentials**: Visit the [PaddleOCR website](https://www.paddleocr.com), click **API**, select the `PP-OCRv5` model, select the language, then copy the `API_URL` and `Token`. They map to these environment variables:
- `PADDLEOCR_OCR_API_URL` — full endpoint URL ending with `/ocr`
- `PADDLEOCR_ACCESS_TOKEN` — 40-character alphanumeric string
Optionally configure `PADDLEOCR_OCR_TIMEOUT` for request timeout. Recommend using the host application's standard configuration method rather than pasting credentials in chat.
3. **Apply credentials** — one of:
- **User configured via the host UI**: ask the user to confirm, then retry.
- **User pastes credentials in chat**: warn that they may be stored in conversation history, help the user persist them using the host's standard configuration method, then retry.
### Error Handling
All errors return JSON with `ok: false`. Show the error message and stop — do not fall back to your own vision capabilities. Identify the issue from `error.code` and `error.message`:
**Authentication failed (403)** — `error.message` contains "Authentication failed"
- Token is invalid, reconfigure with correct credentials
**Quota exceeded (429)** — `error.message` contains "API rate limit exceeded"
- Daily API quota exhausted, inform user to wait or upgrade
**Unsupported format** — `error.message` contains "Unsupported file format"
- File format not supported, convert to PDF/PNG/JPG
**No text detected**:
- `text` field is empty
- Image may be blank, corrupted, or contain no text
### Tips for Better Results
If recognition quality is poor:
- **Low resolution**: Provide a higher resolution image (≥300 DPI works well for most printed text)
- **Noisy background**: A cleaner scan or screenshot typically yields better results than a phone photo
- **Check confidence**: The raw JSON (`result.result.ocrResults[n].prunedResult.rec_scores`) shows per-line confidence scores — low values identify uncertain regions worth reviewing
## Reference Documentation
- `references/output_schema.md` — Full output schema, field descriptions, and command examples
> **Note**: Model version, capabilities, and supported file formats are determined by your API endpoint (`PADDLEOCR_OCR_API_URL`) and its official API documentation.
## Testing the Skill
To verify the skill is working properly:
**Preprocessing options**: By default, the API enables document preprocessing (unwarping and orientation classification). For flat, well-oriented images (screenshots, properly scanned documents), you can disable preprocessing for faster results:
```bash
uv run scripts/smoke_test.py
uv run scripts/smoke_test.py --skip-api-test
uv run scripts/smoke_test.py --test-url "https://..."
paddleocr api --model_type ocr --file_path "./document.pdf" --use_doc_unwarping False --use_doc_orientation_classify False
```
The first form tests configuration and API connectivity. `--skip-api-test` checks configuration only. `--test-url` overrides the default sample image URL.
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 or falling back to your own vision capabilities. Common errors:
- Authentication: `PADDLEOCR_ACCESS_TOKEN` invalid or missing
- Quota: API rate limit exceeded
- No content detected: Image may be blank or contain no text
## CLI Reference
Run `paddleocr api --help` for all options.
For full documentation, see: [PaddleOCR Official Documentation](https://www.paddleocr.ai/latest/en/version3.x/inference_deployment/serving/paddleocr_official_api/cli.html)
@@ -1,111 +0,0 @@
# PaddleOCR Text Recognition Output Schema
This document defines the output envelope returned by `ocr_caller.py`.
By default, `ocr_caller.py` saves the JSON envelope to a unique file under the system temp directory and prints the absolute saved path to `stderr`. Use `--output` when you need a custom destination, or `--stdout` when you want to skip file saving and print JSON directly.
## Output Envelope
`ocr_caller.py` wraps provider response in a stable structure:
```json
{
"ok": true,
"text": "Extracted text from all pages",
"result": { ... }, // raw provider response
"error": null
}
```
On error:
```json
{
"ok": false,
"text": "",
"result": null,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable message"
}
}
```
## Error Codes
| Code | Description |
| -------------- | --------------------------------------------------------------------------- |
| `INPUT_ERROR` | Invalid or unusable input (arguments, file source, format, types). |
| `CONFIG_ERROR` | Missing or invalid API / client configuration. |
| `API_ERROR` | Request or response handling failed (network, HTTP, body parsing, schema). |
## Raw Result Notes
The `result` field contains raw provider output.
Raw fields may vary by model version and endpoint.
## Raw Result Example
```json
{
"logId": "request-uuid",
"errorCode": 0,
"errorMsg": "Success",
"result": {
"ocrResults": [
{
"prunedResult": {
"rec_texts": ["First line", "Second line"],
"rec_scores": [0.98, 0.95],
"...": "other OCR fields"
},
"ocrImage": "https://...",
"inputImage": "https://...",
"...": "other model-specific fields"
}
],
"dataInfo": {
"numPages": 1,
"type": "pdf",
"...": "other metadata"
},
"...": "other top-level fields"
}
}
```
## Stable Fields for Downstream Use
Paths are relative to the output envelope root.
- `result.result.ocrResults[n].prunedResult`
Structured OCR data for page `n`.
- `result.result.ocrResults[n].prunedResult.rec_texts`
Recognized text lines for page `n`.
- `result.result.ocrResults[n].prunedResult.rec_scores`
Confidence scores for recognized text lines.
## Text Extraction
`ocr_caller.py` extracts top-level `text` from `result.result.ocrResults[n].prunedResult.rec_texts`, joins lines with `\n`, and joins pages with `\n\n`.
## Command Examples
```bash
# OCR from URL (result auto-saves to the system temp directory)
uv run scripts/ocr_caller.py --file-url "URL" --pretty
# OCR local file (result auto-saves to the system temp directory)
uv run scripts/ocr_caller.py --file-path "doc.pdf" --pretty
# OCR with explicit file type
uv run scripts/ocr_caller.py --file-url "URL" --file-type 1 --pretty
# Save result to a custom file path
uv run scripts/ocr_caller.py --file-url "URL" --output "./result.json" --pretty
# Print JSON to stdout without saving a file
uv run scripts/ocr_caller.py --file-url "URL" --stdout --pretty
```
@@ -1,388 +0,0 @@
"""
PaddleOCR Text Recognition Library
Simple OCR API wrapper for PaddleOCR text recognition.
"""
import base64
import logging
import math
import os
from pathlib import Path
from typing import Any, Optional
from urllib.parse import unquote, urlparse
import httpx
logger = logging.getLogger(__name__)
# =============================================================================
# Constants
# =============================================================================
DEFAULT_TIMEOUT = 120 # seconds
API_GUIDE_URL = "https://paddleocr.com"
FILE_TYPE_PDF = 0
FILE_TYPE_IMAGE = 1
IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".tif", ".webp")
# =============================================================================
# Environment
# =============================================================================
def _get_env(key: str) -> str:
"""Get environment variable, defaulting to empty string with whitespace stripped."""
return os.getenv(key, "").strip()
def _http_timeout_from_env(env_key: str, default_seconds: float) -> float:
"""
Read HTTP client timeout in seconds from the environment.
Returns a positive finite float. If the variable is missing, empty,
unparsable, non-finite, or not greater than zero, logs a warning and uses the
default_seconds argument value.
"""
raw = os.getenv(env_key)
if raw is None:
return float(default_seconds)
stripped = raw.strip()
if not stripped:
return float(default_seconds)
try:
timeout = float(stripped)
except (ValueError, TypeError):
logger.warning(
"Invalid %s value %r; using default %ss",
env_key,
raw,
default_seconds,
)
return float(default_seconds)
if not math.isfinite(timeout) or timeout <= 0:
logger.warning(
"%s must be a finite number > 0 (got %r); using default %ss",
env_key,
raw,
default_seconds,
)
return float(default_seconds)
return timeout
def _resolve_api_url(api_url: str, env_var: str) -> str:
"""Require https; allow host-only values by prepending https://."""
if api_url.startswith("http://"):
raise ValueError(f"{env_var} must use https://; http:// is not allowed.")
if not api_url.startswith("https://"):
return f"https://{api_url}"
return api_url
def get_config() -> tuple[str, str]:
"""
Get API URL and token from environment.
Returns:
tuple of (api_url, token)
Raises:
ValueError: If required env vars are missing, API URL uses http://,
or URL path doesn't end with /ocr
"""
api_url = _get_env("PADDLEOCR_OCR_API_URL")
token = _get_env("PADDLEOCR_ACCESS_TOKEN")
if not api_url:
raise ValueError(
f"PADDLEOCR_OCR_API_URL not configured. Get your API at: {API_GUIDE_URL}"
)
if not token:
raise ValueError(
f"PADDLEOCR_ACCESS_TOKEN not configured. Get your API at: {API_GUIDE_URL}"
)
api_url = _resolve_api_url(api_url, "PADDLEOCR_OCR_API_URL")
api_path = urlparse(api_url).path.rstrip("/")
if not api_path.endswith("/ocr"):
raise ValueError(
"PADDLEOCR_OCR_API_URL must be a full endpoint ending with /ocr. "
"Example: https://your-service.paddleocr.com/ocr"
)
return api_url, token
# =============================================================================
# File Utilities
# =============================================================================
def _detect_file_type(path_or_url: str) -> int:
"""Detect file type: 0=PDF, 1=Image."""
path = path_or_url.lower()
if path.startswith(("http://", "https://")):
path = unquote(urlparse(path).path)
if path.endswith(".pdf"):
return FILE_TYPE_PDF
elif path.endswith(IMAGE_EXTENSIONS):
return FILE_TYPE_IMAGE
else:
raise ValueError(f"Unsupported file format: {path_or_url}")
def _load_file_as_base64(file_path: str) -> str:
"""Load local file and encode as base64."""
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
if path.stat().st_size == 0:
raise ValueError(f"File is empty (0 bytes): {file_path}")
return base64.b64encode(path.read_bytes()).decode("utf-8")
# =============================================================================
# API Request
# =============================================================================
def _make_api_request(
api_url: str, token: str, params: dict[str, Any]
) -> dict[str, Any]:
"""
Make PaddleOCR API request.
Args:
api_url: API endpoint URL
token: Access token
params: Request parameters
Returns:
API response dict
Raises:
RuntimeError: On API errors
"""
headers = {
"Authorization": f"token {token}",
"Content-Type": "application/json",
"Client-Platform": "official-skill",
}
timeout = _http_timeout_from_env("PADDLEOCR_OCR_TIMEOUT", float(DEFAULT_TIMEOUT))
try:
with httpx.Client(timeout=timeout) as client:
try:
resp = client.post(api_url, json=params, headers=headers)
except TypeError as e:
raise RuntimeError(
"Request parameters cannot be JSON-encoded; use only JSON-serializable "
f"option values ({e})"
) from e
except httpx.TimeoutException:
raise RuntimeError(f"API request timed out after {timeout}s")
except httpx.RequestError as e:
raise RuntimeError(f"API request failed: {e}")
if resp.status_code != 200:
error_detail = ""
try:
error_body = resp.json()
if isinstance(error_body, dict):
error_detail = str(error_body.get("errorMsg", "")).strip()
except Exception:
pass
if not error_detail:
error_detail = (resp.text[:200] or "No response body").strip()
if resp.status_code == 403:
raise RuntimeError(f"Authentication failed (403): {error_detail}")
elif resp.status_code == 429:
raise RuntimeError(f"API rate limit exceeded (429): {error_detail}")
elif resp.status_code >= 500:
raise RuntimeError(
f"API service error ({resp.status_code}): {error_detail}"
)
else:
raise RuntimeError(f"API error ({resp.status_code}): {error_detail}")
try:
result = resp.json()
except Exception:
raise RuntimeError(f"Invalid JSON response: {resp.text[:200]}")
if not isinstance(result, dict):
raise RuntimeError(
f"Unexpected JSON shape (expected object): {resp.text[:200]}"
)
if result.get("errorCode", 0) != 0:
msg = result.get("errorMsg", "Unknown error")
raise RuntimeError(f"API error: {msg}")
return result
# =============================================================================
# Main API
# =============================================================================
def ocr(
file_path: Optional[str] = None,
file_url: Optional[str] = None,
file_type: Optional[int] = None,
**options: Any,
) -> dict[str, Any]:
"""
Perform OCR on image or PDF.
Args:
file_path: Local file path (mutually exclusive with file_url)
file_url: URL to file (mutually exclusive with file_path)
file_type: Optional file type override (0=PDF, 1=Image)
**options: Additional API options (passed directly to API)
Returns:
{
"ok": True,
"text": "extracted text...",
"result": { raw API result },
"error": None
}
or on error:
{
"ok": False,
"text": "",
"result": None,
"error": {"code": "...", "message": "..."}
}
"""
if file_path is not None and not isinstance(file_path, str):
return _error("INPUT_ERROR", "file_path must be a string or None")
if file_url is not None and not isinstance(file_url, str):
return _error("INPUT_ERROR", "file_url must be a string or None")
fp = file_path.strip() if file_path else ""
fu = file_url.strip() if file_url else ""
if fp and fu:
return _error(
"INPUT_ERROR",
"Provide only one of file_path or file_url, not both",
)
if not fp and not fu:
return _error("INPUT_ERROR", "file_path or file_url required")
if file_type is not None and file_type not in (FILE_TYPE_PDF, FILE_TYPE_IMAGE):
return _error("INPUT_ERROR", "file_type must be 0 (PDF) or 1 (Image)")
try:
api_url, token = get_config()
except ValueError as e:
return _error("CONFIG_ERROR", str(e))
# Build request params
try:
resolved_file_type: Optional[int] = None
if fu:
params = {"file": fu}
if file_type is not None:
resolved_file_type = file_type
else:
try:
resolved_file_type = _detect_file_type(fu)
except ValueError:
resolved_file_type = None
else:
resolved_file_type = (
file_type if file_type is not None else _detect_file_type(fp)
)
params = {"file": _load_file_as_base64(fp)}
params["visualize"] = (
False # reduce response payload; callers can override via options
)
params.update(options)
if resolved_file_type is not None:
params["fileType"] = resolved_file_type
else:
params.pop("fileType", None)
except (ValueError, OSError, MemoryError) as e:
return _error("INPUT_ERROR", str(e))
try:
result = _make_api_request(api_url, token, params)
except RuntimeError as e:
return _error("API_ERROR", str(e))
try:
text = _extract_text(result)
except ValueError as e:
return _error("API_ERROR", str(e))
return {
"ok": True,
"text": text,
"result": result,
"error": None,
}
def _extract_text(result: dict[str, Any]) -> str:
"""Extract text from OCR result."""
if not isinstance(result, dict):
raise ValueError("Invalid API response: top-level response must be an object")
raw_result = result.get("result")
if not isinstance(raw_result, dict):
raise ValueError("Invalid API response: missing 'result' object")
pages = raw_result.get("ocrResults")
if not isinstance(pages, list):
raise ValueError("Invalid API response: result.ocrResults must be an array")
all_text = []
for i, item in enumerate(pages):
if not isinstance(item, dict):
raise ValueError(
f"Invalid API response: result.ocrResults[{i}] must be an object"
)
pruned = item.get("prunedResult")
if not isinstance(pruned, dict):
raise ValueError(
f"Invalid API response: result.ocrResults[{i}].prunedResult must be an object"
)
texts = pruned.get("rec_texts", [])
if not isinstance(texts, list):
raise ValueError(
f"Invalid API response: result.ocrResults[{i}].prunedResult.rec_texts "
"must be an array"
)
line_parts: list[str] = []
for j, t in enumerate(texts):
if not isinstance(t, str):
raise ValueError(
f"Invalid API response: result.ocrResults[{i}].prunedResult."
f"rec_texts[{j}] must be a string"
)
line_parts.append(t)
if line_parts:
all_text.append("\n".join(line_parts))
return "\n\n".join(all_text)
def _error(code: str, message: str) -> dict[str, Any]:
"""Create error response."""
return {
"ok": False,
"text": "",
"result": None,
"error": {"code": code, "message": message},
}
@@ -1,149 +0,0 @@
"""
PaddleOCR Text Recognition Caller
Simple CLI wrapper for the PaddleOCR text recognition library.
Usage:
uv run scripts/ocr_caller.py --file-url "URL"
uv run scripts/ocr_caller.py --file-path "image.png" --pretty
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "httpx>=0.24.0",
# ]
# ///
import argparse
import io
import json
import sys
import tempfile
import uuid
from datetime import datetime
from pathlib import Path
from typing import Optional
# Fix Windows console encoding
if sys.platform == "win32":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
# Add scripts dir to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from lib import ocr
def get_default_output_path() -> Path:
"""Build a unique result path under the OS temp directory."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
short_id = uuid.uuid4().hex[:8]
return (
Path(tempfile.gettempdir())
/ "paddleocr"
/ "text-recognition"
/ "results"
/ f"result_{timestamp}_{short_id}.json"
)
def resolve_output_path(output_arg: Optional[str]) -> Path:
if output_arg:
return Path(output_arg).expanduser().resolve()
return get_default_output_path().resolve()
def main() -> None:
parser = argparse.ArgumentParser(
description="PaddleOCR Text Recognition - OCR images/PDFs",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# OCR from URL (result is auto-saved to the system temp directory)
uv run scripts/ocr_caller.py --file-url "https://example.com/image.png"
# OCR local file (result is auto-saved to the system temp directory)
uv run scripts/ocr_caller.py --file-path "./document.pdf" --pretty
# OCR with explicit file type override
uv run scripts/ocr_caller.py --file-url "URL" --file-type 1 --pretty
# Save result to a custom file path
uv run scripts/ocr_caller.py --file-url "URL" --output "./result.json" --pretty
# Print JSON to stdout without saving a file
uv run scripts/ocr_caller.py --file-url "URL" --stdout --pretty
Exit codes:
0 Success (ok=true in JSON output)
1 OCR or API error (ok=false in JSON output; see error.code and error.message)
5 Cannot write result to output file
Configuration:
Set environment variables: PADDLEOCR_OCR_API_URL, PADDLEOCR_ACCESS_TOKEN
Optional: PADDLEOCR_OCR_TIMEOUT
""",
)
input_group = parser.add_mutually_exclusive_group(required=True)
input_group.add_argument("--file-url", help="URL to image or PDF")
input_group.add_argument("--file-path", help="Local path to image or PDF")
# Output options
parser.add_argument(
"--file-type",
type=int,
choices=[0, 1],
help="Optional file type override (0=PDF, 1=Image)",
)
parser.add_argument(
"--pretty", action="store_true", help="Pretty-print JSON output"
)
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument(
"--output",
"-o",
metavar="FILE",
help="Save result to JSON file (default: auto-save to system temp directory)",
)
output_group.add_argument(
"--stdout",
action="store_true",
help="Print JSON to stdout instead of saving to a file",
)
args = parser.parse_args()
# Unwarping and orientation classification are off to cover common scenarios
# with faster response times.
result = ocr(
file_path=args.file_path,
file_url=args.file_url,
file_type=args.file_type,
useDocUnwarping=False,
useDocOrientationClassify=False,
)
indent = 2 if args.pretty else None
json_output = json.dumps(result, indent=indent, ensure_ascii=False)
if args.stdout:
print(json_output)
else:
output_path = resolve_output_path(args.output)
try:
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json_output, encoding="utf-8")
print(f"Result saved to: {output_path}", file=sys.stderr)
except (PermissionError, OSError) as e:
print(f"Error: Cannot write to {output_path}: {e}", file=sys.stderr)
sys.exit(5)
sys.exit(0 if result.get("ok") else 1)
if __name__ == "__main__":
main()
@@ -1,147 +0,0 @@
"""
Smoke Test for PaddleOCR Text Recognition
Verifies configuration and API connectivity.
Usage:
uv run scripts/smoke_test.py
uv run scripts/smoke_test.py --skip-api-test
uv run scripts/smoke_test.py --test-url "https://example.com/test.png"
"""
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "httpx>=0.24.0",
# ]
# ///
import argparse
import sys
from pathlib import Path
# Add scripts dir to path for imports
sys.path.insert(0, str(Path(__file__).parent))
def print_config_guide() -> None:
"""Print friendly configuration guide."""
from lib import DEFAULT_TIMEOUT
print(
f"""
============================================================
HOW TO GET YOUR API CREDENTIALS
============================================================
1. Visit: https://paddleocr.com
2. Sign in to your account
3. Open your model's API call example page
4. Copy the API URL from the example request
5. Copy your access token from the same API setup page
Set environment variables:
export PADDLEOCR_OCR_API_URL=https://your-api-url.paddleocr.com/ocr
export PADDLEOCR_ACCESS_TOKEN=your_token_here
export PADDLEOCR_OCR_TIMEOUT={DEFAULT_TIMEOUT} # optional
============================================================
"""
)
def main() -> int:
parser = argparse.ArgumentParser(
description="PaddleOCR Text Recognition smoke test"
)
parser.add_argument("--test-url", help="Optional: Custom image URL for testing")
parser.add_argument(
"--skip-api-test",
action="store_true",
help="Skip API connectivity test, only check configuration",
)
args = parser.parse_args()
print("=" * 60)
print("PaddleOCR Text Recognition - Smoke Test")
print("=" * 60)
print("\n[1/3] Checking dependencies...")
try:
import httpx
print(f" + httpx: {httpx.__version__}")
except ImportError:
print(" X httpx not installed")
print("\nRun this script with uv to auto-resolve dependencies:")
print(" uv run scripts/smoke_test.py")
print("\nOr install manually:")
print(" pip install httpx")
return 1
print("\n[2/3] Checking configuration...")
from lib import get_config
try:
api_url, token = get_config()
print(f" + PADDLEOCR_OCR_API_URL: {api_url}")
masked_token = token[:8] + "..." + token[-4:] if len(token) > 12 else "***"
print(f" + PADDLEOCR_ACCESS_TOKEN: {masked_token}")
except ValueError as e:
print(f" X {e}")
print_config_guide()
return 1
if args.skip_api_test:
print("\n[3/3] Skipping API connectivity test (--skip-api-test)")
print("\n" + "=" * 60)
print("Configuration Check Complete!")
print("=" * 60)
return 0
print("\n[3/3] Testing API connectivity...")
test_url = (
args.test_url
or "https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_001.png"
)
print(f" Test image: {test_url}")
from lib import ocr
result = ocr(file_url=test_url)
if not result.get("ok"):
error = result.get("error", {})
print(f"\n X API call failed: {error.get('message')}")
if "Authentication" in error.get("message", ""):
print("\n Hint: Check if your token is correct and not expired.")
print(" Get a new token from your API call example page.")
return 1
print(" + API call successful!")
text = result.get("text", "")
if text:
preview = text[:200].replace("\n", " ")
if len(text) > 200:
preview += "..."
print(f"\n Preview: {preview}")
print("\n" + "=" * 60)
print("Smoke Test PASSED")
print("=" * 60)
print("\nNext steps:")
print(' uv run scripts/ocr_caller.py --file-url "URL" --pretty')
print(' uv run scripts/ocr_caller.py --file-path "image.png" --pretty')
print(
" Results are auto-saved to the system temp directory; the caller prints the saved path."
)
return 0
if __name__ == "__main__":
sys.exit(main())