33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
"""Pix2Text 独立微服务的 HTTP 客户端(后续阶段部署 OCR 服务时启用)。"""
|
|
import httpx
|
|
|
|
from app.services.ocr.base import OcrResult
|
|
|
|
|
|
class Pix2TextClient:
|
|
def __init__(self, service_url: str, timeout: float = 60.0):
|
|
self._url = service_url.rstrip("/")
|
|
self._timeout = timeout
|
|
|
|
async def healthy(self) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=5.0) as c:
|
|
r = await c.get(f"{self._url}/health")
|
|
return r.status_code == 200
|
|
except httpx.HTTPError:
|
|
return False
|
|
|
|
async def recognize(self, image_bytes: bytes, mime: str) -> OcrResult:
|
|
async with httpx.AsyncClient(timeout=self._timeout) as c:
|
|
r = await c.post(
|
|
f"{self._url}/ocr",
|
|
files={"file": ("image", image_bytes, mime)},
|
|
)
|
|
r.raise_for_status()
|
|
data = r.json()
|
|
return OcrResult(
|
|
markdown=data["markdown"],
|
|
confidence=float(data.get("confidence", 1.0)),
|
|
engine="pix2text",
|
|
)
|