sdxs / pipeline_sdxs.py
recoilme's picture
Update pipeline_sdxs.py
3d8b2a1 verified
import gradio as gr
import numpy as np
import random
import spaces
import torch
from diffusers import DiffusionPipeline, AutoencoderKL, UNet2DConditionModel, FlowMatchEulerDiscreteScheduler,AsymmetricAutoencoderKL
from transformers import AutoModelForCausalLM, AutoTokenizer
from typing import Optional, Union, List, Tuple
from PIL import Image
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
model_repo_id = "AiArtLab/sdxs-08b"
pipe = DiffusionPipeline.from_pretrained(
model_repo_id,
torch_dtype=dtype,
trust_remote_code=True
).to(device)
# НОВОЕ: Инициализация Qwen3 для рефайнинга
llm_model_id = "Qwen/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(llm_model_id)
llm_model = AutoModelForCausalLM.from_pretrained(llm_model_id, torch_dtype="auto", device_map="auto")
MAX_SEED = np.iinfo(np.int32).max
MIN_IMAGE_SIZE = 640
MAX_IMAGE_SIZE = 1280
STEP = 64
# НОВОЕ: Настройки для LLM
END_THINK_TOKEN_ID = 151668
DEFAULT_REFINE_TEMPLATE = (
"You are a skilled text-to-image prompt engineer whose sole function is to transform the user's input into an aesthetically optimized, detailed, and visually descriptive three-sentence output. "
"**The primary subject (e.g., 'girl', 'dog', 'house') MUST be the main focus of the revised prompt and MUST be described in rich detail within the first sentence or two.** "
"Output **only** the final revised prompt in **English**, with absolutely no commentary, thinking text, or surrounding quotes.\n"
"User input prompt: {prompt}"
)
@spaces.GPU(duration=30)
def infer(
prompt: str,
negative_prompt: str,
seed: int,
randomize_seed: bool,
width: int,
height: int,
guidance_scale: float,
num_inference_steps: int,
refine_prompt: bool,
progress=gr.Progress(track_tqdm=True),
) -> Tuple[Image.Image, int, str]: # Возвращаем prompt в конце
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# НОВОЕ: Логика улучшения промпта
if refine_prompt and prompt:
messages = [{"role": "user", "content": DEFAULT_REFINE_TEMPLATE.format(prompt=prompt)}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=True)
model_inputs = tokenizer([text], return_tensors="pt").to(llm_model.device)
generated_ids = llm_model.generate(**model_inputs, max_new_tokens=2048, do_sample=True, pad_token_id=tokenizer.eos_token_id)
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
try:
index = len(output_ids) - output_ids[::-1].index(END_THINK_TOKEN_ID)
except ValueError:
index = 0
prompt = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n").strip()
output = pipe(
prompt=prompt,
negative_prompt=negative_prompt,
guidance_scale=guidance_scale,
num_inference_steps=num_inference_steps,
width=width,
height=height,
seed=seed,
)
image = output.images[0]
return image, seed, prompt # Возвращаем измененный промпт
examples = [
"A frozen river, surrounded by snow-covered trees, reflects the clear blue sky, with a warm glow from the setting sun.",
"A young woman with striking blue eyes and pointed ears, adorned with a floral kimono and a tattoo. Her hair is styled in a braid, and she wears a pair of ears",
"A volcano explodes, creating a skull face shadow in embers with lightning illuminating the clouds.",
"There is a young male character standing against a vibrant, colorful graffiti wall. he is wearing a straw hat, a black jacket adorned with gold accents, and black shorts.",
"A man with dark hair and a beard is meticulously carving an intricate design on a piece of pottery. He is wearing a traditional scarf and a white shirt, and he is focused on his work.",
"girl, smiling, red eyes, blue hair, white shirt"
]
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(" # Simple Diffusion (sdxs-08b)")
with gr.Row():
prompt = gr.Text(
label="Prompt",
show_label=False,
max_lines=5,
placeholder="Enter your prompt",
container=False,
)
run_button = gr.Button("Run", scale=0, variant="primary")
result = gr.Image(label="Result", show_label=False)
with gr.Accordion("Advanced Settings", open=False):
# Изменено value на True
refine_prompt = gr.Checkbox(label="Refine Prompt with Qwen3", value=True)
negative_prompt = gr.Text(
label="Negative prompt",
max_lines=1,
placeholder="Enter a negative prompt",
value ="bad quality, low resolution"
)
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=MIN_IMAGE_SIZE,
maximum=MAX_IMAGE_SIZE,
step=STEP,
value=1024,
)
height = gr.Slider(
label="Height",
minimum=MIN_IMAGE_SIZE,
maximum=MAX_IMAGE_SIZE,
step=STEP,
value=MAX_IMAGE_SIZE,
)
with gr.Row():
guidance_scale = gr.Slider(
label="Guidance scale",
minimum=0.0,
maximum=10.0,
step=0.5,
value=4.0,
)
num_inference_steps = gr.Slider(
label="Number of inference steps",
minimum=1,
maximum=50,
step=1,
value=40,
)
gr.Examples(examples=examples, inputs=[prompt])
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[
prompt,
negative_prompt,
seed,
randomize_seed,
width,
height,
guidance_scale,
num_inference_steps,
refine_prompt,
],
outputs=[result, seed, prompt], # Добавлен prompt для обновления текста в интерфейсе
)
if __name__ == "__main__":
demo.launch()