Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,7 @@ from fastapi.responses import Response
|
|
| 3 |
from PIL import Image
|
| 4 |
import io
|
| 5 |
import torch
|
| 6 |
-
from
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
@@ -11,16 +11,18 @@ device = torch.device("cpu")
|
|
| 11 |
|
| 12 |
models = {}
|
| 13 |
|
| 14 |
-
def get_model(scale: int):
|
| 15 |
if scale not in models:
|
| 16 |
if scale == 2:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
| 20 |
elif scale == 4:
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
| 24 |
return models[scale]
|
| 25 |
|
| 26 |
@app.post("/upscale")
|
|
@@ -28,13 +30,17 @@ async def upscale(
|
|
| 28 |
image: UploadFile = File(...),
|
| 29 |
scale: int = Form(2)
|
| 30 |
):
|
| 31 |
-
model = get_model(scale)
|
| 32 |
|
| 33 |
img = Image.open(io.BytesIO(await image.read())).convert("RGB")
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
|
|
|
| 36 |
|
|
|
|
| 37 |
buffer = io.BytesIO()
|
| 38 |
-
|
| 39 |
|
| 40 |
return Response(buffer.getvalue(), media_type="image/png")
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import io
|
| 5 |
import torch
|
| 6 |
+
from spandrel import ModelLoader
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
|
|
| 11 |
|
| 12 |
models = {}
|
| 13 |
|
| 14 |
+
async def get_model(scale: int):
|
| 15 |
if scale not in models:
|
| 16 |
if scale == 2:
|
| 17 |
+
loader = ModelLoader()
|
| 18 |
+
model = loader.load_from_file("RealESRGAN_x2.pth")
|
| 19 |
+
model = model.to(device).eval()
|
| 20 |
+
models[2] = model
|
| 21 |
elif scale == 4:
|
| 22 |
+
loader = ModelLoader()
|
| 23 |
+
model = loader.load_from_file("RealESRGAN_x4.pth")
|
| 24 |
+
model = model.to(device).eval()
|
| 25 |
+
models[4] = model
|
| 26 |
return models[scale]
|
| 27 |
|
| 28 |
@app.post("/upscale")
|
|
|
|
| 30 |
image: UploadFile = File(...),
|
| 31 |
scale: int = Form(2)
|
| 32 |
):
|
| 33 |
+
model = await get_model(scale)
|
| 34 |
|
| 35 |
img = Image.open(io.BytesIO(await image.read())).convert("RGB")
|
| 36 |
+
import numpy as np
|
| 37 |
+
arr = np.array(img)
|
| 38 |
|
| 39 |
+
with torch.no_grad():
|
| 40 |
+
result = model(arr)
|
| 41 |
|
| 42 |
+
result_pil = Image.fromarray(result)
|
| 43 |
buffer = io.BytesIO()
|
| 44 |
+
result_pil.save(buffer, format="PNG")
|
| 45 |
|
| 46 |
return Response(buffer.getvalue(), media_type="image/png")
|