Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,20 +2,60 @@ from fastapi import FastAPI, UploadFile, File, Form
|
|
| 2 |
from fastapi.responses import Response
|
| 3 |
from PIL import Image
|
| 4 |
import io
|
|
|
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
@app.post("/upscale")
|
| 9 |
async def upscale(
|
| 10 |
image: UploadFile = File(...),
|
| 11 |
scale: int = Form(2)
|
| 12 |
):
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from fastapi.responses import Response
|
| 3 |
from PIL import Image
|
| 4 |
import io
|
| 5 |
+
import torch
|
| 6 |
+
import numpy as np
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
device = torch.device("cpu")
|
| 11 |
+
torch.set_num_threads(1)
|
| 12 |
+
|
| 13 |
+
models = {}
|
| 14 |
+
|
| 15 |
+
def get_model(scale: int):
|
| 16 |
+
if scale not in models:
|
| 17 |
+
model = torch.hub.load(
|
| 18 |
+
"eugenesiow/edsr",
|
| 19 |
+
"edsr_base",
|
| 20 |
+
scale=scale,
|
| 21 |
+
pretrained=True,
|
| 22 |
+
skip_validation=True,
|
| 23 |
+
)
|
| 24 |
+
model = model.to(device).eval()
|
| 25 |
+
models[scale] = model
|
| 26 |
+
return models[scale]
|
| 27 |
+
|
| 28 |
@app.post("/upscale")
|
| 29 |
async def upscale(
|
| 30 |
image: UploadFile = File(...),
|
| 31 |
scale: int = Form(2)
|
| 32 |
):
|
| 33 |
+
try:
|
| 34 |
+
model = get_model(scale)
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return Response(
|
| 37 |
+
f"Model load failed: {type(e).__name__}: {e}",
|
| 38 |
+
status_code=500,
|
| 39 |
+
media_type="text/plain",
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
img = Image.open(io.BytesIO(await image.read())).convert("RGB")
|
| 44 |
+
|
| 45 |
+
with torch.no_grad():
|
| 46 |
+
sr = model(img)
|
| 47 |
|
| 48 |
+
sr_pil = sr.squeeze(0).clamp(0, 1).cpu().numpy()
|
| 49 |
+
sr_pil = np.transpose(sr_pil, (1, 2, 0))
|
| 50 |
+
sr_pil = (sr_pil * 255).astype(np.uint8)
|
| 51 |
+
sr_pil = Image.fromarray(sr_pil)
|
| 52 |
|
| 53 |
+
buffer = io.BytesIO()
|
| 54 |
+
sr_pil.save(buffer, format="PNG")
|
| 55 |
+
return Response(buffer.getvalue(), media_type="image/png")
|
| 56 |
+
except Exception as e:
|
| 57 |
+
return Response(
|
| 58 |
+
f"Upscale failed: {type(e).__name__}: {e}",
|
| 59 |
+
status_code=500,
|
| 60 |
+
media_type="text/plain",
|
| 61 |
+
)
|