trashchenkov commited on
Commit
ce25251
·
verified ·
1 Parent(s): 8897d33

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -47
app.py CHANGED
@@ -1,20 +1,22 @@
1
  import gradio as gr
2
  import numpy as np
3
- import random
4
  import torch
5
  from diffusers import DiffusionPipeline
 
6
 
 
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
- model_repo_id = "CompVis/stable-diffusion-v1-4" # Replace to the model you would like to use
9
 
10
- if torch.cuda.is_available():
11
- torch_dtype = torch.float16
12
- else:
13
- torch_dtype = torch.float32
14
 
15
- # Изначально загружаем модель по умолчанию (как в исходном коде)
16
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
17
- pipe = pipe.to(device)
 
 
 
18
 
19
  MAX_SEED = np.iinfo(np.int32).max
20
  MAX_IMAGE_SIZE = 1024
@@ -31,28 +33,34 @@ def infer(
31
  progress=gr.Progress(track_tqdm=True),
32
  ):
33
  global model_repo_id, pipe
34
-
35
- # Если пользователь ввёл новую модель, пробуем загрузить
36
  if model != model_repo_id:
 
 
37
  try:
38
- new_pipe = DiffusionPipeline.from_pretrained(model, torch_dtype=torch_dtype)
39
- new_pipe = new_pipe.to(device)
40
  pipe = new_pipe
41
  model_repo_id = model
42
  except Exception as e:
43
  raise gr.Error(f"Не удалось загрузить модель '{model}'.\nОшибка: {e}")
44
 
 
45
  generator = torch.Generator(device=device).manual_seed(seed)
46
 
47
- image = pipe(
48
- prompt=prompt,
49
- negative_prompt=negative_prompt,
50
- guidance_scale=guidance_scale,
51
- num_inference_steps=num_inference_steps,
52
- width=width,
53
- height=height,
54
- generator=generator,
55
- ).images[0]
 
 
 
 
56
 
57
  return image, seed
58
 
@@ -69,14 +77,13 @@ css = """
69
  }
70
  """
71
 
72
- # Убрали выпадающее меню, заменили на текстовое поле
73
  with gr.Blocks(css=css) as demo:
74
  with gr.Column(elem_id="col-container"):
75
- gr.Markdown(" # Text-to-Image App")
76
 
77
  model = gr.Textbox(
78
  label="Model",
79
- value="stabilityai/sdxl-turbo", # Значение по умолчанию
80
  interactive=True
81
  )
82
 
@@ -87,14 +94,14 @@ with gr.Blocks(css=css) as demo:
87
  placeholder="Enter your prompt",
88
  container=False,
89
  )
90
-
91
  negative_prompt = gr.Text(
92
  label="Negative prompt",
93
  max_lines=1,
94
  placeholder="Enter a negative prompt",
95
  visible=True,
96
  )
97
-
98
  seed = gr.Slider(
99
  label="Seed",
100
  minimum=0,
@@ -102,7 +109,7 @@ with gr.Blocks(css=css) as demo:
102
  step=1,
103
  value=42,
104
  )
105
-
106
  guidance_scale = gr.Slider(
107
  label="Guidance scale",
108
  minimum=0.0,
@@ -118,8 +125,8 @@ with gr.Blocks(css=css) as demo:
118
  step=1,
119
  value=20,
120
  )
121
-
122
- run_button = gr.Button("Run", scale=0, variant="primary")
123
  result = gr.Image(label="Result", show_label=False)
124
 
125
  with gr.Accordion("Advanced Settings", open=False):
@@ -129,33 +136,32 @@ with gr.Blocks(css=css) as demo:
129
  minimum=256,
130
  maximum=MAX_IMAGE_SIZE,
131
  step=32,
132
- value=1024,
133
  )
134
  height = gr.Slider(
135
  label="Height",
136
  minimum=256,
137
  maximum=MAX_IMAGE_SIZE,
138
  step=32,
139
- value=1024,
140
  )
141
 
142
  gr.Examples(examples=examples, inputs=[prompt])
143
 
144
- gr.on(
145
- triggers=[run_button.click, prompt.submit],
146
- fn=infer,
147
- inputs=[
148
- model,
149
- prompt,
150
- negative_prompt,
151
- seed,
152
- width,
153
- height,
154
- guidance_scale,
155
- num_inference_steps,
156
- ],
157
- outputs=[result, seed],
158
- )
159
 
160
  if __name__ == "__main__":
161
  demo.launch()
 
1
  import gradio as gr
2
  import numpy as np
 
3
  import torch
4
  from diffusers import DiffusionPipeline
5
+ import re
6
 
7
+ # Устройство и параметры загрузки модели
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
10
 
11
+ # Регулярное выражение для проверки корректности модели
12
+ VALID_REPO_ID_REGEX = re.compile(r"^[a-zA-Z0-9._\-]+/[a-zA-Z0-9._\-]+$")
 
 
13
 
14
+ def is_valid_repo_id(repo_id):
15
+ return bool(VALID_REPO_ID_REGEX.match(repo_id)) and not repo_id.endswith(('-', '.'))
16
+
17
+ # Изначально загружаем модель по умолчанию
18
+ model_repo_id = "CompVis/stable-diffusion-v1-4"
19
+ pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype).to(device)
20
 
21
  MAX_SEED = np.iinfo(np.int32).max
22
  MAX_IMAGE_SIZE = 1024
 
33
  progress=gr.Progress(track_tqdm=True),
34
  ):
35
  global model_repo_id, pipe
36
+
37
+ # Проверяем и загружаем новую модель, если она изменена
38
  if model != model_repo_id:
39
+ if not is_valid_repo_id(model):
40
+ raise gr.Error(f"Некорректный идентификатор модели: '{model}'. Проверьте название.")
41
  try:
42
+ new_pipe = DiffusionPipeline.from_pretrained(model, torch_dtype=torch_dtype).to(device)
 
43
  pipe = new_pipe
44
  model_repo_id = model
45
  except Exception as e:
46
  raise gr.Error(f"Не удалось загрузить модель '{model}'.\nОшибка: {e}")
47
 
48
+ # Генератор случайных чисел для детерминированности
49
  generator = torch.Generator(device=device).manual_seed(seed)
50
 
51
+ # Генерация изображения
52
+ try:
53
+ image = pipe(
54
+ prompt=prompt,
55
+ negative_prompt=negative_prompt,
56
+ guidance_scale=guidance_scale,
57
+ num_inference_steps=num_inference_steps,
58
+ width=width,
59
+ height=height,
60
+ generator=generator,
61
+ ).images[0]
62
+ except Exception as e:
63
+ raise gr.Error(f"Ошибка при генерации изображения: {e}")
64
 
65
  return image, seed
66
 
 
77
  }
78
  """
79
 
 
80
  with gr.Blocks(css=css) as demo:
81
  with gr.Column(elem_id="col-container"):
82
+ gr.Markdown("# Text-to-Image App")
83
 
84
  model = gr.Textbox(
85
  label="Model",
86
+ value="CompVis/stable-diffusion-v1-4", # Значение по умолчанию
87
  interactive=True
88
  )
89
 
 
94
  placeholder="Enter your prompt",
95
  container=False,
96
  )
97
+
98
  negative_prompt = gr.Text(
99
  label="Negative prompt",
100
  max_lines=1,
101
  placeholder="Enter a negative prompt",
102
  visible=True,
103
  )
104
+
105
  seed = gr.Slider(
106
  label="Seed",
107
  minimum=0,
 
109
  step=1,
110
  value=42,
111
  )
112
+
113
  guidance_scale = gr.Slider(
114
  label="Guidance scale",
115
  minimum=0.0,
 
125
  step=1,
126
  value=20,
127
  )
128
+
129
+ run_button = gr.Button("Run", variant="primary")
130
  result = gr.Image(label="Result", show_label=False)
131
 
132
  with gr.Accordion("Advanced Settings", open=False):
 
136
  minimum=256,
137
  maximum=MAX_IMAGE_SIZE,
138
  step=32,
139
+ value=512,
140
  )
141
  height = gr.Slider(
142
  label="Height",
143
  minimum=256,
144
  maximum=MAX_IMAGE_SIZE,
145
  step=32,
146
+ value=512,
147
  )
148
 
149
  gr.Examples(examples=examples, inputs=[prompt])
150
 
151
+ run_button.click(
152
+ infer,
153
+ inputs=[
154
+ model,
155
+ prompt,
156
+ negative_prompt,
157
+ seed,
158
+ width,
159
+ height,
160
+ guidance_scale,
161
+ num_inference_steps,
162
+ ],
163
+ outputs=[result, seed],
164
+ )
 
165
 
166
  if __name__ == "__main__":
167
  demo.launch()