Update app.py
Browse filesSwitch to ONNX model
app.py
CHANGED
|
@@ -4,23 +4,30 @@ import time
|
|
| 4 |
import base64
|
| 5 |
import secrets
|
| 6 |
import logging
|
| 7 |
-
from functools import lru_cache
|
| 8 |
|
| 9 |
from fastapi import FastAPI, HTTPException, Security, Depends
|
| 10 |
from fastapi.security.api_key import APIKeyHeader
|
| 11 |
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
from pydantic import BaseModel
|
| 13 |
from PIL import Image
|
|
|
|
| 14 |
import torch
|
| 15 |
-
|
|
|
|
| 16 |
import uvicorn
|
| 17 |
|
|
|
|
|
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
|
|
|
|
| 24 |
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
| 25 |
|
| 26 |
def verify_key(key: str = Security(api_key_header)):
|
|
@@ -28,22 +35,31 @@ def verify_key(key: str = Security(api_key_header)):
|
|
| 28 |
raise HTTPException(status_code=401, detail="Invalid or missing API key")
|
| 29 |
return key
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
class SolveRequest(BaseModel):
|
| 48 |
image_base64: str
|
| 49 |
|
|
@@ -53,6 +69,7 @@ class SolveResponse(BaseModel):
|
|
| 53 |
processing_time: float = 0.0
|
| 54 |
error: str = ""
|
| 55 |
|
|
|
|
| 56 |
app = FastAPI(title="CAPTCHA Solver API")
|
| 57 |
|
| 58 |
app.add_middleware(
|
|
@@ -62,18 +79,12 @@ app.add_middleware(
|
|
| 62 |
allow_headers=["*"],
|
| 63 |
)
|
| 64 |
|
| 65 |
-
@app.on_event("startup")
|
| 66 |
-
async def startup():
|
| 67 |
-
logger.info("Pre-warming model...")
|
| 68 |
-
load_model()
|
| 69 |
-
logger.info("β
Ready to serve")
|
| 70 |
-
|
| 71 |
@app.get("/health")
|
| 72 |
def health():
|
| 73 |
return {
|
| 74 |
"status": "ok",
|
| 75 |
-
"device":
|
| 76 |
-
"model": "
|
| 77 |
"quantized": True
|
| 78 |
}
|
| 79 |
|
|
@@ -86,33 +97,15 @@ def solve(req: SolveRequest, _: str = Depends(verify_key)):
|
|
| 86 |
raw = raw.split(",", 1)[1]
|
| 87 |
|
| 88 |
image = Image.open(io.BytesIO(base64.b64decode(raw))).convert("RGB")
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
with torch.no_grad():
|
| 92 |
-
pixel_values = processor(
|
| 93 |
-
image,
|
| 94 |
-
return_tensors="pt"
|
| 95 |
-
).pixel_values
|
| 96 |
-
|
| 97 |
-
generated_ids = model.generate(
|
| 98 |
-
pixel_values,
|
| 99 |
-
max_new_tokens=5,
|
| 100 |
-
min_new_tokens=5,
|
| 101 |
-
num_beams=2,
|
| 102 |
-
do_sample=False
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
text = processor.batch_decode(
|
| 106 |
-
generated_ids,
|
| 107 |
-
skip_special_tokens=True
|
| 108 |
-
)[0]
|
| 109 |
|
| 110 |
elapsed = time.time() - start
|
| 111 |
-
logger.info(f"β
Solved: '{text}' in {elapsed:.
|
| 112 |
|
| 113 |
return SolveResponse(
|
| 114 |
success=True,
|
| 115 |
-
text=text
|
| 116 |
processing_time=elapsed
|
| 117 |
)
|
| 118 |
|
|
@@ -125,4 +118,4 @@ def solve(req: SolveRequest, _: str = Depends(verify_key)):
|
|
| 125 |
)
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 4 |
import base64
|
| 5 |
import secrets
|
| 6 |
import logging
|
|
|
|
| 7 |
|
| 8 |
from fastapi import FastAPI, HTTPException, Security, Depends
|
| 9 |
from fastapi.security.api_key import APIKeyHeader
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from pydantic import BaseModel
|
| 12 |
from PIL import Image
|
| 13 |
+
from torchvision import transforms as T
|
| 14 |
import torch
|
| 15 |
+
import onnx
|
| 16 |
+
import onnxruntime as rt
|
| 17 |
import uvicorn
|
| 18 |
|
| 19 |
+
from utils.tokenizer_base import Tokenizer
|
| 20 |
+
|
| 21 |
logging.basicConfig(level=logging.INFO)
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
+
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 25 |
+
API_KEY = os.environ.get("API_KEY", "changeme")
|
| 26 |
+
IMG_SIZE = (32, 128)
|
| 27 |
+
VOCAB = r"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
|
| 28 |
+
MODEL_PATH = "./model/model.onnx"
|
| 29 |
|
| 30 |
+
# ββ API Key Auth ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
| 32 |
|
| 33 |
def verify_key(key: str = Security(api_key_header)):
|
|
|
|
| 35 |
raise HTTPException(status_code=401, detail="Invalid or missing API key")
|
| 36 |
return key
|
| 37 |
|
| 38 |
+
# ββ Load model once at startup ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
logger.info("Loading ONNX model...")
|
| 40 |
+
tokenizer = Tokenizer(VOCAB)
|
| 41 |
+
|
| 42 |
+
transform = T.Compose([
|
| 43 |
+
T.Resize(IMG_SIZE, T.InterpolationMode.BICUBIC),
|
| 44 |
+
T.ToTensor(),
|
| 45 |
+
T.Normalize(0.5, 0.5),
|
| 46 |
+
])
|
| 47 |
+
|
| 48 |
+
onnx_model = onnx.load(MODEL_PATH)
|
| 49 |
+
onnx.checker.check_model(onnx_model)
|
| 50 |
+
session = rt.InferenceSession(MODEL_PATH)
|
| 51 |
+
logger.info("β
ONNX model ready")
|
| 52 |
+
|
| 53 |
+
# ββ Inference βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
+
def solve_image(image: Image.Image) -> str:
|
| 55 |
+
x = transform(image.convert("RGB")).unsqueeze(0)
|
| 56 |
+
ort_inputs = {session.get_inputs()[0].name: x.numpy()}
|
| 57 |
+
logits = session.run(None, ort_inputs)[0]
|
| 58 |
+
probs = torch.tensor(logits).softmax(-1)
|
| 59 |
+
preds, _ = tokenizer.decode(probs)
|
| 60 |
+
return preds[0]
|
| 61 |
+
|
| 62 |
+
# ββ Schemas βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
class SolveRequest(BaseModel):
|
| 64 |
image_base64: str
|
| 65 |
|
|
|
|
| 69 |
processing_time: float = 0.0
|
| 70 |
error: str = ""
|
| 71 |
|
| 72 |
+
# ββ FastAPI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 73 |
app = FastAPI(title="CAPTCHA Solver API")
|
| 74 |
|
| 75 |
app.add_middleware(
|
|
|
|
| 79 |
allow_headers=["*"],
|
| 80 |
)
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
@app.get("/health")
|
| 83 |
def health():
|
| 84 |
return {
|
| 85 |
"status": "ok",
|
| 86 |
+
"device": "cpu",
|
| 87 |
+
"model": "toandev/OCR-for-Captcha (ONNX)",
|
| 88 |
"quantized": True
|
| 89 |
}
|
| 90 |
|
|
|
|
| 97 |
raw = raw.split(",", 1)[1]
|
| 98 |
|
| 99 |
image = Image.open(io.BytesIO(base64.b64decode(raw))).convert("RGB")
|
| 100 |
+
text = solve_image(image)
|
| 101 |
+
text = text.strip()[:5]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
elapsed = time.time() - start
|
| 104 |
+
logger.info(f"β
Solved: '{text}' in {elapsed:.3f}s")
|
| 105 |
|
| 106 |
return SolveResponse(
|
| 107 |
success=True,
|
| 108 |
+
text=text,
|
| 109 |
processing_time=elapsed
|
| 110 |
)
|
| 111 |
|
|
|
|
| 118 |
)
|
| 119 |
|
| 120 |
if __name__ == "__main__":
|
| 121 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|