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