MrDrmm commited on
Commit
f11b4d9
·
verified ·
1 Parent(s): 471029c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -16
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  from random import randint
3
 
@@ -41,6 +42,9 @@ models = [
41
  'Jonjew/NSFWMaster',
42
  ]
43
 
 
 
 
44
  def load_fn(models):
45
  global models_load
46
  models_load = {}
@@ -52,26 +56,72 @@ def load_fn(models):
52
  m = gr.Interface(lambda txt: None, ['text'], ['image'])
53
  models_load.update({model: m})
54
 
 
 
55
  load_fn(models)
56
 
57
  num_models = len(models)
58
  default_models = models[:num_models]
59
 
 
60
  def extend_choices(choices):
61
  return choices + (num_models - len(choices)) * ['NA']
62
 
63
- def update_imgbox(choices):
 
64
  choices_plus = extend_choices(choices)
65
- return [gr.Image(None, label=m, visible=(m != 'NA'), elem_id="custom_image") for m in choices_plus]
 
 
 
 
 
 
 
 
 
66
 
67
- def gen_fn(model_str, prompt):
 
 
 
 
68
  if model_str == 'NA':
69
  return None
 
70
  noise = str(randint(0, 9999999))
71
- return models_load[model_str](f'{prompt} {noise}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
 
73
  def make_me():
74
  with gr.Row():
 
75
  with gr.Column(scale=1):
76
  txt_input = gr.Textbox(
77
  label='Your prompt:',
@@ -80,6 +130,21 @@ def make_me():
80
  elem_id="custom_textbox",
81
  placeholder="Prompt"
82
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  with gr.Row():
84
  gen_button = gr.Button('Generate images', elem_id="custom_gen_button")
85
  stop_button = gr.Button('Stop', variant='secondary', interactive=False, elem_id="custom_stop_button")
@@ -93,25 +158,25 @@ def make_me():
93
  gen_button.click(on_generate_click, inputs=None, outputs=[gen_button, stop_button])
94
  stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button])
95
 
96
- # Делим вывод изображений на два ряда
97
  with gr.Row():
98
  half = len(default_models) // 2
99
- output_row1 = [gr.Image(label=m, min_width=250, height=250, elem_id="custom_image") for m in default_models[:half]]
100
- output_row2 = [gr.Image(label=m, min_width=250, height=250, elem_id="custom_image") for m in default_models[half:]]
101
  current_models_row1 = [gr.Textbox(m, visible=False) for m in default_models[:half]]
102
  current_models_row2 = [gr.Textbox(m, visible=False) for m in default_models[half:]]
103
 
104
- # Первый ряд изображений
105
  for m, o in zip(current_models_row1, output_row1):
106
- gen_event = gen_button.click(gen_fn, [m, txt_input], o)
107
  stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button], cancels=[gen_event])
108
 
109
- # Второй ряд изображений
110
  for m, o in zip(current_models_row2, output_row2):
111
- gen_event = gen_button.click(gen_fn, [m, txt_input], o)
112
  stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button], cancels=[gen_event])
113
 
114
- # Разделяем чекбоксы на два ряда
115
  with gr.Accordion('Model selection', elem_id="custom_accordion"):
116
  half = len(models) // 2
117
  model_choice_row1 = models[:half]
@@ -132,14 +197,16 @@ def make_me():
132
  elem_id="custom_checkbox_group"
133
  )
134
 
135
- # Обновляем первый ряд
136
- model_choice1.change(update_imgbox, model_choice1, output_row1)
137
  model_choice1.change(extend_choices, model_choice1, current_models_row1)
138
 
139
- # Обновляем второй ряд
140
- model_choice2.change(update_imgbox, model_choice2, output_row2)
141
  model_choice2.change(extend_choices, model_choice2, current_models_row2)
142
 
 
 
143
  with gr.Row():
144
  gr.HTML("")
145
 
 
1
+ from PIL import Image
2
  import gradio as gr
3
  from random import randint
4
 
 
42
  'Jonjew/NSFWMaster',
43
  ]
44
 
45
+
46
+
47
+ # Функция загрузки моделей
48
  def load_fn(models):
49
  global models_load
50
  models_load = {}
 
56
  m = gr.Interface(lambda txt: None, ['text'], ['image'])
57
  models_load.update({model: m})
58
 
59
+ # Инициализация моделей
60
+ models = ["Model1", "Model2", "Model3", "Model4"] # Список доступных моделей
61
  load_fn(models)
62
 
63
  num_models = len(models)
64
  default_models = models[:num_models]
65
 
66
+ # Функция расширения списка выборов
67
  def extend_choices(choices):
68
  return choices + (num_models - len(choices)) * ['NA']
69
 
70
+ # Обновление изображений
71
+ def update_imgbox(choices, width, height):
72
  choices_plus = extend_choices(choices)
73
+ return [
74
+ gr.Image(
75
+ None,
76
+ label=m,
77
+ visible=(m != 'NA'),
78
+ elem_id="custom_image",
79
+ width=width,
80
+ height=height
81
+ ) for m in choices_plus
82
+ ]
83
 
84
+ # Генерация изображений
85
+ def gen_fn(model_str, prompt, width, height, max_retries=3):
86
+ """
87
+ Генерация изображения с обработкой ошибок и повторными попытками.
88
+ """
89
  if model_str == 'NA':
90
  return None
91
+
92
  noise = str(randint(0, 9999999))
93
+ retries = 0
94
+
95
+ while retries < max_retries:
96
+ try:
97
+ result = models_load[model_str](f'{prompt} {noise}')
98
+
99
+ # Проверка на тип tuple
100
+ if isinstance(result, tuple):
101
+ print(f"Result is a tuple, retrying... Attempt {retries + 1}")
102
+ retries += 1
103
+ continue
104
+
105
+ # Если результат строка (путь к файлу), открываем изображение
106
+ if isinstance(result, str):
107
+ result = Image.open(result)
108
+
109
+ # Изменение размера изображения
110
+ if isinstance(result, Image.Image):
111
+ result = result.resize((width, height))
112
+
113
+ return result
114
+ except Exception as e:
115
+ print(f"Error generating image: {e}")
116
+ retries += 1
117
+
118
+ print("Failed to generate image after multiple retries.")
119
+ return None
120
 
121
+ # Создание интерфейса
122
  def make_me():
123
  with gr.Row():
124
+ # Ввод текста
125
  with gr.Column(scale=1):
126
  txt_input = gr.Textbox(
127
  label='Your prompt:',
 
130
  elem_id="custom_textbox",
131
  placeholder="Prompt"
132
  )
133
+ # Выбор ширины и высоты
134
+ width_slider = gr.Slider(
135
+ minimum=100,
136
+ maximum=1000,
137
+ step=50,
138
+ value=250,
139
+ label="Width"
140
+ )
141
+ height_slider = gr.Slider(
142
+ minimum=100,
143
+ maximum=1000,
144
+ step=50,
145
+ value=250,
146
+ label="Height"
147
+ )
148
  with gr.Row():
149
  gen_button = gr.Button('Generate images', elem_id="custom_gen_button")
150
  stop_button = gr.Button('Stop', variant='secondary', interactive=False, elem_id="custom_stop_button")
 
158
  gen_button.click(on_generate_click, inputs=None, outputs=[gen_button, stop_button])
159
  stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button])
160
 
161
+ # Вывод изображений в два ряда
162
  with gr.Row():
163
  half = len(default_models) // 2
164
+ output_row1 = [gr.Image(label=m, elem_id="custom_image") for m in default_models[:half]]
165
+ output_row2 = [gr.Image(label=m, elem_id="custom_image") for m in default_models[half:]]
166
  current_models_row1 = [gr.Textbox(m, visible=False) for m in default_models[:half]]
167
  current_models_row2 = [gr.Textbox(m, visible=False) for m in default_models[half:]]
168
 
169
+ # Генерация для первого ряда
170
  for m, o in zip(current_models_row1, output_row1):
171
+ gen_event = gen_button.click(gen_fn, [m, txt_input, width_slider, height_slider], o)
172
  stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button], cancels=[gen_event])
173
 
174
+ # Генерация для второго ряда
175
  for m, o in zip(current_models_row2, output_row2):
176
+ gen_event = gen_button.click(gen_fn, [m, txt_input, width_slider, height_slider], o)
177
  stop_button.click(on_stop_click, inputs=None, outputs=[gen_button, stop_button], cancels=[gen_event])
178
 
179
+ # Чекбоксы выбора моделей в аккордеоне
180
  with gr.Accordion('Model selection', elem_id="custom_accordion"):
181
  half = len(models) // 2
182
  model_choice_row1 = models[:half]
 
197
  elem_id="custom_checkbox_group"
198
  )
199
 
200
+ # Обновление первого ряда
201
+ model_choice1.change(update_imgbox, [model_choice1, width_slider, height_slider], output_row1)
202
  model_choice1.change(extend_choices, model_choice1, current_models_row1)
203
 
204
+ # Обновление второго ряда
205
+ model_choice2.change(update_imgbox, [model_choice2, width_slider, height_slider], output_row2)
206
  model_choice2.change(extend_choices, model_choice2, current_models_row2)
207
 
208
+
209
+
210
  with gr.Row():
211
  gr.HTML("")
212