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

89 lines
2.5 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
from ..diffusion.load import optimize_pipeline
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__)
2023-02-05 13:53:26 +00:00
def load_stable_diffusion(
server: ServerContext, upscale: UpscaleParams, device: DeviceParams
2023-02-05 13:53:26 +00:00
):
model_path = path.join(server.model_path, upscale.upscale_model)
2023-01-28 06:08:52 +00:00
cache_key = (model_path, upscale.format)
cache_pipe = server.cache.get("diffusion", cache_key)
if cache_pipe is not None:
logger.debug("reusing existing Stable Diffusion upscale pipeline")
return cache_pipe
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,
)
pipe = OnnxStableDiffusionUpscalePipeline.from_pretrained(
model_path,
provider=device.ort_provider(),
sess_options=device.sess_options(),
2023-02-05 13:53:26 +00:00
)
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,
)
pipe = StableDiffusionUpscalePipeline.from_pretrained(
model_path,
provider=device.provider,
2023-02-05 13:53:26 +00:00
)
if not server.show_progress:
pipe.set_progress_bar_config(disable=True)
optimize_pipeline(server, pipe)
server.cache.set("diffusion", cache_key, pipe)
run_gc([device])
return pipe
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]