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

85 lines
2.2 KiB
Python
Raw Normal View History

2023-01-28 23:09:19 +00:00
from logging import getLogger
from os import path
from typing import Optional
import numpy as np
2023-02-05 13:53:26 +00:00
from gfpgan import GFPGANer
from PIL import Image
from realesrgan import RealESRGANer
from ..device_pool import JobContext
from ..params import ImageParams, StageParams, UpscaleParams
from ..utils import ServerContext, run_gc
from .upscale_resrgan import load_resrgan
2023-01-28 23:09:19 +00:00
logger = getLogger(__name__)
last_pipeline_instance = None
last_pipeline_params = None
2023-02-05 13:53:26 +00:00
def load_gfpgan(
ctx: ServerContext, upscale: UpscaleParams, upsampler: Optional[RealESRGANer] = None
):
2023-01-28 06:08:52 +00:00
global last_pipeline_instance
global last_pipeline_params
if upsampler is None:
bg_upscale = upscale.rescale(upscale.outscale)
upsampler = load_resrgan(ctx, bg_upscale)
2023-02-05 13:53:26 +00:00
face_path = path.join(ctx.model_path, "%s.pth" % (upscale.correction_model))
2023-02-05 13:53:26 +00:00
if last_pipeline_instance is not None and face_path == last_pipeline_params:
logger.info("reusing existing GFPGAN pipeline")
return last_pipeline_instance
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(
model_path=face_path,
upscale=upscale.outscale,
2023-02-05 13:53:26 +00:00
arch="clean",
channel_multiplier=2,
2023-02-05 13:53:26 +00:00
bg_upsampler=upsampler,
)
last_pipeline_instance = gfpgan
last_pipeline_params = face_path
run_gc()
return gfpgan
def correct_gfpgan(
_job: JobContext,
server: ServerContext,
_stage: StageParams,
_params: ImageParams,
source_image: Image.Image,
*,
upscale: UpscaleParams,
upsampler: Optional[RealESRGANer] = None,
**kwargs,
) -> Image.Image:
if upscale.correction_model is None:
2023-02-05 13:53:26 +00:00
logger.warn("no face model given, skipping")
2023-01-31 14:24:10 +00:00
return source_image
2023-02-05 13:53:26 +00:00
logger.info("correcting faces with GFPGAN model: %s", upscale.correction_model)
gfpgan = load_gfpgan(server, upscale, upsampler=upsampler)
output = np.array(source_image)
_, _, 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