1
0
Fork 0
onnx-web/api/onnx_web/upscale.py

191 lines
5.4 KiB
Python
Raw Normal View History

2023-01-16 00:04:10 +00:00
from basicsr.archs.rrdbnet_arch import RRDBNet
from gfpgan import GFPGANer
from onnxruntime import InferenceSession
2023-01-16 00:04:10 +00:00
from os import path
from PIL import Image
from realesrgan import RealESRGANer
from typing import Any, Literal, Union
2023-01-16 00:04:10 +00:00
import numpy as np
import torch
from .utils import (
2023-01-16 21:11:40 +00:00
ServerContext,
Size,
)
# TODO: these should all be params or config
2023-01-16 00:04:10 +00:00
pre_pad = 0
tile_pad = 10
2023-01-16 17:06:50 +00:00
class ONNXImage():
def __init__(self, source) -> None:
self.source = source
self.data = self
2023-01-16 18:02:37 +00:00
def __getitem__(self, *args):
return torch.from_numpy(self.source.__getitem__(*args)).to(torch.float32)
def squeeze(self):
self.source = np.squeeze(self.source, (0))
return self
def float(self):
return self
def cpu(self):
return self
2023-01-16 17:45:31 +00:00
def clamp_(self, min, max):
self.source = np.clip(self.source, min, max)
2023-01-16 17:46:06 +00:00
return self
def numpy(self):
return self.source
2023-01-16 17:06:50 +00:00
2023-01-16 20:52:56 +00:00
def size(self):
return np.shape(self.source)
class ONNXNet():
'''
2023-01-16 21:11:40 +00:00
Provides the RRDBNet interface using an ONNX session for DirectML acceleration.
'''
2023-01-16 20:58:27 +00:00
def __init__(self, ctx: ServerContext, model: str, provider='DmlExecutionProvider') -> None:
'''
TODO: get platform provider from request params
'''
2023-01-16 20:58:27 +00:00
model_path = path.join(ctx.model_path, model)
self.session = InferenceSession(
2023-01-16 20:58:27 +00:00
model_path, providers=[provider])
def __call__(self, image: Any) -> Any:
input_name = self.session.get_inputs()[0].name
output_name = self.session.get_outputs()[0].name
output = self.session.run([output_name], {
input_name: image.cpu().numpy()
})[0]
2023-01-16 17:06:50 +00:00
return ONNXImage(output)
def eval(self) -> None:
pass
def half(self):
return self
2023-01-22 16:08:26 +00:00
def load_state_dict(self, _net, _strict=True) -> None:
pass
2023-01-22 16:08:26 +00:00
def to(self, _device):
return self
2023-01-16 00:04:10 +00:00
class UpscaleParams():
2023-01-16 20:52:56 +00:00
def __init__(
self,
upscale_model: str,
provider: str,
2023-01-17 02:10:52 +00:00
correction_model: Union[str, None] = None,
2023-01-16 20:52:56 +00:00
denoise: float = 0.5,
faces=True,
face_strength: float = 0.5,
format: Literal['onnx', 'pth'] = 'onnx',
half=False,
outscale: int = 1,
scale: int = 4,
2023-01-16 20:52:56 +00:00
) -> None:
self.upscale_model = upscale_model
self.provider = provider
2023-01-17 02:10:52 +00:00
self.correction_model = correction_model
2023-01-16 20:52:56 +00:00
self.denoise = denoise
self.faces = faces
self.face_strength = face_strength
self.format = format
2023-01-16 20:52:56 +00:00
self.half = half
self.outscale = outscale
self.scale = scale
2023-01-16 21:11:40 +00:00
def resize(self, size: Size) -> Size:
return Size(size.width * self.outscale, size.height * self.outscale)
2023-01-16 21:11:40 +00:00
def make_resrgan(ctx: ServerContext, params: UpscaleParams, tile=0):
model_file = '%s.%s' % (params.upscale_model, params.format)
2023-01-16 20:58:27 +00:00
model_path = path.join(ctx.model_path, model_file)
2023-01-16 00:04:10 +00:00
if not path.isfile(model_path):
2023-01-16 20:52:56 +00:00
raise Exception('Real ESRGAN model not found at %s' % model_path)
2023-01-16 00:04:10 +00:00
# use ONNX acceleration, if available
if params.format == 'onnx':
model = ONNXNet(ctx, model_file, provider=params.provider)
elif params.format == 'pth':
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64,
num_block=23, num_grow_ch=32, scale=params.scale)
2023-01-16 20:52:56 +00:00
else:
raise Exception('unknown platform %s' % params.format)
2023-01-16 00:04:10 +00:00
dni_weight = None
2023-01-16 20:52:56 +00:00
if params.upscale_model == 'realesr-general-x4v3' and params.denoise != 1:
2023-01-16 00:04:10 +00:00
wdn_model_path = model_path.replace(
'realesr-general-x4v3', 'realesr-general-wdn-x4v3')
model_path = [model_path, wdn_model_path]
dni_weight = [params.denoise, 1 - params.denoise]
2023-01-16 00:04:10 +00:00
2023-01-16 21:11:40 +00:00
# TODO: shouldn't need the PTH file
2023-01-16 00:04:10 +00:00
upsampler = RealESRGANer(
scale=params.scale,
2023-01-16 21:11:40 +00:00
model_path=path.join(ctx.model_path, '%s.pth' % params.upscale_model),
2023-01-16 00:04:10 +00:00
dni_weight=dni_weight,
model=model,
tile=tile,
tile_pad=tile_pad,
pre_pad=pre_pad,
2023-01-16 20:52:56 +00:00
half=params.half)
2023-01-16 00:04:10 +00:00
return upsampler
def upscale_resrgan(ctx: ServerContext, params: UpscaleParams, source_image: Image) -> Image:
print('upscaling image with Real ESRGAN', params.scale)
2023-01-17 05:01:15 +00:00
output = np.array(source_image)
2023-01-17 04:35:34 +00:00
upsampler = make_resrgan(ctx, params, tile=512)
2023-01-17 05:01:15 +00:00
if params.scale > 1:
output, _ = upsampler.enhance(output, outscale=params.outscale)
2023-01-16 00:04:10 +00:00
if params.faces:
2023-01-17 04:35:34 +00:00
output = upscale_gfpgan(ctx, params, output, upsampler=upsampler)
output = Image.fromarray(output, 'RGB')
print('final output image size', output.size)
return output
2023-01-16 00:04:10 +00:00
def upscale_gfpgan(ctx: ServerContext, params: UpscaleParams, image, upsampler=None) -> Image:
2023-01-17 02:10:52 +00:00
print('correcting faces with GFPGAN model: %s' % params.correction_model)
2023-01-16 20:52:56 +00:00
2023-01-17 02:10:52 +00:00
if params.correction_model is None:
2023-01-16 20:52:56 +00:00
print('no face model given, skipping')
return image
if upsampler is None:
2023-01-17 04:35:34 +00:00
upsampler = make_resrgan(ctx, params)
2023-01-17 02:10:52 +00:00
face_path = path.join(ctx.model_path, '%s.pth' % (params.correction_model))
# TODO: doesn't have a model param, not sure how to pass ONNX model
2023-01-16 00:04:10 +00:00
face_enhancer = GFPGANer(
model_path=face_path,
2023-01-16 20:52:56 +00:00
upscale=params.outscale,
2023-01-16 00:04:10 +00:00
arch='clean',
channel_multiplier=2,
bg_upsampler=upsampler)
_, _, output = face_enhancer.enhance(
image, has_aligned=False, only_center_face=False, paste_back=True, weight=params.face_strength)
2023-01-16 00:04:10 +00:00
return output