VIN_OCR / app.py
Dirner's picture
Upload app.py
abf9a43 verified
Raw History Blame Contribute Delete
6.39 kB
import time
import urllib.error
import urllib.parse
import urllib.request
import cv2
import numpy as np
from fastapi import Body, FastAPI, File, Form, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from ocr_orchestra import (
FULL_FRAME_SOURCES,
MAX_UPLOAD_BYTES,
prepare_image_for_ocr,
run_crop_strategy,
run_full_frame_strategy,
)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def home():
return {"status": "VIN OCR API is running", "endpoint": "/ocr"}
@app.post("/debug-upload")
async def debug_upload(file: UploadFile = File(...)):
contents = await file.read()
return JSONResponse(
{
"ok": True,
"filename": file.filename,
"content_type": file.content_type,
"size_bytes": len(contents),
"message": "File reached HuggingFace Space",
}
)
@app.post("/ocr")
async def ocr(file: UploadFile = File(...), source: str = Form("unknown")):
started_at = time.perf_counter()
contents = await file.read()
if len(contents) > MAX_UPLOAD_BYTES:
return JSONResponse(
{
"ok": False,
"vin": "",
"confidence": "none",
"score": -999,
"warning": "Файл слишком большой для OCR. Сожмите фото или выберите фрагмент VIN.",
"debug": {
"elapsed_ms": round((time.perf_counter() - started_at) * 1000),
"upload_size_bytes": len(contents),
"max_upload_bytes": MAX_UPLOAD_BYTES,
"passes_used": [],
"passes": [],
"candidates": [],
"reasons": ["upload_too_large"],
},
},
status_code=413,
)
image = cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)
if image is None:
return JSONResponse(
{
"ok": False,
"vin": "",
"confidence": "none",
"score": -999,
"warning": "Не удалось прочитать изображение.",
"debug": {
"elapsed_ms": round((time.perf_counter() - started_at) * 1000),
"passes_used": [],
"passes": [],
"candidates": [],
"reasons": ["image_decode_failed"],
},
},
status_code=400,
)
image, image_debug = prepare_image_for_ocr(image, source)
source_mode = image_debug.get("source", "unknown")
if source_mode in FULL_FRAME_SOURCES:
return run_full_frame_strategy(image, source_mode, started_at, image_debug)
return run_crop_strategy(image, source_mode, started_at, image_debug)
def download_image_url(image_url):
parsed = urllib.parse.urlparse(image_url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
return None, "invalid_image_url"
request = urllib.request.Request(
image_url,
headers={
"User-Agent": "ORIONISPRO-VIN-OCR/1.0",
"Accept": "image/*,*/*;q=0.8",
},
)
try:
with urllib.request.urlopen(request, timeout=20) as response:
content_type = response.headers.get("Content-Type", "")
contents = response.read(MAX_UPLOAD_BYTES + 1)
except urllib.error.URLError as error:
return None, f"url_download_failed:{error.reason}"
if len(contents) > MAX_UPLOAD_BYTES:
return None, "url_image_too_large"
return {
"contents": contents,
"content_type": content_type,
"size_bytes": len(contents),
}, ""
@app.post("/ocr_url")
async def ocr_url(payload: dict = Body(...)):
started_at = time.perf_counter()
image_url = str(payload.get("image_url", "")).strip()
source = str(payload.get("source", "full_frame")).strip() or "full_frame"
downloaded, error = download_image_url(image_url)
if error:
return JSONResponse(
{
"ok": False,
"vin": "",
"confidence": "none",
"score": -999,
"warning": "Could not download image URL for OCR.",
"debug": {
"elapsed_ms": round((time.perf_counter() - started_at) * 1000),
"transport": "url_json",
"image_url": image_url,
"passes_used": [],
"passes": [],
"candidates": [],
"reasons": [error],
},
},
status_code=400,
)
contents = downloaded["contents"]
image = cv2.imdecode(np.frombuffer(contents, np.uint8), cv2.IMREAD_COLOR)
if image is None:
return JSONResponse(
{
"ok": False,
"vin": "",
"confidence": "none",
"score": -999,
"warning": "Could not read image downloaded by URL.",
"debug": {
"elapsed_ms": round((time.perf_counter() - started_at) * 1000),
"transport": "url_json",
"remote_content_type": downloaded["content_type"],
"remote_size_bytes": downloaded["size_bytes"],
"passes_used": [],
"passes": [],
"candidates": [],
"reasons": ["image_decode_failed"],
},
},
status_code=400,
)
image, image_debug = prepare_image_for_ocr(image, source)
image_debug.update(
{
"transport": "url_json",
"remote_content_type": downloaded["content_type"],
"remote_size_bytes": downloaded["size_bytes"],
}
)
source_mode = image_debug.get("source", "unknown")
if source_mode in FULL_FRAME_SOURCES:
return run_full_frame_strategy(image, source_mode, started_at, image_debug)
return run_crop_strategy(image, source_mode, started_at, image_debug)