Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
import io
|
| 2 |
import os
|
| 3 |
import threading
|
|
|
|
| 4 |
from fastapi import FastAPI, File, UploadFile
|
| 5 |
-
from fastapi.responses import StreamingResponse
|
| 6 |
from PIL import Image
|
| 7 |
import torch
|
| 8 |
import torchvision.transforms as transforms
|
|
@@ -30,6 +31,13 @@ print(f"ONNX model loaded with providers: {providers}")
|
|
| 30 |
# Lock for thread-safe ONNX inference
|
| 31 |
onnx_lock = threading.Lock()
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
# Helper functions
|
| 34 |
def run_model_onnx(input_tensor: torch.Tensor) -> torch.Tensor:
|
| 35 |
with onnx_lock: # ensure thread safety
|
|
@@ -56,11 +64,25 @@ app = FastAPI(title="Background Removal API")
|
|
| 56 |
|
| 57 |
@app.post("/remove-background")
|
| 58 |
async def remove_background(file: UploadFile = File(...)):
|
|
|
|
|
|
|
| 59 |
image = Image.open(file.file).convert("RGB")
|
| 60 |
result_image = process_image(image)
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
buf = io.BytesIO()
|
| 63 |
result_image.save(buf, format="PNG")
|
| 64 |
buf.seek(0)
|
| 65 |
|
| 66 |
return StreamingResponse(buf, media_type="image/png")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import io
|
| 2 |
import os
|
| 3 |
import threading
|
| 4 |
+
import time
|
| 5 |
from fastapi import FastAPI, File, UploadFile
|
| 6 |
+
from fastapi.responses import StreamingResponse, JSONResponse
|
| 7 |
from PIL import Image
|
| 8 |
import torch
|
| 9 |
import torchvision.transforms as transforms
|
|
|
|
| 31 |
# Lock for thread-safe ONNX inference
|
| 32 |
onnx_lock = threading.Lock()
|
| 33 |
|
| 34 |
+
# Stats
|
| 35 |
+
stats = {
|
| 36 |
+
"completed": 0,
|
| 37 |
+
"total_time": 0.0,
|
| 38 |
+
"avg_time": 0.0,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
# Helper functions
|
| 42 |
def run_model_onnx(input_tensor: torch.Tensor) -> torch.Tensor:
|
| 43 |
with onnx_lock: # ensure thread safety
|
|
|
|
| 64 |
|
| 65 |
@app.post("/remove-background")
|
| 66 |
async def remove_background(file: UploadFile = File(...)):
|
| 67 |
+
start_time = time.time()
|
| 68 |
+
|
| 69 |
image = Image.open(file.file).convert("RGB")
|
| 70 |
result_image = process_image(image)
|
| 71 |
|
| 72 |
+
elapsed = time.time() - start_time
|
| 73 |
+
stats["completed"] += 1
|
| 74 |
+
stats["total_time"] += elapsed
|
| 75 |
+
stats["avg_time"] = stats["total_time"] / stats["completed"]
|
| 76 |
+
|
| 77 |
buf = io.BytesIO()
|
| 78 |
result_image.save(buf, format="PNG")
|
| 79 |
buf.seek(0)
|
| 80 |
|
| 81 |
return StreamingResponse(buf, media_type="image/png")
|
| 82 |
+
|
| 83 |
+
@app.get("/stats")
|
| 84 |
+
async def get_stats():
|
| 85 |
+
return JSONResponse({
|
| 86 |
+
"completed": stats["completed"],
|
| 87 |
+
"avg_time": round(stats["avg_time"], 3),
|
| 88 |
+
})
|