G-Rost commited on
Commit
f55585f
1 Parent(s): 95c7fbd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -132
app.py CHANGED
@@ -1,148 +1,89 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
- from diffusers import DiffusionPipeline
5
  import torch
6
 
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
8
 
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
12
- pipe.enable_xformers_memory_efficient_attention()
13
- pipe = pipe.to(device)
14
- else:
15
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
16
- pipe = pipe.to(device)
17
 
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 1024
20
 
21
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps):
 
22
 
23
- if randomize_seed:
24
- seed = random.randint(0, MAX_SEED)
25
-
26
- generator = torch.Generator().manual_seed(seed)
27
-
28
- image = pipe(
29
- prompt = prompt,
30
- negative_prompt = negative_prompt,
31
- guidance_scale = guidance_scale,
32
- num_inference_steps = num_inference_steps,
33
- width = width,
34
- height = height,
35
- generator = generator
36
- ).images[0]
37
-
38
- return image
39
-
40
- examples = [
41
- "Chic look, for a teenage girl",
42
- "Chic look, for a teenage boy",
43
- "Dark Academia, for a teenage",
44
-
45
- ]
46
-
47
- css="""
48
- #col-container {
49
- margin: 0 auto;
50
- max-width: 520px;
51
- }
52
- """
53
-
54
- if torch.cuda.is_available():
55
- power_device = "GPU"
56
- else:
57
- power_device = "CPU"
58
-
59
- with gr.Blocks(css=css) as demo:
60
-
61
- with gr.Column(elem_id="col-container"):
62
- gr.Markdown(f"""
63
- # Штучний інтелект створює зображення 🖼 з тексту 🧾
64
- Безкоштовна демоверсія для ознайомлення. Скоріше працює з кількома словами, рекомендовано англ.мову.
65
- Автор-Губа.Р.
66
  """)
 
 
 
 
 
 
 
 
67
 
 
 
 
 
 
 
 
 
68
  with gr.Row():
69
-
70
- prompt = gr.Text(
71
- label="Текст",
72
- show_label=False,
73
- max_lines=1,
74
- placeholder="Введіть текст",
75
- container=False,
76
- )
77
-
78
- run_button = gr.Button("До роботи", scale=0)
79
-
80
- result = gr.Image(label="Малював аж упрів!", show_label=True)
81
-
82
- with gr.Accordion("Advanced Settings", open=False):
83
-
84
- negative_prompt = gr.Text(
85
- label="",
86
- max_lines=1,
87
- placeholder="Enter a negative prompt",
88
- visible=True,
89
- )
90
-
91
- seed = gr.Slider(
92
- label="Кількість операцій накладання.Збільшує час створення",
93
- minimum=0,
94
- maximum=MAX_SEED,
95
- step=1,
96
- value=0,
97
- )
98
-
99
- randomize_seed = gr.Checkbox(label="", value=True)
100
-
101
- with gr.Row():
102
-
103
- width = gr.Slider(
104
- label="Ширина",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=512,
109
- )
110
-
111
- height = gr.Slider(
112
- label="Висота",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=512,
117
- )
118
-
119
- with gr.Row():
120
-
121
- guidance_scale = gr.Slider(
122
- label="Guidance scale",
123
- minimum=0.0,
124
- maximum=10.0,
125
- step=0.1,
126
- value=0.0,
127
- )
128
-
129
- num_inference_steps = gr.Slider(
130
- label="Number of inference steps",
131
- minimum=1,
132
- maximum=12,
133
- step=1,
134
- value=2,
135
- )
136
-
137
- gr.Examples(
138
- examples = examples,
139
- inputs = [prompt]
140
- )
141
 
142
  run_button.click(
143
- fn = infer,
144
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
145
- outputs = [result]
146
  )
147
 
148
- demo.queue().launch()
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ from diffusers import DiffusionPipeline, DDIMScheduler, LMSDiscreteScheduler
5
  import torch
6
 
7
+ # Device configuration (explicitly set to CPU)
8
+ DEVICE = "cpu"
9
 
10
+ # Model Options (for user selection)
11
+ MODEL_OPTIONS = {
12
+ "High Quality (Slower)": "stabilityai/stable-diffusion-xl-base-1.0",
13
+ "Fast (Lower Quality)": "CompVis/stable-diffusion-v1-4", # Smaller, faster model
14
+ }
 
 
 
15
 
16
+ # Default to faster model
17
+ DEFAULT_MODEL_ID = MODEL_OPTIONS["Fast (Lower Quality)"]
18
 
19
+ def generate_image(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, num_images, model_choice):
20
+ model_id = MODEL_OPTIONS[model_choice]
21
 
22
+ # Load Model based on user selection
23
+ pipe = DiffusionPipeline.from_pretrained(
24
+ model_id, torch_dtype=torch.float32
25
+ )
26
+
27
+ # Use LMSDiscreteScheduler for faster generation on CPU with CompVis model
28
+ if model_choice == "Fast (Lower Quality)":
29
+ pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)
30
+
31
+ pipe = pipe.to(DEVICE)
32
+
33
+ generator = torch.Generator(device=DEVICE)
34
+ if not randomize_seed:
35
+ generator = generator.manual_seed(seed)
36
+
37
+ images = pipe(
38
+ prompt,
39
+ negative_prompt=negative_prompt,
40
+ width=width,
41
+ height=height,
42
+ guidance_scale=guidance_scale,
43
+ num_inference_steps=num_inference_steps,
44
+ num_images_per_prompt=num_images,
45
+ generator=generator,
46
+ ).images
47
+
48
+ return images
49
+
50
+ # Gradio Interface
51
+ with gr.Blocks(title="Генерація зображень за текстом", theme=gr.themes.Soft()) as demo:
52
+ gr.Markdown(
53
+ """
54
+ ## Text-to-Image Generation 🤖🎨
55
+ **Створіть дивовижні зображення зі своєї уяви!**
56
+ Введіть опис, налаштуйте параметри і дозвольте моделі створити для вас витвір мистецтва.
 
 
 
 
 
 
 
 
57
  """)
58
+
59
+ with gr.Row():
60
+ prompt = gr.Textbox(label="Опис", placeholder="Напишіть ваш опис тут...")
61
+ negative_prompt = gr.Textbox(label="Негативний опис (необов'язково)")
62
+
63
+ with gr.Row():
64
+ seed = gr.Number(label="Початкове число", value=0)
65
+ randomize_seed = gr.Checkbox(label="Випадкове початкове число", value=True)
66
 
67
+ with gr.Row(): # Added this row for model selection
68
+ model_choice = gr.Radio(label="Виберіть модель", choices=list(MODEL_OPTIONS.keys()), value=DEFAULT_MODEL_ID)
69
+
70
+ with gr.Row():
71
+ width = gr.Slider(label="Ширина", minimum=256, maximum=MAX_IMAGE_SIZE, value=512, step=64)
72
+ height = gr.Slider(label="Висота", minimum=256, maximum=MAX_IMAGE_SIZE, value=512, step=64)
73
+
74
+ with gr.Accordion("Додаткові налаштування", open=False):
75
  with gr.Row():
76
+ guidance_scale = gr.Slider(label="Рівень відповідності опису", minimum=0.0, maximum=20.0, value=7.5, step=0.1, info="Наскільки точно модель повинна слідувати опису.")
77
+ num_inference_steps = gr.Slider(label="Кількість кроків", minimum=10, maximum=100, value=50, step=5, info="Більше кроків може покращити якість, але займе більше часу.")
78
+ num_images = gr.Slider(label="Кількість зображень", minimum=1, maximum=4, value=1, step=1)
79
+
80
+ run_button = gr.Button("Згенерувати")
81
+ gallery = gr.Gallery(label="Згенеровані зображення")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  run_button.click(
84
+ fn=generate_image,
85
+ inputs=[prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, num_images, model_choice],
86
+ outputs=gallery,
87
  )
88
 
89
+ demo.launch(debug=True)