This commit is contained in:
zimoyin
2026-10-11 02:26:26 +08:00
commit 11883e260f
21 changed files with 4306 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
.venv/
__pycache__/
*.py[cod]
.pytest_cache/
.ruff_cache/
.env
data/
.idea/
http/fixtures/*.jpg
http/fixtures/*.jpeg
http/fixtures/*.png
!http/fixtures/general_ocr_002.png
*.egg-info/
dist/
build/
+1
View File
@@ -0,0 +1 @@
3.12
+359
View File
@@ -0,0 +1,359 @@
# OCR Server
基于 FastAPI 和 PaddleOCR **PP-OCRv5** 的图片文字识别服务,支持 Windows 和 Ubuntu 22.04(CPU;GPU 需要额外安装对应的 PaddlePaddle GPU 版本)。
## 目录结构
```text
ocr-server/
├── config.yaml # 项目配置文件(启动前修改)
├── http/ocr-server.http # IDEA / IntelliJ HTTP Client 测试请求
├── models/ # 可随发布包分发的 PP-OCRv5 模型(约 166 MB)
│ └── official_models/
│ ├── PP-OCRv5_server_det/
│ └── PP-OCRv5_server_rec/
├── data/uploads/ # 上传图片运行时目录
├── src/ocr_server/
├── scripts/download_models.py # 下载或补齐缺少的模型
└── scripts/benchmark_ocr.py # 测量当前配置的 OCR 耗时
```
## 模型位置和下载策略
当前已经预下载并放入项目目录:
```text
models/official_models/PP-OCRv5_server_det
models/official_models/PP-OCRv5_server_rec
```
当前分发包内的模型是 PP-OCRv5 中文服务模型,总大小约 166 MB。模型文件只读使用,服务不会修改模型目录中的权重文件。
服务启动后不会立即加载模型。上传接口会立即把图片放入等待队列;第一次有工作线程开始识别时:
1. 优先检查 `model_dir/official_models/` 下的检测模型和识别模型;
2. 模型文件完整时,直接使用项目内模型,不访问网络;
3. 缺少任意模型时,只下载缺少的模型,并保存到同一个 `model_dir`;
4. 后续请求继续复用同一个进程内的 OCR 实例。
默认模型目录是项目根目录下的 `models`,可以直接修改项目根目录的 `config.yaml`:
```yaml
model_dir: /opt/ocr-server/models
```
配置文件中的路径支持绝对路径,也支持相对于项目根目录的路径。服务启动时读取一次配置,修改后需要重启服务。
也可以手动提前下载或补齐模型:
```powershell
uv run python scripts/download_models.py
```
脚本会读取 `config.yaml`,把模型下载到 `model_dir` 指定的目录。模型下载需要联网;完整分发包可以直接携带整个 `models/` 目录,从而不依赖首次启动联网。下载时不会覆盖已有完整模型目录。
## 不同速度档位和模型选择
当前项目默认使用 PP-OCRv5 中文服务模型:
```yaml
det_model_name: PP-OCRv5_server_det
rec_model_name: PP-OCRv5_server_rec
```
PaddleOCR 还提供更小的移动端模型,但 PP-OCRv5 中文识别模型当前默认映射为 `PP-OCRv5_server_rec`;不要只把检测模型替换成其他版本而保持识别模型不变,模型版本和配套模型应成套切换。
| 档位 | 检测模型 | 识别模型 | 特点 |
| --- | --- | --- | --- |
| 速度优先 | PP-OCRv4_mobile_det | PP-OCRv4_mobile_rec | 体积和 CPU 推理开销更小,但不是 PP-OCRv5,中文准确率可能下降 |
| 当前默认 | PP-OCRv5_server_det | PP-OCRv5_server_rec | 中文准确率优先,模型约 166 MB |
| 新版模型 | PP-OCRv6_medium_det | PP-OCRv6_medium_rec | 需要单独下载并验证,模型版本不是 PP-OCRv5 |
切换前建议:
1. 先把当前 `models/` 完整复制成独立备份,例如 `models.backup-ppocrv5/`;
2. 将新模型下载到另一个目录,例如 `models-ppocrv4-mobile/`;
3. 只修改 `config.yaml` 的 `model_dir` 和两个模型名称;
4. 用 `scripts/benchmark_ocr.py` 和真实业务图片对比耗时、漏检率和准确率;
5. 验证不满意时,把 `model_dir` 改回原目录即可,不改动原模型。
当前没有自动下载或替换任何小模型,也没有修改现有 PP-OCRv5 权重。服务只读加载模型;若要切换模型,必须使用新的模型目录或先制作备份。
### 不换模型的加速方式
先尝试以下配置,不会修改模型文件:
```yaml
text_det_limit_side_len: 640
text_recognition_batch_size: 1
ocr_workers: 1
```
`text_det_limit_side_len` 从 `960` 调到 `640` 通常可以降低检测耗时,但小字可能漏检。`text_recognition_batch_size` 主要影响单张图片包含很多文本框时的吞吐;增大到 `2` 或 `4` 会增加内存,单张简单图片不一定更快。
### 如何测速
```powershell
uv run python scripts/benchmark_ocr.py
```
修改 `config.yaml` 后重新执行,比较输出的 `elapsed_ms`。建议至少使用 10 张代表性图片,不要只根据一张图片决定模型或参数。
## Python 版本说明
本项目的 Python 版本约束是 `>=3.10,<3.14`,当前项目固定为 Python 3.12:
```text
.python-version = 3.12
```
这次切换**没有修改系统全局 Python,也没有卸载 Python 3.15**。`uv python pin 3.12` 只修改了当前项目的 `.python-version` 文件;项目使用的 Python 3.12 是 uv 管理的独立解释器,位置是:
```text
C:\Users\zimoyin\AppData\Roaming\uv\python\cpython-3.12-windows-x86_64-none\python.exe
```
机器上原有的 Python 3.15 仍在:
```text
C:\Users\zimoyin\AppData\Local\Python\pythoncore-3.15-64\python.exe
```
项目虚拟环境位于:
```text
D:\code\work\ocr-server\.venv\Scripts\python.exe
```
在 Ubuntu 上,建议使用系统 Python 3.10–3.12 或 uv 创建项目虚拟环境,不会影响系统其他 Python 项目。
## Windows 安装和启动
```powershell
cd D:\code\work\ocr-server
uv sync
uv run ocr-server
```
启动前修改项目根目录的 `config.yaml`:
```yaml
host: 0.0.0.0
port: 8000
device: cpu
ocr_workers: 1
```
然后启动:
```powershell
uv run ocr-server
```
也可以:
```powershell
uv run python -m uvicorn ocr_server.app:app --host 0.0.0.0 --port 8000
```
## Ubuntu 22.04 安装和启动
适用于 Ubuntu 22.04 x86_64 CPU 环境(PaddlePaddle 官方 wheel 通常不覆盖 ARM 架构):
```bash
sudo apt-get update
sudo apt-get install -y curl libgl1 libglib2.0-0
cd /opt/ocr-server
curl -LsSf https://astral.sh/uv/install.sh | sh
# 重新打开 shell,或按安装提示加载 ~/.local/bin
uv python install 3.12
uv sync --python 3.12
# 按需修改项目根目录 config.yaml,然后启动
uv run ocr-server
```
如果服务器不能访问模型下载源,请在联网机器上执行 `scripts/download_models.py`,将完整项目的 `models/` 目录复制到 Ubuntu 服务器,再启动服务。依赖安装仍需要提前完成;完全离线安装还需要准备本地 Python wheel 缓存。
如果 Ubuntu 已经安装了兼容的 Python 3.10–3.12,也可以使用系统 Python(以实际可用的 `python3.10`、`python3.11` 或 `python3.12` 命令替换下面示例):
```bash
python3.10 -m venv .venv
.venv/bin/python -m pip install -U pip
.venv/bin/python -m pip install -e .
.venv/bin/ocr-server
```
GPU 部署不使用当前 CPU 依赖作为判断依据,请按照 PaddlePaddle 官方文档安装与 CUDA、cuDNN、驱动匹配的 GPU 版本,然后再安装本项目依赖。
## API
### 1. 上传图片
```bash
curl -X POST http://127.0.0.1:8000/api/v1/upload \
-F "file=@./receipt.jpg"
```
返回示例(所有接口统一使用 `code`、`message`、`data`):
```json
{
"code": 0,
"message": "success",
"data": {
"file_id": "b5a1e99c-9d7d-46f0-9e1e-1caa1fdc4e51",
"filename": "receipt.jpg",
"size": 123456,
"width": 1600,
"height": 1200,
"status": "queued",
"progress": 0,
"queue_position": 1
}
}
```
### 2. 图片转文字
上传成功后图片会进入内存等待队列,默认由 1 个 OCR 工作线程按 FIFO 顺序识别。调用 `/api/v1/i2t` 时:
- `queued`:任务还在等待,返回 `progress` 和 `queue_position`;
- `processing`:任务正在识别,返回当前 `progress`;
- `completed`:返回 JSON 识别结果;
- `failed`:返回错误信息。
```bash
curl -X POST http://127.0.0.1:8000/api/v1/i2t \
-H "Content-Type: application/json" \
-d '{"file_id":"b5a1e99c-9d7d-46f0-9e1e-1caa1fdc4e51"}'
```
未完成时返回示例:
```json
{
"code": 0,
"message": "success",
"data": {
"file_id": "b5a1e99c-9d7d-46f0-9e1e-1caa1fdc4e51",
"status": "processing",
"progress": 20,
"queue_position": null,
"ocr_started_at": "2026-10-11T10:20:30.123456Z",
"ocr_finished_at": null,
"ocr_elapsed_ms": null,
"result": null,
"error": null
}
}
```
完成时 `result` 使用紧凑的 JSON 对象映射:
```json
{
"text": "BOARDING PASS",
"polygon": {
"text1": {
"text": "BOARDING",
"confidence": 0.9841,
"Location": {
"xtop": 420,
"ytop": 20,
"xbottom": 660,
"ybottom": 66
},
"line": 1,
"paragraphs": 1
}
}
}
```
- 不再返回 `segments` 数组、`lines` 数组和 `paragraphs` 数组;
- 每个 `textN` 对象包含文字、置信度、矩形坐标、行编号和段编号;
- 同一行的 `line` 值相同;
- 同一自然段的 `paragraphs` 值相同;
- `Location` 包含 `xtop`、`ytop`、`xbottom`、`ybottom`。
两个检测框在同一文本行时会分配相同的 `line` 编号;相邻文本行属于同一自然段时会分配相同的 `paragraphs` 编号。可选 `min_confidence`(0–1)过滤低置信度片段,服务会重新计算行编号和段编号。
## IDEA HTTP Client 测试
已提供:
```text
http/ocr-server.http
```
在 IDEA 中打开文件,项目已附带 PaddleOCR 官方示例图片:
```text
http/fixtures/general_ocr_002.png
```
然后按顺序执行:
1. 健康检查;
2. 上传图片;
3. IDEA 自动保存上传响应中的 `file_id`;
4. 立即调用图片转文字接口,观察 `queued` / `processing` 进度;
5. 重复调用直到返回 `completed` 和 JSON 识别结果。
该测试图片来源于 PaddleOCR 官方示例。也可以把自己的图片复制到 `http/fixtures/`,再修改 `.http` 文件中的文件路径。
## 配置
配置统一写在项目根目录的 `config.yaml`,服务启动时读取一次,修改后重启生效:
```yaml
host: 127.0.0.1
port: 8000
upload_dir: data/uploads
model_dir: models
det_model_name: PP-OCRv5_server_det
rec_model_name: PP-OCRv5_server_rec
ocr_workers: 1
device: cpu
lang: ch
max_upload_mb: 10
max_image_pixels: 20000000
text_det_limit_side_len: 960
text_det_limit_type: max
text_det_thresh: 0.3
text_det_box_thresh: 0.6
text_det_unclip_ratio: 1.5
text_rec_score_thresh: 0.0
text_recognition_batch_size: 1
```
| 配置项 | 默认值 | 说明 |
| --- | --- | --- |
| `host` | `127.0.0.1` | 监听地址 |
| `port` | `8000` | 监听端口 |
| `upload_dir` | `data/uploads` | 图片存储目录 |
| `model_dir` | `models` | PaddleOCR 模型下载和缓存目录 |
| `det_model_name` | `PP-OCRv5_server_det` | 文本检测模型名称 |
| `rec_model_name` | `PP-OCRv5_server_rec` | 文本识别模型名称 |
| `ocr_workers` | `1` | OCR 工作线程数;每个线程独立加载一份模型 |
| `max_upload_mb` | `10` | 单文件大小上限 |
| `max_image_pixels` | `20000000` | 图片像素上限 |
| `device` | `cpu` | `cpu` 或 GPU 设备配置 |
| `lang` | `ch` | PaddleOCR 语言 |
| `text_det_limit_side_len` | `960` | 检测图像最长边;调小可加速,可能漏检小字 |
| `text_det_limit_type` | `max` | 检测缩放限制类型 |
| `text_det_thresh` | `0.3` | 检测二值化阈值 |
| `text_det_box_thresh` | `0.6` | 检测框置信度阈值 |
| `text_det_unclip_ratio` | `1.5` | 检测框扩张比例 |
| `text_rec_score_thresh` | `0.0` | 识别结果阈值 |
| `text_recognition_batch_size` | `1` | 识别批量大小;内存足够时可提高 |
接口文档:启动后访问 <http://127.0.0.1:8000/docs>。
## 测试
```bash
uv run pytest -q
uv pip check
```
+35
View File
@@ -0,0 +1,35 @@
# OCR Server 配置文件。修改后重启服务生效。
host: 127.0.0.1
port: 8000
# 支持绝对路径或相对项目根目录的路径。
upload_dir: data/uploads
model_dir: models
# 模型缺失时自动下载到 model_dir/official_models/。
det_model_name: PP-OCRv5_server_det
rec_model_name: PP-OCRv5_server_rec
# 每个线程会独立占用一份 OCR 模型内存。
ocr_workers: 1
device: cpu
lang: ch
# 识别速度/精度参数。
# 速度优先可将 text_det_limit_side_len 调小到 640;默认 960。text_recognition_batch_size 调整为 2 默认 1
# 检测图像最长边
text_det_limit_side_len: 960
# 检测缩放类型
text_det_limit_type: max
# 检测阈值
text_det_thresh: 0.3
text_det_box_thresh: 0.6
text_det_unclip_ratio: 1.5
# 识别置信度阈值
text_rec_score_thresh: 0.0
# 识别批量大小
text_recognition_batch_size: 1
max_upload_mb: 10
max_image_pixels: 20000000
+1
View File
@@ -0,0 +1 @@
将用于测试的图片命名为 `receipt.jpg` 放在此目录,或者修改 `http/ocr-server.http` 中的图片路径。
Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

+37
View File
@@ -0,0 +1,37 @@
@host = http://127.0.0.1:8000
### 健康检查
GET {{host}}/healthz
### 上传图片
# @name uploadImage
POST {{host}}/api/v1/upload
Content-Type: multipart/form-data; boundary=ocrBoundary
--ocrBoundary
Content-Disposition: form-data; name="file"; filename="general_ocr_002.png"
Content-Type: image/jpeg
< ./fixtures/general_ocr_002.png
--ocrBoundary--
> {% client.global.set("fileId", response.body.data.file_id); %}
### 使用上传返回的 file_id 识别文字
# 先执行上面的上传请求,IDEA 会自动保存返回的 file_id。
POST {{host}}/api/v1/i2t
Content-Type: application/json
{
"file_id": "{{fileId}}",
"min_confidence": 0.0
}
### 识别并过滤低置信度文本
POST {{host}}/api/v1/i2t
Content-Type: application/json
{
"file_id": "{{fileId}}",
"min_confidence": 0.8
}
+27
View File
@@ -0,0 +1,27 @@
[project]
name = "ocr-server"
version = "0.1.0"
description = "PaddleOCR PP-OCRv5 HTTP server"
readme = "README.md"
requires-python = ">=3.10,<3.14"
dependencies = [
"fastapi>=0.115,<1",
"pillow>=10.0,<12",
"python-multipart>=0.0.9,<1",
"pyyaml>=6.0,<7",
"uvicorn[standard]>=0.34,<1",
"paddleocr>=3.2,<4",
"paddlepaddle>=3.0,<4",
]
[project.scripts]
ocr-server = "ocr_server:main"
[build-system]
requires = ["uv_build>=0.13.0,<0.14.0"]
build-backend = "uv_build"
[dependency-groups]
dev = [
"pytest>=9.1.1",
]
+33
View File
@@ -0,0 +1,33 @@
"""Benchmark the configured OCR pipeline without modifying model files."""
from pathlib import Path
from time import perf_counter
from ocr_server.config import Settings
from ocr_server.ocr import OCRService
if __name__ == "__main__":
image_path = Path("http/fixtures/general_ocr_002.png")
settings = Settings()
service = OCRService(
lang=settings.lang,
device=settings.device,
model_dir=settings.model_dir,
det_model_name=settings.det_model_name,
rec_model_name=settings.rec_model_name,
text_det_limit_side_len=settings.text_det_limit_side_len,
text_det_limit_type=settings.text_det_limit_type,
text_det_thresh=settings.text_det_thresh,
text_det_box_thresh=settings.text_det_box_thresh,
text_det_unclip_ratio=settings.text_det_unclip_ratio,
text_rec_score_thresh=settings.text_rec_score_thresh,
text_recognition_batch_size=settings.text_recognition_batch_size,
)
service.prepare()
started = perf_counter()
lines = service.recognize(image_path)
elapsed_ms = (perf_counter() - started) * 1000
print(f"image={image_path}")
print(f"elapsed_ms={elapsed_ms:.2f}")
print(f"segments={len(lines)}")
+23
View File
@@ -0,0 +1,23 @@
"""Download PP-OCRv5 models into the project's configured model directory."""
from ocr_server.config import Settings
from ocr_server.ocr import OCRService
if __name__ == "__main__":
settings = Settings()
OCRService(
lang=settings.lang,
device=settings.device,
model_dir=settings.model_dir,
det_model_name=settings.det_model_name,
rec_model_name=settings.rec_model_name,
text_det_limit_side_len=settings.text_det_limit_side_len,
text_det_limit_type=settings.text_det_limit_type,
text_det_thresh=settings.text_det_thresh,
text_det_box_thresh=settings.text_det_box_thresh,
text_det_unclip_ratio=settings.text_det_unclip_ratio,
text_rec_score_thresh=settings.text_rec_score_thresh,
text_recognition_batch_size=settings.text_recognition_batch_size,
).prepare()
print(f"Models are ready in: {settings.model_dir.resolve()}")
+16
View File
@@ -0,0 +1,16 @@
# 这是一个示例 Python 脚本。
# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
def print_hi(name):
# 在下面的代码行中使用断点来调试脚本。
print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。
# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
print_hi('PyCharm')
# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
+11
View File
@@ -0,0 +1,11 @@
from ocr_server.app import app, create_app
from ocr_server.config import Settings
__all__ = ["Settings", "app", "create_app"]
def main() -> None:
import uvicorn
settings = Settings()
uvicorn.run("ocr_server.app:app", host=settings.host, port=settings.port)
+142
View File
@@ -0,0 +1,142 @@
from fastapi import FastAPI, File, HTTPException, UploadFile, status
from fastapi.responses import JSONResponse
from ocr_server.config import Settings
from ocr_server.ocr import OCRService
from ocr_server.schemas import ApiResponse, I2TData, I2TRequest
from ocr_server.storage import ImageStore, InvalidImage
from ocr_server.task_queue import OCRTaskQueue
def create_app(settings: Settings | None = None) -> FastAPI:
settings = settings or Settings()
store = ImageStore(settings)
def create_ocr() -> OCRService:
return OCRService(
lang=settings.lang,
device=settings.device,
model_dir=settings.model_dir,
det_model_name=settings.det_model_name,
rec_model_name=settings.rec_model_name,
text_det_limit_side_len=settings.text_det_limit_side_len,
text_det_limit_type=settings.text_det_limit_type,
text_det_thresh=settings.text_det_thresh,
text_det_box_thresh=settings.text_det_box_thresh,
text_det_unclip_ratio=settings.text_det_unclip_ratio,
text_rec_score_thresh=settings.text_rec_score_thresh,
text_recognition_batch_size=settings.text_recognition_batch_size,
)
tasks = OCRTaskQueue(create_ocr, worker_count=settings.ocr_workers)
app = FastAPI(title="OCR Server", version="0.1.0")
@app.get("/healthz", response_model=ApiResponse, tags=["system"])
def healthz() -> ApiResponse:
return ApiResponse(data={"status": "ok"})
@app.post(
"/api/v1/upload",
response_model=ApiResponse,
status_code=status.HTTP_201_CREATED,
tags=["ocr"],
)
async def upload(file: UploadFile = File(...)) -> ApiResponse:
if not file.filename:
raise HTTPException(status_code=400, detail="请提供图片文件名")
content = await file.read(settings.max_upload_bytes + 1)
if len(content) > settings.max_upload_bytes:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail=f"图片大小不能超过 {settings.max_upload_mb} MB",
)
try:
uploaded = store.save(content, file.filename)
tasks.submit(uploaded.file_id, store.path_for(uploaded.file_id))
snapshot = tasks.snapshot(uploaded.file_id)
if snapshot is not None:
uploaded.status, uploaded.progress, uploaded.queue_position = snapshot[:3]
return ApiResponse(data=uploaded)
except InvalidImage as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.post("/api/v1/i2t", response_model=ApiResponse, tags=["ocr"])
def image_to_text(request: I2TRequest) -> ApiResponse:
snapshot = tasks.snapshot(request.file_id)
if snapshot is None:
raise HTTPException(status_code=404, detail="图片不存在或已过期")
(
status_value,
progress,
queue_position,
result,
error,
ocr_started_at,
ocr_finished_at,
ocr_elapsed_ms,
) = snapshot
if status_value == "queued":
return ApiResponse(
data=I2TData(
file_id=request.file_id,
status=status_value,
progress=progress,
queue_position=queue_position,
ocr_started_at=ocr_started_at,
ocr_finished_at=ocr_finished_at,
ocr_elapsed_ms=ocr_elapsed_ms,
)
)
if status_value == "processing":
return ApiResponse(
data=I2TData(
file_id=request.file_id,
status=status_value,
progress=progress,
ocr_started_at=ocr_started_at,
ocr_finished_at=ocr_finished_at,
ocr_elapsed_ms=ocr_elapsed_ms,
)
)
if status_value == "failed":
return ApiResponse(
data=I2TData(
file_id=request.file_id,
status=status_value,
progress=progress,
ocr_started_at=ocr_started_at,
ocr_finished_at=ocr_finished_at,
ocr_elapsed_ms=ocr_elapsed_ms,
error=error or "OCR 识别失败",
)
)
if result is None:
raise HTTPException(status_code=500, detail="OCR 结果为空")
filtered = OCRTaskQueue.filter_document(result, request.min_confidence)
return ApiResponse(
data=I2TData(
file_id=request.file_id,
status="completed",
progress=100,
ocr_started_at=ocr_started_at,
ocr_finished_at=ocr_finished_at,
ocr_elapsed_ms=ocr_elapsed_ms,
result=filtered,
)
)
@app.exception_handler(413)
async def request_too_large(_, __) -> JSONResponse:
return JSONResponse(status_code=413, content={"detail": "请求体过大"})
return app
app = create_app()
if __name__ == "__main__":
import uvicorn
settings = Settings()
uvicorn.run(app, host=settings.host, port=settings.port)
+52
View File
@@ -0,0 +1,52 @@
from pathlib import Path
from typing import Any, Literal
import yaml
from pydantic import BaseModel, Field
PROJECT_ROOT = Path(__file__).resolve().parents[2]
CONFIG_FILE = PROJECT_ROOT / "config.yaml"
class Settings(BaseModel):
host: str = "127.0.0.1"
port: int = Field(default=8000, ge=1, le=65535)
upload_dir: Path = PROJECT_ROOT / "data" / "uploads"
model_dir: Path = PROJECT_ROOT / "models"
det_model_name: str = "PP-OCRv5_server_det"
rec_model_name: str = "PP-OCRv5_server_rec"
ocr_workers: int = Field(default=1, ge=1, le=32)
max_upload_mb: int = Field(default=10, ge=1, le=100)
max_image_pixels: int = Field(default=20_000_000, ge=1)
device: str = "cpu"
lang: str = "ch"
text_det_limit_side_len: int = Field(default=960, ge=32, le=4096)
text_det_limit_type: Literal["max", "min"] = "max"
text_det_thresh: float = Field(default=0.3, ge=0.0, le=1.0)
text_det_box_thresh: float = Field(default=0.6, ge=0.0, le=1.0)
text_det_unclip_ratio: float = Field(default=1.5, ge=0.1, le=5.0)
text_rec_score_thresh: float = Field(default=0.0, ge=0.0, le=1.0)
text_recognition_batch_size: int = Field(default=1, ge=1, le=64)
def __init__(self, **overrides: Any) -> None:
values = _read_config_file()
values.update(overrides)
for name in ("upload_dir", "model_dir"):
path = Path(values[name])
values[name] = path if path.is_absolute() else PROJECT_ROOT / path
super().__init__(**values)
@property
def max_upload_bytes(self) -> int:
return self.max_upload_mb * 1024 * 1024
def _read_config_file() -> dict[str, Any]:
if not CONFIG_FILE.is_file():
return {}
with CONFIG_FILE.open("r", encoding="utf-8") as stream:
values = yaml.safe_load(stream) or {}
if not isinstance(values, dict):
raise ValueError(f"配置文件必须是 YAML 对象: {CONFIG_FILE}")
return values
+170
View File
@@ -0,0 +1,170 @@
import os
import shutil
import threading
from pathlib import Path
from typing import Any
class OCRNotAvailable(RuntimeError):
pass
class OCRService:
"""Process-local PaddleOCR runner; model initialization is lazy and thread-safe."""
_process_model_lock = threading.Lock()
_MODEL_FILES = (
"config.json",
"inference.yml",
"inference.pdiparams",
"inference.json",
)
def __init__(
self,
lang: str = "ch",
device: str = "cpu",
model_dir: Path | str = "models",
det_model_name: str = "PP-OCRv5_server_det",
rec_model_name: str = "PP-OCRv5_server_rec",
text_det_limit_side_len: int = 960,
text_det_limit_type: str = "max",
text_det_thresh: float = 0.3,
text_det_box_thresh: float = 0.6,
text_det_unclip_ratio: float = 1.5,
text_rec_score_thresh: float = 0.0,
text_recognition_batch_size: int = 1,
) -> None:
self.lang = lang
self.device = device
self.model_dir = Path(model_dir).resolve()
self._det_model_name = det_model_name
self._rec_model_name = rec_model_name
self._text_det_limit_side_len = text_det_limit_side_len
self._text_det_limit_type = text_det_limit_type
self._text_det_thresh = text_det_thresh
self._text_det_box_thresh = text_det_box_thresh
self._text_det_unclip_ratio = text_det_unclip_ratio
self._text_rec_score_thresh = text_rec_score_thresh
self._text_recognition_batch_size = text_recognition_batch_size
self._engine: Any | None = None
self._lock = threading.Lock()
self._inference_lock = threading.Lock()
def _get_engine(self) -> Any:
if self._engine is None:
with self._lock:
if self._engine is None:
self.model_dir.mkdir(parents=True, exist_ok=True)
self._remove_incomplete_models()
# PaddleX stores downloaded official models below this directory.
# Set it before importing PaddleOCR because PaddleX reads it at import time.
os.environ["PADDLE_PDX_CACHE_HOME"] = str(self.model_dir)
try:
from paddleocr import PaddleOCR
except ImportError as exc:
raise OCRNotAvailable(
"PaddleOCR 未安装,请先安装项目依赖"
) from exc
with self._process_model_lock:
self._engine = PaddleOCR(
**self._model_arguments(),
device=self.device,
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
enable_mkldnn=False,
text_det_limit_side_len=self._text_det_limit_side_len,
text_det_limit_type=self._text_det_limit_type,
text_det_thresh=self._text_det_thresh,
text_det_box_thresh=self._text_det_box_thresh,
text_det_unclip_ratio=self._text_det_unclip_ratio,
text_rec_score_thresh=self._text_rec_score_thresh,
text_recognition_batch_size=self._text_recognition_batch_size,
)
return self._engine
def prepare(self) -> None:
"""Load local models or download only the missing model packages."""
self._get_engine()
def _model_arguments(self) -> dict[str, str]:
arguments: dict[str, str] = {
"text_detection_model_name": self._det_model_name,
"text_recognition_model_name": self._rec_model_name,
}
for argument_name, model_name in (
("text_detection_model_dir", self._det_model_name),
("text_recognition_model_dir", self._rec_model_name),
):
local_path = self.model_dir / "official_models" / model_name
if self._is_complete_model(local_path):
arguments[argument_name] = str(local_path)
return arguments
@classmethod
def _is_complete_model(cls, model_path: Path) -> bool:
return model_path.is_dir() and all(
(model_path / filename).is_file() for filename in cls._MODEL_FILES
)
def _remove_incomplete_models(self) -> None:
for model_name in (self._det_model_name, self._rec_model_name):
model_path = self.model_dir / "official_models" / model_name
if model_path.exists() and not self._is_complete_model(model_path):
shutil.rmtree(model_path)
def recognize(self, image_path: Path) -> list[dict[str, Any]]:
with self._inference_lock:
# Passing an ndarray avoids PaddleX treating Windows paths as URLs.
import numpy as np
from PIL import Image
with Image.open(image_path) as image:
image_array = np.ascontiguousarray(image.convert("RGB"))
results = self._get_engine().predict(input=image_array)
return self._parse_results(results)
def _parse_results(self, results: Any) -> list[dict[str, Any]]:
lines: list[dict[str, Any]] = []
for result in results:
payload = self._result_payload(result)
texts = payload.get("rec_texts", [])
scores = payload.get("rec_scores", [])
boxes = payload.get("rec_polys", payload.get("dt_polys", []))
for index, text in enumerate(texts):
score = float(scores[index]) if index < len(scores) else 0.0
polygon = boxes[index] if index < len(boxes) else []
lines.append(
{
"text": str(text),
"confidence": score,
"polygon": self._to_polygon(polygon),
}
)
return lines
@staticmethod
def _result_payload(result: Any) -> dict[str, Any]:
if isinstance(result, dict):
return result
json_value = getattr(result, "json", None)
if callable(json_value):
json_value = json_value()
if isinstance(json_value, str):
import json
json_value = json.loads(json_value)
if isinstance(json_value, dict):
# PaddleOCR 3.x may wrap the actual result under ``res``.
nested = json_value.get("res")
return nested if isinstance(nested, dict) else json_value
data = getattr(result, "data", None)
return data if isinstance(data, dict) else {}
@staticmethod
def _to_polygon(value: Any) -> list[list[float]]:
try:
return [[float(point[0]), float(point[1])] for point in value]
except (IndexError, TypeError, ValueError):
return []
+70
View File
@@ -0,0 +1,70 @@
from datetime import datetime
from typing import Any, Literal
from uuid import UUID
from pydantic import BaseModel, Field
TaskStatus = Literal["queued", "processing", "completed", "failed"]
class ApiResponse(BaseModel):
code: int = 0
message: str = "success"
data: Any | None = None
class UploadData(BaseModel):
file_id: UUID
filename: str
size: int
width: int
height: int
status: TaskStatus = "queued"
progress: int = Field(default=0, ge=0, le=100)
queue_position: int | None = Field(default=None, ge=1)
class I2TRequest(BaseModel):
file_id: UUID
min_confidence: float = Field(default=0.0, ge=0.0, le=1.0)
class OCRSegment(BaseModel):
text: str
confidence: float
polygon: list[list[float]]
class OCRLocation(BaseModel):
"""Bounding rectangle: top-left (xtop, ytop), bottom-right (xbottom, ybottom)."""
xtop: float
ytop: float
xbottom: float
ybottom: float
class OCRTextBox(BaseModel):
text: str
confidence: float
Location: OCRLocation
line: int
paragraphs: int
class OCRDocument(BaseModel):
text: str
polygon: dict[str, OCRTextBox]
class I2TData(BaseModel):
file_id: UUID
status: TaskStatus
progress: int = Field(ge=0, le=100)
queue_position: int | None = Field(default=None, ge=1)
ocr_started_at: datetime | None = None
ocr_finished_at: datetime | None = None
ocr_elapsed_ms: float | None = None
result: OCRDocument | None = None
error: str | None = None
+61
View File
@@ -0,0 +1,61 @@
from io import BytesIO
from pathlib import Path
from uuid import UUID, uuid4
from PIL import Image, UnidentifiedImageError
from ocr_server.config import Settings
from ocr_server.schemas import UploadData
class InvalidImage(ValueError):
pass
class ImageStore:
def __init__(self, settings: Settings):
self.directory = settings.upload_dir.resolve()
self.directory.mkdir(parents=True, exist_ok=True)
self.max_pixels = settings.max_image_pixels
def path_for(self, file_id: UUID) -> Path:
return self.directory / f"{file_id.hex}.png"
def save(self, content: bytes, filename: str) -> UploadData:
try:
with Image.open(BytesIO(content)) as image:
if image.format not in {"JPEG", "PNG", "WEBP", "BMP"}:
raise InvalidImage("仅支持 JPEG、PNG、WEBP、BMP 图片")
width, height = image.size
if width * height > self.max_pixels:
raise InvalidImage(f"图片像素数不能超过 {self.max_pixels}")
if getattr(image, "n_frames", 1) != 1:
raise InvalidImage("不支持多帧图片")
image.load()
# 转为统一的 RGB PNG,不保留原始文件名、元数据或附加内容。
from PIL import ImageOps
oriented = ImageOps.exif_transpose(image)
rgba = oriented.convert("RGBA")
background = Image.new("RGBA", rgba.size, "white")
normalized = Image.alpha_composite(background, rgba).convert("RGB")
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError) as exc:
raise InvalidImage("图片格式无效、已损坏或尺寸过大") from exc
file_id = uuid4()
destination = self.path_for(file_id)
temporary = destination.with_suffix(".tmp")
try:
normalized.save(temporary, format="PNG")
temporary.replace(destination)
finally:
temporary.unlink(missing_ok=True)
normalized.close()
width, height = normalized.size
return UploadData(
file_id=file_id,
filename=filename,
size=destination.stat().st_size,
width=width,
height=height,
)
+314
View File
@@ -0,0 +1,314 @@
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from queue import Queue
from threading import Lock, Thread
from time import perf_counter
from typing import Any, Callable
from uuid import UUID
from ocr_server.ocr import OCRService
from ocr_server.schemas import OCRDocument, OCRLocation, OCRTextBox, TaskStatus
@dataclass
class OCRTask:
file_id: UUID
image_path: Path
status: TaskStatus = "queued"
progress: int = 0
result: OCRDocument | None = None
error: str | None = None
ocr_started_at: datetime | None = None
ocr_finished_at: datetime | None = None
ocr_elapsed_ms: float | None = None
_lock: Lock = field(default_factory=Lock, repr=False)
class OCRTaskQueue:
"""In-memory FIFO queue with one independent OCR service per worker."""
def __init__(
self,
ocr_factory: Callable[[], OCRService],
worker_count: int = 1,
) -> None:
self.worker_count = worker_count
self._tasks: dict[UUID, OCRTask] = {}
self._tasks_lock = Lock()
self._queue: Queue[OCRTask | None] = Queue()
self._ocr_services = [ocr_factory() for _ in range(worker_count)]
self._workers = [
Thread(
target=self._worker_loop,
args=(index,),
name=f"ocr-worker-{index + 1}",
daemon=True,
)
for index in range(worker_count)
]
for worker in self._workers:
worker.start()
def submit(self, file_id: UUID, image_path: Path) -> OCRTask:
task = OCRTask(file_id=file_id, image_path=image_path)
with self._tasks_lock:
self._tasks[file_id] = task
self._queue.put(task)
return task
def get(self, file_id: UUID) -> OCRTask | None:
with self._tasks_lock:
return self._tasks.get(file_id)
def queue_position(self, file_id: UUID) -> int | None:
task = self.get(file_id)
if task is None or task.status != "queued":
return None
with self._queue.mutex:
queued = list(self._queue.queue)
try:
return next(index for index, item in enumerate(queued, 1) if item is task)
except StopIteration:
return None
def snapshot(
self, file_id: UUID
) -> tuple[
TaskStatus,
int,
int | None,
OCRDocument | None,
str | None,
datetime | None,
datetime | None,
float | None,
] | None:
task = self.get(file_id)
if task is None:
return None
with task._lock:
return (
task.status,
task.progress,
self.queue_position(file_id),
task.result,
task.error,
task.ocr_started_at,
task.ocr_finished_at,
task.ocr_elapsed_ms,
)
def _worker_loop(self, worker_index: int) -> None:
ocr = self._ocr_services[worker_index]
while True:
task = self._queue.get()
try:
if task is None:
return
self._run(task, ocr)
finally:
self._queue.task_done()
def _run(self, task: OCRTask, ocr: OCRService) -> None:
started_at = datetime.now(timezone.utc)
started_clock = perf_counter()
with task._lock:
task.status = "processing"
task.progress = 10
task.ocr_started_at = started_at
try:
with task._lock:
task.progress = 20
recognized = ocr.recognize(task.image_path)
with task._lock:
task.progress = 80
task.result = self.build_document(recognized)
task.progress = 100
task.status = "completed"
except Exception as exc:
with task._lock:
task.status = "failed"
task.progress = 100
task.error = str(exc)
finally:
with task._lock:
task.ocr_finished_at = datetime.now(timezone.utc)
task.ocr_elapsed_ms = round((perf_counter() - started_clock) * 1000, 2)
@classmethod
def build_document(cls, recognized: list[dict[str, Any]]) -> OCRDocument:
"""Build the compact polygon object and line/paragraph numbering."""
segments = [item for item in recognized if item.get("text")]
if not segments:
return OCRDocument(text="", polygon={})
ordered = sorted(segments, key=cls._segment_sort_key)
line_groups: list[list[dict[str, Any]]] = []
for segment in ordered:
matching_line = cls._find_line(segment, line_groups)
if matching_line is None:
line_groups.append([segment])
else:
matching_line.append(segment)
for line in line_groups:
line.sort(key=cls._segment_sort_key)
line_groups.sort(key=cls._line_sort_key)
paragraph_groups: list[list[list[dict[str, Any]]]] = []
for line in line_groups:
line_record = {
"segments": line,
"polygon": cls._combined_polygon(
[item.get("polygon", []) for item in line]
),
"text": cls._join_text(line),
}
if not paragraph_groups or not cls._same_paragraph(
paragraph_groups[-1][-1], line_record
):
paragraph_groups.append([line_record])
else:
paragraph_groups[-1].append(line_record)
polygon: dict[str, OCRTextBox] = {}
paragraph_texts: list[str] = []
line_number = 0
for paragraph_number, paragraph in enumerate(paragraph_groups, 1):
paragraph_texts.append("\n".join(line["text"] for line in paragraph))
for line in paragraph:
line_number += 1
for segment in line["segments"]:
bounds = cls._bounds(segment.get("polygon", []))
if bounds is None:
continue
polygon[f"text{len(polygon) + 1}"] = OCRTextBox(
text=str(segment.get("text", "")),
confidence=float(segment.get("confidence", 0.0)),
Location=OCRLocation(
xtop=bounds[0],
ytop=bounds[1],
xbottom=bounds[2],
ybottom=bounds[3],
),
line=line_number,
paragraphs=paragraph_number,
)
return OCRDocument(text="\n\n".join(paragraph_texts), polygon=polygon)
@classmethod
def filter_document(cls, document: OCRDocument, min_confidence: float) -> OCRDocument:
# The compact response is intentionally rebuilt from its own polygon map.
selected = [
{
"text": item.text,
"confidence": item.confidence,
"polygon": [
[item.Location.xtop, item.Location.ytop],
[item.Location.xbottom, item.Location.ytop],
[item.Location.xbottom, item.Location.ybottom],
[item.Location.xtop, item.Location.ybottom],
],
}
for item in document.polygon.values()
if item.confidence >= min_confidence
]
return cls.build_document(selected)
@classmethod
def _find_line(
cls,
segment: dict[str, Any],
line_groups: list[list[dict[str, Any]]],
) -> list[dict[str, Any]] | None:
segment_bounds = cls._bounds(segment.get("polygon", []))
if segment_bounds is None:
return None
_, top, _, bottom = segment_bounds
segment_height = max(bottom - top, 1.0)
best: tuple[float, list[dict[str, Any]]] | None = None
for line in line_groups:
line_bounds = cls._combined_bounds([item.get("polygon", []) for item in line])
if line_bounds is None:
continue
_, line_top, _, line_bottom = line_bounds
line_height = max(line_bottom - line_top, 1.0)
overlap = min(bottom, line_bottom) - max(top, line_top)
center_distance = abs((top + bottom) / 2 - (line_top + line_bottom) / 2)
if overlap >= 0.25 * min(segment_height, line_height) or center_distance <= 0.45 * max(segment_height, line_height):
if best is None or center_distance < best[0]:
best = (center_distance, line)
return best[1] if best else None
@classmethod
def _same_paragraph(cls, previous: dict[str, Any], current: dict[str, Any]) -> bool:
previous_bounds = cls._bounds(previous["polygon"])
current_bounds = cls._bounds(current["polygon"])
if previous_bounds is None or current_bounds is None:
return True
previous_left, previous_top, previous_right, previous_bottom = previous_bounds
current_left, current_top, current_right, _ = current_bounds
previous_height = max(previous_bottom - previous_top, 1.0)
vertical_gap = current_top - previous_bottom
horizontal_overlap = min(previous_right, current_right) - max(previous_left, current_left)
return vertical_gap <= 2.0 * previous_height and (
horizontal_overlap >= 0
or abs(current_left - previous_left) <= 2.0 * previous_height
)
@staticmethod
def _join_text(segments: list[dict[str, Any]]) -> str:
text = ""
for segment in segments:
value = str(segment.get("text", ""))
if text and text[-1].isascii() and text[-1].isalnum() and value[:1].isascii() and value[:1].isalnum():
text += " "
text += value
return text
@staticmethod
def _segment_sort_key(segment: dict[str, Any]) -> tuple[float, float]:
bounds = OCRTaskQueue._bounds(segment.get("polygon", []))
return (bounds[1], bounds[0]) if bounds else (0.0, 0.0)
@classmethod
def _line_sort_key(cls, line: list[dict[str, Any]]) -> tuple[float, float]:
bounds = cls._combined_bounds([item.get("polygon", []) for item in line])
return (bounds[1], bounds[0]) if bounds else (0.0, 0.0)
@staticmethod
def _bounds(polygon: list[list[float]]) -> tuple[float, float, float, float] | None:
if not polygon:
return None
try:
xs = [float(point[0]) for point in polygon]
ys = [float(point[1]) for point in polygon]
except (IndexError, TypeError, ValueError):
return None
return min(xs), min(ys), max(xs), max(ys)
@classmethod
def _combined_bounds(
cls, polygons: list[list[list[float]]]
) -> tuple[float, float, float, float] | None:
bounds = [cls._bounds(polygon) for polygon in polygons]
valid = [item for item in bounds if item is not None]
if not valid:
return None
return (
min(item[0] for item in valid),
min(item[1] for item in valid),
max(item[2] for item in valid),
max(item[3] for item in valid),
)
@classmethod
def _combined_polygon(cls, polygons: list[list[list[float]]]) -> list[list[float]]:
bounds = cls._combined_bounds(polygons)
if bounds is None:
return []
left, top, right, bottom = bounds
return [[left, top], [right, top], [right, bottom], [left, bottom]]
+59
View File
@@ -0,0 +1,59 @@
from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
from fastapi.testclient import TestClient
from PIL import Image
from ocr_server.app import create_app
from ocr_server.config import Settings
def client() -> TestClient:
directory = TemporaryDirectory()
app = create_app(Settings(upload_dir=Path(directory.name)))
test_client = TestClient(app)
test_client._ocr_test_directory = directory # keep temporary storage alive
return test_client
def png_bytes() -> bytes:
output = BytesIO()
Image.new("RGB", (20, 10), "white").save(output, format="PNG")
return output.getvalue()
def test_health() -> None:
response = client().get("/healthz")
assert response.status_code == 200
assert response.json() == {
"code": 0,
"message": "success",
"data": {"status": "ok"},
}
def test_upload_and_missing_image() -> None:
response = client().post(
"/api/v1/upload",
files={"file": ("sample.png", png_bytes(), "image/png")},
)
assert response.status_code == 201
payload = response.json()
assert payload["code"] == 0
assert payload["message"] == "success"
assert payload["data"]["filename"] == "sample.png"
assert payload["data"]["width"] == 20
assert payload["data"]["height"] == 10
missing = client().post("/api/v1/i2t", json={"file_id": str(uuid4())})
assert missing.status_code == 404
def test_rejects_invalid_image() -> None:
response = client().post(
"/api/v1/upload",
files={"file": ("sample.txt", b"not an image", "text/plain")},
)
assert response.status_code == 400
+45
View File
@@ -0,0 +1,45 @@
from pathlib import Path
from uuid import uuid4
from ocr_server.task_queue import OCRTaskQueue
class FakeOCR:
def recognize(self, _: Path) -> list[dict]:
return [
{"text": "Hello", "confidence": 0.95, "polygon": [[0, 0], [40, 0], [40, 10], [0, 10]]},
{"text": "世界", "confidence": 0.85, "polygon": [[45, 0], [85, 0], [85, 10], [45, 10]]},
{"text": "下一行", "confidence": 0.92, "polygon": [[0, 20], [50, 20], [50, 30], [0, 30]]},
]
def test_build_document_groups_segments_into_lines_and_paragraphs() -> None:
document = OCRTaskQueue.build_document(FakeOCR().recognize(Path("sample")))
assert document.text == "Hello世界\n下一行"
assert list(document.polygon) == ["text1", "text2", "text3"]
assert document.polygon["text1"].line == 1
assert document.polygon["text1"].paragraphs == 1
assert document.polygon["text3"].line == 2
def test_filter_document_rebuilds_groups() -> None:
document = OCRTaskQueue.build_document(FakeOCR().recognize(Path("sample")))
filtered = OCRTaskQueue.filter_document(document, 0.9)
assert [item.text for item in filtered.polygon.values()] == ["Hello", "下一行"]
assert filtered.text == "Hello\n下一行"
def test_queue_completes_task() -> None:
queue = OCRTaskQueue(lambda: FakeOCR(), worker_count=1)
file_id = uuid4()
task = queue.submit(file_id, Path("sample"))
queue._queue.join()
assert task.status == "completed"
assert task.progress == 100
assert task.ocr_started_at is not None
assert task.ocr_finished_at is not None
assert task.ocr_elapsed_ms is not None
assert queue.snapshot(file_id)[3] is not None
Generated
+2835
View File
File diff suppressed because it is too large Load Diff