Brazela commited on
Commit
a0543c2
·
verified ·
1 Parent(s): 29d89b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -15
app.py CHANGED
@@ -2,8 +2,8 @@ from fastapi import FastAPI, UploadFile, File, Form
2
  from fastapi.responses import Response
3
  from PIL import Image
4
  import io
 
5
  import torch
6
- from spandrel import ModelLoader
7
 
8
  app = FastAPI()
9
 
@@ -11,17 +11,15 @@ device = torch.device("cpu")
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
 
@@ -30,17 +28,13 @@ async def 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")
 
2
  from fastapi.responses import Response
3
  from PIL import Image
4
  import io
5
+ from realesrgan import RealESRGAN
6
  import torch
 
7
 
8
  app = FastAPI()
9
 
 
11
 
12
  models = {}
13
 
14
+ def get_model(scale: int):
15
  if scale not in models:
16
  if scale == 2:
17
+ model = RealESRGAN(device, scale=2)
18
+ model.load_weights("RealESRGAN_x2.pth", download=True)
 
19
  models[2] = model
20
  elif scale == 4:
21
+ model = RealESRGAN(device, scale=4)
22
+ model.load_weights("RealESRGAN_x4.pth", download=True)
 
23
  models[4] = model
24
  return models[scale]
25
 
 
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
+ result = model.predict(img)
 
36
 
 
37
  buffer = io.BytesIO()
38
+ result.save(buffer, format="PNG")
39
 
40
  return Response(buffer.getvalue(), media_type="image/png")