iresidentevil's picture
Update app.py
b651bcd verified
import gradio as gr
import numpy as np
import random
from rembg import remove
from copy import deepcopy
# import spaces # [uncomment to use ZeroGPU]
from diffusers import StableDiffusionPipeline
import torch
from peft import PeftModel, PeftConfig
import os
os.environ['TRANSFORMERS_OFFLINE'] = '0'
os.environ['HF_HUB_OFFLINE'] = '0'
device = "cuda" if torch.cuda.is_available() else "cpu"
MODEL_OPTIONS = [
"Stable Diffusion v1-4",
"Chris the mouse Adapter"
]
DEFAULT_MODEL_ID = "Stable Diffusion v1-4"
if torch.cuda.is_available():
torch_dtype = torch.float16
else:
torch_dtype = torch.float32
MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 1024
PIPELINES = {}
def load_pipelines():
# SD v1-4
mid = "CompVis/stable-diffusion-v1-4"
pipe = StableDiffusionPipeline.from_pretrained(
mid,
torch_dtype=torch_dtype,
use_safetensors=True
)
pipe = pipe.to(device)
PIPELINES["Stable Diffusion v1-4"] = pipe
# lora adapter
lora_adapter_id = "iresidentevil/lora-sd-v1-4-chris-the-mouse"
pipe_lora = deepcopy(pipe)
pipe_lora.unet = PeftModel.from_pretrained(
pipe_lora.unet,
lora_adapter_id,
adapter_name="default",
subfolder="unet"
)
pipe_lora.text_encoder = PeftModel.from_pretrained(
pipe_lora.text_encoder,
lora_adapter_id,
adapter_name="default",
subfolder="text_encoder"
)
pipe_lora = pipe_lora.to(device)
PIPELINES["Chris the mouse Adapter"] = pipe_lora
# Вызываем сразу при импорте (на сборке образа и при старте Space)
load_pipelines()
def remove_background(image):
"""Удаление фона"""
if image is None:
return None
result = remove(image)
return result
# @spaces.GPU # [uncomment to use ZeroGPU]
def infer(
model_id,
prompt,
negative_prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
remove_bg, # параметр для удаления фона
lora_scale, # параметр для масштаба LoRA
progress=gr.Progress(track_tqdm=True),
):
if randomize_seed:
seed = random.randint(0, MAX_SEED)
generator = torch.Generator().manual_seed(seed)
pipe = PIPELINES[model_id]
# Применяем масштаб LoRA если выбран адаптер и scale != 1.0
if "Adapter" in model_id and lora_scale != 1.0:
pipe.unet.scale_layer(lora_scale)
pipe.text_encoder.scale_layer(lora_scale)
image = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
width=width,
height=height,
generator=generator,
).images[0]
# Удаляем фон если выбрана соответствующая опция
if remove_bg:
image = remove_background(image)
return image, seed
examples = [
"chris_the_mouse with wide, surprised eyes, single black nostril, shaded gray body, and exaggeratedly large pink ears on a plain black background, drawn in a minimalist cartoon style.",
"chris_the_mouse with one eye wide open, mouth agape in shock, red tongue showing, left ear bent, bold black outline, simple cartoon style, white background.",
"chris_the_mouse with large pink ears, wide black eyes gazing upward, clasped hands, and a small smile, set against a plain background in a cartoon sticker style.",
]
css = """
#col-container {
margin: 0 auto;
max-width: 640px;
}
"""
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(" # Text-to-Image Gradio Template")
model_id = gr.Dropdown(
choices=MODEL_OPTIONS,
label="Model",
value=DEFAULT_MODEL_ID,
)
with gr.Row():
prompt = gr.Text(
label="Prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
container=False,
)
negative_prompt = gr.Text(
label="Negative prompt",
max_lines=1,
placeholder="Enter a negative prompt",
visible=True,
)
remove_bg = gr.Checkbox(
label="Delete background?",
value=False,
info="Remove background using rembg"
)
lora_scale = gr.Slider(
label="LoRA scale",
minimum=0.0,
maximum=2.0,
step=0.1,
value=1.0,
visible=False,
info="Adjust LoRA adapter strength"
)
run_button = gr.Button("Run", scale=0, variant="primary")
result = gr.Image(label="Result", show_label=False)
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
with gr.Row():
width = gr.Slider(
label="Width",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=256,
maximum=MAX_IMAGE_SIZE,
step=32,
value=1024,
)
with gr.Row():
guidance_scale = gr.Slider(
label="Guidance scale",
minimum=0.0,
maximum=10.0,
step=0.1,
value=7.5,
)
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=50,
step=1,
value=20,
)
gr.Examples(examples=examples, inputs=[prompt])
# Функция для показа/скрытия слайдера LoRA scale
def toggle_lora_scale_visibility(model_id):
if "Adapter" in model_id:
return gr.Slider(visible=True)
else:
return gr.Slider(visible=False)
# Обработчик изменения модели
model_id.change(
fn=toggle_lora_scale_visibility,
inputs=[model_id],
outputs=[lora_scale]
)
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[
model_id,
prompt,
negative_prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
remove_bg,
lora_scale,
],
outputs=[result, seed],
)
if __name__ == "__main__":
demo.launch()