Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,60 +1,90 @@
|
|
1 |
import gradio as gr
|
2 |
import numpy as np
|
3 |
-
import random
|
4 |
-
|
5 |
-
# import spaces #[uncomment to use ZeroGPU]
|
6 |
-
from diffusers import DiffusionPipeline
|
7 |
import torch
|
|
|
|
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
10 |
-
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
torch_dtype = torch.float32
|
16 |
|
17 |
-
|
18 |
-
pipe
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
MAX_SEED = np.iinfo(np.int32).max
|
21 |
-
MAX_IMAGE_SIZE = 1024
|
22 |
-
|
23 |
-
|
24 |
-
# @spaces.GPU #[uncomment to use ZeroGPU]
|
25 |
def infer(
|
|
|
26 |
prompt,
|
27 |
negative_prompt,
|
28 |
seed,
|
29 |
-
randomize_seed,
|
30 |
width,
|
31 |
height,
|
32 |
guidance_scale,
|
33 |
num_inference_steps,
|
34 |
progress=gr.Progress(track_tqdm=True),
|
35 |
):
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
examples = [
|
55 |
-
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
56 |
-
"An astronaut riding a green horse",
|
57 |
-
"A
|
58 |
]
|
59 |
|
60 |
css = """
|
@@ -66,89 +96,68 @@ css = """
|
|
66 |
|
67 |
with gr.Blocks(css=css) as demo:
|
68 |
with gr.Column(elem_id="col-container"):
|
69 |
-
gr.Markdown("
|
70 |
-
|
71 |
with gr.Row():
|
72 |
-
|
73 |
-
label="
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
)
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
label="Seed",
|
94 |
-
minimum=0,
|
95 |
-
maximum=MAX_SEED,
|
96 |
-
step=1,
|
97 |
-
value=0,
|
98 |
-
)
|
99 |
-
|
100 |
-
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
101 |
-
|
102 |
with gr.Row():
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
maximum=MAX_IMAGE_SIZE,
|
107 |
-
step=32,
|
108 |
-
value=1024, # Replace with defaults that work for your model
|
109 |
-
)
|
110 |
-
|
111 |
-
height = gr.Slider(
|
112 |
-
label="Height",
|
113 |
-
minimum=256,
|
114 |
-
maximum=MAX_IMAGE_SIZE,
|
115 |
-
step=32,
|
116 |
-
value=1024, # Replace with defaults that work for your model
|
117 |
-
)
|
118 |
-
|
119 |
with gr.Row():
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
|
|
139 |
fn=infer,
|
140 |
inputs=[
|
|
|
141 |
prompt,
|
142 |
negative_prompt,
|
143 |
seed,
|
144 |
-
randomize_seed,
|
145 |
width,
|
146 |
height,
|
147 |
guidance_scale,
|
148 |
num_inference_steps,
|
149 |
],
|
150 |
-
outputs=[
|
151 |
)
|
152 |
|
153 |
if __name__ == "__main__":
|
154 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import numpy as np
|
|
|
|
|
|
|
|
|
3 |
import torch
|
4 |
+
from huggingface_hub import list_models, ModelFilter
|
5 |
+
from diffusers import DiffusionPipeline
|
6 |
|
7 |
+
# Проверка доступности модели на Hugging Face Hub
|
8 |
+
def is_model_available(model_id):
|
9 |
+
try:
|
10 |
+
models = list_models(filter=ModelFilter(model_name=model_id))
|
11 |
+
return len(models) > 0
|
12 |
+
except Exception:
|
13 |
+
return False
|
14 |
+
|
15 |
+
def validate_model(model_id):
|
16 |
+
if not model_id:
|
17 |
+
raise ValueError("Необходимо указать модель")
|
18 |
+
|
19 |
+
if not is_model_available(model_id):
|
20 |
+
raise ValueError(f"Модель '{model_id}' не найдена на Hugging Face Hub")
|
21 |
+
|
22 |
+
# Дополнительные проверки модели (можно настроить)
|
23 |
+
if not ("stable-diffusion" in model_id.lower() or "sdxl" in model_id.lower()):
|
24 |
+
raise ValueError("Поддерживаются только Stable Diffusion и SDXL модели")
|
25 |
+
|
26 |
+
# Инициализация устройства
|
27 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
28 |
+
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
29 |
|
30 |
+
# Глобальные переменные
|
31 |
+
current_model = None
|
32 |
+
pipe = None
|
|
|
33 |
|
34 |
+
def load_pipeline(model_id):
|
35 |
+
global pipe, current_model
|
36 |
+
if model_id != current_model:
|
37 |
+
validate_model(model_id)
|
38 |
+
pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch_dtype)
|
39 |
+
pipe = pipe.to(device)
|
40 |
+
current_model = model_id
|
41 |
+
return pipe
|
42 |
|
|
|
|
|
|
|
|
|
|
|
43 |
def infer(
|
44 |
+
model_id,
|
45 |
prompt,
|
46 |
negative_prompt,
|
47 |
seed,
|
|
|
48 |
width,
|
49 |
height,
|
50 |
guidance_scale,
|
51 |
num_inference_steps,
|
52 |
progress=gr.Progress(track_tqdm=True),
|
53 |
):
|
54 |
+
try:
|
55 |
+
# Загрузка и проверка модели
|
56 |
+
pipeline = load_pipeline(model_id)
|
57 |
+
|
58 |
+
# Генерация изображения
|
59 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
60 |
+
|
61 |
+
result = pipeline(
|
62 |
+
prompt=prompt,
|
63 |
+
negative_prompt=negative_prompt,
|
64 |
+
width=width,
|
65 |
+
height=height,
|
66 |
+
guidance_scale=guidance_scale,
|
67 |
+
num_inference_steps=num_inference_steps,
|
68 |
+
generator=generator,
|
69 |
+
).images[0]
|
70 |
+
|
71 |
+
return result, seed
|
72 |
+
|
73 |
+
except Exception as e:
|
74 |
+
raise gr.Error(f"Ошибка генерации: {str(e)}")
|
75 |
+
|
76 |
+
# Список доступных моделей по умолчанию
|
77 |
+
available_models = [
|
78 |
+
"stabilityai/stable-diffusion-2-1",
|
79 |
+
"stabilityai/sdxl-turbo",
|
80 |
+
"runwayml/stable-diffusion-v1-5",
|
81 |
+
"prompthero/openjourney-v4"
|
82 |
+
]
|
83 |
|
84 |
examples = [
|
85 |
+
["stabilityai/sdxl-turbo", "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"],
|
86 |
+
["runwayml/stable-diffusion-v1-5", "An astronaut riding a green horse"],
|
87 |
+
["prompthero/openjourney-v4", "A cyberpunk cityscape at night, neon lights, rain"],
|
88 |
]
|
89 |
|
90 |
css = """
|
|
|
96 |
|
97 |
with gr.Blocks(css=css) as demo:
|
98 |
with gr.Column(elem_id="col-container"):
|
99 |
+
gr.Markdown("# 🎨 Text-to-Image Generator")
|
100 |
+
|
101 |
with gr.Row():
|
102 |
+
model_id = gr.Dropdown(
|
103 |
+
label="Выберите или введите модель",
|
104 |
+
choices=available_models,
|
105 |
+
value="stabilityai/sdxl-turbo",
|
106 |
+
allow_custom_value=True,
|
107 |
+
scale=3
|
108 |
)
|
109 |
+
|
110 |
+
prompt = gr.Textbox(
|
111 |
+
label="Промпт",
|
112 |
+
placeholder="Введите описание изображения...",
|
113 |
+
lines=2
|
114 |
+
)
|
115 |
+
|
116 |
+
negative_prompt = gr.Textbox(
|
117 |
+
label="Негативный промпт",
|
118 |
+
placeholder="Что исключить из изображения...",
|
119 |
+
lines=2
|
120 |
+
)
|
121 |
+
|
122 |
+
with gr.Accordion("Настройки генерации", open=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
with gr.Row():
|
124 |
+
seed = gr.Slider(0, 2147483647, value=42, label="Сид")
|
125 |
+
guidance_scale = gr.Slider(0.0, 20.0, value=7.5, label="Guidance Scale")
|
126 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
with gr.Row():
|
128 |
+
width = gr.Slider(256, 1024, value=512, step=64, label="Ширина")
|
129 |
+
height = gr.Slider(256, 1024, value=512, step=64, label="Высота")
|
130 |
+
|
131 |
+
num_inference_steps = gr.Slider(1, 100, value=20, step=1, label="Шаги генерации")
|
132 |
+
|
133 |
+
generate_btn = gr.Button("Сгенерировать", variant="primary")
|
134 |
+
|
135 |
+
output_image = gr.Image(label="Результат", show_label=False)
|
136 |
+
used_seed = gr.Number(label="Использованный сид", visible=True)
|
137 |
+
|
138 |
+
gr.Examples(
|
139 |
+
examples=examples,
|
140 |
+
inputs=[model_id, prompt],
|
141 |
+
outputs=[output_image, used_seed],
|
142 |
+
fn=infer,
|
143 |
+
cache_examples=True,
|
144 |
+
label="Примеры"
|
145 |
+
)
|
146 |
+
|
147 |
+
generate_btn.click(
|
148 |
fn=infer,
|
149 |
inputs=[
|
150 |
+
model_id,
|
151 |
prompt,
|
152 |
negative_prompt,
|
153 |
seed,
|
|
|
154 |
width,
|
155 |
height,
|
156 |
guidance_scale,
|
157 |
num_inference_steps,
|
158 |
],
|
159 |
+
outputs=[output_image, used_seed]
|
160 |
)
|
161 |
|
162 |
if __name__ == "__main__":
|
163 |
+
demo.launch()
|