ihtesham0345 commited on
Commit
07a2aab
·
1 Parent(s): a8c74c5

Async InvSR: POST returns job_id instantly, poll for result (fixes Swagger timeout)

Browse files
Files changed (1) hide show
  1. app.py +30 -5
app.py CHANGED
@@ -73,6 +73,8 @@ _INVSR_PATH = Path("/app/InvSR")
73
  _sampler_invsr = None
74
  _invsr_status = "not_loaded"
75
  _invsr_error = None
 
 
76
 
77
  def _patch_invsr_source():
78
  p = _INVSR_PATH / "sampler_invsr.py"
@@ -261,10 +263,33 @@ async def route_metrics(file: UploadFile = File(...)):
261
 
262
  @app.post("/upscale/invsr")
263
  async def route_invsr(file: UploadFile = File(...), num_steps: int = Query(1, ge=1, le=5)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  try:
265
- result = upscale_invsr(await file.read(), num_steps=num_steps)
266
- except HTTPException:
267
- raise
268
  except Exception as e:
269
- raise HTTPException(500, f"InvSR failed: {e}")
270
- return StreamingResponse(BytesIO(result), media_type="image/png")
 
 
 
 
 
 
 
 
 
 
73
  _sampler_invsr = None
74
  _invsr_status = "not_loaded"
75
  _invsr_error = None
76
+ _invsr_jobs: dict[str, dict] = {}
77
+ _job_counter = 0
78
 
79
  def _patch_invsr_source():
80
  p = _INVSR_PATH / "sampler_invsr.py"
 
263
 
264
  @app.post("/upscale/invsr")
265
  async def route_invsr(file: UploadFile = File(...), num_steps: int = Query(1, ge=1, le=5)):
266
+ if _invsr_status == "error":
267
+ raise HTTPException(500, f"InvSR not loaded: {_invsr_error}")
268
+ if _sampler_invsr is None:
269
+ raise HTTPException(503, f"InvSR is {_invsr_status}. Check /health for status.")
270
+ global _job_counter
271
+ _job_counter += 1
272
+ job_id = str(_job_counter)
273
+ _invsr_jobs[job_id] = {"status": "queued", "image_bytes": await file.read(), "num_steps": num_steps}
274
+ threading.Thread(target=_run_invsr_job, args=(job_id,), daemon=True).start()
275
+ return JSONResponse({"job_id": job_id, "status": "queued", "check": f"/upscale/invsr/{job_id}"})
276
+
277
+ def _run_invsr_job(job_id: str):
278
+ job = _invsr_jobs.get(job_id)
279
+ if not job: return
280
  try:
281
+ job["status"] = "processing"
282
+ job["result"] = upscale_invsr(job["image_bytes"], job["num_steps"])
283
+ job["status"] = "done"
284
  except Exception as e:
285
+ job["status"] = "error"
286
+ job["error"] = str(e)
287
+
288
+ @app.get("/upscale/invsr/{job_id}")
289
+ async def route_invsr_status(job_id: str):
290
+ job = _invsr_jobs.get(job_id)
291
+ if not job:
292
+ raise HTTPException(404, "Job not found")
293
+ if job["status"] == "done":
294
+ return StreamingResponse(BytesIO(job["result"]), media_type="image/png")
295
+ return JSONResponse({"job_id": job_id, "status": job["status"], "error": job.get("error")})