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