[Feat] Support PP-OCRv6 (#18104)

* Fix bugs

* Fix for python3.8

* Fix mcp server

* Optimize

* Fix bugs

* Refactor

* Fix MCP

* Bump MCP to 0.8.1

* Fix bugs

* Bump version to 0.8.2

* Fix bugs and update docs

* Update docs and fix bugs

* Fix bugs

* update pp-ocrv6

* update pp-ocrv6

# Conflicts:
#	docs/version3.x/module_usage/text_detection.md
#	docs/version3.x/module_usage/text_recognition.md
#	docs/version3.x/pipeline_usage/OCR.md
#	paddleocr/_api_client/models.py
#	paddleocr/_pipelines/ocr.py

* Bump paddleocr version

* update PP-OCRv6 docs: add model metrics, fix sizes, update language count to 50

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update PP-OCRv6: add model metrics/sizes to docs, support az/ku languages

- Add PP-OCRv6 model precision, sizes, descriptions to doc tables
- Add OCR pipeline introduction for PP-OCRv6
- Remove az/ku from unsupported latin langs (dict covers them)
- Update language count: 48->50 (medium/small), 47->49 (tiny)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Change languages

* Bump js version

* add PP-OCRv6 English docs: algorithm doc + update model tables

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Use default model

* Update doc

* Update mcp docs

* update PP-OCRv6 algorithm docs and mkdocs nav: sync speed table with paper

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Support more params

* Fix MCP

* update READMEs and index docs: PP-OCRv5 -> PP-OCRv6 features

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update sdk

* Fix bugs

* Fix unsaved

* Bump versions

* Fix bugs

* updata readme

---------

Co-authored-by: weixin_46524038 <weixin_46524038@noreply.gitcode.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: zhangyubo0722 <zhangyubo0722@163.com>
This commit is contained in:
authored and GitHub committed 2026-06-11 19:27:04 +08:00
1 parent b53e29e858
commit b03f46425e
193 files changed
+30434 -1361

No files matched your search

+17 -3
View File
@@ -44,9 +44,9 @@ English | [简体中文](./readme/README_cn.md) | [繁體中文](./readme/README
### 🔍 Universal Text Recognition (Scene OCR)
> *The global gold standard for high-speed, multilingual text spotting.*
* **100+ Languages Supported**: Native recognition for a vast global library. Our **PP-OCRv5** single-model solution elegantly handles multilingual mixed documents (Chinese, English, Japanese, Pinyin, etc.).
* **100+ Languages Supported**: Native recognition for a vast global library. **PP-OCRv6** supports 50 languages with a single unified model (Chinese, English, Japanese, and 46 Latin-script languages) — no model switching needed for multilingual documents.
* **Complex Element Mastery**: Beyond standard text recognition, we support **natural scene text spotting** across a wide range of environments, including IDs, street views, books, and industrial components
* **Performance Leap**: PP-OCRv5 delivers a **13% accuracy boost** over previous versions, maintaining the "Extreme Efficiency" that PaddleOCR is famous for.
* **Performance Leap**: PP-OCRv6 achieves **+4.6% detection** and **+5.1% recognition** accuracy over PP-OCRv5, surpassing mainstream Vision-Language Models. 5.2× CPU inference speedup end-to-end.
<div align="center">
<p>
@@ -62,7 +62,19 @@ English | [简体中文](./readme/README_cn.md) | [繁體中文](./readme/README
## 📣 Recent updates
### 🔥 2026.05.28: Release of PaddleOCR 3.6.0
### 🔥 2026.06.11: Release of PaddleOCR 3.7.0
- PP-OCRv6 highlights:
- **Accuracy boost**: Medium tier achieves +4.6% detection and +5.1% recognition over PP-OCRv5_server, surpassing mainstream VLMs (Qwen3-VL-235B, GPT-5.5) with only 34.5M parameters.
- **50 languages unified**: Single model covers Chinese, English, Japanese, and 46 Latin-script languages — no model switching needed.
- **Specialized scenarios**: Major improvements in digital displays, dot-matrix characters, tire prints, and industrial text recognition.
- **Faster inference**: 5.2× CPU speedup (OpenVINO), 6.1× on Apple M4 (tiny), 0.13s on A100 GPU.
- **Three tiers for all scenarios**: tiny (1.5M) / small (7.7M) / medium (34.5M) for edge, mobile, and server deployment.
- **Documentation**: [PP-OCRv6 Technical Doc](https://paddlepaddle.github.io/PaddleOCR/latest/version3.x/algorithm/PP-OCRv6/PP-OCRv6.en.html)
<details>
<summary><strong>2026.05.28: Release of PaddleOCR 3.6.0</strong></summary>
- PaddleOCR-VL-1.6 highlights:
- **New SOTA Accuracy**: Achieves over 96.3% on OmniDocBench v1.6, also sets new SOTA on OmniDocBench v1.5 and Real5-OmniDocBench, leading both open-source and proprietary solutions in text, formula, and table recognition.
@@ -70,6 +82,8 @@ English | [简体中文](./readme/README_cn.md) | [繁體中文](./readme/README
- **Seamless Migration**: Model architecture is fully consistent with PaddleOCR-VL-1.5, enabling zero-cost adaptation—swap and go.
- **Try it now**: Available on [HuggingFace](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) or our [Official Website](https://www.paddleocr.com).
</details>
<details>
<summary><strong>2026.04.21: Release of PaddleOCR 3.5.0</strong></summary>
+1 -1
View File
@@ -37,7 +37,7 @@ Run these from the PaddleOCR repo root directory:
```bash
# Python
python -m pytest tests/test_api_client_http.py tests/test_api_client_core.py tests/test_api_client_resources.py
python -m pytest tests/api_client/
# TypeScript
cd api_sdk/typescript
+1 -1
View File
@@ -35,7 +35,7 @@ Python SDK 是主 `paddleocr` 包的一部分。
```bash
# Python
python -m pytest tests/test_api_client_http.py tests/test_api_client_core.py tests/test_api_client_resources.py
python -m pytest tests/api_client/
# TypeScript
cd api_sdk/typescript
+3
View File
@@ -43,6 +43,9 @@ if err != nil {
fmt.Println(result.JobID, len(result.Pages))
```
Set `Model: paddleocr.PPOCRv6` (or `"PP-OCRv6"`) to use the PP-OCRv6 hosted OCR model.
Set `Model: paddleocr.PPOCRv5Latin` (or `"PP-OCRv5-latin"`) to use the PP-OCRv5 Latin-script hosted OCR model.
Document parsing defaults to PaddleOCR-VL-1.6:
```go
+3
View File
@@ -41,6 +41,9 @@ if err != nil {
fmt.Println(result.JobID, len(result.Pages))
```
将 `Model` 设为 `paddleocr.PPOCRv6`(或 `"PP-OCRv6"`)可使用 PP-OCRv6 云端 OCR 模型。
将 `Model` 设为 `paddleocr.PPOCRv5Latin`(或 `"PP-OCRv5-latin"`)可使用 PP-OCRv5 拉丁语系云端 OCR 模型。
文档解析默认使用 PaddleOCR-VL-1.6:
```go
-85
View File
@@ -1,85 +0,0 @@
package paddleocr
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestClientPlatformHeader(t *testing.T) {
var got string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("Client-Platform")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"code": 0,
"data": map[string]string{"jobId": "job-1"},
})
}))
defer server.Close()
client, err := NewClient(
WithToken("token"),
WithBaseURL(server.URL),
WithClientPlatform("my-app"),
)
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
job, err := client.SubmitOCR(context.Background(), &OCRRequest{
FileURL: "https://example.test/input.pdf",
})
if err != nil {
t.Fatalf("SubmitOCR() error = %v", err)
}
if job.JobID != "job-1" {
t.Fatalf("JobID = %q, want job-1", job.JobID)
}
if got != "my-app" {
t.Fatalf("Client-Platform = %q, want my-app", got)
}
}
func TestSubmitOCRAcceptsOfficialModelNameString(t *testing.T) {
var got string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Model string `json:"model"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("Decode request body error = %v", err)
}
got = body.Model
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"code": 0,
"data": map[string]string{"jobId": "job-1"},
})
}))
defer server.Close()
client, err := NewClient(
WithToken("token"),
WithBaseURL(server.URL),
)
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
job, err := client.SubmitOCR(context.Background(), &OCRRequest{
Model: "PP-OCRv5",
FileURL: "https://example.test/input.pdf",
})
if err != nil {
t.Fatalf("SubmitOCR() error = %v", err)
}
if job.Model != "PP-OCRv5" {
t.Fatalf("Job model = %q, want PP-OCRv5", job.Model)
}
if got != "PP-OCRv5" {
t.Fatalf("Request model = %q, want PP-OCRv5", got)
}
}
+235
View File
@@ -0,0 +1,235 @@
package paddleocr
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestClientPlatformHeader(t *testing.T) {
var got string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("Client-Platform")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"code": 0,
"data": map[string]string{"jobId": "job-1"},
})
}))
defer server.Close()
client, err := NewClient(
WithToken("token"),
WithBaseURL(server.URL),
WithClientPlatform("my-app"),
)
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
job, err := client.SubmitOCR(context.Background(), &OCRRequest{
FileURL: "https://example.test/input.pdf",
})
if err != nil {
t.Fatalf("SubmitOCR() error = %v", err)
}
if job.JobID != "job-1" {
t.Fatalf("JobID = %q, want job-1", job.JobID)
}
if got != "my-app" {
t.Fatalf("Client-Platform = %q, want my-app", got)
}
}
func TestDocumentParsingOptionsIncludeCurrentAndFutureServiceParameters(t *testing.T) {
trueValue := true
falseValue := false
var got map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
OptionalPayload map[string]interface{} `json:"optionalPayload"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("Decode request body error = %v", err)
}
got = body.OptionalPayload
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"code": 0,
"data": map[string]string{"jobId": "job-doc"},
})
}))
defer server.Close()
client, err := NewClient(
WithToken("token"),
WithBaseURL(server.URL),
)
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
_, err = client.SubmitDocumentParsing(context.Background(), &DocParsingRequest{
Model: PaddleOCRVL16,
FileURL: "https://example.test/doc.pdf",
Options: &PaddleOCRVLOptions{
UseOcrForImageBlock: &trueValue,
FormatBlockContent: &trueValue,
MarkdownIgnoreLabels: []string{"image"},
VlmExtraArgs: map[string]interface{}{"temperature": 0.1},
ReturnMarkdownImages: &falseValue,
OutputFormats: []string{"docx"},
ExtraOptions: map[string]interface{}{"futureOption": "enabled"},
},
})
if err != nil {
t.Fatalf("SubmitDocumentParsing() error = %v", err)
}
if got["useOcrForImageBlock"] != true || got["formatBlockContent"] != true {
t.Fatalf("got boolean options %#v", got)
}
if got["returnMarkdownImages"] != false || got["futureOption"] != "enabled" {
t.Fatalf("got passthrough options %#v", got)
}
}
func TestResultParsersPreserveRawFieldsAndDataInfo(t *testing.T) {
ocrLine := map[string]interface{}{
"result": map[string]interface{}{
"dataInfo": map[string]interface{}{"numPages": float64(1)},
"ocrResults": []interface{}{
map[string]interface{}{
"prunedResult": map[string]interface{}{"text": "hello"},
"ocrImage": "ocr.png",
"docPreprocessingImage": "pre.png",
"inputImage": "input.png",
},
},
},
}
ocrResult, err := parseOCRResult("job-ocr", []map[string]interface{}{ocrLine})
if err != nil {
t.Fatalf("parseOCRResult() error = %v", err)
}
if ocrResult.DataInfo["numPages"] != float64(1) {
t.Fatalf("OCR metadata not preserved: %#v", ocrResult)
}
if ocrResult.Pages[0].DocPreprocessingImageURL != "pre.png" || ocrResult.Pages[0].InputImageURL != "input.png" {
t.Fatalf("OCR page image URLs not preserved: %#v", ocrResult.Pages[0])
}
if ocrResult.Pages[0].Raw["ocrImage"] != "ocr.png" {
t.Fatalf("OCR raw page not preserved: %#v", ocrResult.Pages[0].Raw)
}
docPage := map[string]interface{}{
"prunedResult": map[string]interface{}{"blocks": []interface{}{map[string]interface{}{"label": "text"}}},
"markdown": map[string]interface{}{"text": "hello", "images": map[string]interface{}{"figure.png": "figure-url"}, "isStart": true},
"outputImages": map[string]interface{}{"page.png": "page-url"},
"inputImage": "input.png",
"exports": map[string]interface{}{"docx": "docx-url"},
}
docLine := map[string]interface{}{
"result": map[string]interface{}{
"dataInfo": map[string]interface{}{"numPages": float64(1)},
"layoutParsingResults": []interface{}{docPage},
},
}
docResult, err := parseDocParsingResult("job-doc", []map[string]interface{}{docLine})
if err != nil {
t.Fatalf("parseDocParsingResult() error = %v", err)
}
if docResult.DataInfo["numPages"] != float64(1) {
t.Fatalf("document metadata not preserved: %#v", docResult)
}
if docResult.Pages[0].PrunedResult == nil || docResult.Pages[0].Raw["inputImage"] != "input.png" {
t.Fatalf("document page raw fields not preserved: %#v", docResult.Pages[0])
}
if docResult.Pages[0].Exports["docx"] != "docx-url" || docResult.Pages[0].Markdown["isStart"] != true {
t.Fatalf("document structured fields not preserved: %#v", docResult.Pages[0])
}
}
func TestSubmitOCRAcceptsOfficialModelNameString(t *testing.T) {
var got string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Model string `json:"model"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("Decode request body error = %v", err)
}
got = body.Model
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"code": 0,
"data": map[string]string{"jobId": "job-1"},
})
}))
defer server.Close()
client, err := NewClient(
WithToken("token"),
WithBaseURL(server.URL),
)
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
job, err := client.SubmitOCR(context.Background(), &OCRRequest{
Model: "PP-OCRv5",
FileURL: "https://example.test/input.pdf",
})
if err != nil {
t.Fatalf("SubmitOCR() error = %v", err)
}
if job.Model != "PP-OCRv5" {
t.Fatalf("Job model = %q, want PP-OCRv5", job.Model)
}
if got != "PP-OCRv5" {
t.Fatalf("Request model = %q, want PP-OCRv5", got)
}
}
func TestSubmitOCRAcceptsPPOCRv5LatinModelNameString(t *testing.T) {
var got string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Model string `json:"model"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("Decode request body error = %v", err)
}
got = body.Model
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"code": 0,
"data": map[string]string{"jobId": "job-latin"},
})
}))
defer server.Close()
client, err := NewClient(
WithToken("token"),
WithBaseURL(server.URL),
)
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
job, err := client.SubmitOCR(context.Background(), &OCRRequest{
Model: PPOCRv5Latin,
FileURL: "https://example.test/latin.pdf",
})
if err != nil {
t.Fatalf("SubmitOCR() error = %v", err)
}
if job.Model != PPOCRv5Latin {
t.Fatalf("Job model = %q, want %s", job.Model, PPOCRv5Latin)
}
if got != PPOCRv5Latin {
t.Fatalf("Request model = %q, want %s", got, PPOCRv5Latin)
}
}
+2 -2
View File
@@ -15,8 +15,8 @@
// Package paddleocr provides a Go client for the PaddleOCR official API.
//
// Create a client with NewClient and authenticate with WithToken or the
// PADDLEOCR_ACCESS_TOKEN environment variable. Use OCR for OCR models such as
// PP-OCRv5 and ParseDocument for document parsing models such as PPStructureV3.
// PADDLEOCR_ACCESS_TOKEN environment variable. Use OCR for supported OCR models
// and ParseDocument for document parsing models.
// SubmitOCR and SubmitDocumentParsing return an Operation for non-blocking
// status checks with Poll or typed waits with WaitOCR and WaitDocumentParsing.
// SaveResource downloads one result resource URL. SaveOCRResultResources and
+77 -62
View File
@@ -16,6 +16,8 @@ package paddleocr
const (
PPOCRv5 = "PP-OCRv5"
PPOCRv5Latin = "PP-OCRv5-latin"
PPOCRv6 = "PP-OCRv6"
PPStructureV3 = "PP-StructureV3"
PaddleOCRVL = "PaddleOCR-VL"
PaddleOCRVL15 = "PaddleOCR-VL-1.5"
@@ -24,7 +26,7 @@ const (
// IsOCRModel reports whether model is supported by OCR APIs.
func IsOCRModel(model string) bool {
return model == PPOCRv5
return model == PPOCRv5 || model == PPOCRv5Latin || model == PPOCRv6
}
// IsDocumentParsingModel reports whether model is supported by document parsing APIs.
@@ -48,73 +50,86 @@ func IsVLModel(model string) bool {
}
type OCROptions struct {
UseDocOrientationClassify *bool `json:"useDocOrientationClassify,omitempty"`
UseDocUnwarping *bool `json:"useDocUnwarping,omitempty"`
UseTextlineOrientation *bool `json:"useTextlineOrientation,omitempty"`
TextDetLimitSideLen *int `json:"textDetLimitSideLen,omitempty"`
TextDetLimitType *string `json:"textDetLimitType,omitempty"`
TextDetThresh *float64 `json:"textDetThresh,omitempty"`
TextDetBoxThresh *float64 `json:"textDetBoxThresh,omitempty"`
TextDetUnclipRatio *float64 `json:"textDetUnclipRatio,omitempty"`
TextRecScoreThresh *float64 `json:"textRecScoreThresh,omitempty"`
Visualize *bool `json:"visualize,omitempty"`
UseDocOrientationClassify *bool `json:"useDocOrientationClassify,omitempty"`
UseDocUnwarping *bool `json:"useDocUnwarping,omitempty"`
UseTextlineOrientation *bool `json:"useTextlineOrientation,omitempty"`
TextDetLimitSideLen *int `json:"textDetLimitSideLen,omitempty"`
TextDetLimitType *string `json:"textDetLimitType,omitempty"`
TextDetThresh *float64 `json:"textDetThresh,omitempty"`
TextDetBoxThresh *float64 `json:"textDetBoxThresh,omitempty"`
TextDetUnclipRatio *float64 `json:"textDetUnclipRatio,omitempty"`
TextRecScoreThresh *float64 `json:"textRecScoreThresh,omitempty"`
Visualize *bool `json:"visualize,omitempty"`
ExtraOptions map[string]interface{} `json:"-"`
}
type PPStructureV3Options struct {
UseDocOrientationClassify *bool `json:"useDocOrientationClassify,omitempty"`
UseDocUnwarping *bool `json:"useDocUnwarping,omitempty"`
UseTextlineOrientation *bool `json:"useTextlineOrientation,omitempty"`
UseSealRecognition *bool `json:"useSealRecognition,omitempty"`
UseTableRecognition *bool `json:"useTableRecognition,omitempty"`
UseFormulaRecognition *bool `json:"useFormulaRecognition,omitempty"`
UseChartRecognition *bool `json:"useChartRecognition,omitempty"`
UseRegionDetection *bool `json:"useRegionDetection,omitempty"`
LayoutThreshold interface{} `json:"layoutThreshold,omitempty"`
LayoutNms *bool `json:"layoutNms,omitempty"`
LayoutUnclipRatio interface{} `json:"layoutUnclipRatio,omitempty"`
LayoutMergeBboxesMode *string `json:"layoutMergeBboxesMode,omitempty"`
TextDetLimitSideLen *int `json:"textDetLimitSideLen,omitempty"`
TextDetLimitType *string `json:"textDetLimitType,omitempty"`
TextDetThresh *float64 `json:"textDetThresh,omitempty"`
TextDetBoxThresh *float64 `json:"textDetBoxThresh,omitempty"`
TextDetUnclipRatio *float64 `json:"textDetUnclipRatio,omitempty"`
TextRecScoreThresh *float64 `json:"textRecScoreThresh,omitempty"`
UseWiredTableCellsTransToHtml *bool `json:"useWiredTableCellsTransToHtml,omitempty"`
UseWirelessTableCellsTransToHtml *bool `json:"useWirelessTableCellsTransToHtml,omitempty"`
UseTableOrientationClassify *bool `json:"useTableOrientationClassify,omitempty"`
UseOcrResultsWithTableCells *bool `json:"useOcrResultsWithTableCells,omitempty"`
UseE2eWiredTableRecModel *bool `json:"useE2eWiredTableRecModel,omitempty"`
UseE2eWirelessTableRecModel *bool `json:"useE2eWirelessTableRecModel,omitempty"`
PrettifyMarkdown *bool `json:"prettifyMarkdown,omitempty"`
ShowFormulaNumber *bool `json:"showFormulaNumber,omitempty"`
Visualize *bool `json:"visualize,omitempty"`
UseDocOrientationClassify *bool `json:"useDocOrientationClassify,omitempty"`
UseDocUnwarping *bool `json:"useDocUnwarping,omitempty"`
UseTextlineOrientation *bool `json:"useTextlineOrientation,omitempty"`
UseSealRecognition *bool `json:"useSealRecognition,omitempty"`
UseTableRecognition *bool `json:"useTableRecognition,omitempty"`
UseFormulaRecognition *bool `json:"useFormulaRecognition,omitempty"`
UseChartRecognition *bool `json:"useChartRecognition,omitempty"`
UseRegionDetection *bool `json:"useRegionDetection,omitempty"`
LayoutThreshold interface{} `json:"layoutThreshold,omitempty"`
LayoutNms *bool `json:"layoutNms,omitempty"`
LayoutUnclipRatio interface{} `json:"layoutUnclipRatio,omitempty"`
LayoutMergeBboxesMode interface{} `json:"layoutMergeBboxesMode,omitempty"`
FormatBlockContent *bool `json:"formatBlockContent,omitempty"`
TextDetLimitSideLen *int `json:"textDetLimitSideLen,omitempty"`
TextDetLimitType *string `json:"textDetLimitType,omitempty"`
TextDetThresh *float64 `json:"textDetThresh,omitempty"`
TextDetBoxThresh *float64 `json:"textDetBoxThresh,omitempty"`
TextDetUnclipRatio *float64 `json:"textDetUnclipRatio,omitempty"`
TextRecScoreThresh *float64 `json:"textRecScoreThresh,omitempty"`
UseWiredTableCellsTransToHtml *bool `json:"useWiredTableCellsTransToHtml,omitempty"`
UseWirelessTableCellsTransToHtml *bool `json:"useWirelessTableCellsTransToHtml,omitempty"`
UseTableOrientationClassify *bool `json:"useTableOrientationClassify,omitempty"`
UseOcrResultsWithTableCells *bool `json:"useOcrResultsWithTableCells,omitempty"`
UseE2eWiredTableRecModel *bool `json:"useE2eWiredTableRecModel,omitempty"`
UseE2eWirelessTableRecModel *bool `json:"useE2eWirelessTableRecModel,omitempty"`
MarkdownIgnoreLabels []string `json:"markdownIgnoreLabels,omitempty"`
PrettifyMarkdown *bool `json:"prettifyMarkdown,omitempty"`
ShowFormulaNumber *bool `json:"showFormulaNumber,omitempty"`
ReturnMarkdownImages *bool `json:"returnMarkdownImages,omitempty"`
OutputFormats []string `json:"outputFormats,omitempty"`
Visualize *bool `json:"visualize,omitempty"`
ExtraOptions map[string]interface{} `json:"-"`
}
type PaddleOCRVLOptions struct {
UseDocOrientationClassify *bool `json:"useDocOrientationClassify,omitempty"`
UseDocUnwarping *bool `json:"useDocUnwarping,omitempty"`
UseLayoutDetection *bool `json:"useLayoutDetection,omitempty"`
UseChartRecognition *bool `json:"useChartRecognition,omitempty"`
UseSealRecognition *bool `json:"useSealRecognition,omitempty"`
LayoutThreshold interface{} `json:"layoutThreshold,omitempty"`
LayoutNms *bool `json:"layoutNms,omitempty"`
LayoutUnclipRatio interface{} `json:"layoutUnclipRatio,omitempty"`
LayoutMergeBboxesMode interface{} `json:"layoutMergeBboxesMode,omitempty"`
LayoutShapeMode *string `json:"layoutShapeMode,omitempty"`
PromptLabel *string `json:"promptLabel,omitempty"`
RepetitionPenalty *float64 `json:"repetitionPenalty,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"topP,omitempty"`
MinPixels *int `json:"minPixels,omitempty"`
MaxPixels *int `json:"maxPixels,omitempty"`
MaxNewTokens *int `json:"maxNewTokens,omitempty"`
MergeLayoutBlocks *bool `json:"mergeLayoutBlocks,omitempty"`
PrettifyMarkdown *bool `json:"prettifyMarkdown,omitempty"`
ShowFormulaNumber *bool `json:"showFormulaNumber,omitempty"`
RestructurePages *bool `json:"restructurePages,omitempty"`
MergeTables *bool `json:"mergeTables,omitempty"`
RelevelTitles *bool `json:"relevelTitles,omitempty"`
Visualize *bool `json:"visualize,omitempty"`
UseDocOrientationClassify *bool `json:"useDocOrientationClassify,omitempty"`
UseDocUnwarping *bool `json:"useDocUnwarping,omitempty"`
UseLayoutDetection *bool `json:"useLayoutDetection,omitempty"`
UseChartRecognition *bool `json:"useChartRecognition,omitempty"`
UseSealRecognition *bool `json:"useSealRecognition,omitempty"`
UseOcrForImageBlock *bool `json:"useOcrForImageBlock,omitempty"`
LayoutThreshold interface{} `json:"layoutThreshold,omitempty"`
LayoutNms *bool `json:"layoutNms,omitempty"`
LayoutUnclipRatio interface{} `json:"layoutUnclipRatio,omitempty"`
LayoutMergeBboxesMode interface{} `json:"layoutMergeBboxesMode,omitempty"`
LayoutShapeMode *string `json:"layoutShapeMode,omitempty"`
PromptLabel *string `json:"promptLabel,omitempty"`
FormatBlockContent *bool `json:"formatBlockContent,omitempty"`
RepetitionPenalty *float64 `json:"repetitionPenalty,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"topP,omitempty"`
MinPixels *int `json:"minPixels,omitempty"`
MaxPixels *int `json:"maxPixels,omitempty"`
MaxNewTokens *int `json:"maxNewTokens,omitempty"`
VlmExtraArgs map[string]interface{} `json:"vlmExtraArgs,omitempty"`
MergeLayoutBlocks *bool `json:"mergeLayoutBlocks,omitempty"`
MarkdownIgnoreLabels []string `json:"markdownIgnoreLabels,omitempty"`
PrettifyMarkdown *bool `json:"prettifyMarkdown,omitempty"`
ShowFormulaNumber *bool `json:"showFormulaNumber,omitempty"`
RestructurePages *bool `json:"restructurePages,omitempty"`
MergeTables *bool `json:"mergeTables,omitempty"`
RelevelTitles *bool `json:"relevelTitles,omitempty"`
ReturnMarkdownImages *bool `json:"returnMarkdownImages,omitempty"`
OutputFormats []string `json:"outputFormats,omitempty"`
Visualize *bool `json:"visualize,omitempty"`
ExtraOptions map[string]interface{} `json:"-"`
}
// DocParsingOptionsProvider marks document parsing option structs.
+72 -13
View File
@@ -19,7 +19,6 @@ import (
"encoding/json"
)
// OCR performs PP-OCRv5 text recognition. Blocks until result is ready.
func (c *Client) OCR(ctx context.Context, req *OCRRequest) (*OCRResult, error) {
job, err := c.SubmitOCR(ctx, req)
if err != nil {
@@ -44,7 +43,7 @@ func (c *Client) SubmitOCR(ctx context.Context, req *OCRRequest) (*Job, error) {
}
model := req.Model
if model == "" {
model = PPOCRv5
model = PPOCRv6
}
if !IsOCRModel(model) {
return nil, &InvalidRequestError{PaddleOCRAPIError{Message: "model is not an OCR model: " + model}}
@@ -123,25 +122,65 @@ func (c *Client) submit(ctx context.Context, model, fileURL, filePath string, op
}
func defaultPayload(model string, options interface{}) interface{} {
if options != nil {
return options
switch typed := options.(type) {
case *OCROptions:
if typed != nil {
return payloadWithExtraOptions(typed)
}
case *PPStructureV3Options:
if typed != nil {
return payloadWithExtraOptions(typed)
}
case *PaddleOCRVLOptions:
if typed != nil {
return payloadWithExtraOptions(typed)
}
default:
if options != nil {
return payloadWithExtraOptions(options)
}
}
if model == PPOCRv5 {
return &OCROptions{}
if IsOCRModel(model) {
return payloadWithExtraOptions(&OCROptions{})
}
if IsVLModel(model) {
return &PaddleOCRVLOptions{}
return payloadWithExtraOptions(&PaddleOCRVLOptions{})
}
return &PPStructureV3Options{}
return payloadWithExtraOptions(&PPStructureV3Options{})
}
func payloadWithExtraOptions(options interface{}) interface{} {
payloadBytes, _ := json.Marshal(options)
payload := map[string]interface{}{}
_ = json.Unmarshal(payloadBytes, &payload)
var extraOptions map[string]interface{}
switch typed := options.(type) {
case *OCROptions:
extraOptions = typed.ExtraOptions
case *PPStructureV3Options:
extraOptions = typed.ExtraOptions
case *PaddleOCRVLOptions:
extraOptions = typed.ExtraOptions
}
for key, value := range extraOptions {
payload[key] = value
}
return payload
}
func parseOCRResult(jobID string, jsonlData []map[string]interface{}) (*OCRResult, error) {
result := &OCRResult{JobID: jobID}
result := &OCRResult{JobID: jobID, DataInfo: map[string]interface{}{}}
for _, lineObj := range jsonlData {
resultData, ok := lineObj["result"].(map[string]interface{})
if !ok {
return nil, &ResultParseError{PaddleOCRAPIError{Message: "OCR result item is missing result"}}
}
if dataInfo, ok := resultData["dataInfo"].(map[string]interface{}); ok {
for key, value := range dataInfo {
result.DataInfo[key] = value
}
}
ocrResults, ok := resultData["ocrResults"].([]interface{})
if !ok {
return nil, &ResultParseError{PaddleOCRAPIError{Message: "OCR result item is missing ocrResults"}}
@@ -155,9 +194,11 @@ func parseOCRResult(jobID string, jsonlData []map[string]interface{}) (*OCRResul
return nil, &ResultParseError{PaddleOCRAPIError{Message: "OCR result page is missing prunedResult"}}
}
page := OCRPage{
PrunedResult: itemMap["prunedResult"],
OCRImageURL: getString(itemMap, "ocrImage"),
Raw: itemMap,
PrunedResult: itemMap["prunedResult"],
OCRImageURL: getString(itemMap, "ocrImage"),
DocPreprocessingImageURL: getString(itemMap, "docPreprocessingImage"),
InputImageURL: getString(itemMap, "inputImage"),
Raw: itemMap,
}
result.Pages = append(result.Pages, page)
}
@@ -166,12 +207,17 @@ func parseOCRResult(jobID string, jsonlData []map[string]interface{}) (*OCRResul
}
func parseDocParsingResult(jobID string, jsonlData []map[string]interface{}) (*DocParsingResult, error) {
result := &DocParsingResult{JobID: jobID}
result := &DocParsingResult{JobID: jobID, DataInfo: map[string]interface{}{}}
for _, lineObj := range jsonlData {
resultData, ok := lineObj["result"].(map[string]interface{})
if !ok {
return nil, &ResultParseError{PaddleOCRAPIError{Message: "document parsing result item is missing result"}}
}
if dataInfo, ok := resultData["dataInfo"].(map[string]interface{}); ok {
for key, value := range dataInfo {
result.DataInfo[key] = value
}
}
lpResults, ok := resultData["layoutParsingResults"].([]interface{})
if !ok {
return nil, &ResultParseError{PaddleOCRAPIError{Message: "document parsing result item is missing layoutParsingResults"}}
@@ -189,6 +235,11 @@ func parseDocParsingResult(jobID string, jsonlData []map[string]interface{}) (*D
MarkdownText: getString(markdown, "text"),
MarkdownImages: getStringMap(markdown, "images"),
OutputImages: getStringMap(itemMap, "outputImages"),
PrunedResult: itemMap["prunedResult"],
InputImageURL: getString(itemMap, "inputImage"),
Exports: getMap(itemMap, "exports"),
Markdown: markdown,
Raw: itemMap,
}
result.Pages = append(result.Pages, page)
}
@@ -204,6 +255,14 @@ func getString(m map[string]interface{}, key string) string {
return v
}
func getMap(m map[string]interface{}, key string) map[string]interface{} {
value, ok := m[key].(map[string]interface{})
if !ok {
return map[string]interface{}{}
}
return value
}
func getStringMap(m map[string]interface{}, key string) map[string]string {
if m == nil {
return nil
+1 -1
View File
@@ -33,7 +33,7 @@ func (op *Operation) Wait(ctx context.Context) (interface{}, error) {
if err != nil {
return nil, err
}
if op.model == PPOCRv5 {
if IsOCRModel(op.model) {
return parseOCRResult(op.JobID, jsonlData)
}
return parseDocParsingResult(op.JobID, jsonlData)
+19 -10
View File
@@ -15,25 +15,34 @@
package paddleocr
type OCRPage struct {
PrunedResult interface{} `json:"prunedResult"`
OCRImageURL string `json:"ocrImageUrl,omitempty"`
Raw map[string]interface{} `json:"raw,omitempty"`
PrunedResult interface{} `json:"prunedResult"`
OCRImageURL string `json:"ocrImageUrl,omitempty"`
DocPreprocessingImageURL string `json:"docPreprocessingImageUrl,omitempty"`
InputImageURL string `json:"inputImageUrl,omitempty"`
Raw map[string]interface{} `json:"raw,omitempty"`
}
type DocParsingPage struct {
MarkdownText string `json:"markdownText"`
MarkdownImages map[string]string `json:"markdownImages"`
OutputImages map[string]string `json:"outputImages"`
MarkdownText string `json:"markdownText"`
MarkdownImages map[string]string `json:"markdownImages"`
OutputImages map[string]string `json:"outputImages"`
PrunedResult interface{} `json:"prunedResult,omitempty"`
InputImageURL string `json:"inputImageUrl,omitempty"`
Exports map[string]interface{} `json:"exports,omitempty"`
Markdown map[string]interface{} `json:"markdown,omitempty"`
Raw map[string]interface{} `json:"raw,omitempty"`
}
type OCRResult struct {
JobID string `json:"jobId"`
Pages []OCRPage `json:"pages"`
JobID string `json:"jobId"`
Pages []OCRPage `json:"pages"`
DataInfo map[string]interface{} `json:"dataInfo,omitempty"`
}
type DocParsingResult struct {
JobID string `json:"jobId"`
Pages []DocParsingPage `json:"pages"`
JobID string `json:"jobId"`
Pages []DocParsingPage `json:"pages"`
DataInfo map[string]interface{} `json:"dataInfo,omitempty"`
}
type Progress struct {
+3
View File
@@ -46,6 +46,9 @@ const result = await client.ocr({
console.log(result.jobId, result.pages.length);
```
Specify `model: Model.PPOCRv6` (or `"PP-OCRv6"`) to use the PP-OCRv6 hosted OCR model.
Use `Model.PPOCRv5Latin` (or `"PP-OCRv5-latin"`) for the PP-OCRv5 Latin-script hosted OCR model.
Document parsing defaults to PaddleOCR-VL-1.6:
```ts
+3
View File
@@ -44,6 +44,9 @@ const result = await client.ocr({
console.log(result.jobId, result.pages.length);
```
通过 `model: Model.PPOCRv6`(或 `"PP-OCRv6"`)可指定 PP-OCRv6 云端 OCR 模型。
使用 `Model.PPOCRv5Latin`(或 `"PP-OCRv5-latin"`)可指定 PP-OCRv5 拉丁语系云端 OCR 模型。
文档解析默认使用 PaddleOCR-VL-1.6:
```ts
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@paddleocr/api-sdk",
"version": "0.1.0",
"version": "0.2.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@paddleocr/api-sdk",
"version": "0.1.0",
"version": "0.2.2",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^25.9.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@paddleocr/api-sdk",
"version": "0.1.0",
"version": "0.2.3",
"description": "TypeScript SDK for the PaddleOCR official API",
"type": "module",
"main": "./dist/index.cjs",
+19 -4
View File
@@ -62,7 +62,7 @@ export class PaddleOCRClient {
}
async submitOcr(req: OCRRequest, options?: { signal?: AbortSignal }): Promise<Job> {
const model = req.model ?? Model.PPOCRv5;
const model = req.model ?? Model.PPOCRv6;
const jobId = await this.submit(model, "ocr", req, options?.signal);
return { jobId, model, task: "ocr", pageRanges: req.pageRanges, batchId: req.batchId };
}
@@ -274,10 +274,14 @@ export class PaddleOCRClient {
}
private parseOCRResult(jobId: string, jsonlData: unknown[]): OCRResult {
const dataInfo: Record<string, unknown> = {};
const pages = jsonlData.flatMap((lineObj) => {
if (!isRecord(lineObj) || !isRecord(lineObj.result) || !Array.isArray(lineObj.result.ocrResults)) {
throw new ResultParseError("OCR result item is missing result.ocrResults.");
}
if (isRecord(lineObj.result.dataInfo)) {
Object.assign(dataInfo, lineObj.result.dataInfo);
}
return lineObj.result.ocrResults.map((item) => {
if (!isRecord(item) || !("prunedResult" in item)) {
throw new ResultParseError("OCR result page is missing prunedResult.");
@@ -285,18 +289,24 @@ export class PaddleOCRClient {
return {
prunedResult: item.prunedResult,
ocrImageUrl: typeof item.ocrImage === "string" ? item.ocrImage : undefined,
docPreprocessingImageUrl: typeof item.docPreprocessingImage === "string" ? item.docPreprocessingImage : undefined,
inputImageUrl: typeof item.inputImage === "string" ? item.inputImage : undefined,
raw: item,
};
});
});
return { jobId, pages };
return { jobId, pages, dataInfo };
}
private parseDocParsingResult(jobId: string, jsonlData: unknown[]): DocParsingResult {
const dataInfo: Record<string, unknown> = {};
const pages = jsonlData.flatMap((lineObj) => {
if (!isRecord(lineObj) || !isRecord(lineObj.result) || !Array.isArray(lineObj.result.layoutParsingResults)) {
throw new ResultParseError("Document parsing result item is missing result.layoutParsingResults.");
}
if (isRecord(lineObj.result.dataInfo)) {
Object.assign(dataInfo, lineObj.result.dataInfo);
}
return lineObj.result.layoutParsingResults.map((item) => {
if (!isRecord(item) || !isRecord(item.markdown) || typeof item.markdown.text !== "string") {
throw new ResultParseError("Document parsing result page is missing markdown.text.");
@@ -305,17 +315,22 @@ export class PaddleOCRClient {
markdownText: item.markdown.text,
markdownImages: isRecord(item.markdown.images) ? stringMap(item.markdown.images) : {},
outputImages: isRecord(item.outputImages) ? stringMap(item.outputImages) : {},
prunedResult: item.prunedResult,
inputImageUrl: typeof item.inputImage === "string" ? item.inputImage : undefined,
exports: isRecord(item.exports) ? item.exports : {},
markdown: item.markdown,
raw: item,
};
});
});
return { jobId, pages };
return { jobId, pages, dataInfo };
}
private resolveJob(job: Job | string, expectedTask: Job["task"]): Job {
if (typeof job === "string") {
return {
jobId: job,
model: expectedTask === "ocr" ? Model.PPOCRv5 : Model.PaddleOCRVL16,
model: expectedTask === "ocr" ? Model.PPOCRv6 : Model.PaddleOCRVL16,
task: expectedTask,
};
}
+20 -3
View File
@@ -14,13 +14,15 @@
export enum Model {
PPOCRv5 = "PP-OCRv5",
PPOCRv5Latin = "PP-OCRv5-latin",
PPOCRv6 = "PP-OCRv6",
PPStructureV3 = "PP-StructureV3",
PaddleOCRVL = "PaddleOCR-VL",
PaddleOCRVL15 = "PaddleOCR-VL-1.5",
PaddleOCRVL16 = "PaddleOCR-VL-1.6",
}
const OCR_MODELS = new Set<string>([Model.PPOCRv5]);
const OCR_MODELS = new Set<string>([Model.PPOCRv5, Model.PPOCRv5Latin, Model.PPOCRv6]);
const DOCUMENT_PARSING_MODELS = new Set<string>([
Model.PPStructureV3,
Model.PaddleOCRVL,
@@ -33,7 +35,9 @@ const VL_MODELS = new Set<string>([
Model.PaddleOCRVL16,
]);
export function isOCRModel(model: string): model is Model.PPOCRv5 {
export function isOCRModel(
model: string
): model is Model.PPOCRv5 | Model.PPOCRv5Latin | Model.PPOCRv6 {
return OCR_MODELS.has(model);
}
@@ -56,6 +60,7 @@ export interface OCROptions {
textDetUnclipRatio?: number;
textRecScoreThresh?: number;
visualize?: boolean;
[key: string]: unknown;
}
export interface PPStructureV3Options {
@@ -70,7 +75,8 @@ export interface PPStructureV3Options {
layoutThreshold?: number | Record<string, number>;
layoutNms?: boolean;
layoutUnclipRatio?: number | number[] | Record<string, number>;
layoutMergeBboxesMode?: string;
layoutMergeBboxesMode?: string | Record<string, string>;
formatBlockContent?: boolean;
textDetLimitSideLen?: number;
textDetLimitType?: string;
textDetThresh?: number;
@@ -83,9 +89,13 @@ export interface PPStructureV3Options {
useOcrResultsWithTableCells?: boolean;
useE2eWiredTableRecModel?: boolean;
useE2eWirelessTableRecModel?: boolean;
markdownIgnoreLabels?: string[];
prettifyMarkdown?: boolean;
showFormulaNumber?: boolean;
returnMarkdownImages?: boolean;
outputFormats?: string[];
visualize?: boolean;
[key: string]: unknown;
}
export interface PaddleOCRVLOptions {
@@ -94,25 +104,32 @@ export interface PaddleOCRVLOptions {
useLayoutDetection?: boolean;
useChartRecognition?: boolean;
useSealRecognition?: boolean;
useOcrForImageBlock?: boolean;
layoutThreshold?: number | Record<string, number>;
layoutNms?: boolean;
layoutUnclipRatio?: number | number[] | Record<string, number>;
layoutMergeBboxesMode?: string | Record<string, string>;
layoutShapeMode?: "rect" | "quad" | "poly" | "auto";
promptLabel?: "ocr" | "formula" | "table" | "chart" | "seal" | "spotting";
formatBlockContent?: boolean;
repetitionPenalty?: number;
temperature?: number;
topP?: number;
minPixels?: number;
maxPixels?: number;
maxNewTokens?: number;
vlmExtraArgs?: Record<string, unknown>;
mergeLayoutBlocks?: boolean;
markdownIgnoreLabels?: string[];
prettifyMarkdown?: boolean;
showFormulaNumber?: boolean;
restructurePages?: boolean;
mergeTables?: boolean;
relevelTitles?: boolean;
returnMarkdownImages?: boolean;
outputFormats?: string[];
visualize?: boolean;
[key: string]: unknown;
}
export type DocParsingOptions = PPStructureV3Options | PaddleOCRVLOptions;
+9
View File
@@ -15,6 +15,8 @@
export interface OCRPage {
prunedResult: unknown;
ocrImageUrl?: string;
docPreprocessingImageUrl?: string;
inputImageUrl?: string;
raw?: unknown;
}
@@ -22,16 +24,23 @@ export interface DocParsingPage {
markdownText: string;
markdownImages: Record<string, string>;
outputImages: Record<string, string>;
prunedResult?: unknown;
inputImageUrl?: string;
exports?: Record<string, unknown>;
markdown?: Record<string, unknown>;
raw?: unknown;
}
export interface OCRResult {
jobId: string;
pages: OCRPage[];
dataInfo?: Record<string, unknown>;
}
export interface DocParsingResult {
jobId: string;
pages: DocParsingPage[];
dataInfo?: Record<string, unknown>;
}
export interface Progress {
+124 -7
View File
@@ -113,7 +113,7 @@ describe("PaddleOCRClient public contract", () => {
expect(job).toEqual({
jobId: "job-1",
model: Model.PPOCRv5,
model: Model.PPOCRv6,
task: "ocr",
pageRanges: "1-2",
batchId: "batch-1",
@@ -126,7 +126,7 @@ describe("PaddleOCRClient public contract", () => {
});
expect(JSON.parse(String(calls[0].init.body))).toEqual({
fileUrl: "https://files.example.test/invoice.pdf",
model: Model.PPOCRv5,
model: Model.PPOCRv6,
optionalPayload: { visualize: true },
pageRanges: "1-2",
batchId: "batch-1",
@@ -146,7 +146,7 @@ describe("PaddleOCRClient public contract", () => {
});
});
test("submitOcr propagates explicit OCR model and defaults to PP-OCRv5", async () => {
test("submitOcr propagates explicit OCR model and defaults to PP-OCRv6", async () => {
const { fetch, calls } = captureFetch([
jsonResponse({ data: { jobId: "job-explicit" } }),
jsonResponse({ data: { jobId: "job-default" } }),
@@ -162,9 +162,35 @@ describe("PaddleOCRClient public contract", () => {
});
expect(explicit.model).toBe(Model.PPOCRv5);
expect(implicit.model).toBe(Model.PPOCRv5);
expect(implicit.model).toBe(Model.PPOCRv6);
expect(JSON.parse(String(calls[0].init.body)).model).toBe(Model.PPOCRv5);
expect(JSON.parse(String(calls[1].init.body)).model).toBe(Model.PPOCRv5);
expect(JSON.parse(String(calls[1].init.body)).model).toBe(Model.PPOCRv6);
});
test("submitOcr accepts PP-OCRv6 model name", async () => {
const { fetch, calls } = captureFetch([jsonResponse({ data: { jobId: "job-v6" } })]);
const client = createClient(fetch);
const job = await client.submitOcr({
model: Model.PPOCRv6,
fileUrl: "https://files.example.test/v6.pdf",
});
expect(job.model).toBe(Model.PPOCRv6);
expect(JSON.parse(String(calls[0].init.body)).model).toBe(Model.PPOCRv6);
});
test("submitOcr accepts PP-OCRv5-latin model name", async () => {
const { fetch, calls } = captureFetch([jsonResponse({ data: { jobId: "job-latin" } })]);
const client = createClient(fetch);
const job = await client.submitOcr({
model: Model.PPOCRv5Latin,
fileUrl: "https://files.example.test/latin.pdf",
});
expect(job.model).toBe(Model.PPOCRv5Latin);
expect(JSON.parse(String(calls[0].init.body)).model).toBe(Model.PPOCRv5Latin);
});
test("submitOcr and submitDocumentParsing accept official model name strings", async () => {
@@ -193,6 +219,8 @@ describe("PaddleOCRClient public contract", () => {
const mod = await import("../src/index.js");
expect(mod.isOCRModel(Model.PPOCRv5)).toBe(true);
expect(mod.isOCRModel(Model.PPOCRv5Latin)).toBe(true);
expect(mod.isOCRModel(Model.PPOCRv6)).toBe(true);
expect(mod.isOCRModel(Model.PPStructureV3)).toBe(false);
expect(mod.isOCRModel("future-unknown-model")).toBe(false);
expect(mod.isDocumentParsingModel(Model.PaddleOCRVL)).toBe(true);
@@ -200,6 +228,35 @@ describe("PaddleOCRClient public contract", () => {
expect(mod.isDocumentParsingModel(Model.PPOCRv5)).toBe(false);
});
test("submitDocumentParsing passes current and future document parsing options", async () => {
const { fetch, calls } = captureFetch([jsonResponse({ data: { jobId: "job-doc" } })]);
const client = createClient(fetch);
await client.submitDocumentParsing({
model: Model.PaddleOCRVL16,
fileUrl: "https://files.example.test/doc.pdf",
options: {
useOcrForImageBlock: true,
formatBlockContent: true,
markdownIgnoreLabels: ["image"],
vlmExtraArgs: { temperature: 0.1 },
returnMarkdownImages: false,
outputFormats: ["docx"],
futureOption: "enabled",
},
});
expect(JSON.parse(String(calls[0].init.body)).optionalPayload).toEqual({
useOcrForImageBlock: true,
formatBlockContent: true,
markdownIgnoreLabels: ["image"],
vlmExtraArgs: { temperature: 0.1 },
returnMarkdownImages: false,
outputFormats: ["docx"],
futureOption: "enabled",
});
});
test("submitDocumentParsing defaults to PaddleOCR-VL-1.6", async () => {
const { fetch, calls } = captureFetch([jsonResponse({ data: { jobId: "job-doc" } })]);
const client = createClient(fetch);
@@ -269,13 +326,41 @@ describe("PaddleOCRClient public contract", () => {
test("typed wait accepts bare jobId, fetches JSONL without Authorization, and parses OCR results", async () => {
const { fetch, calls } = captureFetch([
jsonResponse({ data: { state: "done", resultUrl: { jsonUrl: "https://storage.example.test/job-1.jsonl" } } }),
textResponse(JSON.stringify({ result: { ocrResults: [{ prunedResult: { text: "hello" }, ocrImage: "img.png" }] } })),
textResponse(
JSON.stringify({
result: {
dataInfo: { numPages: 1 },
ocrResults: [
{
prunedResult: { text: "hello" },
ocrImage: "img.png",
docPreprocessingImage: "pre.png",
inputImage: "input.png",
},
],
},
}),
),
]);
const client = createClient(fetch);
await expect(client.waitOcrResult("job-1")).resolves.toMatchObject({
jobId: "job-1",
pages: [{ prunedResult: { text: "hello" }, ocrImageUrl: "img.png" }],
dataInfo: { numPages: 1 },
pages: [
{
prunedResult: { text: "hello" },
ocrImageUrl: "img.png",
docPreprocessingImageUrl: "pre.png",
inputImageUrl: "input.png",
raw: {
prunedResult: { text: "hello" },
ocrImage: "img.png",
docPreprocessingImage: "pre.png",
inputImage: "input.png",
},
},
],
});
expect(calls[1].url).toBe("https://storage.example.test/job-1.jsonl");
expect((calls[1].init.headers as Record<string, string>).Authorization).toBeUndefined();
@@ -359,6 +444,38 @@ describe("PaddleOCRClient public contract", () => {
await expect(client.waitOcrResult("job-1")).rejects.toThrow(ResultParseError);
});
test("waitDocumentParsingResult preserves raw page data and dataInfo", async () => {
const page = {
prunedResult: { blocks: [{ label: "text", content: "hello" }] },
markdown: { text: "hello", images: { "figure.png": "https://example.test/figure.png" }, isStart: true, isEnd: true },
outputImages: { "page.png": "https://example.test/page.png" },
inputImage: "https://example.test/input.png",
exports: { docx: "https://example.test/result.docx" },
};
const { fetch } = captureFetch([
jsonResponse({ data: { state: "done", resultUrl: { jsonUrl: "https://storage.example.test/job.jsonl" } } }),
textResponse(JSON.stringify({ result: { dataInfo: { numPages: 1 }, layoutParsingResults: [page] } })),
]);
const client = createClient(fetch);
await expect(client.waitDocumentParsingResult("job-1")).resolves.toMatchObject({
jobId: "job-1",
dataInfo: { numPages: 1 },
pages: [
{
markdownText: "hello",
markdownImages: { "figure.png": "https://example.test/figure.png" },
outputImages: { "page.png": "https://example.test/page.png" },
prunedResult: { blocks: [{ label: "text", content: "hello" }] },
inputImageUrl: "https://example.test/input.png",
exports: { docx: "https://example.test/result.docx" },
markdown: page.markdown,
raw: page,
},
],
});
});
test("malformed fetched document result records use ResultParseError", async () => {
const client = createClient(
captureFetch([
@@ -1,11 +1,11 @@
Global:
model_name: PP-OCRv6_base_rec
model_name: PP-OCRv6_medium_rec
debug: false
use_gpu: true
epoch_num: 100
log_smooth_window: 20
print_batch_step: 10
save_model_dir: ./output/PP-OCRv6_base_rec
save_model_dir: ./output/PP-OCRv6_medium_rec
save_epoch_step: 10
eval_batch_step: [0, 2000]
cal_metric_during_train: true
@@ -14,12 +14,12 @@ Global:
save_inference_dir:
use_visualdl: false
infer_img: doc/imgs_words/ch/word_1.jpg
character_dict_path: ppocr/utils/dict/ppocrv5_dict.txt
character_dict_path: ppocr/utils/dict/ppocrv6_dict.txt
max_text_length: &max_text_length 25
infer_mode: false
use_space_char: true
distributed: true
save_res_path: ./output/rec/predicts_ppocrv6_base.txt
save_res_path: ./output/rec/predicts_ppocrv6_medium.txt
d2s_train_image_shape: [3, 48, 320]
@@ -42,7 +42,7 @@ Architecture:
Transform:
Backbone:
name: PPLCNetV4
model_size: base
model_size: medium
Head:
name: MultiHead
head_list:
@@ -50,14 +50,14 @@ Architecture:
Neck:
name: lightsvtr
dims: 192
depth: 3
depth: 2
mlp_ratio: 4.0
local_kernel: 7
use_guide: true
use_guide: false
Head:
fc_decay: 0.00001
- NRTRHead:
nrtr_dim: 384
nrtr_dim: 512
max_text_length: *max_text_length
Loss:
+1 -1
View File
@@ -14,7 +14,7 @@ Global:
save_inference_dir:
use_visualdl: false
infer_img: doc/imgs_words/ch/word_1.jpg
character_dict_path: ppocr/utils/dict/ppocrv5_dict.txt
character_dict_path: ppocr/utils/dict/ppocrv6_dict.txt
max_text_length: &max_text_length 25
infer_mode: false
use_space_char: true
+1 -1
View File
@@ -14,7 +14,7 @@ Global:
save_inference_dir:
use_visualdl: false
infer_img: doc/imgs_words/ch/word_1.jpg
character_dict_path: ppocr/utils/ppocr_keys_v1.txt
character_dict_path: ppocr/utils/dict/ppocrv6_tiny_dict.txt
max_text_length: &max_text_length 25
infer_mode: false
use_space_char: true
+2 -2
View File
@@ -24,7 +24,7 @@ SubPipelines:
SubModules:
TextDetection:
module_name: text_detection
model_name: PP-OCRv5_server_det
model_name: PP-OCRv6_medium_det
model_dir: null
limit_side_len: 64
limit_type: min
@@ -39,7 +39,7 @@ SubModules:
batch_size: 6
TextRecognition:
module_name: text_recognition
model_name: PP-OCRv5_server_rec
model_name: PP-OCRv6_medium_rec
model_dir: null
batch_size: 6
score_thresh: 0.0
+1 -1
View File
@@ -36,7 +36,7 @@ HPS_INFERENCE_TIMEOUT=600
# Health check timeout in seconds
HPS_HEALTH_CHECK_TIMEOUT=5
# VLM server URL for health checks
# VLM server URL
# HPS_VLM_URL=http://paddleocr-vlm-server:8080
# Log level: DEBUG, INFO, WARNING, ERROR
+1 -1
View File
@@ -112,7 +112,7 @@ export HPS_MAX_CONCURRENT_INFERENCE_REQUESTS=8
| `HPS_MAX_CONCURRENT_NON_INFERENCE_REQUESTS` | 64                | 非推理操作(多页重组)最大并发请求数  |
| `HPS_INFERENCE_TIMEOUT`           | 600               | 请求超时时间(秒)           |
| `HPS_HEALTH_CHECK_TIMEOUT`         | 5                | 健康检查超时时间(秒)         |
| `HPS_VLM_URL`                | http://paddleocr-vlm-server:8080 | VLM 服务器地址(用于健康检查)     |
| `HPS_VLM_URL`                | http://paddleocr-vlm-server:8080 | VLM 服务器地址 |
| `HPS_LOG_LEVEL`               | INFO               | 日志级别(DEBUG, INFO, WARNING, ERROR) |
| `HPS_FILTER_HEALTH_ACCESS_LOG`       | true               | 是否过滤健康检查的访问日志       |
| `HPS_UVICORN_WORKERS`            | 4                | 网关 Worker 进程数           |
+1 -1
View File
@@ -112,7 +112,7 @@ Common examples:
| `HPS_MAX_CONCURRENT_NON_INFERENCE_REQUESTS` | 64 | Max concurrent non-inference requests (page restructuring) |
| `HPS_INFERENCE_TIMEOUT` | 600 | Request timeout in seconds |
| `HPS_HEALTH_CHECK_TIMEOUT` | 5 | Health check timeout in seconds |
| `HPS_VLM_URL` | http://paddleocr-vlm-server:8080 | VLM server URL (for health checks) |
| `HPS_VLM_URL` | http://paddleocr-vlm-server:8080 | VLM server URL |
| `HPS_LOG_LEVEL` | INFO | Log level (DEBUG, INFO, WARNING, ERROR) |
| `HPS_FILTER_HEALTH_ACCESS_LOG` | true | Whether to filter health check access logs |
| `HPS_UVICORN_WORKERS` | 4 | Number of gateway worker processes |
+6 -12
View File
@@ -13,6 +13,7 @@ HPS_PIPELINE_NAME="${HPS_PIPELINE_NAME:-PaddleOCR-VL-1.6}"
HPS_PADDLEX_VERSION="${HPS_PADDLEX_VERSION:-3.6}"
HPS_SDK_VERSION="${HPS_SDK_VERSION:-v${HPS_PADDLEX_VERSION}}"
HPS_SDK_DIR="${HPS_SDK_DIR:-paddlex_hps_${HPS_PIPELINE_NAME}_sdk}"
HPS_VLM_URL="${HPS_VLM_URL:-http://paddleocr-vlm-server:8080}"
SDK_ARCHIVE="${HPS_SDK_DIR}.tar.gz"
SDK_URL="https://paddle-model-ecology.bj.bcebos.com/paddlex/PaddleX3.0/deploy/paddlex_hps/public/sdks/${HPS_SDK_VERSION}/${SDK_ARCHIVE}"
@@ -35,8 +36,7 @@ _set_env_value() {
fi
if grep -q "^${key}=" "$file"; then
sed -i.bak "s|^${key}=.*|${key}=${value}|" "$file"
rm -f "${file}.bak"
sed -i "s|^${key}=.*|${key}=${value}|" "$file"
else
echo "${key}=${value}" >>"$file"
fi
@@ -48,17 +48,10 @@ echo " SDK archive: ${SDK_ARCHIVE}"
wget "${SDK_URL}"
tar -xf "${SDK_ARCHIVE}"
sed -i.bak \
-e "s/^pipeline_name:.*/pipeline_name: ${HPS_PIPELINE_NAME}/" \
"${PIPELINE_CONFIG}"
rm -f "${PIPELINE_CONFIG}.bak"
if grep -qE '^\s*backend: native\s*$' "${PIPELINE_CONFIG}"; then
sed -i.bak \
-e 's|^\( *\)batch_size: -1$|\1batch_size: 4096|' \
-e 's|^\( *\)backend: native$|\1backend: vllm-server\n\1server_url: http://paddleocr-vlm-server:8080/v1|' \
sed -i \
-e "s|^\( *\)backend: native$|\1backend: vllm-server\n\1server_url: ${HPS_VLM_URL%/}/v1|" \
"${PIPELINE_CONFIG}"
rm -f "${PIPELINE_CONFIG}.bak"
fi
VLM_NAME="$(_extract_vlm_name "${PIPELINE_CONFIG}")"
@@ -66,9 +59,10 @@ if [ -z "${VLM_NAME}" ]; then
echo "Failed to read VLM name from ${PIPELINE_CONFIG}" >&2
exit 1
fi
echo " VLM name (from pipeline_config.yaml): ${VLM_NAME}"
echo " VLM name: ${VLM_NAME}"
_set_env_value "HPS_PIPELINE_NAME" "${HPS_PIPELINE_NAME}"
_set_env_value "HPS_SDK_DIR" "${HPS_SDK_DIR}"
_set_env_value "HPS_VLM_URL" "${HPS_VLM_URL}"
echo "High-stability serving SDK prepared at ${HPS_SDK_DIR}/"
+4 -2
View File
@@ -19,6 +19,8 @@ On January 29, 2026, PaddleOCR open-sourced the advanced and efficient document
**On May 28, 2026, PaddleOCR open-sourced PaddleOCR-VL-1.6, the latest version in the PaddleOCR-VL series.** With an accuracy of 96.3%, PaddleOCR-VL-1.6 once again set a new benchmark on OmniDocBench v1.6, while also achieving new state-of-the-art (SOTA) results on OmniDocBench v1.5 and Real5-OmniDocBench. It delivers industry-leading performance in text, formula, and table recognition across both open-source and proprietary solutions. In addition, the model shows substantial improvements in ancient document and rare character recognition, as well as significantly enhanced capabilities in multiple scenarios such as seal recognition, spotting, and chart understanding. PaddleOCR-VL-1.6 further upgrades the VLM component (PaddleOCR-VL-1.6-0.9B) on top of PaddleOCR-VL-1.5 and continues to use PP-DocLayoutV3 for layout analysis. The model architecture remains fully consistent with PaddleOCR-VL-1.5, enabling seamless migration at zero cost.
**On June 11, 2026, PaddleOCR released PP-OCRv6, the next-generation universal OCR system.** Built on the newly designed PPLCNetV4 unified backbone, PP-OCRv6 offers tiny/small/medium tiers (1.5M–34.5M parameters). In terms of accuracy, the medium tier achieves +5.1% recognition and +4.6% detection over PP-OCRv5_server, surpassing mainstream Vision-Language Models with only 34.5M parameters. For multilingual support, a single model covers 50 languages (Chinese, English, Japanese, and 46 Latin-script languages) without switching models. PP-OCRv6 significantly improves recognition in specialized scenarios such as digital displays, dot-matrix characters, tire prints, and industrial text that are traditionally underserved by VLMs. In terms of speed, PP-OCRv6_medium achieves 5.2× speedup over PP-OCRv5_server on Intel Xeon CPU with OpenVINO (1.40s vs 7.30s), the tiny tier reaches 6.1× speedup on Apple M4 (0.96s vs 5.82s), and only 0.13s on A100 GPU. See [PP-OCRv6 Technical Documentation](./version3.x/algorithm/PP-OCRv6/PP-OCRv6.en.md) for details.
You can use it online on the [PaddleOCR official website](https://www.paddleocr.com) or call the model API.
@@ -27,8 +29,8 @@ You can use it online on the [PaddleOCR official website](https://www.paddleocr.
- **PaddleOCR-VL - Multilingual Document Parsing via a 0.9B VLM**
**The SOTA and resource-efficient model tailored for document parsing**, that supports 109 languages and excels in recognizing complex elements (e.g., text, tables, formulas, and charts), while maintaining minimal resource consumption.
- **PP-OCRv5 — Universal Scene Text Recognition**
**Single model supports five text types** (Simplified Chinese, Traditional Chinese, English, Japanese, and Pinyin) with **13% accuracy improvement**. Solves multilingual mixed document recognition challenges.
- **PP-OCRv6 — Universal Multi-Language Text Recognition**
**Single model supports 50 languages** (Chinese, English, Japanese, and 46 Latin-script languages), with **+4.6% detection** and **+5.1% recognition** accuracy over PP-OCRv5, surpassing mainstream Vision-Language Models. Medium tier achieves 5.2× CPU speedup end-to-end, covering specialized scenarios like digital displays, dot-matrix, and industrial characters. Three tiers (tiny/small/medium, 1.5M–34.5M params) for edge-to-server deployment.
- **PP-StructureV3 — Complex Document Parsing**
Intelligently converts complex PDFs and document images into **Markdown and JSON files that preserve original structure**. **Outperforms** numerous commercial solutions in public benchmarks. **Perfectly maintains document layout and hierarchical structure**.
+4 -2
View File
@@ -19,6 +19,8 @@ PaddleOCR自发布以来凭借学术前沿算法和产业落地实践,受到
**2026 年 5 月 28 日,PaddleOCR 开源了 PaddleOCR-VL-1.6,作为 PaddleOCR-VL 系列的最新版本。** PaddleOCR-VL-1.6 以 96.3% 精度再次刷新评测集 OmniDocBench v1.6,并在 OmniDocBench v1.5、Real5-OmniDocBench 上同步达到全新 SOTA,文本、公式、表格识别全面领先开源与闭源方案。此外,模型在古籍、生僻字识别上大幅提升,印章、spotting、图表识别等多场景能力也显著增强。PaddleOCR-VL-1.6 在 PaddleOCR-VL-1.5 的基础上进一步升级了 VLM 组件(PaddleOCR-VL-1.6-0.9B),并继续采用 PP-DocLayoutV3 作为版面分析模型;模型结构与 PaddleOCR-VL-1.5 完全一致,支持零成本无缝迁移。
**2026 年 6 月 11 日,PaddleOCR 发布 PP-OCRv6,作为 PP-OCR 系列的最新版本。** PP-OCRv6 基于全新设计的 PPLCNetV4 统一骨干网络,提供 tiny/small/medium 三档模型(1.5M~34.5M 参数)。在精度方面,medium 档相比 PP-OCRv5_server 识别精度提升 5.1%、检测精度提升 4.6%,以仅 34.5M 参数的规模超越 Qwen3-VL-235B、GPT-5.5 等大型视觉语言模型。在多语种方面,单一模型统一支持中文、英文、日文及 46 种拉丁语系共 50 种语言,无需为不同语种切换模型。在场景覆盖方面,PP-OCRv6 大幅提升了数码管、点阵字符、轮胎印字、工业字符等传统 VLM 难以覆盖的专业场景识别能力。在速度方面,PP-OCRv6_medium 在 Intel Xeon CPU OpenVINO 下相比 PP-OCRv5_server 加速 5.2×(1.40s vs 7.30s),tiny 档在纯前端浏览器环境的极低算力下,直接轰出了单图 97ms 的惊人成绩。
您可以在 [PaddleOCR官网](https://www.paddleocr.com) 在线使用或者调用该模型的API。
**PaddleOCR 3.x 核心特色能力:**
@@ -27,8 +29,8 @@ PaddleOCR自发布以来凭借学术前沿算法和产业落地实践,受到
- **PaddleOCR-VL - 通过 0.9B 超紧凑视觉语言模型增强多语种文档解析**
**面向文档解析的 SOTA 且资源高效的模型**, 支持 109 种语言,在复杂元素(如文本、表格、公式和图表)识别方面表现出色,同时资源消耗极低。
- **PP-OCRv5 — 全场景文字识别**
**单模型支持五种文字类型**(简中、繁中、英文、日文及拼音),精度提升**13个百分点**。解决多语言混合文档的识别难题。
- **PP-OCRv6 — 全场景多语言文字识别**
**单模型支持 50 种语言**(中、英、日及 46 种拉丁语系),检测精度提升 **4.6%**、识别精度提升 **5.1%**,超越主流视觉语言大模型。medium 档位模型端到端 CPU 推理加速 5.2×,覆盖数码屏/点阵/工业字符等专业场景。三档模型(tiny/small/medium,1.5M~34.5M 参数)满足端侧到服务端全场景部署。
- **PP-StructureV3 — 复杂文档解析**
将复杂PDF和文档图像智能转换为保留**原始结构的Markdown文件和JSON**文件,在公开评测中**领先**众多商业方案。**完美保持文档版式和层次结构**。
+6 -6
View File
@@ -50,7 +50,7 @@ PaddleOCR also supports installing specific features as needed. For details, ple
### Command Line Usage
=== "PP-OCRv5"
=== "PP-OCRv6"
```bash linenums="1"
# Use PaddlePaddle for inference
@@ -70,7 +70,7 @@ PaddleOCR also supports installing specific features as needed. For details, ple
--engine transformers
```
=== "PP-OCRv5 Text Detection Module"
=== "PP-OCRv6 Text Detection Module"
```bash linenums="1"
# Use PaddlePaddle for inference
@@ -82,7 +82,7 @@ PaddleOCR also supports installing specific features as needed. For details, ple
paddleocr text_detection -i ./general_ocr_001.png --engine transformers
```
=== "PP-OCRv5 Text Recognition Module"
=== "PP-OCRv6 Text Recognition Module"
```bash linenums="1"
# Use PaddlePaddle for inference
@@ -115,7 +115,7 @@ PaddleOCR also supports installing specific features as needed. For details, ple
### Python Script Usage
=== "PP-OCRv5"
=== "PP-OCRv6"
```python linenums="1"
# Use PaddlePaddle for inference
@@ -175,7 +175,7 @@ PaddleOCR also supports installing specific features as needed. For details, ple
[ 99, ..., 480]], dtype=int16)}}
```
=== "PP-OCRv5 Text Detection Module"
=== "PP-OCRv6 Text Detection Module"
```python linenums="1"
# Use PaddlePaddle for inference
@@ -213,7 +213,7 @@ PaddleOCR also supports installing specific features as needed. For details, ple
[ 36, 456]]], dtype=int16), 'dt_scores': [0.8562385635646694, 0.8818259002228059, 0.8406072284043453, 0.8855339313157491]}}
```
=== "PP-OCRv5 Text Recognition Module"
=== "PP-OCRv6 Text Recognition Module"
```python linenums="1"
# Use PaddlePaddle for inference
+6 -6
View File
@@ -48,7 +48,7 @@ PaddleOCR 也支持根据需要安装部分功能,详情请参考 [PaddleOCR
### 命令行使用
=== "PP-OCRv5"
=== "PP-OCRv6"
```bash linenums="1"
# 使用 PaddlePaddle 进行推理
@@ -68,7 +68,7 @@ PaddleOCR 也支持根据需要安装部分功能,详情请参考 [PaddleOCR
--engine transformers
```
=== "PP-OCRv5文本检测模块"
=== "PP-OCRv6文本检测模块"
```bash linenums="1"
# 使用 PaddlePaddle 进行推理
@@ -80,7 +80,7 @@ PaddleOCR 也支持根据需要安装部分功能,详情请参考 [PaddleOCR
paddleocr text_detection -i ./general_ocr_001.png --engine transformers
```
=== "PP-OCRv5文本识别模块"
=== "PP-OCRv6文本识别模块"
```bash linenums="1"
# 使用 PaddlePaddle 进行推理
@@ -113,7 +113,7 @@ PaddleOCR 也支持根据需要安装部分功能,详情请参考 [PaddleOCR
### Python脚本使用
=== "PP-OCRv5"
=== "PP-OCRv6"
```python linenums="1"
# 使用 PaddlePaddle 进行推理
@@ -173,7 +173,7 @@ PaddleOCR 也支持根据需要安装部分功能,详情请参考 [PaddleOCR
[ 99, ..., 479]], dtype=int16)}}
```
=== "PP-OCRv5文本检测模块"
=== "PP-OCRv6文本检测模块"
```python linenums="1"
# 使用 PaddlePaddle 进行推理
@@ -211,7 +211,7 @@ PaddleOCR 也支持根据需要安装部分功能,详情请参考 [PaddleOCR
[ 36, 456]]], dtype=int16), 'dt_scores': [0.8562385635646694, 0.8818259002228059, 0.8406072284043453, 0.8855339313157491]}}
```
=== "PP-OCRv5文本识别模块"
=== "PP-OCRv6文本识别模块"
```python linenums="1"
# 使用 PaddlePaddle 进行推理
@@ -0,0 +1,226 @@
# 1. PP-OCRv6 Introduction
**PP-OCRv6** is the latest generation of the PP-OCR universal text recognition solution. Built on the newly designed PPLCNetV4 unified backbone, it offers tiny, small, and medium tiers targeting edge/IoT, mobile/desktop, and server scenarios respectively. PP-OCRv6 achieves a major breakthrough in language coverage—the medium/small tiers support 50 languages with a single unified model, including Simplified Chinese, Traditional Chinese, English, Japanese, and 46 Latin-script languages (tiny supports 49, excluding Japanese). On our in-house multi-scenario benchmark, PP-OCRv6_medium achieves +5.1% recognition accuracy and +4.6% detection Hmean over PP-OCRv5_server, with 2.37× GPU inference speedup; with only 34.5M parameters, it surpasses VLMs such as Qwen3-VL-235B and GPT-5.5 in accuracy.
Main contributions:
1. **Unified and Scalable Model Family**: A three-tier OCR model family spanning 1.5M to 34.5M parameters. The medium tier achieves 86.2% detection Hmean and 83.2% recognition accuracy, serving as production-ready infrastructure for industrial deployment and large-scale data pipelines.
2. **Tailored Lightweight Architectural Innovations**: (i) LCNetV4: a MetaFormer-style lightweight backbone with structural reparameterization; (ii) RepLKFPN: a detection neck with dilated reparameterizable depthwise convolutions for large receptive fields; (iii) EncoderWithLightSVTR: a recognition neck with local-global attention and additive skip connections.
3. **Extensive Multi-Language and Scenario Generalization**: A single model scaled to support 50 languages and diverse challenging industrial scenes (e.g., digital displays, dot-matrix characters, tire prints), significantly improving OCR performance in scenarios traditionally underserved by general-purpose VLMs.
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/v6acc_opt.png" width="800"/>
</div>
<p align="center">Performance comparison between PP-OCRv6, PP-OCRv5, and Vision-Language Models. Left: text detection average Hmean (%); Right: text recognition weighted average accuracy (%).</p>
# 2. Key Technical Improvements
## 2.1 Unified Backbone: PPLCNetV4
**LCNetV4Block**: Following the MetaFormer paradigm, each layer is decomposed into a Token Mixer and a Channel Mixer. Given input feature $\mathbf{x} \in \mathbb{R}^{C \times H \times W}$:
$$\hat{\mathbf{x}} = \text{SE}(\text{DW}(\mathbf{x})) + \mathbf{x}$$
$$\mathbf{y} = W_2\,\sigma(W_1\,\hat{\mathbf{x}}) + \hat{\mathbf{x}}$$
where $\text{DW}(\cdot)$ is a 3×3 depthwise convolution (Token Mixer), SE is an optional channel attention module, $W_1 \in \mathbb{R}^{2C \times C}$ and $W_2 \in \mathbb{R}^{C \times 2C}$ form the Channel Mixer with expansion ratio 2, and $\sigma$ is GELU activation.
**Task-Adaptive Downsampling**: The same backbone serves both tasks via different stride strategies—detection mode uses standard stride-2 spatial downsampling producing multi-scale feature maps (stride 4/8/16/32); recognition mode uses asymmetric stride $(2,1)$ at Stage 3/4, reducing height only while preserving width, followed by height-axis average pooling to produce 1-D sequential features for CTC/NRTR decoding.
**Comparison with LCNetV3**:
| Design Aspect | LCNetV3 | LCNetV4 |
|--------------|---------|---------|
| Architecture | MobileNet-style (DW→SE→PW) | MetaFormer (TokenMixer + ChannelMixer) |
| Channel Interaction | Single 1×1 PW Conv | Expand(2×)→Act→Compress + residual |
| Spatial Mixing | Plain DW Conv | RepDWConv (3×3 + 1×1 + identity) |
| BN Initialization | Standard | Zero-init on compress BN |
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/backbone.png" width="600"/>
</div>
<p align="center">PPLCNetV4 backbone architecture.</p>
## 2.2 Detection Module
- **RepLKFPN**: Lightweight large-kernel FPN using DilatedReparamBlock (7×7 depthwise conv + dilated branches), 31% fewer parameters than PP-OCRv5's RSEFPN (118K vs 172K) with receptive field expanded from 3×3 to 7×7.
- **Auxiliary Deep Supervision**: Prediction heads at P2, P3, P4 levels for stronger gradient signals during training.
- **DiceBCE Loss**: Combined DiceLoss + Focal Loss for better per-pixel supervision on small and dense text.
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/ppocrv6_det_pip_ori.png" width="600"/>
</div>
<p align="center">PP-OCRv6 detection module architecture.</p>
## 2.3 Recognition Module
- **EncoderWithLightSVTR Neck**: Local context modeling (1×7 depthwise conv) + global self-attention (1-2 Transformer layers), with additive skip connections (instead of concatenation in PP-OCRv5) to reduce parameters.
- **Multi-Head Decoder**: CTCHead for efficient parallel inference; NRTRHead for auxiliary training supervision (removed at inference).
- **Tiny Model Design**: No neck (direct reshape + FC), trained with knowledge distillation from the medium model.
- **Multilingual Unification**: Dictionary extended with ~200 diacritical characters, enabling single-model 50-language coverage.
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/rec.png" width="600"/>
</div>
<p align="center">PP-OCRv6 recognition module architecture.</p>
# 3. Key Metrics
## 3.1 Text Detection
Text detection Hmean (%) on our in-house multi-scenario benchmark (16 categories):
| Model | AVG | HW-CN | HW-EN | Print-CN | Print-EN | TC | Anc. | JP | Blur | Emo. | Warp | Pin. | Art. | Tab. | Rot. | Indus. | Gen. |
|-------|-----|-------|-------|----------|----------|-----|------|-----|------|------|------|------|------|------|------|--------|------|
| **PP-OCRv6_medium** | **86.2** | **83.7** | 84.0 | **95.1** | **93.7** | **86.3** | **80.2** | **84.3** | **94.1** | 99.6 | **88.6** | **74.0** | **69.0** | 96.8 | **93.8** | **73.3** | **82.8** |
| **PP-OCRv6_small** | **84.1** | 80.5 | **87.1** | 94.2 | 93.6 | 85.7 | 72.6 | 82.3 | 92.6 | 99.7 | 87.6 | 69.6 | 65.3 | 95.6 | 93.7 | 67.6 | 78.2 |
| **PP-OCRv6_tiny** | **80.6** | 79.4 | 85.9 | 93.1 | 92.3 | 83.7 | 63.0 | 76.6 | 89.3 | **99.8** | 86.1 | 59.0 | 60.1 | 94.7 | 91.0 | 62.0 | 73.8 |
| PP-OCRv5_server | 81.6 | 80.3 | 84.1 | 94.5 | 91.7 | 81.5 | 67.6 | 77.2 | 90.1 | 96.2 | 87.6 | 67.1 | 67.3 | **97.1** | 80.0 | 64.3 | 79.7 |
| PP-OCRv5_mobile | 75.2 | 74.4 | 77.7 | 90.5 | 91.0 | 82.3 | 58.1 | 72.7 | 87.4 | 93.6 | 82.7 | 57.5 | 52.5 | 92.8 | 64.7 | 52.8 | 72.1 |
| Gemini-3.1-Pro | 46.8 | 53.4 | 56.5 | 47.3 | 47.6 | 39.0 | 45.8 | 38.2 | 50.0 | 68.1 | 44.6 | 40.6 | 65.2 | 26.9 | 22.1 | 52.5 | 50.2 |
| GPT-5.5 | 45.6 | 42.4 | 58.5 | 50.2 | 51.9 | 35.0 | 26.7 | 42.0 | 49.1 | 97.5 | 37.7 | 36.3 | 52.0 | 71.0 | 10.0 | 36.2 | 32.6 |
| Qwen3-VL-235B | 38.3 | 56.5 | 66.0 | 41.7 | 37.0 | 19.3 | 13.1 | 27.0 | 38.5 | 81.2 | 28.5 | 33.0 | 68.3 | 19.6 | 2.1 | 48.4 | 32.3 |
## 3.2 Text Recognition
Text recognition accuracy (%) on our in-house multi-scenario benchmark (15 categories):
| Model | W-Avg | HW-CN | HW-EN | Print-CN | Print-EN | TC | Anc. | JP | Conf. | Spec. | Gen. | Pin. | Art. | Indus. | Screen | Card |
|-------|-------|-------|-------|----------|----------|-----|------|-----|-------|-------|------|------|------|--------|--------|------|
| **PP-OCRv6_medium** | **83.2** | **62.1** | 67.8 | **91.5** | **94.1** | **78.6** | **72.4** | **90.5** | **64.9** | **61.7** | **87.5** | **78.1** | **71.2** | **77.4** | **82.5** | **88.1** |
| **PP-OCRv6_small** | **81.3** | 57.6 | 61.1 | 90.5 | 93.3 | 77.0 | 71.1 | 88.2 | 64.1 | 60.2 | 85.7 | 75.9 | 68.4 | 76.4 | 79.7 | 86.9 |
| **PP-OCRv6_tiny** | 73.5 | 40.1 | 39.3 | 86.7 | 88.4 | 65.0 | 68.4 | 89.8 | 52.3 | 57.1 | 78.0 | 65.4 | 54.7 | 62.1 | 71.2 | 80.5 |
| PP-OCRv5_server | 78.1 | 58.0 | 59.6 | 90.1 | 85.1 | 74.7 | 60.4 | 73.7 | 59.4 | 56.8 | 86.5 | 74.4 | 64.0 | 70.2 | 68.1 | 87.6 |
| PP-OCRv5_mobile | 73.7 | 41.7 | 50.9 | 86.0 | 86.0 | 72.0 | 57.8 | 75.8 | 55.7 | 54.8 | 80.7 | 72.5 | 54.0 | 59.3 | 57.6 | 81.7 |
| Qwen3-VL-235B | 74.9 | 49.7 | **73.2** | 82.3 | 86.2 | 76.4 | 33.6 | 66.2 | 56.1 | 49.0 | 82.5 | 76.5 | 69.6 | 74.7 | 73.8 | 78.7 |
| Gemini-3.1-Pro | 71.4 | 46.4 | 73.0 | 80.0 | 90.5 | 69.5 | 18.0 | 67.2 | 54.4 | 50.3 | 74.6 | 75.9 | 63.1 | 69.1 | 73.2 | 75.9 |
| GPT-5.5 | 64.2 | 19.2 | 56.9 | 75.7 | 82.2 | 57.5 | 63.7 | 58.6 | 49.1 | 48.3 | 67.7 | 50.4 | 53.0 | 62.4 | 67.7 | 71.1 |
## 3.3 End-to-End Inference Speed (s/image)
Tested on 200 images (general + document scenes), including image I/O, pre/post-processing, and model inference.
| Hardware | Backend | PP-OCRv6_medium | PP-OCRv6_small | PP-OCRv6_tiny | PP-OCRv5_server | PP-OCRv5_mobile | PP-OCRv4_mobile |
|----------|---------|-----------------|----------------|---------------|-----------------|-----------------|-----------------|
| NVIDIA A100 | PaddlePaddle | 0.29 | 0.25 | 0.13 | 0.32 | 0.25 | 0.14 |
| NVIDIA A100 | TensorRT | -- | 0.32 | 0.16 | -- | 0.33 | 0.16 |
| NVIDIA V100 | PaddlePaddle | 0.72 | 0.49 | 0.21 | 0.66 | 0.50 | 0.25 |
| NVIDIA V100 | ONNX Runtime | 0.67 | 0.53 | 0.29 | 0.77 | 0.46 | 0.27 |
| NVIDIA V100 | TensorRT | 0.77 | 0.60 | 0.23 | 0.73 | 0.59 | 0.27 |
| Intel Xeon 8350C | PaddlePaddle | 2.05 | 0.79 | 0.32 | 2.04 | 0.80 | 0.62 |
| Intel Xeon 8350C | OpenVINO | 1.40 | 0.59 | 0.20 | 7.30 | 0.78 | 0.60 |
| Intel Xeon 8350C | ONNX Runtime | 3.31 | 0.61 | 0.22 | 6.36 | 0.61 | 0.49 |
| Apple M4 | PaddlePaddle | 8.82 | 3.07 | 0.96 | >10 | 5.82 | 5.65 |
| Apple M4 | ONNX Runtime | 5.55 | 1.29 | 0.35 | 7.20 | 1.10 | 1.02 |
- PP-OCRv6_medium matches or outperforms PP-OCRv5_server on all platforms: 1.1× faster on A100 (0.29s vs 0.32s), 1.15× on V100 ONNX Runtime (0.67s vs 0.77s), 5.2× on Intel Xeon OpenVINO (1.40s vs 7.30s).
- PP-OCRv6_small matches PP-OCRv5_mobile in latency on most platforms with higher accuracy; 1.9× faster on Apple M4 PaddlePaddle (3.07s vs 5.82s).
- PP-OCRv6_tiny is the fastest model across all platforms: 6.1× over PP-OCRv5_mobile on Apple M4 PaddlePaddle (0.96s vs 5.82s), 3.9× on Intel Xeon OpenVINO (0.20s vs 0.78s), reaching 0.13s on A100.
# 4. Visualization
## 4.1 Detection Comparison
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/ppocrv6_det_vis.jpg" width="800"/>
</div>
<p align="center">Text detection comparison. Left to right: PP-OCRv6_medium, PP-OCRv5_server, Gemini-3.1-Pro, GPT-5.5.</p>
## 4.2 Hallucination Comparison
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/huanjue.jpg" width="800"/>
</div>
<p align="center">PP-OCRv6_medium vs VLMs hallucination comparison. PP-OCRv6 faithfully reproduces visual text content, while VLMs introduce hallucinated corrections based on linguistic priors.</p>
## 4.3 End-to-End OCR Comparison
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/case1.jpg" width="800"/>
</div>
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/case2.jpg" width="800"/>
</div>
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/case3.jpg" width="800"/>
</div>
<p align="center">End-to-end OCR comparison between PP-OCRv6_medium and PP-OCRv5_server across Chinese, English, Japanese, artistic fonts, industrial characters, rotated text, pinyin, and dot-matrix characters.</p>
# 5. Quick Start
```python
from paddleocr import PaddleOCR
# Default: PP-OCRv6_medium
ocr = PaddleOCR(
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
result = ocr.predict("https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png")
for res in result:
res.print()
res.save_to_img("output")
res.save_to_json("output")
```
```bash
# CLI usage
paddleocr ocr -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
--use_textline_orientation False
```
**Using Transformers Engine:**
PP-OCRv6 supports inference via Hugging Face Transformers (requires `transformers>=5.8.0`):
```python
from paddleocr import TextRecognition
model = TextRecognition(
model_name="PP-OCRv6_medium_rec",
engine="transformers",
)
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
```
**Using High-Performance Inference (ONNX Runtime backend):**
Enable the high-performance inference plugin with `enable_hpi=True`:
```python
from paddleocr import PaddleOCR
ocr = PaddleOCR(
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
enable_hpi=True,
)
result = ocr.predict("general_ocr_002.png")
```
> The HPI plugin requires additional installation. See [High-Performance Inference Guide](../../inference_deployment/local_inference/high_performance_inference.md).
# 6. Deployment and Custom Development
* **Multi-OS Support**: Compatible with Windows, Linux, and Mac.
* **Multi-Hardware Support**: Supports NVIDIA GPU, Intel CPU, Kunlun, Ascend, and more.
* **High-Performance Inference Plugin**: See [High-Performance Inference Guide](../../inference_deployment/local_inference/high_performance_inference.md).
* **Serving Deployment**: See [Serving Deployment Guide](../../inference_deployment/serving/serving.md).
* **Custom Development**: Supports custom dataset training, dictionary extension, and model fine-tuning. See [Text Detection Tutorial](../../module_usage/text_detection.md) and [Text Recognition Tutorial](../../module_usage/text_recognition.md).
@@ -0,0 +1,260 @@
# 一、PP-OCRv6简介
**PP-OCRv6** 是 PP-OCR 最新一代通用文字识别解决方案。PP-OCRv6 基于全新设计的 PPLCNetV4 统一骨干网络,提供 tiny、small、medium 三档模型,分别面向端侧/IoT、移动端/桌面端、服务端场景。PP-OCRv6 在语言覆盖方面实现重大突破,medium/small 档单一模型统一支持简体中文、繁体中文、英文、日文及 46 种拉丁语系语言共 50 种语言(tiny 档支持 49 种,不含日文)。在内部多场景综合评估集上,PP-OCRv6_medium 相比 PP-OCRv5_server 识别精度提升 5.1%、检测精度提升 4.6%,同时 GPU 推理速度提升 2.37×;以仅 34.5M 参数的规模,精度超越 Qwen3-VL-235B、GPT-5.5 等大型视觉语言模型。
PP-OCRv6 的主要贡献如下:
1. **统一可扩展的模型族**:提供覆盖 1.5M 至 34.5M 参数的三档完整 OCR 模型族。medium 档达到 86.2% 检测 Hmean 和 83.2% 识别准确率,可作为工业部署和大规模数据管线的高效生产级基础设施。
2. **面向 OCR 的轻量级架构创新**:提出一系列专为 OCR 任务定制的轻量级架构组件——(i) LCNetV4:集成结构重参数化的 MetaFormer 风格轻量骨干;(ii) RepLKFPN:利用膨胀可重参数化深度卷积实现大感受野的检测颈部;(iii) EncoderWithLightSVTR:基于局部-全局注意力和加性跳跃连接的识别颈部。
3. **广泛的多语言与多场景泛化**:单一模型扩展至支持 50 种语言和多种挑战性工业场景(如数码显示屏、点阵字符、轮胎印字等),显著提升了传统通用视觉语言模型难以覆盖的专业场景 OCR 性能。
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/v6acc_opt.png" width="800"/>
</div>
<p align="center">图:PP-OCRv6 与 PP-OCRv5 及视觉语言模型的性能对比。左:文本检测平均 Hmean(%);右:文本识别加权平均准确率(%)。</p>
# 二、核心技术升级
## 1. 统一骨干网络 PPLCNetV4
PP-OCRv6 采用全新设计的 PPLCNetV4 作为检测和识别的统一骨干网络,核心创新包括:
**LCNetV4Block**:遵循 MetaFormer 范式,将每层解耦为 Token Mixer 和 Channel Mixer。设输入特征 $\mathbf{x} \in \mathbb{R}^{C \times H \times W}$,Block 计算如下:
$$\hat{\mathbf{x}} = \text{SE}(\text{DW}(\mathbf{x})) + \mathbf{x}$$
$$\mathbf{y} = W_2\,\sigma(W_1\,\hat{\mathbf{x}}) + \hat{\mathbf{x}}$$
其中 $\text{DW}(\cdot)$ 是 3×3 深度卷积(Token Mixer),SE 是可选的通道注意力模块,$W_1 \in \mathbb{R}^{2C \times C}$、$W_2 \in \mathbb{R}^{C \times 2C}$ 构成扩展比为 2 的 Channel Mixer,$\sigma$ 为 GELU 激活。
**Task-Adaptive Downsampling**:同一骨干通过不同下采样策略服务两个任务——检测模式使用标准 stride-2 空间下采样产出多尺度特征图(stride 4/8/16/32);识别模式在 Stage 3/4 使用非对称 stride $(2,1)$,仅缩减高度保留宽度,经 height-axis 平均池化后产出 1-D 序列特征用于 CTC/NRTR 解码。
**与 LCNetV3 对比**:
| 设计维度 | LCNetV3 | LCNetV4 |
|---------|---------|---------|
| 架构范式 | MobileNet-style (DW→SE→PW) | MetaFormer (TokenMixer + ChannelMixer) |
| 通道交互 | 单个 1×1 PW Conv | Expand(2×)→Act→Compress + 残差 |
| 空间混合 | 普通 DW Conv | RepDWConv(3×3 + 1×1 + identity 三分支) |
| BN 初始化 | 标准 | Compress 层 BN 零初始化 |
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/backbone.png" width="600"/>
</div>
<p align="center">图:PPLCNetV4 骨干网络结构</p>
## 2. 检测模块升级
- **RepLKFPN**:轻量级大核特征金字塔,使用 DilatedReparamBlock(7×7 深度卷积 + 膨胀分支),相比 PP-OCRv5 的 RSEFPN 参数减少 31%(118K vs 172K),同时感受野从 3×3 扩大到 7×7。
- **辅助深度监督**:在 P2、P3、P4 层级添加预测头,训练时提供更强梯度信号。
- **DiceBCE Loss**:组合 DiceLoss + Focal Loss,对小目标和密集文本提供更好的逐像素监督。
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/ppocrv6_det_pip_ori.png" width="600"/>
</div>
<p align="center">图:PP-OCRv6 检测模块结构</p>
## 3. 识别模块升级
- **EncoderWithLightSVTR 颈部**:局部上下文建模(1×7 深度卷积)+ 全局自注意力(1-2 层 Transformer),通过加性跳跃连接(而非 PP-OCRv5 的拼接)减少参数。
- **多头解码器**:CTCHead 用于高效并行推理,NRTRHead 用于训练时辅助监督(推理时移除)。
- **Tiny 模型特殊设计**:无颈部(直接 reshape + FC),使用 medium 模型蒸馏训练。
- **多语言统一**:字典扩展约 200 个带变音符号字符,实现单模型 48 语言覆盖。
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/rec.png" width="600"/>
</div>
<p align="center">图:PP-OCRv6 识别模块结构</p>
# 三、关键指标
## 1. 文本检测指标
在内部多场景基准上对 16 类场景进行文本检测 Hmean(%) 评测:
| 模型 | AVG | 手写CN | 手写EN | 印刷CN | 印刷EN | 繁体 | 古籍 | 日文 | 模糊 | 表情 | 扭曲 | 拼音 | 艺术字 | 表格 | 旋转 | 工业 | 通用 |
|------|-----|--------|--------|--------|--------|------|------|------|------|------|------|------|--------|------|------|------|------|
| **PP-OCRv6_medium** | **86.2** | **83.7** | 84.0 | **95.1** | **93.7** | **86.3** | **80.2** | **84.3** | **94.1** | 99.6 | **88.6** | **74.0** | **69.0** | 96.8 | **93.8** | **73.3** | **82.8** |
| **PP-OCRv6_small** | **84.1** | 80.5 | **87.1** | 94.2 | 93.6 | 85.7 | 72.6 | 82.3 | 92.6 | 99.7 | 87.6 | 69.6 | 65.3 | 95.6 | 93.7 | 67.6 | 78.2 |
| **PP-OCRv6_tiny** | **80.6** | 79.4 | 85.9 | 93.1 | 92.3 | 83.7 | 63.0 | 76.6 | 89.3 | **99.8** | 86.1 | 59.0 | 60.1 | 94.7 | 91.0 | 62.0 | 73.8 |
| PP-OCRv5_server | 81.6 | 80.3 | 84.1 | 94.5 | 91.7 | 81.5 | 67.6 | 77.2 | 90.1 | 96.2 | 87.6 | 67.1 | 67.3 | **97.1** | 80.0 | 64.3 | 79.7 |
| PP-OCRv5_mobile | 75.2 | 74.4 | 77.7 | 90.5 | 91.0 | 82.3 | 58.1 | 72.7 | 87.4 | 93.6 | 82.7 | 57.5 | 52.5 | 92.8 | 64.7 | 52.8 | 72.1 |
| Gemini-3.1-Pro | 46.8 | 53.4 | 56.5 | 47.3 | 47.6 | 39.0 | 45.8 | 38.2 | 50.0 | 68.1 | 44.6 | 40.6 | 65.2 | 26.9 | 22.1 | 52.5 | 50.2 |
| GPT-5.5 | 45.6 | 42.4 | 58.5 | 50.2 | 51.9 | 35.0 | 26.7 | 42.0 | 49.1 | 97.5 | 37.7 | 36.3 | 52.0 | 71.0 | 10.0 | 36.2 | 32.6 |
| Qwen3-VL-235B | 38.3 | 56.5 | 66.0 | 41.7 | 37.0 | 19.3 | 13.1 | 27.0 | 38.5 | 81.2 | 28.5 | 33.0 | 68.3 | 19.6 | 2.1 | 48.4 | 32.3 |
PP-OCRv6_medium 平均 Hmean 达 86.2%,相比 PP-OCRv5_server 提升 4.6 个百分点,在日文、古籍、旋转文本、工业字符等场景提升尤为显著。
## 2. 文本识别指标
在内部多场景基准上对 15 类场景进行文本识别准确率(%) 评测:
| 模型 | W-Avg | 手写CN | 手写EN | 印刷CN | 印刷EN | 繁体 | 古籍 | 日文 | 易混淆 | 特殊字符 | 通用 | 拼音 | 艺术字 | 工业 | 屏幕 | 卡片 |
|------|-------|--------|--------|--------|--------|------|------|------|--------|----------|------|------|--------|------|------|------|
| **PP-OCRv6_medium** | **83.2** | **62.1** | 67.8 | **91.5** | **94.1** | **78.6** | **72.4** | **90.5** | **64.9** | **61.7** | **87.5** | **78.1** | **71.2** | **77.4** | **82.5** | **88.1** |
| **PP-OCRv6_small** | **81.3** | 57.6 | 61.1 | 90.5 | 93.3 | 77.0 | 71.1 | 88.2 | 64.1 | 60.2 | 85.7 | 75.9 | 68.4 | 76.4 | 79.7 | 86.9 |
| **PP-OCRv6_tiny** | 73.5 | 40.1 | 39.3 | 86.7 | 88.4 | 65.0 | 68.4 | 89.8 | 52.3 | 57.1 | 78.0 | 65.4 | 54.7 | 62.1 | 71.2 | 80.5 |
| PP-OCRv5_server | 78.1 | 58.0 | 59.6 | 90.1 | 85.1 | 74.7 | 60.4 | 73.7 | 59.4 | 56.8 | 86.5 | 74.4 | 64.0 | 70.2 | 68.1 | 87.6 |
| PP-OCRv5_mobile | 73.7 | 41.7 | 50.9 | 86.0 | 86.0 | 72.0 | 57.8 | 75.8 | 55.7 | 54.8 | 80.7 | 72.5 | 54.0 | 59.3 | 57.6 | 81.7 |
| Qwen3-VL-235B | 74.9 | 49.7 | **73.2** | 82.3 | 86.2 | 76.4 | 33.6 | 66.2 | 56.1 | 49.0 | 82.5 | 76.5 | 69.6 | 74.7 | 73.8 | 78.7 |
| Gemini-3.1-Pro | 71.4 | 46.4 | 73.0 | 80.0 | 90.5 | 69.5 | 18.0 | 67.2 | 54.4 | 50.3 | 74.6 | 75.9 | 63.1 | 69.1 | 73.2 | 75.9 |
| GPT-5.5 | 64.2 | 19.2 | 56.9 | 75.7 | 82.2 | 57.5 | 63.7 | 58.6 | 49.1 | 48.3 | 67.7 | 50.4 | 53.0 | 62.4 | 67.7 | 71.1 |
PP-OCRv6_medium 加权平均准确率 83.2%,相比 PP-OCRv5_server 提升 5.1%,在日文(+16.8%)、古籍(+12.0%)、屏幕显示(+14.4%) 等类别提升显著。即使是仅 1.1M 参数的 PP-OCRv6_tiny,也超越了 4/5 的 VLM 模型。
## 4. 端到端推理速度(s/image)
在 200 张图像(通用场景 + 文档场景)上测试端到端 OCR 产线速度,包含读图、前后处理、模型推理全流程。
| 硬件 | 推理后端 | PP-OCRv6_medium | PP-OCRv6_small | PP-OCRv6_tiny | PP-OCRv5_server | PP-OCRv5_mobile | PP-OCRv4_mobile |
|------|---------|-----------------|----------------|---------------|-----------------|-----------------|-----------------|
| NVIDIA A100 | PaddlePaddle | 0.29 | 0.25 | 0.13 | 0.32 | 0.25 | 0.14 |
| NVIDIA A100 | TensorRT | -- | 0.32 | 0.16 | -- | 0.33 | 0.16 |
| NVIDIA V100 | PaddlePaddle | 0.72 | 0.49 | 0.21 | 0.66 | 0.50 | 0.25 |
| NVIDIA V100 | ONNX Runtime | 0.67 | 0.53 | 0.29 | 0.77 | 0.46 | 0.27 |
| NVIDIA V100 | TensorRT | 0.77 | 0.60 | 0.23 | 0.73 | 0.59 | 0.27 |
| Intel Xeon 8350C | PaddlePaddle | 2.05 | 0.79 | 0.32 | 2.04 | 0.80 | 0.62 |
| Intel Xeon 8350C | OpenVINO | 1.40 | 0.59 | 0.20 | 7.30 | 0.78 | 0.60 |
| Intel Xeon 8350C | ONNX Runtime | 3.31 | 0.61 | 0.22 | 6.36 | 0.61 | 0.49 |
| Apple M4 | PaddlePaddle | 8.82 | 3.07 | 0.96 | >10 | 5.82 | 5.65 |
| Apple M4 | ONNX Runtime | 5.55 | 1.29 | 0.35 | 7.20 | 1.10 | 1.02 |
- PP-OCRv6_medium 在所有平台上均匹配或优于 PP-OCRv5_server:A100 上快 1.1×(0.29s vs 0.32s),V100 ONNX Runtime 快 1.15×(0.67s vs 0.77s),Intel Xeon OpenVINO 快 5.2×(1.40s vs 7.30s)。
- PP-OCRv6_small 在大多数平台上与 PP-OCRv5_mobile 速度持平但精度更高;Apple M4 PaddlePaddle 快 1.9×(3.07s vs 5.82s)。
- PP-OCRv6_tiny 是所有平台上最快的模型,Apple M4 PaddlePaddle 快 6.1×(0.96s vs 5.82s),Intel Xeon OpenVINO 快 3.9×(0.20s vs 0.78s),A100 上仅需 0.13s。
# 四、语言支持
PP-OCRv6 medium/small 档支持以下 50 种语言:
**核心语言**:简体中文、繁体中文、英文、日文
**拉丁语系(46种)**:法文、德文、意大利文、西班牙文、葡萄牙文、荷兰文、波兰文、罗马尼亚文、捷克文、瑞典文、挪威文、丹麦文、芬兰文、匈牙利文、土耳其文、越南文、印尼文、马来文、阿塞拜疆文、南非荷兰文、波斯尼亚文、克罗地亚文、威尔士文、爱沙尼亚文、爱尔兰文、冰岛文、库尔德文、立陶宛文、拉脱维亚文、马耳他文、毛利文、奥克文、斯洛伐克文、斯洛文尼亚文、阿尔巴尼亚文、斯瓦希里文、他加禄文、乌兹别克文、拉丁文、塞尔维亚文(拉丁)、加泰罗尼亚文、巴斯克文、加利西亚文、卢森堡文、罗曼什文、克丘亚文
> PP-OCRv6_tiny 档支持 49 种语言(不含日文,以避免约 4000 个汉字/假名字符对 1.1M 参数输出层的影响)。
# 五、效果可视化
## 1. 检测效果对比
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/ppocrv6_det_vis.jpg" width="800"/>
</div>
<p align="center">图:文本检测效果对比。从左到右:PP-OCRv6_medium、PP-OCRv5_server、Gemini-3.1-Pro、GPT-5.5。</p>
## 2. 幻觉对比
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/huanjue.jpg" width="800"/>
</div>
<p align="center">图:PP-OCRv6_medium 与 VLM 的幻觉对比。PP-OCRv6 忠实还原图像中的文字内容,而 VLM 基于语言先验进行"纠正",引入了图像中不存在的幻觉。</p>
## 3. 端到端 OCR 效果对比
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/case1.jpg" width="800"/>
</div>
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/case2.jpg" width="800"/>
</div>
<div align="center">
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/refs/heads/main/images/paddleocr/PP-OCRv6/case3.jpg" width="800"/>
</div>
<p align="center">图:PP-OCRv6_medium 与 PP-OCRv5_server 端到端 OCR 效果对比,涵盖中文、英文、日文、艺术字、工业字符、旋转文本、拼音、点阵字符等场景。</p>
# 六、快速使用
```python
from paddleocr import PaddleOCR
# 默认使用 PP-OCRv6_medium
ocr = PaddleOCR(
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
result = ocr.predict("https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png")
for res in result:
res.print()
res.save_to_img("output")
res.save_to_json("output")
```
```bash
# 命令行使用
paddleocr ocr -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
--use_textline_orientation False
```
**使用 Transformers 引擎推理:**
PP-OCRv6 支持通过 Hugging Face Transformers 引擎进行推理(需安装 `transformers>=5.8.0`):
```python
from paddleocr import TextRecognition
model = TextRecognition(
model_name="PP-OCRv6_medium_rec",
engine="transformers",
)
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
```
```bash
# 命令行方式
paddleocr text_recognition -i general_ocr_rec_001.png \
--text_recognition_model_name PP-OCRv6_medium_rec \
--engine transformers
```
**使用高性能推理(ONNX Runtime 后端):**
通过 `enable_hpi=True` 启用高性能推理插件,底层会自动使用 ONNX Runtime 加速:
```python
from paddleocr import PaddleOCR
ocr = PaddleOCR(
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
enable_hpi=True,
)
result = ocr.predict("general_ocr_002.png")
```
```bash
# 命令行方式
paddleocr ocr -i general_ocr_002.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
--use_textline_orientation False \
--enable_hpi True
```
> 高性能推理插件需额外安装,详见[高性能推理指南](../../inference_deployment/local_inference/high_performance_inference.md)。
# 七、部署与二次开发
* **多系统支持**:兼容 Windows、Linux、Mac 等主流操作系统。
* **多硬件支持**:支持英伟达 GPU、Intel CPU、昆仑芯、昇腾等硬件推理和部署。
* **高性能推理插件**:推荐结合高性能推理插件进一步提升推理速度,详见[高性能推理指南](../../inference_deployment/local_inference/high_performance_inference.md)。
* **服务化部署**:支持高稳定性服务化部署方案,详见[服务化部署指南](../../inference_deployment/serving/serving.md)。
* **二次开发能力**:支持自定义数据集训练、字典扩展、模型微调,详见[文本检测模块使用教程](../../module_usage/text_detection.md)及[文本识别模块使用教程](../../module_usage/text_recognition.md)。
@@ -33,7 +33,7 @@ paddleocr api \
## Common Options
- `--model_type`: task type, either `ocr` or `doc_parsing`.
- `--model`: model name. OCR defaults to PP-OCRv5; document parsing defaults to PaddleOCR-VL-1.6 when omitted.
- `--model`: model name.
- `--file_url`: file URL to process.
- `--file_path`: local file path to upload and process.
- `--base_url`: base URL of the PaddleOCR API service; defaults to the official service URL (can also be set via `PADDLEOCR_BASE_URL`).
@@ -84,7 +84,7 @@ paddleocr api \
| Task | `--model_type` | Default model | Supported models |
| --- | --- | --- | --- |
| OCR | `ocr` | `PP-OCRv5` | `PP-OCRv5` |
| OCR | `ocr` | `PP-OCRv6` | `PP-OCRv5`, `PP-OCRv5-latin`, `PP-OCRv6` |
| Document parsing | `doc_parsing` | `PaddleOCR-VL-1.6` | `PP-StructureV3`, `PaddleOCR-VL`, `PaddleOCR-VL-1.5`, `PaddleOCR-VL-1.6` |
## Output Behavior
@@ -33,7 +33,7 @@ paddleocr api \
## 常用参数
- `--model_type`:任务类型,`ocr` 或 `doc_parsing`。
- `--model`:模型名称。OCR 任务默认使用 PP-OCRv5;文档解析任务未指定时默认使用 PaddleOCR-VL-1.6。
- `--model`:模型名称。
- `--file_url`:待处理文件 URL。
- `--file_path`:待上传并处理的本地文件路径。
- `--base_url`:PaddleOCR API 服务的 base URL;缺省使用官方服务地址(也可通过 `PADDLEOCR_BASE_URL` 环境变量设置)。
@@ -84,7 +84,7 @@ paddleocr api \
| 任务 | `--model_type` | 默认模型 | 可选模型 |
| --- | --- | --- | --- |
| OCR | `ocr` | `PP-OCRv5` | `PP-OCRv5` |
| OCR | `ocr` | `PP-OCRv6` | `PP-OCRv5`、`PP-OCRv5-latin`、`PP-OCRv6` |
| 文档解析 | `doc_parsing` | `PaddleOCR-VL-1.6` | `PP-StructureV3`、`PaddleOCR-VL`、`PaddleOCR-VL-1.5`、`PaddleOCR-VL-1.6` |
## 输出行为
@@ -58,7 +58,7 @@ The model constants in the table are type-safe aliases for the official API mode
| Task | Interfaces | Default model | Supported models | Option type |
| --- | --- | --- | --- | --- |
| OCR | `OCR`, `SubmitOCR`, `WaitOCRResult` | `PPOCRv5` | `PPOCRv5` | `*OCROptions` |
| OCR | `OCR`, `SubmitOCR`, `WaitOCRResult` | `PPOCRv6` | `PPOCRv5`, `PPOCRv6` | `*OCROptions` |
| Document parsing | `ParseDocument`, `SubmitDocumentParsing`, `WaitDocumentParsingResult` | `PaddleOCRVL16` | `PPStructureV3`, `PaddleOCRVL`, `PaddleOCRVL15`, `PaddleOCRVL16` | Use `*PPStructureV3Options` with `PPStructureV3`, and `*PaddleOCRVLOptions` with PaddleOCR-VL models. |
## Configuration
@@ -58,7 +58,7 @@ Go SDK 常用公共方法包括:
| 任务 | 适用接口 | 默认模型 | 可选模型 | 参数类型 |
| --- | --- | --- | --- | --- |
| OCR | `OCR`、`SubmitOCR`、`WaitOCRResult` | `PPOCRv5` | `PPOCRv5` | `*OCROptions` |
| OCR | `OCR`、`SubmitOCR`、`WaitOCRResult` | `PPOCRv6` | `PPOCRv5`、`PPOCRv6` | `*OCROptions` |
| 文档解析 | `ParseDocument`、`SubmitDocumentParsing`、`WaitDocumentParsingResult` | `PaddleOCRVL16` | `PPStructureV3`、`PaddleOCRVL`、`PaddleOCRVL15`、`PaddleOCRVL16` | 选择 `PPStructureV3` 时传入 `*PPStructureV3Options`;选择 PaddleOCR-VL 系列模型时传入 `*PaddleOCRVLOptions`。 |
## 配置与参数
@@ -57,7 +57,7 @@ The `Model` enum values in the table are type-safe aliases for the official API
| Task | Interfaces | Default model | Supported models | Option type |
| --- | --- | --- | --- | --- |
| OCR | `ocr`, `submit_ocr`, `wait_ocr_result` | `Model.PP_OCRV5` | `Model.PP_OCRV5` | `OCROptions` |
| OCR | `ocr`, `submit_ocr`, `wait_ocr_result` | `Model.PP_OCRV6` | `Model.PP_OCRV5`, `Model.PP_OCRV6` | `OCROptions` |
| Document parsing | `parse_document`, `submit_document_parsing`, `wait_document_parsing_result` | `Model.PADDLE_OCR_VL_16` | `Model.PP_STRUCTURE_V3`, `Model.PADDLE_OCR_VL`, `Model.PADDLE_OCR_VL_15`, `Model.PADDLE_OCR_VL_16` | Use `PPStructureV3Options` with `PP-StructureV3`, and `PaddleOCRVLOptions` with PaddleOCR-VL models. |
## Configuration
@@ -57,7 +57,7 @@ Python SDK 常用公共方法包括:
| 任务 | 适用接口 | 默认模型 | 可选模型 | 参数类型 |
| --- | --- | --- | --- | --- |
| OCR | `ocr`、`submit_ocr`、`wait_ocr_result` | `Model.PP_OCRV5` | `Model.PP_OCRV5` | `OCROptions` |
| OCR | `ocr`、`submit_ocr`、`wait_ocr_result` | `Model.PP_OCRV6` | `Model.PP_OCRV5`、`Model.PP_OCRV6` | `OCROptions` |
| 文档解析 | `parse_document`、`submit_document_parsing`、`wait_document_parsing_result` | `Model.PADDLE_OCR_VL_16` | `Model.PP_STRUCTURE_V3`、`Model.PADDLE_OCR_VL`、`Model.PADDLE_OCR_VL_15`、`Model.PADDLE_OCR_VL_16` | 选择 `PP-StructureV3` 时传入 `PPStructureV3Options`;选择 `PaddleOCR-VL` 系列模型时传入 `PaddleOCRVLOptions`。 |
## 配置与参数
@@ -61,7 +61,7 @@ The `Model` enum values in the table are type-safe aliases for the official API
| Task | Interfaces | Default model | Supported models | Option type |
| --- | --- | --- | --- | --- |
| OCR | `ocr`, `submitOcr`, `waitOcrResult` | `Model.PPOCRv5` | `Model.PPOCRv5` | `OCROptions` |
| OCR | `ocr`, `submitOcr`, `waitOcrResult` | `Model.PPOCRv6` | `Model.PPOCRv5`, `Model.PPOCRv6` | `OCROptions` |
| Document parsing | `parseDocument`, `submitDocumentParsing`, `waitDocumentParsingResult` | `Model.PaddleOCRVL16` | `Model.PPStructureV3`, `Model.PaddleOCRVL`, `Model.PaddleOCRVL15`, `Model.PaddleOCRVL16` | Use `PPStructureV3Options` with `PPStructureV3`, and `PaddleOCRVLOptions` with PaddleOCR-VL models. |
## Configuration
@@ -61,7 +61,7 @@ TypeScript SDK 常用公共方法包括:
| 任务 | 适用接口 | 默认模型 | 可选模型 | 参数类型 |
| --- | --- | --- | --- | --- |
| OCR | `ocr`、`submitOcr`、`waitOcrResult` | `Model.PPOCRv5` | `Model.PPOCRv5` | `OCROptions` |
| OCR | `ocr`、`submitOcr`、`waitOcrResult` | `Model.PPOCRv6` | `Model.PPOCRv5`、`Model.PPOCRv6` | `OCROptions` |
| 文档解析 | `parseDocument`、`submitDocumentParsing`、`waitDocumentParsingResult` | `Model.PaddleOCRVL16` | `Model.PPStructureV3`、`Model.PaddleOCRVL`、`Model.PaddleOCRVL15`、`Model.PaddleOCRVL16` | 选择 `PPStructureV3` 时传入 `PPStructureV3Options`;选择 PaddleOCR-VL 系列模型时传入 `PaddleOCRVLOptions`。 |
## 配置与参数
+27 -23
View File
@@ -11,13 +11,13 @@ PaddleOCR provides a lightweight [Model Context Protocol (MCP)](https://modelcon
### Key features include:
- **Currently Supported Pipelines**
- **Currently Supported Models**
| Pipeline | MCP tool name | Description |
| Model | MCP tool name | Description |
| --- | --- | --- |
| `OCR` | `ocr` | Performs text detection and recognition on images and PDF files. |
| `PP-OCRv5`, `PP-OCRv5-latin`, `PP-OCRv6` | `ocr` | Performs text detection and recognition on images and PDF files. |
| `PP-StructureV3` | `pp_structurev3` | Identifies and extracts text blocks, titles, paragraphs, images, tables, and other layout elements from images or PDF files, converting the input into Markdown documents. |
| `PaddleOCR-VL Series` | `paddleocr_vl` | Performs layout parsing with a VLM-based approach and converts the input into Markdown documents. Includes versions: PaddleOCR-VL, PaddleOCR-VL-1.5, and PaddleOCR-VL-1.6. |
| `PaddleOCR-VL`, `PaddleOCR-VL-1.5`, `PaddleOCR-VL-1.6` | `paddleocr_vl` | Performs layout parsing with a VLM-based approach and converts the input into Markdown documents. |
- **Supported Inference Methods**
- **Local Inference**: Runs PaddleOCR pipelines directly on the local machine. This method has certain requirements for the local environment and hardware performance, and is suitable for offline use and scenarios with strict data privacy requirements.
@@ -93,7 +93,7 @@ Convert images containing formulas and tables to editable csv/Excel format:
This section explains how to install the `paddleocr-mcp` library via pip.
`paddleocr-mcp` requires Python 3.10 or later.
`paddleocr-mcp` depends on `paddleocr>=3.6.0` by default, so Official API, Qianfan API, and self-hosted API modes do not require installing PaddleOCR separately. Local inference additionally requires the document-parsing dependencies and an inference engine required to run PaddleOCR pipelines locally; see [Method 1: Local Inference](#method-1-local-inference) for details.
`paddleocr-mcp` depends on `paddleocr>=3.7.0` by default, so Official API, Qianfan API, and self-hosted API modes do not require installing PaddleOCR separately. Local inference additionally requires the document-parsing dependencies and an inference engine required to run PaddleOCR pipelines locally; see [Method 1: Local Inference](#method-1-local-inference) for details.
Install from PyPI:
@@ -153,7 +153,7 @@ The following quick start uses **Official API** inference as an example to get y
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "aistudio",
"PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN": "<your-access-token>"
}
@@ -191,7 +191,7 @@ You can configure the MCP server according to your requirements to use different
#### Method 1: Local Inference {#method-1-local-inference}
1. Install `paddleocr-mcp` and the local inference dependencies. `paddleocr-mcp` already depends on PaddleOCR; local inference additionally requires the document-parsing dependencies and an inference engine. You can install them manually by referring to the [PaddleOCR installation guide](../installation.en.md), or use the corresponding optional dependencies:
- `paddleocr-mcp[local]`: includes `paddleocr[doc-parser]>=3.6.0` (without the inference engine).
- `paddleocr-mcp[local]`: includes `paddleocr[doc-parser]>=3.7.0` (without the inference engine).
- `paddleocr-mcp[local-cpu]`: based on `local`, additionally includes the CPU PaddlePaddle inference engine (`paddlepaddle>=3.2.1`).
```bash
@@ -214,7 +214,7 @@ Configuration example:
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
}
}
@@ -224,13 +224,12 @@ Configuration example:
**Notes**:
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for details.
- `PADDLEOCR_MCP_MODEL` should be set to the model name. See Section 4 for details.
- `PADDLEOCR_MCP_PIPELINE_CONFIG` is optional. If not set, the default pipeline configuration is used. To adjust the configuration, such as changing models, refer to the [PaddleOCR documentation](../paddleocr_and_paddlex.md) to export the pipeline configuration file, and set `PADDLEOCR_MCP_PIPELINE_CONFIG` to the absolute path of this file.
- **Inference Performance Tips**:
If you encounter long inference time or insufficient memory, consider adjusting the pipeline configuration:
- **OCR Pipeline**: It is recommended to switch to the `mobile` series models. For example, use `PP-OCRv5_mobile_det` for detection and `PP-OCRv5_mobile_rec` for recognition.
- **PP-StructureV3 Pipeline**:
- Disable unused features, such as setting `use_formula_recognition` to `False` to disable formula recognition.
@@ -265,7 +264,7 @@ Configuration example:
Refer to [2.1 Quick Start](#21-quick-start).
For tasks other than text recognition, set `PADDLEOCR_MCP_PIPELINE` correctly (see Section 4 for parameter details).
For tasks other than text recognition, set `PADDLEOCR_MCP_MODEL` correctly (see Section 4 for parameter details).
#### Method 3: Qianfan API
@@ -283,7 +282,7 @@ Configuration example:
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "PaddleOCR-VL",
"PADDLEOCR_MCP_MODEL": "PaddleOCR-VL",
"PADDLEOCR_MCP_PPOCR_SOURCE": "qianfan",
"PADDLEOCR_MCP_QIANFAN_API_KEY": "<your-api-key>"
}
@@ -294,7 +293,7 @@ Configuration example:
**Notes**:
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. Qianfan supports only `PP-StructureV3` and `PaddleOCR-VL`.
- `PADDLEOCR_MCP_MODEL` should be set to the model name. Qianfan supports only `PP-StructureV3` and `PaddleOCR-VL`.
- `PADDLEOCR_MCP_QIANFAN_BASE_URL` is the Qianfan API base URL (optional).
- `PADDLEOCR_MCP_QIANFAN_API_KEY` is your Qianfan API key for authentication.
@@ -314,7 +313,7 @@ Configuration example:
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
}
@@ -325,7 +324,7 @@ Configuration example:
**Notes**:
- `PADDLEOCR_MCP_PIPELINE` should be set to the pipeline name. See Section 4 for details.
- `PADDLEOCR_MCP_MODEL` should be set to the model name. See Section 4 for details.
- Replace `<your-server-url>` with the underlying service base URL (e.g. `http://127.0.0.1:8080`, **without** path suffixes such as `/ocr` or `/layout-parsing`; MCP appends them by pipeline).
### 2.4 Using `uvx`
@@ -348,7 +347,7 @@ PaddleOCR also supports starting the MCP server via `uvx`. With this approach, m
"paddleocr_mcp"
],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
}
@@ -370,7 +369,7 @@ PaddleOCR also supports starting the MCP server via `uvx`. With this approach, m
"paddleocr_mcp"
],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
}
}
@@ -395,14 +394,17 @@ paddleocr_mcp --help
Example commands:
```bash
# OCR + Official API + stdio
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --pipeline OCR --ppocr_source aistudio
# PP-OCRv5 + Official API + stdio
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --model PP-OCRv5 --ppocr_source aistudio
# PP-OCRv6 + Official API + stdio
paddleocr_mcp --model PP-OCRv6 --ppocr_source aistudio
# PP-StructureV3 + Local Inference + stdio
paddleocr_mcp --pipeline PP-StructureV3 --ppocr_source local
paddleocr_mcp --model PP-StructureV3 --ppocr_source local
# OCR + Self-hosted API + Streamable HTTP
paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --self-hosted-base-url http://127.0.0.1:8080 --http
paddleocr_mcp --model PP-OCRv5 --ppocr_source self_hosted --self-hosted-base-url http://127.0.0.1:8080 --http
```
See [4. Parameter Reference](#4-parameter-reference) for all parameters supported by the PaddleOCR MCP server.
@@ -413,14 +415,16 @@ You can control the MCP server via environment variables or CLI arguments.
| Environment Variable | CLI Argument | Type | Description | Options | Default |
|:---------|:-----------|:-----|:-----|:-------|:-------|
| `PADDLEOCR_MCP_PIPELINE` | `--pipeline` | `str` | Pipeline to run. | `"OCR"`, `"PP-StructureV3"`, `"PaddleOCR-VL"`, `"PaddleOCR-VL-1.5"`, `"PaddleOCR-VL-1.6"` | `"OCR"` |
| `PADDLEOCR_MCP_MODEL` | `--model` | `str` | Model to run. MCP selects the tool automatically from the model. | `"PP-OCRv5"`, `"PP-OCRv5-latin"`, `"PP-OCRv6"`, `"PP-StructureV3"`, `"PaddleOCR-VL"`, `"PaddleOCR-VL-1.5"`, `"PaddleOCR-VL-1.6"` | `"PP-OCRv6"` |
| `PADDLEOCR_MCP_PPOCR_SOURCE` | `--ppocr_source` | `str` | Source of PaddleOCR capabilities. | `"local"` (local inference), `"aistudio"` (Official API), `"qianfan"` (Qianfan API), `"self_hosted"` (self-hosted API) | `"local"` |
| `PADDLEOCR_MCP_AISTUDIO_BASE_URL` | `--aistudio-base-url` | `str` | AI Studio API base URL (optional for `aistudio` source). | - | `None` |
| `PADDLEOCR_MCP_QIANFAN_BASE_URL` | `--qianfan-base-url` | `str` | Qianfan API base URL (optional for `qianfan` source). | - | `https://qianfan.baidubce.com/v2/ocr` |
| `PADDLEOCR_MCP_SELF_HOSTED_BASE_URL` | `--self-hosted-base-url` | `str` | Self-hosted PaddleX serve base URL (required for `self_hosted` source). | - | `None` |
| `PADDLEOCR_MCP_QIANFAN_API_KEY` | `--qianfan_api_key` | `str` | Qianfan API authentication key (required for `qianfan` source). | - | `None` |
| `PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN` | `--aistudio_access_token` | `str` | AI Studio access token (required for `aistudio` source). | - | `None` |
| `PADDLEOCR_MCP_TIMEOUT` | `--timeout` | `int` | Underlying request timeout in seconds. For `aistudio`, used as the per-request timeout; polling timeout is 10× this value. For `qianfan` and `self_hosted`, used as the HTTP read timeout. | - | `60` |
| `PADDLEOCR_MCP_HTTP_TIMEOUT` | `--http-timeout` | `int` | HTTP read timeout in seconds for synchronous APIs (`qianfan`, `self_hosted`). | - | `600` |
| `PADDLEOCR_MCP_AISTUDIO_REQUEST_TIMEOUT` | `--aistudio-request-timeout` | `int` | Per-request HTTP timeout in seconds for AI Studio API calls (job submission, status checks, etc.). | - | `120` |
| `PADDLEOCR_MCP_AISTUDIO_POLL_TIMEOUT` | `--aistudio-poll-timeout` | `int` | Total job polling timeout in seconds for AI Studio. | - | `600` |
| `PADDLEOCR_MCP_DEVICE` | `--device` | `str` | Device for inference (only effective for `local` source). | - | `None` |
| `PADDLEOCR_MCP_PIPELINE_CONFIG` | `--pipeline_config` | `str` | PaddleOCR pipeline configuration file path (only effective for `local` source). | - | `None` |
| - | `--http` | `bool` | Use Streamable HTTP transport instead of stdio (for remote deployment and multiple clients). | - | `False` |
+27 -23
View File
@@ -11,13 +11,13 @@ PaddleOCR 提供轻量级的 [Model Context Protocol(MCP)](https://modelcont
### 主要功能如下:
- **当前支持的产线**
- **当前支持的模型**
| 产线 | MCP 工具名称 | 说明 |
| 模型 | MCP 工具名称 | 说明 |
| --- | --- | --- |
| `OCR` | `ocr` | 对图像和 PDF 文件进行文本检测与识别。 |
| `PP-OCRv5`、`PP-OCRv5-latin`、`PP-OCRv6` | `ocr` | 对图像和 PDF 文件进行文本检测与识别。 |
| `PP-StructureV3` | `pp_structurev3` | 从图像或 PDF 文件中识别和提取文本块、标题、段落、图片、表格以及其他版面元素,将输入转换为 Markdown 文档。 |
| `PaddleOCR-VL 系列` | `paddleocr_vl` | 使用基于多模态大模型的方案进行版面解析,将输入转换为 Markdown 文档。包含版本:PaddleOCR-VL、PaddleOCR-VL-1.5、PaddleOCR-VL-1.6。 |
| `PaddleOCR-VL`、`PaddleOCR-VL-1.5`、`PaddleOCR-VL-1.6` | `paddleocr_vl` | 使用基于多模态大模型的方案进行版面解析,将输入转换为 Markdown 文档。 |
- **支持的推理方式**
- **本地推理**:在本机直接运行 PaddleOCR 产线。此方式对本地环境与计算机性能有一定要求,适用于需要离线使用、对数据隐私有严格要求的场景。
@@ -94,7 +94,7 @@ PaddleOCR 提供轻量级的 [Model Context Protocol(MCP)](https://modelcont
本节将介绍如何通过 pip 安装 `paddleocr-mcp` 库。
`paddleocr-mcp` 要求 Python 版本不低于 3.10。
`paddleocr-mcp` 默认依赖 `paddleocr>=3.6.0`,因此官方 API、千帆 API 和自建 API 推理方式无需额外安装 PaddleOCR。如需使用本地推理,还需要安装本地运行产线所需的文档解析依赖和推理引擎,详情请参考 [方式一:本地推理](#方式一本地推理)。
`paddleocr-mcp` 默认依赖 `paddleocr>=3.7.0`,因此官方 API、千帆 API 和自建 API 推理方式无需额外安装 PaddleOCR。如需使用本地推理,还需要安装本地运行产线所需的文档解析依赖和推理引擎,详情请参考 [方式一:本地推理](#方式一本地推理)。
从 PyPI 安装:
@@ -154,7 +154,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "aistudio",
"PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN": "<your-access-token>"
}
@@ -192,7 +192,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
#### 方式一:本地推理 {#方式一本地推理}
1. 安装 `paddleocr-mcp` 及本地推理依赖。`paddleocr-mcp` 已默认依赖 PaddleOCR;本地推理还需要文档解析依赖和推理引擎。可以参考 [PaddleOCR 安装文档](../installation.md) 手动安装,也可以使用相应的可选依赖:
- `paddleocr-mcp[local]`:包含 `paddleocr[doc-parser]>=3.6.0`(不包含推理引擎)。
- `paddleocr-mcp[local]`:包含 `paddleocr[doc-parser]>=3.7.0`(不包含推理引擎)。
- `paddleocr-mcp[local-cpu]`:在 `local` 基础上额外包含 CPU 版本的 PaddlePaddle 推理引擎(`paddlepaddle>=3.2.1`)。
```bash
@@ -215,7 +215,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
}
}
@@ -225,13 +225,12 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
**说明**:
- `PADDLEOCR_MCP_PIPELINE` 需要被设置为产线名称。详见第 4 节。
- `PADDLEOCR_MCP_MODEL` 需要被设置为模型名称。详见第 4 节。
- `PADDLEOCR_MCP_PIPELINE_CONFIG` 为可选项,不设置时使用产线默认配置。如需调整配置,例如更换模型,请参考 [PaddleOCR 文档](../paddleocr_and_paddlex.md) 导出产线配置文件,并将 `PADDLEOCR_MCP_PIPELINE_CONFIG` 设置为配置文件的绝对路径。
- **推理性能提示**:
如果使用过程中出现推理耗时过长、内存不足等问题,可考虑参考如下建议调整产线配置:
- **OCR 产线**:建议更换 `mobile` 系列模型。例如,您可以在产线配置文件中将检测和识别模型分别修改为 `PP-OCRv5_mobile_det` 和 `PP-OCRv5_mobile_rec`。
- **PP-StructureV3 产线**:
- 关闭不需要用到的功能,例如设置 `use_formula_recognition` 为 `False` 以禁用公式识别。
@@ -266,7 +265,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
请参考 [2.1 快速开始](#21)。
对于文字识别以外的任务,请正确设置 `PADDLEOCR_MCP_PIPELINE`(参数说明详见第 4 节)。
对于文字识别以外的任务,请正确设置 `PADDLEOCR_MCP_MODEL`(参数说明详见第 4 节)。
#### 方式三:千帆 API
@@ -284,7 +283,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "PaddleOCR-VL",
"PADDLEOCR_MCP_MODEL": "PaddleOCR-VL",
"PADDLEOCR_MCP_PPOCR_SOURCE": "qianfan",
"PADDLEOCR_MCP_QIANFAN_API_KEY": "<your-api-key>"
}
@@ -295,7 +294,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
**说明**:
- `PADDLEOCR_MCP_PIPELINE` 需设置为产线名称;千帆仅支持 `PP-StructureV3` 与 `PaddleOCR-VL`。
- `PADDLEOCR_MCP_MODEL` 需设置为模型名称;千帆仅支持 `PP-StructureV3` 与 `PaddleOCR-VL`。
- `PADDLEOCR_MCP_QIANFAN_BASE_URL` 为千帆 API 基础 URL(可选)。
- `PADDLEOCR_MCP_QIANFAN_API_KEY` 是您的千帆 API key,用于认证。
@@ -315,7 +314,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
"command": "paddleocr_mcp",
"args": [],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
}
@@ -326,7 +325,7 @@ PaddleOCR 也支持通过 `uvx` 等方式免安装运行服务器,详情请参
**说明**:
- `PADDLEOCR_MCP_PIPELINE` 需要被设置为产线名称。详见第 4 节。
- `PADDLEOCR_MCP_MODEL` 需要被设置为模型名称。详见第 4 节。
- 将 `<your-server-url>` 替换为底层服务的基础 URL(如:`http://127.0.0.1:8080`,**不要**包含 `/ocr`、`/layout-parsing` 等路径;MCP 会按产线自动拼接)。
### 2.4 使用 `uvx`
@@ -349,7 +348,7 @@ PaddleOCR 也支持通过 `uvx` 启动 MCP 服务器。这种方式不需要手
"paddleocr_mcp"
],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "self_hosted",
"PADDLEOCR_MCP_SELF_HOSTED_BASE_URL": "<your-server-url>"
}
@@ -371,7 +370,7 @@ PaddleOCR 也支持通过 `uvx` 启动 MCP 服务器。这种方式不需要手
"paddleocr_mcp"
],
"env": {
"PADDLEOCR_MCP_PIPELINE": "OCR",
"PADDLEOCR_MCP_MODEL": "PP-OCRv5",
"PADDLEOCR_MCP_PPOCR_SOURCE": "local"
}
}
@@ -396,14 +395,17 @@ paddleocr_mcp --help
示例命令如下:
```bash
# OCR + 官方 API + stdio
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --pipeline OCR --ppocr_source aistudio
# PP-OCRv5 + 官方 API + stdio
PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN=xxxxxx paddleocr_mcp --model PP-OCRv5 --ppocr_source aistudio
# PP-OCRv6 + 官方 API + stdio
paddleocr_mcp --model PP-OCRv6 --ppocr_source aistudio
# PP-StructureV3 + 本地推理 + stdio
paddleocr_mcp --pipeline PP-StructureV3 --ppocr_source local
paddleocr_mcp --model PP-StructureV3 --ppocr_source local
# OCR + 自建 API + Streamable HTTP
paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --self-hosted-base-url http://127.0.0.1:8080 --http
paddleocr_mcp --model PP-OCRv5 --ppocr_source self_hosted --self-hosted-base-url http://127.0.0.1:8080 --http
```
在 [4. 参数说明](#4) 中可以了解 PaddleOCR MCP 服务器支持的全部参数。
@@ -414,14 +416,16 @@ paddleocr_mcp --pipeline OCR --ppocr_source self_hosted --self-hosted-base-url h
| 环境变量 | 命令行参数 | 类型 | 描述 | 可选值 | 默认值 |
|:---------|:-----------|:-----|:-----|:-------|:-------|
| `PADDLEOCR_MCP_PIPELINE` | `--pipeline` | `str` | 要运行的产线。 | `"OCR"`,`"PP-StructureV3"`,`"PaddleOCR-VL"`,`"PaddleOCR-VL-1.5"`,`"PaddleOCR-VL-1.6"` | `"OCR"` |
| `PADDLEOCR_MCP_MODEL` | `--model` | `str` | 要运行的模型。MCP 会根据模型自动选择对应的工具。 | `"PP-OCRv5"`,`"PP-OCRv5-latin"`,`"PP-OCRv6"`,`"PP-StructureV3"`,`"PaddleOCR-VL"`,`"PaddleOCR-VL-1.5"`,`"PaddleOCR-VL-1.6"` | `"PP-OCRv6"` |
| `PADDLEOCR_MCP_PPOCR_SOURCE` | `--ppocr_source` | `str` | PaddleOCR能力来源。 | `"local"`(本地推理),`"aistudio"`(官方 API),`"qianfan"`(千帆 API),`"self_hosted"`(自建 API) | `"local"` |
| `PADDLEOCR_MCP_AISTUDIO_BASE_URL` | `--aistudio-base-url` | `str` | AI Studio API 基础 URL(`aistudio` 推理方式下可选)。 | - | `None` |
| `PADDLEOCR_MCP_QIANFAN_BASE_URL` | `--qianfan-base-url` | `str` | 千帆 API 基础 URL(`qianfan` 推理方式下可选)。 | - | `https://qianfan.baidubce.com/v2/ocr` |
| `PADDLEOCR_MCP_SELF_HOSTED_BASE_URL` | `--self-hosted-base-url` | `str` | 自建 PaddleX 服务基础 URL(`self_hosted` 推理方式下必需)。 | - | `None` |
| `PADDLEOCR_MCP_QIANFAN_API_KEY` | `--qianfan_api_key` | `str` | 千帆 API 认证密钥(`qianfan` 推理方式下必需)。 | - | `None` |
| `PADDLEOCR_MCP_AISTUDIO_ACCESS_TOKEN` | `--aistudio_access_token` | `str` | AI Studio 访问令牌(`aistudio` 推理方式下必需)。 | - | `None` |
| `PADDLEOCR_MCP_TIMEOUT` | `--timeout` | `int` | 底层服务请求超时时间(秒)。在 `aistudio` 推理方式下用作单次请求超时,轮询超时为该值的 10 倍;在 `qianfan` 和 `self_hosted` 推理方式下用作 HTTP 读取超时。 | - | `60` |
| `PADDLEOCR_MCP_HTTP_TIMEOUT` | `--http-timeout` | `int` | 同步 HTTP API(`qianfan`、`self_hosted`)的单次 POST 读取超时(秒)。 | - | `600` |
| `PADDLEOCR_MCP_AISTUDIO_REQUEST_TIMEOUT` | `--aistudio-request-timeout` | `int` | AI Studio 单次 HTTP 请求超时(秒),用于提交任务、查询状态等。 | - | `120` |
| `PADDLEOCR_MCP_AISTUDIO_POLL_TIMEOUT` | `--aistudio-poll-timeout` | `int` | AI Studio 任务轮询总等待上限(秒)。 | - | `600` |
| `PADDLEOCR_MCP_DEVICE` | `--device` | `str` | 指定运行推理的设备(仅在 `local` 推理方式下生效)。 | - | `None` |
| `PADDLEOCR_MCP_PIPELINE_CONFIG` | `--pipeline_config` | `str` | PaddleOCR 产线配置文件路径(仅在 `local` 推理方式下生效)。 | - | `None` |
| - | `--http` | `bool` | 使用 Streamable HTTP 传输而非 stdio(适用于远程部署和多客户端)。 | - | `False` |
+1 -1
View File
@@ -21,7 +21,7 @@ PaddleOCR provides official Agent Skills that package the routing rules, calling
## Prerequisites
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"`
2. Install PaddleOCR 3.7.0+: `pip install "paddleocr>=3.7.0"`
3. Get access token from [AI Studio](https://aistudio.baidu.com/account/accessToken)
## Install into AI Apps
+1 -1
View File
@@ -21,7 +21,7 @@ PaddleOCR 提供官方 Agent Skills,将 OCR 与文档解析任务的触发规
## 安装前准备
1. 请确保执行 Skill 的设备已安装 Python 3.9 或以上版本。
2. Skills 依赖 PaddleOCR 3.6.0+。请安装:`pip install "paddleocr>=3.6.0"`
2. Skills 依赖 PaddleOCR 3.7.0+。请安装:`pip install "paddleocr>=3.7.0"`
3. 获取 access token:访问 [AI Studio Access Token 页面](https://aistudio.baidu.com/account/accessToken)
## 安装到 AI 应用
+54
View File
@@ -22,6 +22,33 @@ PaddleOCR 内置了多条产线,每条产线都包含了若干模块,每个
</thead>
<tbody>
<tr>
<td>PP-OCRv6_medium_det</td>
<td>-</td>
<td>- / -</td>
<td>- / -</td>
<td>-</td>
<td><a href="https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/configs/modules/text_detection/PP-OCRv6_medium_det.yaml">PP-OCRv6_medium_det.yaml</a></td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
</tr>
<tr>
<td>PP-OCRv6_small_det</td>
<td>-</td>
<td>- / -</td>
<td>- / -</td>
<td>-</td>
<td><a href="https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/configs/modules/text_detection/PP-OCRv6_small_det.yaml">PP-OCRv6_small_det.yaml</a></td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
</tr>
<tr>
<td>PP-OCRv6_tiny_det</td>
<td>-</td>
<td>- / -</td>
<td>- / -</td>
<td>-</td>
<td><a href="https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/configs/modules/text_detection/PP-OCRv6_tiny_det.yaml">PP-OCRv6_tiny_det.yaml</a></td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
</tr>
<tr>
<td>PP-OCRv5_server_det</td>
<td>83.8</td>
<td>89.55 / 70.19</td>
@@ -126,6 +153,33 @@ PaddleOCR 内置了多条产线,每条产线都包含了若干模块,每个
<th>模型下载链接</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td>-</td>
<td>- / -</td>
<td>- / -</td>
<td>-</td>
<td><a href="https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/configs/modules/text_recognition/PP-OCRv6_medium_rec.yaml">PP-OCRv6_medium_rec.yaml</a></td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td>-</td>
<td>- / -</td>
<td>- / -</td>
<td>-</td>
<td><a href="https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/configs/modules/text_recognition/PP-OCRv6_small_rec.yaml">PP-OCRv6_small_rec.yaml</a></td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td>-</td>
<td>- / -</td>
<td>- / -</td>
<td>-</td>
<td><a href="https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/configs/modules/text_recognition/PP-OCRv6_tiny_rec.yaml">PP-OCRv6_tiny_rec.yaml</a></td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td>86.38</td>
<td>8.46 / 2.36</td>
@@ -24,6 +24,33 @@ The text detection module is a critical component of OCR (Optical Character Reco
</thead>
<tbody>
<tr>
<td>PP-OCRv6_medium_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_det_infer.tar">Inference Model</a>/<a href="">Training Model</a></td>
<td>86.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>59.4</td>
<td>PP-OCRv6 medium-scale text detection model based on PPLCNetV4 + RepLKFPN, highest accuracy, suitable for server deployment</td>
</tr>
<tr>
<td>PP-OCRv6_small_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_infer.tar">Inference Model</a>/<a href="">Training Model</a></td>
<td>84.1*</td>
<td>- / -</td>
<td>- / -</td>
<td>9.6</td>
<td>PP-OCRv6 small text detection model, balancing accuracy and efficiency, suitable for mobile deployment</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_infer.tar">Inference Model</a>/<a href="">Training Model</a></td>
<td>80.6*</td>
<td>- / -</td>
<td>- / -</td>
<td>1.9</td>
<td>PP-OCRv6 ultra-lightweight text detection model (0.43M params), suitable for edge/IoT scenarios</td>
</tr>
<tr>
<td>PP-OCRv5_server_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_server_det_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_det_pretrained.pdparams">Training Model</a></td>
<td>83.8</td>
@@ -146,7 +173,7 @@ You can also integrate the model inference into your project. Before running the
```python
from paddleocr import TextDetection
model = TextDetection(model_name="PP-OCRv5_server_det")
model = TextDetection()
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
@@ -160,10 +187,7 @@ If you choose `transformers` as the inference engine, make sure the Transformers
```python
from paddleocr import TextDetection
model = TextDetection(
model_name="PP-OCRv5_server_det",
engine="transformers",
)
model = TextDetection(engine="transformers")
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
@@ -175,10 +199,7 @@ If you choose `onnxruntime` as the inference engine, make sure the ONNX Runtime
```python
from paddleocr import TextDetection
model = TextDetection(
model_name="PP-OCRv5_server_det",
engine="onnxruntime",
)
model = TextDetection(engine="onnxruntime")
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
@@ -218,7 +239,7 @@ Visualization example:
Method and parameter descriptions:
* Instantiate the text detection model (e.g., <code>PP-OCRv5_server_det</code>):
* Instantiate the text detection model with <code>TextDetection</code>:
<table>
<thead>
<tr>
@@ -233,7 +254,7 @@ Method and parameter descriptions:
<td><code>model_name</code></td>
<td><b>Meaning:</b>Model name.<br/>
<b>Description:</b>
If set to <code>None</code>, <code>PP-OCRv5_server_det</code> will be used.</td>
If set to <code>None</code>, <code>PP-OCRv6_medium_det</code> will be used.</td>
<td><code>str|None</code></td>
<td><code>None</code></td>
</tr>
+40 -23
View File
@@ -24,6 +24,33 @@ comments: true
</thead>
<tbody>
<tr>
<td>PP-OCRv6_medium_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
<td>86.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>59.4</td>
<td>PP-OCRv6 的中等规模文本检测模型,基于 PPLCNetV4 + RepLKFPN,精度最高,适合服务端部署</td>
</tr>
<tr>
<td>PP-OCRv6_small_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
<td>84.1*</td>
<td>- / -</td>
<td>- / -</td>
<td>9.6</td>
<td>PP-OCRv6 的小型文本检测模型,兼顾精度与效率,适合移动端部署</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
<td>80.6*</td>
<td>- / -</td>
<td>- / -</td>
<td>1.9</td>
<td>PP-OCRv6 的超轻量文本检测模型(0.43M 参数),适合端侧/IoT 场景</td>
</tr>
<tr>
<td>PP-OCRv5_server_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_server_det_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_det_pretrained.pdparams">训练模型</a></td>
<td>83.8</td>
@@ -148,11 +175,8 @@ print(f"GPU数量: {paddle.device.cuda.device_count()}")
# 使用默认模型进行文本检测
paddleocr text_detection -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_001.png
# 指定模型进行检测
paddleocr text_detection -i general_ocr_001.png --model_name PP-OCRv5_server_det
# 批量处理本地图片
paddleocr text_detection -i ./images/ --model_name PP-OCRv5_mobile_det
# 指定模型
paddleocr text_detection -i general_ocr_001.png --model_name PP-OCRv6_small_det
```
上述示例默认使用 <code>paddle_static</code> 推理引擎,请先按照[飞桨框架安装](../paddlepaddle_installation.md)完成 PaddlePaddle 安装。
@@ -183,7 +207,7 @@ paddleocr text_detection -i https://paddle-model-ecology.bj.bcebos.com/paddlex/i
```python
from paddleocr import TextDetection
model = TextDetection(model_name="PP-OCRv5_server_det")
model = TextDetection()
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
@@ -197,10 +221,7 @@ for res in output:
```python
from paddleocr import TextDetection
model = TextDetection(
model_name="PP-OCRv5_server_det",
engine="transformers",
)
model = TextDetection(engine="transformers")
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
@@ -212,10 +233,7 @@ for res in output:
```python
from paddleocr import TextDetection
model = TextDetection(
model_name="PP-OCRv5_server_det",
engine="onnxruntime",
)
model = TextDetection(engine="onnxruntime")
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
@@ -254,7 +272,7 @@ for res in output:
相关方法、参数等说明如下:
* <code>TextDetection</code>类实例化文本检测模型(此处以<code>PP-OCRv5_server_det</code>为例),具体说明如下:
* <code>TextDetection</code>类实例化文本检测模型,具体说明如下:
<table>
<thead>
<tr>
@@ -269,7 +287,7 @@ for res in output:
<td><code>model_name</code></td>
<td><b>含义:</b>模型名称。<br/>
<b>说明:</b>
如果设置为<code>None</code>,则使用<code>PP-OCRv5_server_det</code>。</td>
如果设置为<code>None</code>,则使用<code>PP-OCRv6_medium_det</code>。</td>
<td><code>str|None</code></td>
<td><code>None</code></td>
</tr>
@@ -844,7 +862,7 @@ python3 tools/export_model.py -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml -o
(2)启用TensorRT加速:设置`use_tensorrt=True`,需要CUDA 11.8+和TensorRT 8.6+
(3)使用半精度:设置`precision="fp16"`,可以显著提升速度
(4)调整批处理大小:根据显存大小设置合适的`batch_size`
(5)使用移动端模型:在精度要求不高时使用`PP-OCRv5_mobile`系列模型
(5)使用轻量模型:在精度要求不高时使用 `PP-OCRv6_small`/`PP-OCRv6_tiny` 等轻量级模型
#### Q: GPU内存不足(CUDA out of memory)怎么办?
@@ -853,7 +871,7 @@ python3 tools/export_model.py -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml -o
(2)减小图像尺寸:设置`det_limit_side_len=640`
(3)启用内存优化:设置`enable_memory_optim=True`
(4)限制GPU内存使用:设置`gpu_mem=200`
(5)使用移动端模型:切换到`PP-OCRv5_mobile`系列模型
(5)使用轻量模型:切换到 `PP-OCRv6_small`/`PP-OCRv6_tiny` 等轻量级模型
### 6.2 检测精度问题
@@ -863,7 +881,6 @@ python3 tools/export_model.py -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml -o
(1)调整检测参数:
```python
model = TextDetection(
model_name="PP-OCRv5_server_det",
thresh=0.3, # 降低像素阈值
box_thresh=0.5, # 降低检测框阈值
unclip_ratio=2.0, # 增大扩张系数
@@ -878,10 +895,10 @@ model = TextDetection(
#### Q: 如何选择合适的模型?
**A**: 根据应用场景选择:
- 服务器高精度场景:使用`PP-OCRv5_server_det`,精度最高
- 移动端部署:使用`PP-OCRv5_mobile_det`,模型小速度快
- 实时处理:使用`PP-OCRv5_mobile_det`,推理速度快
- 批量处理:使用`PP-OCRv5_server_det`,精度高
- 服务器高精度场景:使用 `PP-OCRv6_medium_det`,精度最高
- 移动端部署:使用 `PP-OCRv6_small_det`,兼顾精度与效率
- 端侧/IoT:使用 `PP-OCRv6_tiny_det`,模型最小
- 实时处理:使用 `PP-OCRv6_small_det` 或 `PP-OCRv6_tiny_det`,推理更快
### 6.4 参数调优建议
@@ -22,6 +22,31 @@ The text recognition module is the core part of the OCR (Optical Character Recog
<th>Introduction</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_medium_rec_pretrained.pdparams">Training Model</a></td>
<td>83.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>73.3</td>
<td rowspan="3">PP-OCRv6 text recognition models based on PPLCNetV4 + LightSVTR + CTC/NRTR multi-head decoder, single model supports 50 languages (tiny: 49). Medium achieves +5.1% over PP-OCRv5_server.</td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_small_rec_pretrained.pdparams">Training Model</a></td>
<td>81.3*</td>
<td>- / -</td>
<td>- / -</td>
<td>20.4</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_tiny_rec_pretrained.pdparams">Training Model</a></td>
<td>73.5*</td>
<td>- / -</td>
<td>- / -</td>
<td>4.4</td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/\
PP-OCRv5_server_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_rec_pretrained.pdparams">Pretrained Model</a></td>
@@ -84,6 +109,19 @@ en_PP-OCRv4_mobile_rec_infer.tar">Inference Model</a>/<a href="https://paddle-mo
<details><summary> 👉Model List Details</summary>
* <b>PP-OCRv6 Multi-Scenario Models</b>
<table>
<tr>
<th>Model</th><th>Model Download Links</th>
<th>Recognition Avg Accuracy(%)</th>
<th>GPU Inference Time (ms)<br/>[Normal Mode / High-Performance Mode]</th>
<th>CPU Inference Time (ms)<br/>[Normal Mode / High-Performance Mode]</th>
<th>Model Storage Size (MB)</th>
<th>Introduction</th>
</tr>
</table>
* <b>PP-OCRv5 Multi-Scenario Models</b>
<table>
@@ -99,6 +137,31 @@ en_PP-OCRv4_mobile_rec_infer.tar">Inference Model</a>/<a href="https://paddle-mo
<th>Introduction</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_medium_rec_pretrained.pdparams">Training Model</a></td>
<td>83.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>73.3</td>
<td rowspan="3">PP-OCRv6 text recognition models based on PPLCNetV4 + LightSVTR + CTC/NRTR multi-head decoder, single model supports 50 languages (tiny: 49). Medium achieves +5.1% over PP-OCRv5_server.</td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_small_rec_pretrained.pdparams">Training Model</a></td>
<td>81.3*</td>
<td>- / -</td>
<td>- / -</td>
<td>20.4</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_tiny_rec_pretrained.pdparams">Training Model</a></td>
<td>73.5*</td>
<td>- / -</td>
<td>- / -</td>
<td>4.4</td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/\
PP-OCRv5_server_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_rec_pretrained.pdparams">Pretrained Model</a></td>
@@ -568,7 +631,7 @@ You can also integrate the model inference of the text recognition module into y
```python
from paddleocr import TextRecognition
model = TextRecognition(model_name="PP-OCRv5_server_rec")
model = TextRecognition()
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
@@ -582,10 +645,7 @@ If you choose `transformers` as the inference engine, make sure the Transformers
```python
from paddleocr import TextRecognition
model = TextRecognition(
model_name="PP-OCRv5_server_rec",
engine="transformers",
)
model = TextRecognition(engine="transformers")
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
@@ -597,10 +657,7 @@ If you choose `onnxruntime` as the inference engine, make sure the ONNX Runtime
```python
from paddleocr import TextRecognition
model = TextRecognition(
model_name="PP-OCRv5_server_rec",
engine="onnxruntime",
)
model = TextRecognition(engine="onnxruntime")
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
@@ -630,7 +687,7 @@ The visualized image is as follows:
Descriptions of related methods and parameters are as follows:
* Instantiate the text recognition model using <code>TextRecognition</code> (using <code>PP-OCRv5_server_rec</code> as an example), as follows:
* Instantiate the text recognition model using <code>TextRecognition</code>, as follows:
<table>
<thead>
<tr>
@@ -643,7 +700,7 @@ Descriptions of related methods and parameters are as follows:
<tbody>
<tr>
<td><code>model_name</code></td>
<td><b>Description:</b> If set to <code>None</code>, <code>PP-OCRv5_server_rec</code> is used.</td>
<td><b>Description:</b> If set to <code>None</code>, <code>PP-OCRv6_medium_rec</code> is used.</td>
<td><code>str|None</code></td>
<td><code>None</code></td>
</tr>
@@ -22,6 +22,31 @@ comments: true
<th>介绍</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_medium_rec_pretrained.pdparams">训练模型</a></td>
<td>83.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>73.3</td>
<td rowspan="3">PP-OCRv6 文本识别模型,基于 PPLCNetV4 + LightSVTR + CTC/NRTR 多头解码器,单模型支持 50 种语言(tiny 档 49 种)。medium 档相比 PP-OCRv5_server 综合识别精度提升 5.1%。</td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_small_rec_pretrained.pdparams">训练模型</a></td>
<td>81.3*</td>
<td>- / -</td>
<td>- / -</td>
<td>20.4</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_tiny_rec_pretrained.pdparams">训练模型</a></td>
<td>73.5*</td>
<td>- / -</td>
<td>- / -</td>
<td>4.4</td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/\
PP-OCRv5_server_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_rec_pretrained.pdparams">训练模型</a></td>
@@ -84,6 +109,19 @@ en_PP-OCRv4_mobile_rec_infer.tar">推理模型</a>/<a href="https://paddle-model
<details><summary> 👉模型列表详情</summary>
* <b>PP-OCRv6 多场景模型</b>
<table>
<tr>
<th>模型</th><th>模型下载链接</th>
<th>识别 Avg Accuracy(%)</th>
<th>GPU推理耗时(ms)<br/>[常规模式 / 高性能模式]</th>
<th>CPU推理耗时(ms)<br/>[常规模式 / 高性能模式]</th>
<th>模型存储大小(MB)</th>
<th>介绍</th>
</tr>
</table>
* <b>PP-OCRv5 多场景模型</b>
<table>
@@ -99,6 +137,31 @@ en_PP-OCRv4_mobile_rec_infer.tar">推理模型</a>/<a href="https://paddle-model
<th>介绍</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_medium_rec_pretrained.pdparams">训练模型</a></td>
<td>83.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>73.3</td>
<td rowspan="3">PP-OCRv6 文本识别模型,基于 PPLCNetV4 + LightSVTR + CTC/NRTR 多头解码器,单模型支持 50 种语言(tiny 档 49 种)。medium 档相比 PP-OCRv5_server 综合识别精度提升 5.1%。</td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_small_rec_pretrained.pdparams">训练模型</a></td>
<td>81.3*</td>
<td>- / -</td>
<td>- / -</td>
<td>20.4</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_tiny_rec_pretrained.pdparams">训练模型</a></td>
<td>73.5*</td>
<td>- / -</td>
<td>- / -</td>
<td>4.4</td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/\
PP-OCRv5_server_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_rec_pretrained.pdparams">训练模型</a></td>
@@ -577,7 +640,7 @@ paddleocr text_recognition -i https://paddle-model-ecology.bj.bcebos.com/paddlex
```python
from paddleocr import TextRecognition
model = TextRecognition(model_name="PP-OCRv5_server_rec")
model = TextRecognition()
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
@@ -591,10 +654,7 @@ for res in output:
```python
from paddleocr import TextRecognition
model = TextRecognition(
model_name="PP-OCRv5_server_rec",
engine="transformers",
)
model = TextRecognition(engine="transformers")
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
@@ -606,10 +666,7 @@ for res in output:
```python
from paddleocr import TextRecognition
model = TextRecognition(
model_name="PP-OCRv5_server_rec",
engine="onnxruntime",
)
model = TextRecognition(engine="onnxruntime")
output = model.predict(input="general_ocr_rec_001.png", batch_size=1)
for res in output:
res.print()
@@ -640,7 +697,7 @@ for res in output:
相关方法、参数等说明如下:
* <code>TextRecognition</code>实例化文本识别模型(此处以<code>PP-OCRv5_server_rec</code>为例),具体说明如下:
* <code>TextRecognition</code>实例化文本识别模型,具体说明如下:
<table>
<thead>
<tr>
@@ -655,7 +712,7 @@ for res in output:
<td><code>model_name</code></td>
<td><b>含义:</b>模型名称。<br/>
<b>说明:</b>
如果设置为<code>None</code>,则使用<code>PP-OCRv5_server_rec</code>。</td>
如果设置为<code>None</code>,则使用<code>PP-OCRv6_medium_rec</code>。</td>
<td><code>str|None</code></td>
<td><code>None</code></td>
</tr>
@@ -36,6 +36,7 @@ The version correspondence between PaddleOCR, PaddleX, and the PaddlePaddle fram
| `3.4.x` | `>= 3.4.0, < 3.5.0` | `>= 3.0.0` |
| `3.5.x` | `>= 3.5.0, < 3.6.0` | `>= 3.0.0` |
| `3.6.x` | `>= 3.6.0, < 3.7.0` | `>= 3.0.0` |
| `3.7.x` | `>= 3.7.0, < 3.8.0` | `>= 3.0.0` |
## 2. Correspondence Between PaddleOCR Pipelines and PaddleX Pipeline Registration Names
+1
View File
@@ -36,6 +36,7 @@ PaddleOCR、PaddleX 和飞桨框架的版本存在如下对应关系:
| `3.4.x` | `>= 3.4.0, < 3.5.0` | `>= 3.0.0` |
| `3.5.x` | `>= 3.5.0, < 3.6.0` | `>= 3.0.0` |
| `3.6.x` | `>= 3.6.0, < 3.7.0` | `>= 3.0.0` |
| `3.7.x` | `>= 3.7.0, < 3.8.0` | `>= 3.0.0` |
## 2. PaddleOCR 产线与 PaddleX 产线注册名的对应关系
+63 -6
View File
@@ -8,7 +8,7 @@ comments: true
OCR is a technology that converts text from images into editable text. It is widely used in fields such as document digitization, information extraction, and data processing. OCR can recognize printed text, handwritten text, and even certain types of fonts and symbols.
The general OCR pipeline is used to solve text recognition tasks by extracting text information from images and outputting it in text form. This pipeline supports the use of PP-OCRv3, PP-OCRv4, and PP-OCRv5 models, with the default model being the PP-OCRv5_server model released by PaddleOCR 3.0, which improves by 13 percentage points over PP-OCRv4_server in various scenarios.
The general OCR pipeline is used to solve text recognition tasks by extracting text information from images and outputting it in text form. This pipeline supports PP-OCRv3, PP-OCRv4, PP-OCRv5, and PP-OCRv6 models, with the default model being **PP-OCRv6_medium** released with PaddleOCR 3.7. PP-OCRv6, built on the newly designed PPLCNetV4 unified backbone, offers tiny/small/medium tiers. The medium tier achieves +5.1% (recognition) and +4.6% (detection) over PP-OCRv5_server with faster inference; a single model supports 50 languages including Chinese, English, Japanese, and 46 Latin-script languages.
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/main/images/pipelines/ocr/01.png"/>
@@ -130,6 +130,33 @@ In this pipeline, you can select models based on the benchmark test data provide
</thead>
<tbody>
<tr>
<td>PP-OCRv6_medium_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_det_infer.tar">Inference Model</a>/<a href="">Training Model</a></td>
<td>86.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>59.4</td>
<td>PP-OCRv6 medium-scale text detection model based on PPLCNetV4 + RepLKFPN, highest accuracy, suitable for server deployment</td>
</tr>
<tr>
<td>PP-OCRv6_small_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_infer.tar">Inference Model</a>/<a href="">Training Model</a></td>
<td>84.1*</td>
<td>- / -</td>
<td>- / -</td>
<td>9.6</td>
<td>PP-OCRv6 small text detection model, balancing accuracy and efficiency, suitable for mobile deployment</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_infer.tar">Inference Model</a>/<a href="">Training Model</a></td>
<td>80.6*</td>
<td>- / -</td>
<td>- / -</td>
<td>1.9</td>
<td>PP-OCRv6 ultra-lightweight text detection model (0.43M params), suitable for edge/IoT scenarios</td>
</tr>
<tr>
<td>PP-OCRv5_server_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_server_det_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_det_pretrained.pdparams">Training Model</a></td>
<td>83.8</td>
@@ -181,6 +208,31 @@ In this pipeline, you can select models based on the benchmark test data provide
<th>Introduction</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_medium_rec_pretrained.pdparams">Training Model</a></td>
<td>83.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>73.3</td>
<td rowspan="3">PP-OCRv6 text recognition models based on PPLCNetV4 + LightSVTR + CTC/NRTR multi-head decoder, single model supports 50 languages (tiny: 49)</td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_small_rec_pretrained.pdparams">Training Model</a></td>
<td>81.3*</td>
<td>- / -</td>
<td>- / -</td>
<td>20.4</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_tiny_rec_pretrained.pdparams">Training Model</a></td>
<td>73.5*</td>
<td>- / -</td>
<td>- / -</td>
<td>4.4</td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/\
PP-OCRv5_server_rec_infer.tar">Inference Model</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_rec_pretrained.pdparams">Pretrained Model</a></td>
@@ -743,7 +795,6 @@ Please note: If you encounter issues such as the program becoming unresponsive,
Run a single command to quickly test the OCR pipeline. Before running the code below, please download the [example image](https://paddle-model-ecology.bj.bcebos.com/paddlex/demo_image/pipelines/general_formula_recognition_001.png) locally:
```bash
# Default: Uses PP-OCRv5 model
paddleocr ocr -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
@@ -1024,6 +1075,7 @@ The table in the appendix lists all the supported languages.
<td><b>Meaning:</b>Version of OCR models.<br/>
<b>Description:</b>
<ul>
<li><b>PP-OCRv6</b>: Use PP-OCRv6 series models;
<li><b>PP-OCRv5</b>: Use PP-OCRv5 series models;
<li><b>PP-OCRv4</b>: Use PP-OCRv4 series models;
<li><b>PP-OCRv3</b>: Use PP-OCRv3 series models.</li>
@@ -1507,6 +1559,7 @@ The table in the appendix lists all the supported languages.
<td><b>Meaning:</b>Version of OCR models. <br/>
<b>Description:</b>
<ul>
<li><b>PP-OCRv6</b>: Use PP-OCRv6 series models;</li>
<li><b>PP-OCRv5</b>: Use PP-OCRv5 series models;</li>
<li><b>PP-OCRv4</b>: Use PP-OCRv4 series models;</li>
<li><b>PP-OCRv3</b>: Use PP-OCRv3 series models.</li>
@@ -2542,7 +2595,7 @@ Command line mode:
# Specify the local model path via --text_detection_model_dir
paddleocr ocr -i ./general_ocr_002.png --text_detection_model_dir your_det_model_path
# PP-OCRv5_server_det model is used as the default text detection model. If you do not fine-tune this model, modify the model name by using --text_detection_model_name
# Modify the model name via --text_detection_model_name
paddleocr ocr -i ./general_ocr_002.png --text_detection_model_name PP-OCRv5_mobile_det --text_detection_model_dir your_v5_mobile_det_model_path
```
@@ -2555,7 +2608,7 @@ from paddleocr import PaddleOCR
# Specify the local model path via text_detection_model_dir
pipeline = PaddleOCR(text_detection_model_dir="./your_det_model_path")
# PP-OCRv5_server_det model is used as the default text detection model. If you do not fine-tune this model, modify the model name by using text_detection_model_name
# Modify the model name via text_detection_model_name
# pipeline = PaddleOCR(text_detection_model_name="PP-OCRv5_mobile_det", text_detection_model_dir="./your_v5_mobile_det_model_path")
```
@@ -2648,7 +2701,7 @@ SubModules:
limit_type: min
max_side_limit: 4000
model_dir: null # Replace with the path to your fine-tuned text detection model weights
model_name: PP-OCRv5_server_det # If the name of the fine-tuned model is different from the default model name, please modify it here as well
model_name: PP-OCRv6_medium_det # If the name of the fine-tuned model is different from the default model name, please modify it here as well
module_name: text_detection
thresh: 0.3
unclip_ratio: 1.5
@@ -2660,7 +2713,7 @@ SubModules:
TextRecognition:
batch_size: 6
model_dir: null # Replace with the path to your fine-tuned text recognition model weights
model_name: PP-OCRv5_server_rec # If the name of the fine-tuned model is different from the default model name, please modify it here as well
model_name: PP-OCRv6_medium_rec # If the name of the fine-tuned model is different from the default model name, please modify it here as well
module_name: text_recognition
score_thresh: 0.0
......
@@ -2793,6 +2846,10 @@ pipeline = PaddleOCR(paddlex_config="PaddleOCR.yaml")
</tr>
</thead>
<tbody>
<tr>
<td><code>PP-OCRv6</code></td>
<td><code>ch</code>, <code>chinese_cht</code>, <code>en</code>, <code>japan</code>, <code>af</code>, <code>az</code>, <code>bs</code>, <code>ca</code>, <code>cs</code>, <code>cy</code>, <code>da</code>, <code>de</code>, <code>es</code>, <code>et</code>, <code>eu</code>, <code>fi</code>, <code>fr</code>, <code>ga</code>, <code>gl</code>, <code>hr</code>, <code>hu</code>, <code>id</code>, <code>is</code>, <code>it</code>, <code>ku</code>, <code>la</code>, <code>lb</code>, <code>lt</code>, <code>lv</code>, <code>mi</code>, <code>ms</code>, <code>mt</code>, <code>nl</code>, <code>no</code>, <code>oc</code>, <code>pl</code>, <code>pt</code>, <code>qu</code>, <code>rm</code>, <code>ro</code>, <code>rs_latin</code>, <code>sk</code>, <code>sl</code>, <code>sq</code>, <code>sv</code>, <code>sw</code>, <code>tl</code>, <code>tr</code>, <code>uz</code>, <code>vi</code>, <code>french</code>, <code>german</code>. <code>PP-OCRv6_tiny</code> does not support <code>japan</code>; set <code>PP-OCRv6_tiny_det</code>/<code>PP-OCRv6_tiny_rec</code> explicitly.</td>
</tr>
<tr>
<td><code>PP-OCRv5</code></td>
<td><code>ch</code>, <code>en</code>, <code>fr</code>, <code>de</code>, <code>japan</code>, <code>korean</code>, <code>chinese_cht</code>, <code>af</code>, <code>it</code>, <code>es</code>, <code>bs</code>, <code>pt</code>, <code>cs</code>, <code>cy</code>, <code>da</code>, <code>et</code>, <code>ga</code>, <code>hr</code>, <code>hu</code>, <code>rslatin</code>, <code>id</code>, <code>oc</code>, <code>is</code>, <code>lt</code>, <code>mi</code>, <code>ms</code>, <code>nl</code>, <code>no</code>, <code>pl</code>, <code>sk</code>, <code>sl</code>, <code>sq</code>, <code>sv</code>, <code>sw</code>, <code>tl</code>, <code>tr</code>, <code>uz</code>, <code>la</code>, <code>ru</code>, <code>be</code>, <code>uk</code>, <code>th</code>, <code>el</code>, <code>az</code>, <code>ku</code>, <code>lv</code>, <code>mt</code>, <code>pi</code>, <code>ro</code>, <code>vi</code>, <code>fi</code>, <code>eu</code>, <code>gl</code>, <code>lb</code>, <code>rm</code>, <code>ca</code>, <code>qu</code>, <code>te</code>, <code>sr</code>, <code>bg</code>, <code>mn</code>, <code>ab</code>, <code>ady</code>, <code>kbd</code>, <code>av</code>, <code>dar</code>, <code>inh</code>, <code>ce</code>, <code>lki</code>, <code>lez</code>, <code>tab</code>, <code>kk</code>, <code>ky</code>, <code>tg</code>, <code>mk</code>, <code>tt</code>, <code>cv</code>, <code>ba</code>, <code>mhr</code>, <code>mo</code>, <code>udm</code>, <code>kv</code>, <code>os</code>, <code>bua</code>, <code>xal</code>, <code>tyv</code>, <code>sah</code>, <code>kaa</code>, <code>ar</code>, <code>fa</code>, <code>ug</code>, <code>ur</code>, <code>ps</code>, <code>ku</code>, <code>sd</code>, <code>bal</code>, <code>hi</code>, <code>mr</code>, <code>ne</code>, <code>bh</code>, <code>mai</code>, <code>ang</code>, <code>bho</code>, <code>mah</code>, <code>sck</code>, <code>new</code>, <code>gom</code>, <code>sa</code>, <code>bgc</code>, <code>ta</code></td>
+64 -7
View File
@@ -8,7 +8,7 @@ comments: true
OCR(光学字符识别,Optical Character Recognition)是一种将图像中的文字转换为可编辑文本的技术。它广泛应用于文档数字化、信息提取和数据处理等领域。OCR 可以识别印刷文本、手写文本,甚至某些类型的字体和符号。
通用 OCR 产线用于解决文字识别任务,提取图片中的文字信息以文本形式输出,本产线支持PP-OCRv3、PP-OCRv4、PP-OCRv5模型的使用,其中默认模型为 PaddleOCR3.0 发布的 PP-OCRv5_server 模型,其在多个场景中较 PP-OCRv4_server 提升 13 个百分点。
通用 OCR 产线用于解决文字识别任务,提取图片中的文字信息以文本形式输出,本产线支持PP-OCRv3、PP-OCRv4、PP-OCRv5、PP-OCRv6模型的使用,其中默认模型为 PaddleOCR3.7 发布的 **PP-OCRv6_medium** 模型。PP-OCRv6 基于全新设计的 PPLCNetV4 统一骨干网络,提供 tiny/small/medium 三档模型,medium 档在综合精度上相比 PP-OCRv5_server 提升 5.1%(识别)和 4.6%(检测),同时推理速度更快;单一模型统一支持中、英、日及 46 种拉丁语系共 50 种语言。
<img src="https://raw.githubusercontent.com/cuicheng01/PaddleX_doc_images/main/images/pipelines/ocr/01.png"/>
@@ -131,6 +131,33 @@ OCR(光学字符识别,Optical Character Recognition)是一种将图像中
</thead>
<tbody>
<tr>
<td>PP-OCRv6_medium_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
<td>86.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>59.4</td>
<td>PP-OCRv6 的中等规模文本检测模型,基于 PPLCNetV4 + RepLKFPN,精度最高,适合服务端部署</td>
</tr>
<tr>
<td>PP-OCRv6_small_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
<td>84.1*</td>
<td>- / -</td>
<td>- / -</td>
<td>9.6</td>
<td>PP-OCRv6 的小型文本检测模型,兼顾精度与效率,适合移动端部署</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_det_infer.tar">推理模型</a>/<a href="">训练模型</a></td>
<td>80.6*</td>
<td>- / -</td>
<td>- / -</td>
<td>1.9</td>
<td>PP-OCRv6 的超轻量文本检测模型(0.43M 参数),适合端侧/IoT 场景</td>
</tr>
<tr>
<td>PP-OCRv5_server_det</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv5_server_det_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_det_pretrained.pdparams">训练模型</a></td>
<td>83.8</td>
@@ -182,6 +209,31 @@ OCR(光学字符识别,Optical Character Recognition)是一种将图像中
<th>介绍</th>
</tr>
<tr>
<td>PP-OCRv6_medium_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_medium_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_medium_rec_pretrained.pdparams">训练模型</a></td>
<td>83.2*</td>
<td>- / -</td>
<td>- / -</td>
<td>73.3</td>
<td rowspan="3">PP-OCRv6 文本识别模型,基于 PPLCNetV4 + LightSVTR + CTC/NRTR 多头解码器,单模型支持 50 种语言(tiny 档 49 种)</td>
</tr>
<tr>
<td>PP-OCRv6_small_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_small_rec_pretrained.pdparams">训练模型</a></td>
<td>81.3*</td>
<td>- / -</td>
<td>- / -</td>
<td>20.4</td>
</tr>
<tr>
<td>PP-OCRv6_tiny_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_tiny_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv6_tiny_rec_pretrained.pdparams">训练模型</a></td>
<td>73.5*</td>
<td>- / -</td>
<td>- / -</td>
<td>4.4</td>
</tr>
<tr>
<td>PP-OCRv5_server_rec</td>
<td><a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/\
PP-OCRv5_server_rec_infer.tar">推理模型</a>/<a href="https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_rec_pretrained.pdparams">训练模型</a></td>
@@ -774,7 +826,6 @@ os.environ['PADDLE_PDX_MODEL_SOURCE'] = 'BOS' # 使用百度云存储
一行命令即可快速体验OCR产线效果。运行以下代码前,请您下载[示例图片](https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png)到本地:
```bash
# 默认使用 PP-OCRv5 模型
paddleocr ocr -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_002.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
@@ -1011,6 +1062,7 @@ paddleocr ocr -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_im
<td><b>含义:</b>OCR 模型版本。
<br><b>说明:</b>
<ul>
<li><b>PP-OCRv6</b>:使用PP-OCRv6系列模型;
<li><b>PP-OCRv5</b>:使用PP-OCRv5系列模型;
<li><b>PP-OCRv4</b>:使用PP-OCRv4系列模型;
<li><b>PP-OCRv3</b>:使用PP-OCRv3系列模型。
@@ -1516,6 +1568,7 @@ for res in result:
<td><b>含义:</b>OCR 模型版本。
<br><b>说明:</b>
<ul>
<li><b>PP-OCRv6</b>:使用PP-OCRv6系列模型;
<li><b>PP-OCRv5</b>:使用PP-OCRv5系列模型;
<li><b>PP-OCRv4</b>:使用PP-OCRv4系列模型;
<li><b>PP-OCRv3</b>:使用PP-OCRv3系列模型。
@@ -2543,7 +2596,7 @@ foreach ($result as $i => $item) {
# 通过 --text_detection_model_dir 指定本地模型路径
paddleocr ocr -i ./general_ocr_002.png --text_detection_model_dir your_det_model_path
# 默认使用 PP-OCRv5_server_det 模型作为默认文本检测模型,如果微调的不是该模型,通过 --text_detection_model_name 修改模型名称
# 通过 --text_detection_model_name 修改模型名称
paddleocr ocr -i ./general_ocr_002.png --text_detection_model_name PP-OCRv5_mobile_det --text_detection_model_dir your_v5_mobile_det_model_path
```
@@ -2556,7 +2609,7 @@ from paddleocr import PaddleOCR
# 通过 text_detection_model_dir 指定本地模型路径
pipeline = PaddleOCR(text_detection_model_dir="./your_det_model_path")
# 默认使用 PP-OCRv5_server_det 模型作为默认文本检测模型,如果微调的不是该模型,通过 text_detection_model_name 修改模型名称
# 通过 text_detection_model_name 修改模型名称
# pipeline = PaddleOCR(text_detection_model_name="PP-OCRv5_mobile_det", text_detection_model_dir="./your_v5_mobile_det_model_path")
```
@@ -2589,7 +2642,7 @@ SubModules:
limit_type: min
max_side_limit: 4000
model_dir: null # 替换为微调后的文本测模型权重路径
model_name: PP-OCRv5_server_det # 如果微调的模型名称与默认模型名称不同,请一并修改此处
model_name: PP-OCRv6_medium_det # 如果微调的模型名称与默认模型名称不同,请一并修改此处
module_name: text_detection
thresh: 0.3
unclip_ratio: 1.5
@@ -2601,7 +2654,7 @@ SubModules:
TextRecognition:
batch_size: 6
model_dir: null # 替换为微调后的文本识模型权重路径
model_name: PP-OCRv5_server_rec # 如果微调的模型名称与默认模型名称不同,请一并修改此处
model_name: PP-OCRv6_medium_rec # 如果微调的模型名称与默认模型名称不同,请一并修改此处
module_name: text_recognition
score_thresh: 0.0
......
@@ -2734,6 +2787,10 @@ pipeline = PaddleOCR(paddlex_config="PaddleOCR.yaml")
</tr>
</thead>
<tbody>
<tr>
<td><code>PP-OCRv6</code></td>
<td><code>ch</code>, <code>chinese_cht</code>, <code>en</code>, <code>japan</code>, <code>af</code>, <code>az</code>, <code>bs</code>, <code>ca</code>, <code>cs</code>, <code>cy</code>, <code>da</code>, <code>de</code>, <code>es</code>, <code>et</code>, <code>eu</code>, <code>fi</code>, <code>fr</code>, <code>ga</code>, <code>gl</code>, <code>hr</code>, <code>hu</code>, <code>id</code>, <code>is</code>, <code>it</code>, <code>ku</code>, <code>la</code>, <code>lb</code>, <code>lt</code>, <code>lv</code>, <code>mi</code>, <code>ms</code>, <code>mt</code>, <code>nl</code>, <code>no</code>, <code>oc</code>, <code>pl</code>, <code>pt</code>, <code>qu</code>, <code>rm</code>, <code>ro</code>, <code>rs_latin</code>, <code>sk</code>, <code>sl</code>, <code>sq</code>, <code>sv</code>, <code>sw</code>, <code>tl</code>, <code>tr</code>, <code>uz</code>, <code>vi</code>, <code>french</code>, <code>german</code>。<code>PP-OCRv6_tiny</code> 不支持 <code>japan</code>,需显式指定 <code>PP-OCRv6_tiny_det</code>/<code>PP-OCRv6_tiny_rec</code>。</td>
</tr>
<tr>
<td><code>PP-OCRv5</code></td>
<td><code>ch</code>, <code>en</code>, <code>fr</code>, <code>de</code>, <code>japan</code>, <code>korean</code>, <code>chinese_cht</code>, <code>af</code>, <code>it</code>, <code>es</code>, <code>bs</code>, <code>pt</code>, <code>cs</code>, <code>cy</code>, <code>da</code>, <code>et</code>, <code>ga</code>, <code>hr</code>, <code>hu</code>, <code>rslatin</code>, <code>id</code>, <code>oc</code>, <code>is</code>, <code>lt</code>, <code>mi</code>, <code>ms</code>, <code>nl</code>, <code>no</code>, <code>pl</code>, <code>sk</code>, <code>sl</code>, <code>sq</code>, <code>sv</code>, <code>sw</code>, <code>tl</code>, <code>tr</code>, <code>uz</code>, <code>la</code>, <code>ru</code>, <code>be</code>, <code>uk</code>, <code>th</code>, <code>el</code>, <code>az</code>, <code>ku</code>, <code>lv</code>, <code>mt</code>, <code>pi</code>, <code>ro</code>, <code>vi</code>, <code>fi</code>, <code>eu</code>, <code>gl</code>, <code>lb</code>, <code>rm</code>, <code>ca</code>, <code>qu</code>, <code>te</code>, <code>sr</code>, <code>bg</code>, <code>mn</code>, <code>ab</code>, <code>ady</code>, <code>kbd</code>, <code>av</code>, <code>dar</code>, <code>inh</code>, <code>ce</code>, <code>lki</code>, <code>lez</code>, <code>tab</code>, <code>kk</code>, <code>ky</code>, <code>tg</code>, <code>mk</code>, <code>tt</code>, <code>cv</code>, <code>ba</code>, <code>mhr</code>, <code>mo</code>, <code>udm</code>, <code>kv</code>, <code>os</code>, <code>bua</code>, <code>xal</code>, <code>tyv</code>, <code>sah</code>, <code>kaa</code>, <code>ar</code>, <code>fa</code>, <code>ug</code>, <code>ur</code>, <code>ps</code>, <code>ku</code>, <code>sd</code>, <code>bal</code>, <code>hi</code>, <code>mr</code>, <code>ne</code>, <code>bh</code>, <code>mai</code>, <code>ang</code>, <code>bho</code>, <code>mah</code>, <code>sck</code>, <code>new</code>, <code>gom</code>, <code>sa</code>, <code>bgc</code>, <code>ta</code></td>
@@ -2794,7 +2851,7 @@ pipeline = PaddleOCR(paddlex_config="PaddleOCR.yaml")
- 移动端部署:使用`PP-OCRv5_mobile`系列,模型小速度快
- 实时处理:使用`PP-OCRv5_mobile`系列,推理速度快
- 批量处理:使用`PP-OCRv5_server`系列,精度高
- 多语言识别:使用`PP-OCRv5_multi_languages`,支持37种语言
- 多语言识别:拉丁语系等可使用 `PP-OCRv6`;阿拉伯文、西里尔文、天城文等语系请使用 `PP-OCRv5`
### 5.3 最佳实践
+3 -2
View File
@@ -18,7 +18,7 @@ pip install langchain-paddleocr
The `PaddleOCRVLLoader` enables you to:
- Extract text and layout information from PDF and image files using models from Baidu's PaddleOCR-VL series (e.g., PaddleOCR-VL, PaddleOCR-VL-1.5)
- Extract text and layout information from PDF and image files using models from Baidu's PaddleOCR-VL series (e.g., PaddleOCR-VL, PaddleOCR-VL-1.5, PaddleOCR-VL-1.6)
- Process documents from local files or remote URLs
Basic usage of `PaddleOCRVLLoader` looks as follows:
@@ -29,7 +29,8 @@ from pydantic import SecretStr
loader = PaddleOCRVLLoader(
file_path="path/to/document.pdf",
api_url="your-api-endpoint",
base_url="your-api-endpoint",
model="PaddleOCR-VL-1.5",
access_token=SecretStr("your-access-token") # Optional if using environment variable `PADDLEOCR_ACCESS_TOKEN`
)
+3 -2
View File
@@ -18,7 +18,7 @@ pip install langchain-paddleocr
`PaddleOCRVLLoader` 允许你:
- 使用百度 PaddleOCR-VL 系列模型(例如 PaddleOCR-VL、PaddleOCR-VL-1.5)从 PDF 和图像文件中提取文本和版面布局信息
- 使用百度 PaddleOCR-VL 系列模型(例如 PaddleOCR-VL、PaddleOCR-VL-1.5、PaddleOCR-VL-1.6)从 PDF 和图像文件中提取文本和版面布局信息
- 处理来自本地文件或远程 URL 的文档
`PaddleOCRVLLoader` 的基本用法如下:
@@ -29,7 +29,8 @@ from pydantic import SecretStr
loader = PaddleOCRVLLoader(
file_path="path/to/document.pdf",
api_url="your-api-endpoint",
base_url="your-api-endpoint",
model="PaddleOCR-VL-1.5",
access_token=SecretStr("your-access-token") # 如果使用环境变量 `PADDLEOCR_ACCESS_TOKEN`,则此项为可选
)
@@ -1,3 +1,17 @@
# 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.
from .document_loaders import PaddleOCRVLLoader
__all__ = ["PaddleOCRVLLoader"]
@@ -1,3 +1,17 @@
# 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.
from .paddleocr_vl import PaddleOCRVLLoader
__all__ = ["PaddleOCRVLLoader"]
@@ -1,3 +1,17 @@
# 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.
from __future__ import annotations
import logging
@@ -8,6 +22,7 @@ from typing import Any
from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
from paddleocr import Model, PaddleOCRClient, PaddleOCRVLOptions
from pydantic import SecretStr
logger = logging.getLogger(__name__)
@@ -17,6 +32,19 @@ _DEFAULT_BASE_URL = "https://paddleocr.aistudio-app.com"
_PAGES_DELIMITER = "\n\f"
def _resolve_vl_model(model: str | Model) -> Model:
if isinstance(model, Model):
resolved = model
else:
try:
resolved = Model(model)
except ValueError as exc:
msg = f"Unsupported model: {model!r}"
raise ValueError(msg) from exc
return resolved
class PaddleOCRVLLoader(BaseLoader):
"""Load documents using the PaddleOCR-VL document parsing API via SDK."""
@@ -26,11 +54,13 @@ class PaddleOCRVLLoader(BaseLoader):
*,
access_token: SecretStr | None = None,
base_url: str | None = None,
model: str | Model | None = None,
use_doc_orientation_classify: bool | None = False,
use_doc_unwarping: bool | None = False,
use_layout_detection: bool | None = None,
use_chart_recognition: bool | None = None,
use_seal_recognition: bool | None = None,
use_ocr_for_image_block: bool | None = None,
layout_threshold: float | dict[int, float] | None = None,
layout_nms: bool | None = None,
layout_unclip_ratio: (
@@ -39,19 +69,25 @@ class PaddleOCRVLLoader(BaseLoader):
layout_merge_bboxes_mode: str | dict[str, float] | None = None,
layout_shape_mode: str | None = None,
prompt_label: str | None = None,
format_block_content: bool | None = None,
repetition_penalty: float | None = None,
temperature: float | None = None,
top_p: float | None = None,
min_pixels: int | None = None,
max_pixels: int | None = None,
max_new_tokens: int | None = None,
vlm_extra_args: dict[str, Any] | None = None,
merge_layout_blocks: bool | None = None,
markdown_ignore_labels: list[str] | None = None,
prettify_markdown: bool | None = None,
show_formula_number: bool | None = None,
restructure_pages: bool | None = None,
merge_tables: bool | None = None,
relevel_titles: bool | None = None,
return_markdown_images: bool | None = None,
output_formats: list[str] | None = None,
visualize: bool | None = None,
extra_options: dict[str, Any] | None = None,
timeout: int = 300,
) -> None:
"""Initialize the PaddleOCR-VL loader.
@@ -62,32 +98,40 @@ class PaddleOCRVLLoader(BaseLoader):
access_token: Optional access token as ``SecretStr``. If ``None``, the value
from the ``PADDLEOCR_ACCESS_TOKEN`` environment variable will be used.
base_url: Base URL of the PaddleOCR API service. Defaults to the official
service. Most users do not need to set this.
service.
model: PaddleOCR-VL model name or ``Model`` enum value.
use_doc_orientation_classify: Whether to enable document orientation
classification.
use_doc_unwarping: Whether to enable document unwarping.
use_layout_detection: Whether to enable layout detection.
use_chart_recognition: Whether to enable chart recognition.
use_seal_recognition: Whether to enable seal recognition.
use_ocr_for_image_block: Whether to use OCR for image layout blocks.
layout_threshold: Layout detection threshold.
layout_nms: Whether to apply non-maximum suppression for layout detection.
layout_unclip_ratio: Layout unclip ratio.
layout_merge_bboxes_mode: Mode for merging layout bounding boxes.
layout_shape_mode: Layout shape mode.
prompt_label: Prompt label for the VLM.
format_block_content: Whether to save formatted Markdown in JSON.
repetition_penalty: Repetition penalty for VLM sampling.
temperature: Temperature for VLM sampling.
top_p: Top-p sampling value for VLM.
min_pixels: Minimum number of pixels allowed in preprocessing.
max_pixels: Maximum number of pixels allowed in preprocessing.
max_new_tokens: Maximum number of tokens generated by the VLM.
vlm_extra_args: Additional VLM arguments passed through to the service.
merge_layout_blocks: Whether to merge layout blocks across columns.
markdown_ignore_labels: Layout labels to ignore in Markdown.
prettify_markdown: Whether to prettify the Markdown output.
show_formula_number: Whether to include formula numbers in Markdown.
restructure_pages: Whether to restructure results across pages.
merge_tables: Whether to merge tables across pages.
relevel_titles: Whether to relevel titles.
return_markdown_images: Whether to return images referenced by Markdown.
output_formats: Additional export formats such as ``docx``.
visualize: Whether to include visualization results.
extra_options: Additional service options passed through as-is.
timeout: Poll timeout in seconds.
"""
self._file_paths = (
@@ -105,7 +149,7 @@ class PaddleOCRVLLoader(BaseLoader):
self._base_url = base_url or _DEFAULT_BASE_URL
self._timeout = timeout
from paddleocr import PaddleOCRVLOptions
self._model = _resolve_vl_model(model) if model is not None else None
options_kwargs: dict[str, Any] = {
key: val
@@ -115,25 +159,32 @@ class PaddleOCRVLLoader(BaseLoader):
"use_layout_detection": use_layout_detection,
"use_chart_recognition": use_chart_recognition,
"use_seal_recognition": use_seal_recognition,
"use_ocr_for_image_block": use_ocr_for_image_block,
"layout_threshold": layout_threshold,
"layout_nms": layout_nms,
"layout_unclip_ratio": layout_unclip_ratio,
"layout_merge_bboxes_mode": layout_merge_bboxes_mode,
"layout_shape_mode": layout_shape_mode,
"prompt_label": prompt_label,
"format_block_content": format_block_content,
"repetition_penalty": repetition_penalty,
"temperature": temperature,
"top_p": top_p,
"min_pixels": min_pixels,
"max_pixels": max_pixels,
"max_new_tokens": max_new_tokens,
"vlm_extra_args": vlm_extra_args,
"merge_layout_blocks": merge_layout_blocks,
"markdown_ignore_labels": markdown_ignore_labels,
"prettify_markdown": prettify_markdown,
"show_formula_number": show_formula_number,
"restructure_pages": restructure_pages,
"merge_tables": merge_tables,
"relevel_titles": relevel_titles,
"return_markdown_images": return_markdown_images,
"output_formats": output_formats,
"visualize": visualize,
"extra_options": extra_options,
}.items()
if val is not None
}
@@ -146,19 +197,17 @@ class PaddleOCRVLLoader(BaseLoader):
def _process_file(self, file_path: str) -> tuple[str, dict[str, Any]]:
"""Process a single file through the SDK and return text + raw result."""
from paddleocr import PaddleOCRClient
with PaddleOCRClient(
token=self._token,
base_url=self._base_url,
client_platform="langchain",
poll_timeout=self._timeout,
) as client:
parse_kwargs: dict[str, Any] = {"options": self._options}
if self._model is not None:
parse_kwargs["model"] = self._model
if self._is_url(file_path):
result = client.parse_document(
file_url=file_path,
options=self._options,
)
result = client.parse_document(file_url=file_path, **parse_kwargs)
else:
local_path = Path(file_path)
if not local_path.exists():
@@ -166,7 +215,7 @@ class PaddleOCRVLLoader(BaseLoader):
raise ValueError(msg)
result = client.parse_document(
file_path=str(local_path),
options=self._options,
**parse_kwargs,
)
text_parts = [page.markdown_text for page in result.pages if page.markdown_text]
@@ -174,11 +223,17 @@ class PaddleOCRVLLoader(BaseLoader):
raw_response = {
"job_id": result.job_id,
"data_info": result.data_info,
"pages": [
{
"markdown_text": page.markdown_text,
"markdown_images": page.markdown_images,
"output_images": page.output_images,
"pruned_result": page.pruned_result,
"input_image_url": page.input_image_url,
"exports": page.exports,
"markdown": page.markdown,
"raw": page.raw,
}
for page in result.pages
],
@@ -203,5 +258,7 @@ class PaddleOCRVLLoader(BaseLoader):
"source": str(file_path),
"paddleocr_vl_raw_response": raw_response,
}
if self._model is not None:
metadata["model"] = self._model.value
yield Document(page_content=text, metadata=metadata)
+2 -2
View File
@@ -4,14 +4,14 @@ build-backend = "hatchling.build"
[project]
name = "langchain-paddleocr"
version = "0.2.0"
version = "0.2.2"
description = "An integration package connecting PaddleOCR and LangChain"
authors = []
readme = "README.md"
license = { text = "Apache License 2.0" }
requires-python = ">=3.10"
dependencies = [
"paddleocr>=3.6.0",
"paddleocr>=3.7.0",
"langchain-core>=1.2.5,<2.0.0",
"pydantic>=2.0.0,<3.0.0",
]
@@ -1,3 +1,17 @@
# 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 sys
import traceback
from importlib.machinery import SourceFileLoader
+14
View File
@@ -0,0 +1,14 @@
# 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.
@@ -0,0 +1,14 @@
# 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.
@@ -0,0 +1,14 @@
# 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.
@@ -1,3 +1,17 @@
# 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.
from __future__ import annotations
import os
@@ -0,0 +1,14 @@
# 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.
@@ -0,0 +1,14 @@
# 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.
@@ -1,8 +1,23 @@
# 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.
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
import pytest
from paddleocr import Model
from langchain_paddleocr import PaddleOCRVLLoader
@@ -46,17 +61,88 @@ def test_options_are_built_correctly() -> None:
assert loader._options.top_p == 0.9
def test_options_none_when_no_params() -> None:
"""Ensure options is None when no OCR params are provided."""
def test_options_include_default_flags() -> None:
"""Ensure default boolean flags are included in options."""
loader = PaddleOCRVLLoader(file_path="dummy.pdf")
assert loader._options is None
assert loader._options is not None
assert loader._options.use_doc_orientation_classify is False
assert loader._options.use_doc_unwarping is False
def test_lazy_load_raises_for_missing_file() -> None:
def test_lazy_load_raises_for_missing_file(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensure lazy_load raises when a local file does not exist."""
monkeypatch.setenv("PADDLEOCR_ACCESS_TOKEN", "test-token")
loader = PaddleOCRVLLoader(
file_path="nonexistent-file.pdf",
access_token=None,
)
with pytest.raises(ValueError, match="File not found"):
list(loader.lazy_load())
def test_default_model() -> None:
loader = PaddleOCRVLLoader(file_path="dummy.pdf")
assert loader._model is None
def test_parse_document_omits_model_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
mock_result = MagicMock()
mock_result.job_id = "job-1"
mock_result.pages = []
mock_client = MagicMock()
mock_client.parse_document.return_value = mock_result
mock_client.__enter__.return_value = mock_client
mock_client.__exit__.return_value = None
monkeypatch.setattr(
"langchain_paddleocr.document_loaders.paddleocr_vl.PaddleOCRClient",
lambda **kwargs: mock_client,
)
monkeypatch.setenv("PADDLEOCR_ACCESS_TOKEN", "test-token")
loader = PaddleOCRVLLoader(file_path="https://example.com/doc.pdf")
list(loader.lazy_load())
mock_client.parse_document.assert_called_once_with(
file_url="https://example.com/doc.pdf",
options=loader._options,
)
def test_custom_model_string() -> None:
loader = PaddleOCRVLLoader(
file_path="dummy.pdf",
model="PaddleOCR-VL-1.5",
)
assert loader._model == Model.PADDLE_OCR_VL_15
def test_parse_document_receives_model(monkeypatch: pytest.MonkeyPatch) -> None:
mock_result = MagicMock()
mock_result.job_id = "job-1"
mock_result.pages = []
mock_client = MagicMock()
mock_client.parse_document.return_value = mock_result
mock_client.__enter__.return_value = mock_client
mock_client.__exit__.return_value = None
monkeypatch.setattr(
"langchain_paddleocr.document_loaders.paddleocr_vl.PaddleOCRClient",
lambda **kwargs: mock_client,
)
loader = PaddleOCRVLLoader(
file_path="https://example.com/doc.pdf",
access_token=None,
model=Model.PADDLE_OCR_VL_15,
)
monkeypatch.setenv("PADDLEOCR_ACCESS_TOKEN", "test-token")
list(loader.lazy_load())
mock_client.parse_document.assert_called_once_with(
file_url="https://example.com/doc.pdf",
model=Model.PADDLE_OCR_VL_15,
options=loader._options,
)
@@ -0,0 +1,48 @@
# 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.
from __future__ import annotations
from paddleocr import PaddleOCRVLOptions
from langchain_paddleocr import PaddleOCRVLLoader
def test_vl_options_are_mapped_to_paddleocr_vl_options() -> None:
loader = PaddleOCRVLLoader(
file_path="dummy.pdf",
use_doc_orientation_classify=True,
layout_unclip_ratio=(0.1, 0.9),
prompt_label="ocr",
use_ocr_for_image_block=True,
format_block_content=True,
markdown_ignore_labels=["image"],
vlm_extra_args={"temperature": 0.1},
return_markdown_images=False,
output_formats=["docx"],
extra_options={"futureOption": "enabled"},
)
assert isinstance(loader._options, PaddleOCRVLOptions)
assert loader._options.use_doc_orientation_classify is True
assert loader._options.layout_unclip_ratio == (0.1, 0.9)
assert loader._options.prompt_label == "ocr"
assert loader._options.use_ocr_for_image_block is True
assert loader._options.format_block_content is True
assert loader._options.markdown_ignore_labels == ["image"]
assert loader._options.vlm_extra_args == {"temperature": 0.1}
assert loader._options.return_markdown_images is False
assert loader._options.output_formats == ["docx"]
assert loader._options.extra_options == {"futureOption": "enabled"}
assert loader._options.to_payload()["futureOption"] == "enabled"
+1 -1
View File
@@ -823,7 +823,7 @@ wheels = [
[[package]]
name = "langchain-paddleocr"
version = "0.1.0"
version = "0.2.1"
source = { editable = "." }
dependencies = [
{ name = "langchain-core" },
+67 -51
View File
@@ -3,7 +3,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -23,32 +24,25 @@ import sys
from fastmcp import FastMCP
from .inference import create_inference
from .selection import DEFAULT_MODEL, resolve_model
from .providers import InferenceProvider, provider_choices
from .tasks import create_task
_QIANFAN_SUPPORTED_PIPELINES = frozenset({"PP-StructureV3", "PaddleOCR-VL"})
def _parse_args() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="PaddleOCR MCP server.")
parser.add_argument(
"--pipeline",
choices=[
"OCR",
"PP-StructureV3",
"PaddleOCR-VL",
"PaddleOCR-VL-1.5",
"PaddleOCR-VL-1.6",
],
default=os.getenv("PADDLEOCR_MCP_PIPELINE", "OCR"),
help="Pipeline to run. Env: PADDLEOCR_MCP_PIPELINE.",
"--model",
default=os.getenv("PADDLEOCR_MCP_MODEL", DEFAULT_MODEL),
help="Model to run. Env: PADDLEOCR_MCP_MODEL.",
)
parser.add_argument(
"--ppocr_source",
choices=["local", "aistudio", "qianfan", "self_hosted"],
choices=provider_choices(),
default=os.getenv("PADDLEOCR_MCP_PPOCR_SOURCE", "local"),
help="Inference backend. Env: PADDLEOCR_MCP_PPOCR_SOURCE.",
help="Inference provider. Env: PADDLEOCR_MCP_PPOCR_SOURCE.",
)
parser.add_argument(
@@ -114,10 +108,34 @@ def _parse_args() -> argparse.Namespace:
help="Qianfan API key (qianfan). Env: PADDLEOCR_MCP_QIANFAN_API_KEY.",
)
parser.add_argument(
"--timeout",
"--http-timeout",
dest="http_timeout",
type=int,
default=int(os.getenv("PADDLEOCR_MCP_TIMEOUT", "60")),
help="Request timeout in seconds. Env: PADDLEOCR_MCP_TIMEOUT.",
default=int(os.getenv("PADDLEOCR_MCP_HTTP_TIMEOUT", "600")),
help=(
"HTTP read timeout in seconds for synchronous APIs. "
"Env: PADDLEOCR_MCP_HTTP_TIMEOUT."
),
)
parser.add_argument(
"--aistudio-request-timeout",
dest="aistudio_request_timeout",
type=int,
default=int(os.getenv("PADDLEOCR_MCP_AISTUDIO_REQUEST_TIMEOUT", "120")),
help=(
"Per-request HTTP timeout in seconds for AI Studio API calls. "
"Env: PADDLEOCR_MCP_AISTUDIO_REQUEST_TIMEOUT."
),
)
parser.add_argument(
"--aistudio-poll-timeout",
dest="aistudio_poll_timeout",
type=int,
default=int(os.getenv("PADDLEOCR_MCP_AISTUDIO_POLL_TIMEOUT", "600")),
help=(
"Total job polling timeout in seconds for AI Studio. "
"Env: PADDLEOCR_MCP_AISTUDIO_POLL_TIMEOUT."
),
)
return parser.parse_args()
@@ -132,7 +150,7 @@ def _validate_args(args: argparse.Namespace) -> None:
)
sys.exit(2)
if args.ppocr_source == "aistudio":
if args.ppocr_source == InferenceProvider.AISTUDIO.value:
if not args.aistudio_access_token:
print("Error: The AI Studio access token is required.", file=sys.stderr)
print(
@@ -141,15 +159,7 @@ def _validate_args(args: argparse.Namespace) -> None:
file=sys.stderr,
)
sys.exit(2)
elif args.ppocr_source == "qianfan":
if args.pipeline not in _QIANFAN_SUPPORTED_PIPELINES:
supported = ", ".join(sorted(_QIANFAN_SUPPORTED_PIPELINES))
print(
f"Error: Pipeline {args.pipeline!r} is not supported with qianfan source. "
f"Supported pipelines: {supported}. ",
file=sys.stderr,
)
sys.exit(2)
elif args.ppocr_source == InferenceProvider.QIANFAN.value:
if not args.qianfan_api_key:
print("Error: The Qianfan API key is required.", file=sys.stderr)
print(
@@ -158,7 +168,7 @@ def _validate_args(args: argparse.Namespace) -> None:
file=sys.stderr,
)
sys.exit(2)
elif args.ppocr_source == "self_hosted":
elif args.ppocr_source == InferenceProvider.SELF_HOSTED.value:
if not args.self_hosted_base_url:
print(
"Error: The self-hosted service base URL is required.", file=sys.stderr
@@ -171,42 +181,42 @@ def _validate_args(args: argparse.Namespace) -> None:
sys.exit(2)
def _create_inference_from_args(args: argparse.Namespace):
source = args.ppocr_source
def _create_inference_from_args(args: argparse.Namespace, model: str):
provider = args.ppocr_source
if source == "local":
if provider == InferenceProvider.LOCAL.value:
return create_inference(
pipeline=args.pipeline,
source=source,
model=model,
provider=provider,
config=args.pipeline_config,
device=args.device,
)
elif source == "aistudio":
elif provider == InferenceProvider.AISTUDIO.value:
return create_inference(
pipeline=args.pipeline,
source=source,
model=model,
provider=provider,
token=args.aistudio_access_token,
base_url=args.aistudio_base_url,
request_timeout=float(args.timeout),
poll_timeout=float(args.timeout * 10),
request_timeout=float(args.aistudio_request_timeout),
poll_timeout=float(args.aistudio_poll_timeout),
)
elif source == "qianfan":
elif provider == InferenceProvider.QIANFAN.value:
return create_inference(
pipeline=args.pipeline,
source=source,
model=model,
provider=provider,
base_url=args.qianfan_base_url,
api_key=args.qianfan_api_key,
timeout=args.timeout,
http_timeout=args.http_timeout,
)
elif source == "self_hosted":
elif provider == InferenceProvider.SELF_HOSTED.value:
return create_inference(
pipeline=args.pipeline,
source=source,
model=model,
provider=provider,
base_url=args.self_hosted_base_url,
timeout=args.timeout,
http_timeout=args.http_timeout,
)
else:
raise ValueError(f"Unknown source: {source}")
raise ValueError(f"Unknown provider: {provider}")
async def async_main() -> None:
@@ -214,14 +224,20 @@ async def async_main() -> None:
args = _parse_args()
_validate_args(args)
inference = _create_inference_from_args(args)
try:
model = resolve_model(args.model, args.ppocr_source)
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(2)
inference = _create_inference_from_args(args, model)
try:
await inference.start()
task = create_task(args.pipeline, inference)
task = create_task(model, inference)
server_name = f"PaddleOCR {args.pipeline} MCP server"
server_name = f"PaddleOCR {model} MCP server"
mcp = FastMCP(
name=server_name,
mask_error_details=True,
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
+10 -2
View File
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -14,10 +15,17 @@
import abc
from typing import Any, Dict
from .shared.input_adapters import InputAdapter
from .types import InferenceRequest, InferenceResult
class Inference(abc.ABC):
@property
@abc.abstractmethod
def input_adapter(self) -> InputAdapter:
"""Input adapter that validates and prepares user input for this source."""
pass
@abc.abstractmethod
async def start(self) -> None:
"""Initialize inference resources."""
@@ -68,7 +76,7 @@ class Inference(abc.ABC):
if invalid_params:
raise ValueError(
f"Invalid runtime parameters: {invalid_params}. "
f"Valid parameters are: {sorted(valid_params)}"
f"Valid parameters are: {sorted(valid_params)}."
)
def get_final_params(self, runtime_params: Dict[str, Any]) -> Dict[str, Any]:
+2 -1
View File
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
+142 -50
View File
@@ -1,7 +1,7 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# you may not use this file except in compliance with the License.
#
# http://www.apache.org/licenses/LICENSE-2.0
#
@@ -25,84 +25,176 @@ from .pp_structurev3.aistudio import PPStructureV3AIStudioInference
from .pp_structurev3.local import PPStructureV3LocalInference
from .pp_structurev3.qianfan import PPStructureV3QianfanInference
from .pp_structurev3.self_hosted import PPStructureV3SelfHostedInference
from ..selection import tool_for_model
from ..providers import InferenceProvider, normalize_provider
class InferenceFactory:
_registry: dict[tuple[str, str], Callable[..., Inference]] = {}
_registry: dict[tuple[str, InferenceProvider], Callable[..., Inference]] = {}
@classmethod
def register(
cls,
pipeline: str,
source: str,
tool: str,
provider: InferenceProvider | str,
factory_fn: Callable[..., Inference],
) -> None:
cls._registry[(pipeline, source)] = factory_fn
cls._registry[(tool, normalize_provider(provider))] = factory_fn
@classmethod
def create(
cls,
pipeline: str,
source: str,
model: str,
provider: InferenceProvider | str,
**kwargs,
) -> Inference:
key = (pipeline, source)
tool = tool_for_model(model)
normalized_provider = normalize_provider(provider)
key = (tool, normalized_provider)
if key not in cls._registry:
supported = [
(tool, provider.value)
for tool, provider in sorted(
cls._registry.keys(), key=lambda item: (item[0], item[1].value)
)
]
raise ValueError(
f"Unsupported inference combination: {pipeline} + {source}. "
f"Supported combinations: {sorted(cls._registry.keys())}"
f"Unsupported inference combination: model={model!r}, "
f"provider={normalized_provider.value!r}. Supported combinations: "
f"{supported}"
)
factory_fn = cls._registry[key]
return factory_fn(**kwargs)
return factory_fn(model=model, **kwargs)
@classmethod
def list_supported(cls) -> set[tuple[str, str]]:
def list_supported(cls) -> set[tuple[str, InferenceProvider]]:
return set(cls._registry.keys())
InferenceFactory.register("OCR", "local", OCRLocalInference)
InferenceFactory.register("OCR", "aistudio", OCRAIStudioInference)
InferenceFactory.register("OCR", "self_hosted", OCRSelfHostedInference)
def _create_ocr_local(model: str, **kwargs: Any) -> Inference:
return OCRLocalInference(
config=kwargs.get("config"),
device=kwargs.get("device"),
model=model,
)
def _create_ocr_aistudio(model: str, **kwargs: Any) -> Inference:
return OCRAIStudioInference(
token=kwargs["token"],
base_url=kwargs.get("base_url"),
request_timeout=kwargs.get("request_timeout", 120.0),
poll_timeout=kwargs.get("poll_timeout", 600.0),
model=model,
)
def _create_ocr_self_hosted(model: str, **kwargs: Any) -> Inference:
return OCRSelfHostedInference(
base_url=kwargs["base_url"],
http_timeout=kwargs.get("http_timeout", 600),
)
def _create_pp_structurev3_local(model: str, **kwargs: Any) -> Inference:
return PPStructureV3LocalInference(
config=kwargs.get("config"),
device=kwargs.get("device"),
)
def _create_pp_structurev3_aistudio(model: str, **kwargs: Any) -> Inference:
return PPStructureV3AIStudioInference(
token=kwargs["token"],
base_url=kwargs.get("base_url"),
request_timeout=kwargs.get("request_timeout", 120.0),
poll_timeout=kwargs.get("poll_timeout", 600.0),
model=model,
)
def _create_pp_structurev3_self_hosted(model: str, **kwargs: Any) -> Inference:
return PPStructureV3SelfHostedInference(
base_url=kwargs["base_url"],
http_timeout=kwargs.get("http_timeout", 600),
)
def _create_paddleocr_vl_local(model: str, **kwargs: Any) -> Inference:
return PaddleOCRVLLocalInference(
config=kwargs.get("config"),
device=kwargs.get("device"),
model=model,
)
def _create_paddleocr_vl_aistudio(model: str, **kwargs: Any) -> Inference:
return PaddleOCRVLAIStudioInference(
token=kwargs["token"],
base_url=kwargs.get("base_url"),
request_timeout=kwargs.get("request_timeout", 120.0),
poll_timeout=kwargs.get("poll_timeout", 600.0),
model=model,
)
def _create_paddleocr_vl_self_hosted(model: str, **kwargs: Any) -> Inference:
return PaddleOCRVLSelfHostedInference(
base_url=kwargs["base_url"],
http_timeout=kwargs.get("http_timeout", 600),
)
def _create_pp_structurev3_qianfan(model: str, **kwargs: Any) -> Inference:
return PPStructureV3QianfanInference(
base_url=kwargs["base_url"],
api_key=kwargs["api_key"],
http_timeout=kwargs.get("http_timeout", 600),
)
def _create_paddleocr_vl_qianfan(model: str, **kwargs: Any) -> Inference:
return PaddleOCRVLQianfanInference(
base_url=kwargs["base_url"],
api_key=kwargs["api_key"],
http_timeout=kwargs.get("http_timeout", 600),
)
InferenceFactory.register("ocr", InferenceProvider.LOCAL, _create_ocr_local)
InferenceFactory.register("ocr", InferenceProvider.AISTUDIO, _create_ocr_aistudio)
InferenceFactory.register("ocr", InferenceProvider.SELF_HOSTED, _create_ocr_self_hosted)
InferenceFactory.register("PP-StructureV3", "local", PPStructureV3LocalInference)
InferenceFactory.register("PP-StructureV3", "aistudio", PPStructureV3AIStudioInference)
InferenceFactory.register("PP-StructureV3", "qianfan", PPStructureV3QianfanInference)
InferenceFactory.register(
"PP-StructureV3", "self_hosted", PPStructureV3SelfHostedInference
"pp_structurev3", InferenceProvider.LOCAL, _create_pp_structurev3_local
)
InferenceFactory.register(
"pp_structurev3", InferenceProvider.AISTUDIO, _create_pp_structurev3_aistudio
)
InferenceFactory.register(
"pp_structurev3", InferenceProvider.QIANFAN, _create_pp_structurev3_qianfan
)
InferenceFactory.register(
"pp_structurev3", InferenceProvider.SELF_HOSTED, _create_pp_structurev3_self_hosted
)
InferenceFactory.register(
"paddleocr_vl", InferenceProvider.LOCAL, _create_paddleocr_vl_local
)
InferenceFactory.register(
"paddleocr_vl", InferenceProvider.AISTUDIO, _create_paddleocr_vl_aistudio
)
InferenceFactory.register(
"paddleocr_vl", InferenceProvider.QIANFAN, _create_paddleocr_vl_qianfan
)
InferenceFactory.register(
"paddleocr_vl", InferenceProvider.SELF_HOSTED, _create_paddleocr_vl_self_hosted
)
def _create_paddleocr_vl_local(version: str) -> Callable[..., Inference]:
def _factory(**kwargs: Any) -> Inference:
return PaddleOCRVLLocalInference(**kwargs, version=version)
return _factory
def _create_paddleocr_vl_aistudio(version: str) -> Callable[..., Inference]:
def _factory(**kwargs: Any) -> Inference:
return PaddleOCRVLAIStudioInference(**kwargs, version=version)
return _factory
for _pipeline, _version in {
"PaddleOCR-VL": "v1",
"PaddleOCR-VL-1.5": "v1.5",
"PaddleOCR-VL-1.6": "v1.6",
}.items():
InferenceFactory.register(_pipeline, "local", _create_paddleocr_vl_local(_version))
InferenceFactory.register(
_pipeline, "aistudio", _create_paddleocr_vl_aistudio(_version)
)
InferenceFactory.register(_pipeline, "self_hosted", PaddleOCRVLSelfHostedInference)
InferenceFactory.register("PaddleOCR-VL", "qianfan", PaddleOCRVLQianfanInference)
def create_inference(
pipeline: str,
source: str,
model: str,
provider: InferenceProvider | str,
**kwargs,
) -> Inference:
return InferenceFactory.create(pipeline, source, **kwargs)
return InferenceFactory.create(model, provider, **kwargs)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -24,6 +25,7 @@ from ..shared.paddleocr_api_sdk import (
ServiceUnavailableError,
Model,
OCROptions,
resolve_ocr_model,
)
from ..base import Inference
@@ -33,6 +35,7 @@ from ..errors import (
InferenceError,
ResourceUnavailableError,
)
from ..shared.input_adapters import AISTUDIO_INPUT_ADAPTER, InputAdapter
from ..types import InferenceRequest, OCRResult, TextLine
from .params import OCR_DEFAULT_PARAMS, OCR_RUNTIME_PARAMS
@@ -42,15 +45,21 @@ class OCRAIStudioInference(Inference):
self,
token: str,
base_url: Optional[str] = None,
request_timeout: float = 300.0,
request_timeout: float = 120.0,
poll_timeout: float = 600.0,
model: str = Model.PP_OCRV5.value,
):
self._token = token
self._base_url = base_url
self._request_timeout = request_timeout
self._poll_timeout = poll_timeout
self._model = resolve_ocr_model(model)
self._client = None
@property
def input_adapter(self) -> InputAdapter:
return AISTUDIO_INPUT_ADAPTER
async def start(self) -> None:
try:
self._client = AsyncPaddleOCRClient(
@@ -72,12 +81,12 @@ class OCRAIStudioInference(Inference):
raise RuntimeError("Inference not started")
try:
input_source = self._resolve_input_source(request.input_data)
options = OCROptions(**request.runtime_params, visualize=False)
with self.input_adapter.prepare(request.input_data) as input_payload:
options = OCROptions(**request.runtime_params, visualize=False)
result = await self._client.ocr(
model=Model.PP_OCRV5, **input_source, options=options
)
result = await self._client.ocr(
model=self._model, **input_payload, options=options
)
return self._parse_result(result)
@@ -96,11 +105,6 @@ class OCRAIStudioInference(Inference):
def get_default_params(self) -> dict[str, object]:
return OCR_DEFAULT_PARAMS.copy()
def _resolve_input_source(self, input_data: str) -> dict[str, str]:
if input_data.startswith("http://") or input_data.startswith("https://"):
return {"file_url": input_data}
return {"file_path": input_data}
def _parse_result(self, result) -> OCRResult:
clean_texts, confidences, text_lines = [], [], []
+52 -12
View File
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -11,31 +12,69 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import io
from typing import Any, Optional
from paddleocr import PaddleOCR
from ..base import Inference
from ..shared.input_adapters import LOCAL_INPUT_ADAPTER, InputAdapter
from ..shared.local_sync_runner import LocalSyncRunner
from ..shared.local_input import LocalInputProcessor
from ..types import InferenceRequest, OCRResult, TextLine
from .params import OCR_DEFAULT_PARAMS, OCR_RUNTIME_PARAMS
_LOCAL_OCR_INIT_BY_MODEL: dict[str, dict[str, str]] = {
"PP-OCRv5": {"ocr_version": "PP-OCRv5"},
"PP-OCRv6": {"ocr_version": "PP-OCRv6"},
"PP-OCRv5-latin": {
"text_detection_model_name": "PP-OCRv5_server_det",
"text_recognition_model_name": "latin_PP-OCRv5_mobile_rec",
},
}
def _build_local_ocr_init_kwargs(
*,
config: Optional[str],
device: Optional[str],
model: Optional[str],
) -> dict[str, Any]:
init_kwargs: dict[str, Any] = {
"paddlex_config": config,
"device": device,
}
if config is None and model is not None:
model_kwargs = _LOCAL_OCR_INIT_BY_MODEL.get(model)
if model_kwargs is None:
raise ValueError(f"Unsupported local OCR model: {model!r}")
init_kwargs.update(model_kwargs)
return init_kwargs
class OCRLocalInference(Inference):
def __init__(self, config: Optional[str] = None, device: Optional[str] = None):
def __init__(
self,
config: Optional[str] = None,
device: Optional[str] = None,
model: Optional[str] = None,
):
self._config = config
self._device = device
self._model = model
self._inference: Optional[Any] = None
self._wrapper: Optional[LocalSyncRunner] = None
@property
def input_adapter(self) -> InputAdapter:
return LOCAL_INPUT_ADAPTER
async def start(self) -> None:
try:
self._inference = PaddleOCR(
paddlex_config=self._config, device=self._device
init_kwargs = _build_local_ocr_init_kwargs(
config=self._config,
device=self._device,
model=self._model,
)
self._inference = PaddleOCR(**init_kwargs)
self._wrapper = LocalSyncRunner(self._inference)
except Exception as e:
raise RuntimeError(f"Failed to create PaddleOCR inference: {str(e)}") from e
@@ -49,11 +88,12 @@ class OCRLocalInference(Inference):
if not self._wrapper:
raise RuntimeError("Inference not started")
processed_input = LocalInputProcessor.process_for_local(request.input_data)
result = await self._wrapper.call(
self._wrapper.inference.predict, processed_input, **request.runtime_params
)
with self.input_adapter.prepare(request.input_data) as processed_input:
result = await self._wrapper.call(
self._wrapper.inference.predict,
processed_input,
**request.runtime_params,
)
return self._parse_result(result)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -14,6 +15,7 @@
from typing import Any
from typing_extensions import override
from ...providers import InferenceProvider
from ..shared.http_base import HTTPInferenceBase
from ..types import InferenceResult
from ..shared.http_result_parsers import parse_ocr_result
@@ -21,8 +23,13 @@ from .params import OCR_DEFAULT_PARAMS, OCR_RUNTIME_PARAMS
class OCRSelfHostedInference(HTTPInferenceBase):
def __init__(self, base_url: str, timeout: int = 60):
super().__init__(base_url, timeout, api_key=None)
def __init__(self, base_url: str, http_timeout: int = 600):
super().__init__(
base_url,
http_timeout,
api_key=None,
provider=InferenceProvider.SELF_HOSTED,
)
@override
def _get_endpoint(self) -> str:
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -24,6 +25,7 @@ from ..shared.paddleocr_api_sdk import (
ServiceUnavailableError,
Model,
PaddleOCRVLOptions,
resolve_document_model,
)
from ..base import Inference
@@ -34,32 +36,31 @@ from ..errors import (
ResourceUnavailableError,
)
from ..shared.doc_parsing_result_adapters import parse_aistudio_doc_parsing_result
from ..shared.input_adapters import AISTUDIO_INPUT_ADAPTER, InputAdapter
from ..types import DocParsingResult, InferenceRequest
from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
class PaddleOCRVLAIStudioInference(Inference):
_MODEL_MAP = {
"v1": Model.PADDLE_OCR_VL,
"v1.5": Model.PADDLE_OCR_VL_15,
"v1.6": Model.PADDLE_OCR_VL_16,
}
def __init__(
self,
token: str,
base_url: Optional[str] = None,
request_timeout: float = 300.0,
request_timeout: float = 120.0,
poll_timeout: float = 600.0,
version: str = "v1",
model: str = Model.PADDLE_OCR_VL.value,
):
self._token = token
self._base_url = base_url
self._request_timeout = request_timeout
self._poll_timeout = poll_timeout
self._version = version
self._model = resolve_document_model(model)
self._client = None
@property
def input_adapter(self) -> InputAdapter:
return AISTUDIO_INPUT_ADAPTER
async def start(self) -> None:
try:
self._client = AsyncPaddleOCRClient(
@@ -81,13 +82,13 @@ class PaddleOCRVLAIStudioInference(Inference):
raise RuntimeError("Inference not started")
try:
input_source = self._resolve_input_source(request.input_data)
options = PaddleOCRVLOptions(**request.runtime_params)
with self.input_adapter.prepare(request.input_data) as input_payload:
options = PaddleOCRVLOptions(**request.runtime_params)
model = self._MODEL_MAP[self._version]
result = await self._client.parse_document(
model=model, **input_source, options=options
)
model = self._model
result = await self._client.parse_document(
model=model, **input_payload, options=options
)
return self._parse_result(result)
@@ -106,10 +107,5 @@ class PaddleOCRVLAIStudioInference(Inference):
def get_default_params(self) -> dict[str, object]:
return PADDLEOCR_VL_DEFAULT_PARAMS.copy()
def _resolve_input_source(self, input_data: str) -> dict[str, str]:
if input_data.startswith("http://") or input_data.startswith("https://"):
return {"file_url": input_data}
return {"file_path": input_data}
def _parse_result(self, result) -> DocParsingResult:
return parse_aistudio_doc_parsing_result(result)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -15,8 +16,8 @@ from typing import Any, Optional
from ..base import Inference
from ..shared.doc_parsing_result_adapters import parse_local_doc_parsing_result
from ..shared.input_adapters import LOCAL_INPUT_ADAPTER, InputAdapter
from ..shared.local_sync_runner import LocalSyncRunner
from ..shared.local_input import LocalInputProcessor
from ..types import DocParsingResult, InferenceRequest
from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
@@ -27,26 +28,37 @@ try:
except ImportError:
LOCAL_VL_AVAILABLE = False
_PIPELINE_VERSION_BY_MODEL = {
"PaddleOCR-VL": "v1",
"PaddleOCR-VL-1.5": "v1.5",
"PaddleOCR-VL-1.6": "v1.6",
}
class PaddleOCRVLLocalInference(Inference):
def __init__(
self,
config: Optional[str] = None,
device: Optional[str] = None,
version: str = "v1",
model: str = "PaddleOCR-VL",
):
self._config = config
self._device = device
self._version = version
self._model = model
self._inference: Optional[Any] = None
self._wrapper: Optional[LocalSyncRunner] = None
@property
def input_adapter(self) -> InputAdapter:
return LOCAL_INPUT_ADAPTER
async def start(self) -> None:
if not LOCAL_VL_AVAILABLE:
raise RuntimeError("PaddleOCRVL is not locally available")
try:
pipeline_version = _PIPELINE_VERSION_BY_MODEL[self._model]
self._inference = PaddleOCRVL(
pipeline_version=self._version,
pipeline_version=pipeline_version,
paddlex_config=self._config,
device=self._device,
)
@@ -65,11 +77,12 @@ class PaddleOCRVLLocalInference(Inference):
if not self._wrapper:
raise RuntimeError("Inference not started")
processed_input = LocalInputProcessor.process_for_local(request.input_data)
result = await self._wrapper.call(
self._wrapper.inference.predict, processed_input, **request.runtime_params
)
with self.input_adapter.prepare(request.input_data) as processed_input:
result = await self._wrapper.call(
self._wrapper.inference.predict,
processed_input,
**request.runtime_params,
)
return self._parse_result(result)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -20,18 +21,23 @@ PADDLEOCR_VL_RUNTIME_PARAMS: dict[str, type] = {
"use_layout_detection": bool,
"use_chart_recognition": bool,
"use_seal_recognition": bool,
"use_ocr_for_image_block": bool,
"layout_threshold": float,
"layout_nms": bool,
"layout_unclip_ratio": float,
"layout_merge_bboxes_mode": int,
"layout_shape_mode": str,
"prompt_label": str,
"format_block_content": bool,
"repetition_penalty": float,
"temperature": float,
"top_p": float,
"min_pixels": int,
"max_pixels": int,
"max_new_tokens": int,
"vlm_extra_args": dict,
"merge_layout_blocks": bool,
"markdown_ignore_labels": list,
}
PADDLEOCR_VL_DEFAULT_PARAMS: dict[str, Any] = {
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -14,6 +15,7 @@
from typing import Any
from typing_extensions import override
from ...providers import InferenceProvider
from ..shared.http_base import HTTPInferenceBase
from ..types import InferenceResult
from ..shared.http_result_parsers import parse_doc_parsing_result
@@ -21,8 +23,10 @@ from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
class PaddleOCRVLQianfanInference(HTTPInferenceBase):
def __init__(self, base_url: str, api_key: str, timeout: int = 60):
super().__init__(base_url, timeout, api_key)
def __init__(self, base_url: str, api_key: str, http_timeout: int = 600):
super().__init__(
base_url, http_timeout, api_key, provider=InferenceProvider.QIANFAN
)
@override
def _get_endpoint(self) -> str:
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -14,6 +15,7 @@
from typing import Any
from typing_extensions import override
from ...providers import InferenceProvider
from ..shared.http_base import HTTPInferenceBase
from ..types import InferenceResult
from ..shared.http_result_parsers import parse_doc_parsing_result
@@ -21,8 +23,13 @@ from .params import PADDLEOCR_VL_DEFAULT_PARAMS, PADDLEOCR_VL_RUNTIME_PARAMS
class PaddleOCRVLSelfHostedInference(HTTPInferenceBase):
def __init__(self, base_url: str, timeout: int = 60):
super().__init__(base_url, timeout, api_key=None)
def __init__(self, base_url: str, http_timeout: int = 600):
super().__init__(
base_url,
http_timeout,
api_key=None,
provider=InferenceProvider.SELF_HOSTED,
)
@override
def _get_endpoint(self) -> str:
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -24,6 +25,7 @@ from ..shared.paddleocr_api_sdk import (
ServiceUnavailableError,
Model,
PPStructureV3Options,
resolve_document_model,
)
from ..base import Inference
@@ -34,6 +36,7 @@ from ..errors import (
ResourceUnavailableError,
)
from ..shared.doc_parsing_result_adapters import parse_aistudio_doc_parsing_result
from ..shared.input_adapters import AISTUDIO_INPUT_ADAPTER, InputAdapter
from ..types import DocParsingResult, InferenceRequest
from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
@@ -43,15 +46,21 @@ class PPStructureV3AIStudioInference(Inference):
self,
token: str,
base_url: Optional[str] = None,
request_timeout: float = 300.0,
request_timeout: float = 120.0,
poll_timeout: float = 600.0,
model: str = Model.PP_STRUCTURE_V3.value,
):
self._token = token
self._base_url = base_url
self._request_timeout = request_timeout
self._poll_timeout = poll_timeout
self._model = resolve_document_model(model)
self._client = None
@property
def input_adapter(self) -> InputAdapter:
return AISTUDIO_INPUT_ADAPTER
async def start(self) -> None:
try:
self._client = AsyncPaddleOCRClient(
@@ -73,12 +82,14 @@ class PPStructureV3AIStudioInference(Inference):
raise RuntimeError("Inference not started")
try:
input_source = self._resolve_input_source(request.input_data)
options = PPStructureV3Options(**request.runtime_params, visualize=False)
with self.input_adapter.prepare(request.input_data) as input_payload:
options = PPStructureV3Options(
**request.runtime_params, visualize=False
)
result = await self._client.parse_document(
model=Model.PP_STRUCTURE_V3, **input_source, options=options
)
result = await self._client.parse_document(
model=self._model, **input_payload, options=options
)
return self._parse_result(result)
@@ -97,10 +108,5 @@ class PPStructureV3AIStudioInference(Inference):
def get_default_params(self) -> dict[str, object]:
return PP_STRUCTUREV3_DEFAULT_PARAMS.copy()
def _resolve_input_source(self, input_data: str) -> dict[str, str]:
if input_data.startswith("http://") or input_data.startswith("https://"):
return {"file_url": input_data}
return {"file_path": input_data}
def _parse_result(self, result) -> DocParsingResult:
return parse_aistudio_doc_parsing_result(result)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -15,8 +16,8 @@ from typing import Any, Optional
from ..base import Inference
from ..shared.doc_parsing_result_adapters import parse_local_doc_parsing_result
from ..shared.input_adapters import LOCAL_INPUT_ADAPTER, InputAdapter
from ..shared.local_sync_runner import LocalSyncRunner
from ..shared.local_input import LocalInputProcessor
from ..types import DocParsingResult, InferenceRequest
from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
@@ -35,6 +36,10 @@ class PPStructureV3LocalInference(Inference):
self._inference: Optional[Any] = None
self._wrapper: Optional[LocalSyncRunner] = None
@property
def input_adapter(self) -> InputAdapter:
return LOCAL_INPUT_ADAPTER
async def start(self) -> None:
if not LOCAL_PPSTRUCTURE_AVAILABLE:
raise RuntimeError("PPStructureV3 is not locally available")
@@ -57,11 +62,12 @@ class PPStructureV3LocalInference(Inference):
if not self._wrapper:
raise RuntimeError("Inference not started")
processed_input = LocalInputProcessor.process_for_local(request.input_data)
result = await self._wrapper.call(
self._wrapper.inference.predict, processed_input, **request.runtime_params
)
with self.input_adapter.prepare(request.input_data) as processed_input:
result = await self._wrapper.call(
self._wrapper.inference.predict,
processed_input,
**request.runtime_params,
)
return self._parse_result(result)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -27,6 +28,7 @@ PP_STRUCTUREV3_RUNTIME_PARAMS: dict[str, type] = {
"layout_nms": bool,
"layout_unclip_ratio": float,
"layout_merge_bboxes_mode": int,
"format_block_content": bool,
"text_det_limit_side_len": int,
"text_det_limit_type": str,
"text_det_thresh": float,
@@ -45,6 +47,7 @@ PP_STRUCTUREV3_RUNTIME_PARAMS: dict[str, type] = {
"use_ocr_results_with_table_cells": bool,
"use_e2e_wired_table_rec_model": bool,
"use_e2e_wireless_table_rec_model": bool,
"markdown_ignore_labels": list,
}
PP_STRUCTUREV3_DEFAULT_PARAMS: dict[str, Any] = {
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -14,6 +15,7 @@
from typing import Any
from typing_extensions import override
from ...providers import InferenceProvider
from ..shared.http_base import HTTPInferenceBase
from ..types import InferenceResult
from ..shared.http_result_parsers import parse_doc_parsing_result
@@ -21,8 +23,10 @@ from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
class PPStructureV3QianfanInference(HTTPInferenceBase):
def __init__(self, base_url: str, api_key: str, timeout: int = 60):
super().__init__(base_url, timeout, api_key)
def __init__(self, base_url: str, api_key: str, http_timeout: int = 600):
super().__init__(
base_url, http_timeout, api_key, provider=InferenceProvider.QIANFAN
)
@override
def _get_endpoint(self) -> str:
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -14,6 +15,7 @@
from typing import Any
from typing_extensions import override
from ...providers import InferenceProvider
from ..shared.http_base import HTTPInferenceBase
from ..types import InferenceResult
from ..shared.http_result_parsers import parse_doc_parsing_result
@@ -21,8 +23,13 @@ from .params import PP_STRUCTUREV3_DEFAULT_PARAMS, PP_STRUCTUREV3_RUNTIME_PARAMS
class PPStructureV3SelfHostedInference(HTTPInferenceBase):
def __init__(self, base_url: str, timeout: int = 60):
super().__init__(base_url, timeout, api_key=None)
def __init__(self, base_url: str, http_timeout: int = 600):
super().__init__(
base_url,
http_timeout,
api_key=None,
provider=InferenceProvider.SELF_HOSTED,
)
@override
def _get_endpoint(self) -> str:
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -20,16 +21,22 @@ class AsyncHTTPClient:
def __init__(
self,
base_url: str,
timeout: int = 60,
http_timeout: int = 600,
headers: Optional[dict[str, str]] = None,
):
self._base_url = base_url
self._timeout = timeout
self._http_timeout = http_timeout
self._headers = headers or {}
self._client: Optional[httpx.AsyncClient] = None
async def start(self) -> None:
timeout = httpx.Timeout(connect=30.0, read=self._timeout, write=30.0, pool=30.0)
write_timeout = min(float(self._http_timeout), 120.0)
timeout = httpx.Timeout(
connect=30.0,
read=float(self._http_timeout),
write=write_timeout,
pool=30.0,
)
self._client = httpx.AsyncClient(timeout=timeout)
async def stop(self) -> None:
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -11,35 +12,43 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
from abc import abstractmethod
from pathlib import Path
from typing import Any, Optional
import httpx
from ..base import Inference
from ..errors import InferenceError
from ..types import InferenceRequest, InferenceResult
from .async_http_client import AsyncHTTPClient
from .input_adapters import HTTPInputAdapter, InputAdapter
from .param_mapping import convert_params_to_camel
from ...providers import InferenceProvider
class HTTPInferenceBase(Inference):
def __init__(
self,
base_url: str,
timeout: int = 60,
http_timeout: int = 600,
api_key: Optional[str] = None,
provider: InferenceProvider | str = InferenceProvider.SELF_HOSTED,
):
self._base_url = base_url
self._timeout = timeout
self._http_timeout = http_timeout
self._api_key = api_key
self._input_adapter = HTTPInputAdapter(provider)
self._client: Optional[AsyncHTTPClient] = None
@property
def input_adapter(self) -> InputAdapter:
return self._input_adapter
async def start(self) -> None:
headers = {}
if self._api_key:
headers["Authorization"] = f"Bearer {self._api_key}"
self._client = AsyncHTTPClient(self._base_url, self._timeout, headers)
self._client = AsyncHTTPClient(self._base_url, self._http_timeout, headers)
await self._client.start()
async def stop(self) -> None:
@@ -57,27 +66,34 @@ class HTTPInferenceBase(Inference):
**request.runtime_params,
)
endpoint = self._get_endpoint()
provider = self._input_adapter.provider.value
try:
response = await self._client.post(self._get_endpoint(), payload)
response = await self._client.post(endpoint, payload)
return self._parse_result(response)
except httpx.ReadTimeout as e:
raise InferenceError(
f"HTTP read timeout after {self._http_timeout}s "
f"({provider}/{endpoint}): {e}"
) from e
except httpx.HTTPStatusError as e:
raise InferenceError(
f"HTTP {e.response.status_code} ({provider}/{endpoint}): {e}"
) from e
except httpx.HTTPError as e:
raise InferenceError(f"HTTP error ({provider}/{endpoint}): {e}") from e
except Exception as e:
raise InferenceError(f"HTTP request failed: {e}") from e
def _encode_file_field(self, input_data: str) -> str:
"""Encode local paths to Base64; pass through URLs and raw payloads."""
if input_data.startswith("http://") or input_data.startswith("https://"):
return input_data
from .local_input import LocalInputProcessor
if LocalInputProcessor.is_file_path(input_data):
path = Path(input_data).expanduser()
return base64.b64encode(path.read_bytes()).decode("ascii")
return input_data
raise InferenceError(
f"HTTP request failed ({provider}/{endpoint}): {e}"
) from e
def _prepare_payload(
self, input_data: str, file_type: Optional[str], **params
) -> dict[str, Any]:
payload: dict[str, Any] = {"file": self._encode_file_field(input_data)}
http_adapter = self._input_adapter
payload: dict[str, Any] = {
"file": http_adapter.prepare_http_file_field(input_data)
}
if file_type == "image":
payload["fileType"] = 1
elif file_type == "pdf":
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -0,0 +1,182 @@
# 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.
"""Provider-specific input adapters for the unified MCP input contract."""
from __future__ import annotations
import abc
import base64
import io
from contextlib import contextmanager
from typing import Any, Generator, Union
from .input_contract import (
COMMON_INPUT_DESCRIPTION,
InputKind,
classify_input,
decode_input_bytes,
extract_base64_payload,
infer_file_type_from_bytes,
materialize_bytes_as_temp_file,
normalize,
resolve_absolute_path,
validate_external_contract,
)
from ...providers import (
InferenceProvider,
get_provider_spec,
is_http_provider,
normalize_provider,
)
class InputAdapter(abc.ABC):
@property
@abc.abstractmethod
def provider(self) -> InferenceProvider:
pass
@property
def description(self) -> str:
spec = get_provider_spec(self.provider)
return (
f"Inference provider: {spec.provider.value} ({spec.display_name}). "
f"{COMMON_INPUT_DESCRIPTION}"
)
def normalize(self, input_data: str) -> str:
return normalize(input_data)
def validate(self, input_data: str) -> None:
validate_external_contract(input_data)
@abc.abstractmethod
@contextmanager
def prepare(self, input_data: str) -> Generator[Any, None, None]:
"""Convert user input into the inference provider's native form."""
raise NotImplementedError
class LocalInputAdapter(InputAdapter):
@property
def provider(self) -> InferenceProvider:
return InferenceProvider.LOCAL
@contextmanager
def prepare(self, input_data: str) -> Generator[Union[str, Any], None, None]:
value = normalize(input_data)
kind = classify_input(value)
if kind is InputKind.URL:
yield value
return
if kind is InputKind.ABSOLUTE_PATH:
yield str(resolve_absolute_path(value))
return
data = decode_input_bytes(value, kind)
file_type = infer_file_type_from_bytes(data)
if file_type == "image":
import numpy as np
from PIL import Image as PILImage
try:
image_pil = PILImage.open(io.BytesIO(data))
image_arr = np.array(image_pil.convert("RGB"))
yield np.ascontiguousarray(image_arr[..., ::-1])
except Exception as e:
raise ValueError(f"Failed to decode Base64 image: {e}") from e
return
if file_type == "pdf":
with materialize_bytes_as_temp_file(data, file_type="pdf") as temp_path:
yield str(temp_path)
return
raise ValueError(
"Unsupported Base64 content type for local inference. "
"Only image and PDF inputs are supported."
)
class AIStudioInputAdapter(InputAdapter):
@property
def provider(self) -> InferenceProvider:
return InferenceProvider.AISTUDIO
@contextmanager
def prepare(self, input_data: str) -> Generator[dict[str, str], None, None]:
value = normalize(input_data)
kind = classify_input(value)
if kind is InputKind.URL:
yield {"file_url": value}
return
if kind is InputKind.ABSOLUTE_PATH:
yield {"file_path": str(resolve_absolute_path(value))}
return
data = decode_input_bytes(value, kind)
file_type = infer_file_type_from_bytes(data)
if file_type not in ("image", "pdf"):
raise ValueError(
"Unsupported Base64 content type for AI Studio. "
"Only image and PDF inputs are supported."
)
with materialize_bytes_as_temp_file(data, file_type=file_type) as temp_path:
yield {"file_path": str(temp_path)}
class HTTPInputAdapter(InputAdapter):
def __init__(self, provider: InferenceProvider | str) -> None:
normalized_provider = normalize_provider(provider)
if not is_http_provider(normalized_provider):
raise ValueError(
f"HTTPInputAdapter requires an HTTP transport provider, "
f"got {normalized_provider.value!r}."
)
self._provider = normalized_provider
@property
def provider(self) -> InferenceProvider:
return self._provider
@contextmanager
def prepare(self, input_data: str) -> Generator[str, None, None]:
yield self.prepare_http_file_field(input_data)
def prepare_http_file_field(self, input_data: str) -> str:
value = normalize(input_data)
kind = classify_input(value)
if kind is InputKind.URL:
return value
if kind is InputKind.ABSOLUTE_PATH:
path = resolve_absolute_path(value)
return base64.b64encode(path.read_bytes()).decode("ascii")
payload = extract_base64_payload(value)
decode_input_bytes(value, kind)
return payload
LOCAL_INPUT_ADAPTER = LocalInputAdapter()
AISTUDIO_INPUT_ADAPTER = AIStudioInputAdapter()
SELF_HOSTED_INPUT_ADAPTER = HTTPInputAdapter(InferenceProvider.SELF_HOSTED)
QIANFAN_INPUT_ADAPTER = HTTPInputAdapter(InferenceProvider.QIANFAN)
@@ -0,0 +1,153 @@
# 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.
"""Shared user-facing input contract for all MCP inference providers."""
from __future__ import annotations
import tempfile
from contextlib import contextmanager
from enum import Enum
from pathlib import Path
from typing import Generator, Optional
from ...utils import (
decode_base64_payload,
extract_base64_payload,
infer_file_type_from_bytes,
is_base64,
is_url,
)
COMMON_INPUT_DESCRIPTION = (
"Supported input_data: absolute file path accessible to the MCP server process "
"(~ is expanded), HTTP(S) URL, raw Base64, or data URL. Relative paths are "
"rejected. Backend-specific conversion is handled by the MCP server."
)
_INPUT_EXTENSIONS = frozenset(
{
".jpg",
".jpeg",
".png",
".pdf",
".bmp",
".webp",
".tiff",
".tif",
".gif",
}
)
_SUFFIX_BY_FILE_TYPE = {
"image": ".png",
"pdf": ".pdf",
}
class InputKind(str, Enum):
URL = "url"
ABSOLUTE_PATH = "absolute_path"
BASE64 = "base64"
DATA_URL = "data_url"
def normalize(input_data: str) -> str:
return input_data.strip()
def looks_like_file_path(value: str) -> bool:
if is_url(value) or value.startswith("data:"):
return False
if value.startswith("~") or "/" in value or "\\" in value:
return True
return Path(value).suffix.lower() in _INPUT_EXTENSIONS
def classify_input(value: str) -> InputKind:
if is_url(value):
return InputKind.URL
if value.startswith("data:"):
payload = extract_base64_payload(value)
if not is_base64(payload):
raise ValueError("Invalid data URL: payload is not valid Base64.")
return InputKind.DATA_URL
if is_base64(value):
return InputKind.BASE64
if looks_like_file_path(value):
return InputKind.ABSOLUTE_PATH
raise ValueError(f"Invalid input_data. {COMMON_INPUT_DESCRIPTION}")
def resolve_absolute_path(value: str) -> Path:
path = Path(value).expanduser()
if not path.is_absolute():
raise ValueError(
f"Relative paths are not supported: {value!r}. "
"Use an absolute path accessible to the MCP server process."
)
if not path.exists():
raise ValueError(
f"File not found: {value!r} (resolved to {path}). "
f"{COMMON_INPUT_DESCRIPTION}"
)
return path.resolve()
def validate_external_contract(input_data: str) -> InputKind:
value = normalize(input_data)
if not value:
raise ValueError("input_data must not be empty.")
kind = classify_input(value)
if kind is InputKind.ABSOLUTE_PATH:
resolve_absolute_path(value)
return kind
if kind in (InputKind.BASE64, InputKind.DATA_URL):
payload = extract_base64_payload(value)
data = decode_base64_payload(payload)
file_type = infer_file_type_from_bytes(data)
if file_type not in ("image", "pdf"):
raise ValueError(
"Unsupported Base64 content type. Only image and PDF inputs are "
"supported."
)
return kind
def decode_input_bytes(value: str, kind: InputKind) -> bytes:
if kind is InputKind.ABSOLUTE_PATH:
return resolve_absolute_path(value).read_bytes()
payload = extract_base64_payload(value)
return decode_base64_payload(payload)
@contextmanager
def materialize_bytes_as_temp_file(
data: bytes,
*,
file_type: str,
) -> Generator[Path, None, None]:
suffix = _SUFFIX_BY_FILE_TYPE.get(file_type, ".bin")
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
temp_path = Path(temp_file.name)
try:
temp_file.write(data)
temp_file.close()
yield temp_path
finally:
temp_path.unlink(missing_ok=True)
@@ -1,84 +0,0 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import io
import re
from pathlib import Path
from typing import Any, Optional, Union
from urllib.parse import urlparse
class LocalInputProcessor:
@staticmethod
def is_file_path(value: str) -> bool:
return Path(value).expanduser().exists()
@staticmethod
def is_url(value: str) -> bool:
if not (value.startswith("http://") or value.startswith("https://")):
return False
result = urlparse(value)
return all([result.scheme, result.netloc]) and result.scheme in (
"http",
"https",
)
@staticmethod
def is_base64(value: str) -> bool:
if value.startswith("data:"):
return "," in value and LocalInputProcessor.is_base64(
value.split(",", 1)[1]
)
pattern = r"^[A-Za-z0-9+/]+={0,2}$"
return bool(re.fullmatch(pattern, value))
@staticmethod
def infer_file_type_from_bytes(data: bytes) -> Optional[str]:
import puremagic
mime = puremagic.from_string(data, mime=True)
if mime.startswith("image/"):
return "image"
if mime == "application/pdf":
return "pdf"
return None
@classmethod
def process_for_local(cls, input_data: str) -> Union[str, Any]:
if cls.is_url(input_data) or cls.is_file_path(input_data):
return input_data
if cls.is_base64(input_data):
import numpy as np
from PIL import Image as PILImage
base64_data = (
input_data.split(",", 1)[1]
if input_data.startswith("data:")
else input_data
)
try:
image_bytes = base64.b64decode(base64_data)
file_type = cls.infer_file_type_from_bytes(image_bytes)
if file_type != "image":
raise ValueError("Currently, only images can be passed via Base64.")
image_pil = PILImage.open(io.BytesIO(image_bytes))
image_arr = np.array(image_pil.convert("RGB"))
return np.ascontiguousarray(image_arr[..., ::-1])
except Exception as e:
raise ValueError(f"Failed to decode Base64 image: {str(e)}") from e
raise ValueError("Invalid input data format")
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -179,3 +180,8 @@ RequestTimeoutError = _SDK.RequestTimeoutError
ResponseFormatError = _SDK.ResponseFormatError
ResultParseError = _SDK.ResultParseError
ServiceUnavailableError = _SDK.ServiceUnavailableError
from paddleocr._api_client._core import ( # noqa: E402
resolve_document_model,
resolve_ocr_model,
)
@@ -1,7 +1,8 @@
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may obtain a copy of the License at
# 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
#
@@ -16,7 +17,9 @@ from typing import Any
def snake_to_camel(name: str) -> str:
components = name.split("_")
return components[0] + "".join(component.title() for component in components[1:])
return components[0] + "".join(
component.capitalize() for component in components[1:]
)
def convert_params_to_camel(params: dict[str, Any]) -> dict[str, Any]:
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more