Commit
·
4b9df52
1
Parent(s):
7dd48b3
Async queue: /generate → job_id, /result/{id} polling
Browse files- rest_api.py +26 -6
rest_api.py
CHANGED
|
@@ -1,9 +1,14 @@
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from pydantic import BaseModel
|
|
|
|
|
|
|
| 3 |
import wai_service
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
|
|
|
|
|
|
|
|
|
| 7 |
class InferenceRequest(BaseModel):
|
| 8 |
word: str
|
| 9 |
optimized_letter: str
|
|
@@ -14,10 +19,25 @@ class InferenceRequest(BaseModel):
|
|
| 14 |
extra = "allow"
|
| 15 |
|
| 16 |
@app.post("/generate")
|
| 17 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
try:
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
from pydantic import BaseModel
|
| 3 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 4 |
+
import uuid, time
|
| 5 |
import wai_service
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
+
EXEC = ThreadPoolExecutor(max_workers=1)
|
| 10 |
+
JOBS = {} # job_id ➜ (start_ts, Future)
|
| 11 |
+
|
| 12 |
class InferenceRequest(BaseModel):
|
| 13 |
word: str
|
| 14 |
optimized_letter: str
|
|
|
|
| 19 |
extra = "allow"
|
| 20 |
|
| 21 |
@app.post("/generate")
|
| 22 |
+
def enqueue(req: InferenceRequest):
|
| 23 |
+
"""Start a job and return its UUID immediately."""
|
| 24 |
+
job_id = str(uuid.uuid4())
|
| 25 |
+
fut = EXEC.submit(wai_service.handler, dict(req.__dict__))
|
| 26 |
+
JOBS[job_id] = (time.time(), fut)
|
| 27 |
+
return {"job_id": job_id}
|
| 28 |
+
|
| 29 |
+
@app.get("/result/{job_id}")
|
| 30 |
+
def get_result(job_id: str):
|
| 31 |
+
"""Poll for job completion."""
|
| 32 |
+
if job_id not in JOBS:
|
| 33 |
+
raise HTTPException(404, "job_id not found")
|
| 34 |
+
|
| 35 |
+
start, fut = JOBS[job_id]
|
| 36 |
+
if not fut.done():
|
| 37 |
+
return {"status": "running", "elapsed": int(time.time() - start)}
|
| 38 |
+
|
| 39 |
try:
|
| 40 |
+
img = fut.result()
|
| 41 |
+
return {"status": "finished", "image_base64": img}
|
| 42 |
+
finally:
|
| 43 |
+
del JOBS[job_id] # housekeeping
|
|
|