init
This commit is contained in:
+16
@@ -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 帮助
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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 []
|
||||
@@ -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
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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]]
|
||||
Reference in New Issue
Block a user