Zaiiida commited on
Commit
d845598
·
verified ·
1 Parent(s): 334697f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -51
app.py CHANGED
@@ -5,8 +5,8 @@ import spaces
5
  from diffusers import DiffusionPipeline
6
  import torch
7
 
 
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
-
10
  model_repo_id = "stabilityai/stable-diffusion-3-medium-diffusers"
11
 
12
  if torch.cuda.is_available():
@@ -17,43 +17,35 @@ else:
17
  pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
  pipe = pipe.to(device)
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 512
22
 
23
- def calculate_duration(width, height, num_inference_steps):
24
- # Примерная оценка времени выполнения
25
- base_time = 10 # Минимальное время для 512x512, 10 шагов
26
- time_factor = (width * height) / (512 * 512) # Увеличение времени от размера
27
- step_factor = num_inference_steps / 10 # Увеличение времени от числа шагов
28
- return int(base_time * time_factor * step_factor)
29
  examples = [
30
  "A border collie lying in some Fall leaves as the forest trees change colors",
 
 
31
  ]
32
- @spaces.GPU(duration=30) # Устанавливаем 30 секунд
 
 
33
  def infer(
34
  prompt,
35
  width=512,
36
  height=512,
37
- num_inference_steps=20, # Оптимальные шаги
38
- guidance_scale=7.5,
39
  ):
40
- # Оценка необходимого времени
41
- duration = calculate_duration(width, height, num_inference_steps)
42
- print(f"Запрашиваемая квота: {duration} секунд")
43
- # Настраиваем параметры в pipe
44
  image = pipe(
45
  prompt=prompt,
46
  num_inference_steps=num_inference_steps,
 
47
  width=width,
48
  height=height,
49
- guidance_scale=guidance_scale,
50
  ).images[0]
51
  return image
52
 
53
-
54
-
55
-
56
- # Define the custom theme with input styles
57
  class CustomTheme(gr.themes.Base):
58
  def __init__(self):
59
  super().__init__()
@@ -64,12 +56,12 @@ class CustomTheme(gr.themes.Base):
64
  self.text_color_primary = "#AEB3B8"
65
  self.text_color_secondary = "#AEB3B8"
66
  self.text_color_tertiary = "#AEB3B8"
67
- self.input_background_fill = "#17181B" # Set input background color
68
- self.input_text_color = "#AEB3B8" # Set input text color
69
 
70
- # Custom CSS to hide the footer, set fonts, and adjust font weights
71
  css = """
72
- /* Hide the footer */
73
  footer {
74
  visibility: hidden;
75
  height: 0;
@@ -78,26 +70,21 @@ footer {
78
  overflow: hidden;
79
  }
80
 
81
- /* Import Google Fonts */
82
  @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Montserrat:wght@500;700&display=swap');
83
 
84
- /* Apply fonts to different elements */
85
  body, input, button, textarea, select, .gr-button {
86
  font-family: 'Roboto', sans-serif;
87
  }
88
 
89
- /* Make button text normal weight */
90
- .generate-button, .generate-button .gr-button {
91
- font-weight: normal !important;
92
- }
93
-
94
- /* Ensure headings use Montserrat */
95
  h1, h2, h3, h4, h5, h6 {
96
  font-family: 'Montserrat', sans-serif;
97
  font-weight: 700;
98
  }
99
 
100
- /* Additional styling for sliders and checkboxes if needed */
101
  input[type="range"]::-webkit-slider-thumb {
102
  background: #5271FF;
103
  }
@@ -111,15 +98,16 @@ input[type="checkbox"]:checked {
111
  background-color: #5271FF;
112
  }
113
 
114
- /* Make Prompt text bold */
115
  .prompt-text {
116
  font-weight: bold;
117
  }
118
  """
119
 
 
120
  with gr.Blocks(theme=CustomTheme(), css=css) as demo:
121
  with gr.Column(elem_id="col-container"):
122
- # Make "Prompt" bold using Markdown syntax and assign a class
123
  gr.Markdown("**Prompt**", elem_classes="prompt-text")
124
 
125
  with gr.Row():
@@ -140,21 +128,22 @@ with gr.Blocks(theme=CustomTheme(), css=css) as demo:
140
 
141
  result = gr.Image(label="Result", show_label=False)
142
 
143
-
144
- prompt.submit(
145
- fn=infer,
146
- inputs=[
147
- prompt,
148
- negative_prompt,
149
- seed,
150
- randomize_seed,
151
- width,
152
- height,
153
- guidance_scale,
154
- num_inference_steps,
155
- ],
156
- outputs=[result, seed],
157
- )
 
158
 
159
  if __name__ == "__main__":
160
  demo.launch(
 
5
  from diffusers import DiffusionPipeline
6
  import torch
7
 
8
+ # Подключение к устройству
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
10
  model_repo_id = "stabilityai/stable-diffusion-3-medium-diffusers"
11
 
12
  if torch.cuda.is_available():
 
17
  pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
  pipe = pipe.to(device)
19
 
20
+ MAX_IMAGE_SIZE = 512 # Максимальный размер изображения
 
21
 
22
+ # Примеры для интерфейса
 
 
 
 
 
23
  examples = [
24
  "A border collie lying in some Fall leaves as the forest trees change colors",
25
+ "A cyberpunk cityscape with neon lights and flying cars at night",
26
+ "A fantasy castle surrounded by mountains under a pink and purple sunset",
27
  ]
28
+
29
+ # Функция генерации изображений
30
+ @spaces.GPU(duration=30) # Устанавливаем время выполнения задачи
31
  def infer(
32
  prompt,
33
  width=512,
34
  height=512,
35
+ num_inference_steps=20, # Количество итераций
36
+ guidance_scale=7.5, # Вес промпта
37
  ):
38
+ # Генерация изображения
 
 
 
39
  image = pipe(
40
  prompt=prompt,
41
  num_inference_steps=num_inference_steps,
42
+ guidance_scale=guidance_scale,
43
  width=width,
44
  height=height,
 
45
  ).images[0]
46
  return image
47
 
48
+ # Класс для пользовательской темы интерфейса
 
 
 
49
  class CustomTheme(gr.themes.Base):
50
  def __init__(self):
51
  super().__init__()
 
56
  self.text_color_primary = "#AEB3B8"
57
  self.text_color_secondary = "#AEB3B8"
58
  self.text_color_tertiary = "#AEB3B8"
59
+ self.input_background_fill = "#17181B" # Цвет фона для ввода текста
60
+ self.input_text_color = "#AEB3B8" # Цвет текста для ввода
61
 
62
+ # CSS для интерфейса
63
  css = """
64
+ /* Скрываем нижний колонтитул */
65
  footer {
66
  visibility: hidden;
67
  height: 0;
 
70
  overflow: hidden;
71
  }
72
 
73
+ /* Импортируем шрифты */
74
  @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Montserrat:wght@500;700&display=swap');
75
 
76
+ /* Применяем шрифты */
77
  body, input, button, textarea, select, .gr-button {
78
  font-family: 'Roboto', sans-serif;
79
  }
80
 
81
+ /* Настройки заголовков */
 
 
 
 
 
82
  h1, h2, h3, h4, h5, h6 {
83
  font-family: 'Montserrat', sans-serif;
84
  font-weight: 700;
85
  }
86
 
87
+ /* Дополнительный стиль для слайдеров и чекбоксов */
88
  input[type="range"]::-webkit-slider-thumb {
89
  background: #5271FF;
90
  }
 
98
  background-color: #5271FF;
99
  }
100
 
101
+ /* Выделяем текст для Prompt */
102
  .prompt-text {
103
  font-weight: bold;
104
  }
105
  """
106
 
107
+ # Создание интерфейса Gradio
108
  with gr.Blocks(theme=CustomTheme(), css=css) as demo:
109
  with gr.Column(elem_id="col-container"):
110
+ # Заголовок для ввода промпта
111
  gr.Markdown("**Prompt**", elem_classes="prompt-text")
112
 
113
  with gr.Row():
 
128
 
129
  result = gr.Image(label="Result", show_label=False)
130
 
131
+ # Примеры для интерфейса
132
+ gr.Examples(
133
+ examples=examples,
134
+ inputs=[prompt],
135
+ outputs=[result],
136
+ fn=infer,
137
+ cache_examples=True,
138
+ cache_mode="lazy"
139
+ )
140
+
141
+ # Подключение кнопки к функции
142
+ run_button.click(
143
+ fn=infer,
144
+ inputs=[prompt],
145
+ outputs=[result],
146
+ )
147
 
148
  if __name__ == "__main__":
149
  demo.launch(