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

86 lines
2.4 KiB
Python
Raw Normal View History

2023-01-28 23:09:19 +00:00
from logging import getLogger
from os import path
2023-02-05 13:53:26 +00:00
import torch
from diffusers import StableDiffusionUpscalePipeline
from PIL import Image
2023-01-29 17:42:42 +00:00
from ..diffusion.pipeline_onnx_stable_diffusion_upscale import (
OnnxStableDiffusionUpscalePipeline,
)
2023-02-05 13:53:26 +00:00
from ..params import DeviceParams, ImageParams, StageParams, UpscaleParams
from ..server.device_pool import JobContext, ProgressCallback
2023-02-05 13:53:26 +00:00
from ..utils import ServerContext, run_gc
2023-01-28 23:09:19 +00:00
logger = getLogger(__name__)
last_pipeline_instance = None
last_pipeline_params = (None, None)
2023-02-05 13:53:26 +00:00
def load_stable_diffusion(
ctx: ServerContext, upscale: UpscaleParams, device: DeviceParams
):
2023-01-28 06:08:52 +00:00
global last_pipeline_instance
global last_pipeline_params
model_path = path.join(ctx.model_path, upscale.upscale_model)
cache_params = (model_path, upscale.format)
2023-02-05 13:53:26 +00:00
if last_pipeline_instance is not None and cache_params == last_pipeline_params:
logger.debug("reusing existing Stable Diffusion upscale pipeline")
return last_pipeline_instance
2023-02-05 13:53:26 +00:00
if upscale.format == "onnx":
logger.debug(
"loading Stable Diffusion upscale ONNX model from %s, using provider %s",
model_path,
device.provider,
)
pipeline = OnnxStableDiffusionUpscalePipeline.from_pretrained(
model_path, provider=device.provider, provider_options=device.options
)
else:
2023-02-05 13:53:26 +00:00
logger.debug(
"loading Stable Diffusion upscale model from %s, using provider %s",
model_path,
device.provider,
)
pipeline = StableDiffusionUpscalePipeline.from_pretrained(
model_path, provider=device.provider
)
last_pipeline_instance = pipeline
last_pipeline_params = cache_params
run_gc()
return pipeline
def upscale_stable_diffusion(
job: JobContext,
server: ServerContext,
_stage: StageParams,
params: ImageParams,
source: Image.Image,
*,
upscale: UpscaleParams,
2023-01-29 05:06:25 +00:00
prompt: str = None,
2023-02-12 18:22:11 +00:00
callback: ProgressCallback = None,
**kwargs,
) -> Image.Image:
2023-01-29 05:06:25 +00:00
prompt = prompt or params.prompt
2023-02-05 13:53:26 +00:00
logger.info("upscaling with Stable Diffusion, %s steps: %s", params.steps, prompt)
pipeline = load_stable_diffusion(server, upscale, job.get_device())
2023-01-30 00:42:05 +00:00
generator = torch.manual_seed(params.seed)
return pipeline(
params.prompt,
source,
2023-01-29 22:57:18 +00:00
generator=generator,
num_inference_steps=params.steps,
callback=callback,
).images[0]