1
0
Fork 0
onnx-web/api/onnx_web/chain/correct_gfpgan.py

82 lines
2.0 KiB
Python
Raw Normal View History

2023-01-28 23:09:19 +00:00
from logging import getLogger
from os import path
import numpy as np
2023-02-05 13:53:26 +00:00
from PIL import Image
from ..params import DeviceParams, ImageParams, StageParams, UpscaleParams
2023-02-26 20:15:30 +00:00
from ..server import ServerContext
2023-02-19 02:28:21 +00:00
from ..utils import run_gc
2023-02-26 05:49:39 +00:00
from ..worker import WorkerContext
2023-01-28 23:09:19 +00:00
logger = getLogger(__name__)
2023-02-06 23:26:51 +00:00
def load_gfpgan(
server: ServerContext,
_stage: StageParams,
2023-02-06 23:26:51 +00:00
upscale: UpscaleParams,
device: DeviceParams,
2023-02-06 23:26:51 +00:00
):
# must be within the load function for patch to take effect
from gfpgan import GFPGANer
face_path = path.join(server.cache_path, "%s.pth" % (upscale.correction_model))
cache_key = (face_path,)
cache_pipe = server.cache.get("gfpgan", cache_key)
if cache_pipe is not None:
2023-02-05 13:53:26 +00:00
logger.info("reusing existing GFPGAN pipeline")
return cache_pipe
2023-02-05 13:53:26 +00:00
logger.debug("loading GFPGAN model from %s", face_path)
# TODO: find a way to pass the ONNX model to underlying architectures
gfpgan = GFPGANer(
2023-02-05 13:53:26 +00:00
arch="clean",
bg_upsampler=None,
channel_multiplier=2,
model_path=face_path,
upscale=upscale.face_outscale,
2023-02-05 13:53:26 +00:00
)
server.cache.set("gfpgan", cache_key, gfpgan)
run_gc([device])
return gfpgan
def correct_gfpgan(
2023-02-26 05:49:39 +00:00
job: WorkerContext,
server: ServerContext,
stage: StageParams,
_params: ImageParams,
source: Image.Image,
*,
upscale: UpscaleParams,
stage_source: Image.Image,
**kwargs,
) -> Image.Image:
upscale = upscale.with_args(**kwargs)
source = stage_source or source
if upscale.correction_model is None:
2023-02-05 13:53:26 +00:00
logger.warn("no face model given, skipping")
return source
2023-02-05 13:53:26 +00:00
logger.info("correcting faces with GFPGAN model: %s", upscale.correction_model)
device = job.get_device()
gfpgan = load_gfpgan(server, stage, upscale, device)
output = np.array(source)
_, _, output = gfpgan.enhance(
2023-02-05 13:53:26 +00:00
output,
has_aligned=False,
only_center_face=False,
paste_back=True,
weight=upscale.face_strength,
)
output = Image.fromarray(output, "RGB")
return output