Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -19,35 +19,46 @@ def get_model(scale: int):
|
|
| 19 |
return models[scale]
|
| 20 |
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@app.post("/upscale")
|
| 23 |
async def upscale(image: UploadFile = File(...), scale: int = Form(2)):
|
| 24 |
try:
|
| 25 |
-
|
| 26 |
except Exception as e:
|
| 27 |
return Response(
|
| 28 |
-
f"
|
| 29 |
status_code=500,
|
| 30 |
media_type="text/plain",
|
| 31 |
)
|
| 32 |
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
ImageLoader.save_image(pred, path)
|
| 41 |
-
os.close(fd)
|
| 42 |
-
with open(path, "rb") as f:
|
| 43 |
-
data = f.read()
|
| 44 |
-
finally:
|
| 45 |
-
os.unlink(path)
|
| 46 |
-
|
| 47 |
-
return Response(data, media_type="image/png")
|
| 48 |
except Exception as e:
|
| 49 |
return Response(
|
| 50 |
f"Upscale failed: {type(e).__name__}: {e}",
|
| 51 |
status_code=500,
|
| 52 |
media_type="text/plain",
|
| 53 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
return models[scale]
|
| 20 |
|
| 21 |
|
| 22 |
+
def _upscale_image(img: Image.Image, scale: int) -> Image.Image:
|
| 23 |
+
model = get_model(scale)
|
| 24 |
+
inputs = ImageLoader.load_image(img)
|
| 25 |
+
pred = model(inputs)
|
| 26 |
+
fd, path = tempfile.mkstemp(suffix=".png")
|
| 27 |
+
try:
|
| 28 |
+
ImageLoader.save_image(pred, path)
|
| 29 |
+
os.close(fd)
|
| 30 |
+
result = Image.open(path).convert("RGB")
|
| 31 |
+
result.load()
|
| 32 |
+
finally:
|
| 33 |
+
os.unlink(path)
|
| 34 |
+
return result
|
| 35 |
+
|
| 36 |
+
|
| 37 |
@app.post("/upscale")
|
| 38 |
async def upscale(image: UploadFile = File(...), scale: int = Form(2)):
|
| 39 |
try:
|
| 40 |
+
img = Image.open(io.BytesIO(await image.read())).convert("RGB")
|
| 41 |
except Exception as e:
|
| 42 |
return Response(
|
| 43 |
+
f"Image load failed: {type(e).__name__}: {e}",
|
| 44 |
status_code=500,
|
| 45 |
media_type="text/plain",
|
| 46 |
)
|
| 47 |
|
| 48 |
try:
|
| 49 |
+
if scale == 8:
|
| 50 |
+
# Chain: 4x → 2x
|
| 51 |
+
img = _upscale_image(img, 4)
|
| 52 |
+
img = _upscale_image(img, 2)
|
| 53 |
+
else:
|
| 54 |
+
img = _upscale_image(img, scale)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
except Exception as e:
|
| 56 |
return Response(
|
| 57 |
f"Upscale failed: {type(e).__name__}: {e}",
|
| 58 |
status_code=500,
|
| 59 |
media_type="text/plain",
|
| 60 |
)
|
| 61 |
+
|
| 62 |
+
buf = io.BytesIO()
|
| 63 |
+
img.save(buf, format="PNG")
|
| 64 |
+
return Response(buf.getvalue(), media_type="image/png")
|