from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler, DPMSolverMultistepScheduler, AutoencoderKL import torch loaded_pipe = None loaded_pipe_id = None vae_model_path = "https://huggingface.co/madebyollin/sdxl-vae-fp16-fix/resolve/main/sdxl_vae.safetensors" def load_model(pipe_id, unet_model_id): global loaded_pipe, loaded_pipe_id if loaded_pipe_id != pipe_id: unet = UNet2DConditionModel.from_pretrained( unet_model_id, torch_dtype=torch.float16, variant="fp16", ) vae = AutoencoderKL.from_single_file(vae_model_path) loaded_pipe = StableDiffusionXLPipeline.from_pretrained( pipe_id, unet=unet, vae=vae, torch_dtype=torch.float16, variant="fp16", ).to("cuda") loaded_pipe_id = pipe_id return loaded_pipe def set_scheduler(pipe, scheduler_type): if scheduler_type == "LCM": pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config) elif scheduler_type == "DPM++ 2M Karras": pipe.scheduler = DPMSolverMultistepScheduler(use_karras_sigmas="yes") return pipe def generate_image(prompt, num_inference_steps, seed, guidance_scale, negative_prompt=None, pipe_id="Linaqruf/animagine-xl", unet_model_id="latent-consistency/lcm-sdxl", scheduler_type="LCM"): global loaded_pipe pipe = load_model(pipe_id, unet_model_id) pipe = set_scheduler(pipe, scheduler_type) generator = torch.manual_seed(seed) image = pipe(prompt=prompt, negative_prompt=negative_prompt, num_inference_steps=num_inference_steps, generator=generator, guidance_scale=guidance_scale).images[0] return image