fazzebo commited on
Commit
6671685
1 Parent(s): ba572c6
Files changed (1) hide show
  1. app.py +606 -0
app.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import os
4
+ import json
5
+ import time
6
+ import shared
7
+ import modules.config
8
+ import fooocus_version
9
+ import modules.html
10
+ import modules.async_worker as worker
11
+ import modules.constants as constants
12
+ import modules.flags as flags
13
+ import modules.gradio_hijack as grh
14
+ import modules.advanced_parameters as advanced_parameters
15
+ import modules.style_sorter as style_sorter
16
+ import modules.meta_parser
17
+ import args_manager
18
+ import copy
19
+
20
+ from modules.sdxl_styles import legal_style_names
21
+ from modules.private_logger import get_current_html_path
22
+ from modules.ui_gradio_extensions import reload_javascript
23
+ from modules.auth import auth_enabled, check_auth
24
+
25
+
26
+ def generate_clicked(*args):
27
+ import ldm_patched.modules.model_management as model_management
28
+
29
+ with model_management.interrupt_processing_mutex:
30
+ model_management.interrupt_processing = False
31
+
32
+ # outputs=[progress_html, progress_window, progress_gallery, gallery]
33
+
34
+ execution_start_time = time.perf_counter()
35
+ task = worker.AsyncTask(args=list(args))
36
+ finished = False
37
+
38
+ yield gr.update(visible=True, value=modules.html.make_progress_html(1, 'Waiting for task to start ...')), \
39
+ gr.update(visible=True, value=None), \
40
+ gr.update(visible=False, value=None), \
41
+ gr.update(visible=False)
42
+
43
+ worker.async_tasks.append(task)
44
+
45
+ while not finished:
46
+ time.sleep(0.01)
47
+ if len(task.yields) > 0:
48
+ flag, product = task.yields.pop(0)
49
+ if flag == 'preview':
50
+
51
+ # help bad internet connection by skipping duplicated preview
52
+ if len(task.yields) > 0: # if we have the next item
53
+ if task.yields[0][0] == 'preview': # if the next item is also a preview
54
+ # print('Skipped one preview for better internet connection.')
55
+ continue
56
+
57
+ percentage, title, image = product
58
+ yield gr.update(visible=True, value=modules.html.make_progress_html(percentage, title)), \
59
+ gr.update(visible=True, value=image) if image is not None else gr.update(), \
60
+ gr.update(), \
61
+ gr.update(visible=False)
62
+ if flag == 'results':
63
+ yield gr.update(visible=True), \
64
+ gr.update(visible=True), \
65
+ gr.update(visible=True, value=product), \
66
+ gr.update(visible=False)
67
+ if flag == 'finish':
68
+ yield gr.update(visible=False), \
69
+ gr.update(visible=False), \
70
+ gr.update(visible=False), \
71
+ gr.update(visible=True, value=product)
72
+ finished = True
73
+
74
+ execution_time = time.perf_counter() - execution_start_time
75
+ print(f'Total time: {execution_time:.2f} seconds')
76
+ return
77
+
78
+
79
+ reload_javascript()
80
+
81
+ title = f'Fooocus {fooocus_version.version}'
82
+
83
+ if isinstance(args_manager.args.preset, str):
84
+ title += ' ' + args_manager.args.preset
85
+
86
+ shared.gradio_root = gr.Blocks(
87
+ title=title,
88
+ css=modules.html.css).queue()
89
+
90
+ with shared.gradio_root:
91
+ with gr.Row():
92
+ with gr.Column(scale=2):
93
+ with gr.Row():
94
+ progress_window = grh.Image(label='Preview', show_label=True, visible=False, height=768,
95
+ elem_classes=['main_view'])
96
+ progress_gallery = gr.Gallery(label='Finished Images', show_label=True, object_fit='contain',
97
+ height=768, visible=False, elem_classes=['main_view', 'image_gallery'])
98
+ progress_html = gr.HTML(value=modules.html.make_progress_html(32, 'Progress 32%'), visible=False,
99
+ elem_id='progress-bar', elem_classes='progress-bar')
100
+ gallery = gr.Gallery(label='Gallery', show_label=False, object_fit='contain', visible=True, height=768,
101
+ elem_classes=['resizable_area', 'main_view', 'final_gallery', 'image_gallery'],
102
+ elem_id='final_gallery')
103
+ with gr.Row(elem_classes='type_row'):
104
+ with gr.Column(scale=17):
105
+ prompt = gr.Textbox(show_label=False, placeholder="Type prompt here or paste parameters.", elem_id='positive_prompt',
106
+ container=False, autofocus=True, elem_classes='type_row', lines=1024)
107
+
108
+ default_prompt = modules.config.default_prompt
109
+ if isinstance(default_prompt, str) and default_prompt != '':
110
+ shared.gradio_root.load(lambda: default_prompt, outputs=prompt)
111
+
112
+ with gr.Column(scale=3, min_width=0):
113
+ generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', elem_id='generate_button', visible=True)
114
+ load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", elem_classes='type_row', elem_id='load_parameter_button', visible=False)
115
+ skip_button = gr.Button(label="Skip", value="Skip", elem_classes='type_row_half', visible=False)
116
+ stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', elem_id='stop_button', visible=False)
117
+
118
+ def stop_clicked():
119
+ import ldm_patched.modules.model_management as model_management
120
+ shared.last_stop = 'stop'
121
+ model_management.interrupt_current_processing()
122
+ return [gr.update(interactive=False)] * 2
123
+
124
+ def skip_clicked():
125
+ import ldm_patched.modules.model_management as model_management
126
+ shared.last_stop = 'skip'
127
+ model_management.interrupt_current_processing()
128
+ return
129
+
130
+ stop_button.click(stop_clicked, outputs=[skip_button, stop_button],
131
+ queue=False, show_progress=False, _js='cancelGenerateForever')
132
+ skip_button.click(skip_clicked, queue=False, show_progress=False)
133
+ with gr.Row(elem_classes='advanced_check_row'):
134
+ input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, elem_classes='min_check')
135
+ advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, container=False, elem_classes='min_check')
136
+ with gr.Row(visible=False) as image_input_panel:
137
+ with gr.Tabs():
138
+ with gr.TabItem(label='Upscale or Variation') as uov_tab:
139
+ with gr.Row():
140
+ with gr.Column():
141
+ uov_input_image = grh.Image(label='Drag above image to here', source='upload', type='numpy')
142
+ with gr.Column():
143
+ uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, value=flags.disabled)
144
+ gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/390" target="_blank">\U0001F4D4 Document</a>')
145
+ with gr.TabItem(label='Image Prompt') as ip_tab:
146
+ with gr.Row():
147
+ ip_images = []
148
+ ip_types = []
149
+ ip_stops = []
150
+ ip_weights = []
151
+ ip_ctrls = []
152
+ ip_ad_cols = []
153
+ for _ in range(4):
154
+ with gr.Column():
155
+ ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, height=300)
156
+ ip_images.append(ip_image)
157
+ ip_ctrls.append(ip_image)
158
+ with gr.Column(visible=False) as ad_col:
159
+ with gr.Row():
160
+ default_end, default_weight = flags.default_parameters[flags.default_ip]
161
+
162
+ ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, value=default_end)
163
+ ip_stops.append(ip_stop)
164
+ ip_ctrls.append(ip_stop)
165
+
166
+ ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, value=default_weight)
167
+ ip_weights.append(ip_weight)
168
+ ip_ctrls.append(ip_weight)
169
+
170
+ ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, container=False)
171
+ ip_types.append(ip_type)
172
+ ip_ctrls.append(ip_type)
173
+
174
+ ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], outputs=[ip_stop, ip_weight], queue=False, show_progress=False)
175
+ ip_ad_cols.append(ad_col)
176
+ ip_advanced = gr.Checkbox(label='Advanced', value=False, container=False)
177
+ gr.HTML('* \"Image Prompt\" is powered by Fooocus Image Mixture Engine (v1.0.1). <a href="https://github.com/lllyasviel/Fooocus/discussions/557" target="_blank">\U0001F4D4 Document</a>')
178
+
179
+ def ip_advance_checked(x):
180
+ return [gr.update(visible=x)] * len(ip_ad_cols) + \
181
+ [flags.default_ip] * len(ip_types) + \
182
+ [flags.default_parameters[flags.default_ip][0]] * len(ip_stops) + \
183
+ [flags.default_parameters[flags.default_ip][1]] * len(ip_weights)
184
+
185
+ ip_advanced.change(ip_advance_checked, inputs=ip_advanced,
186
+ outputs=ip_ad_cols + ip_types + ip_stops + ip_weights,
187
+ queue=False, show_progress=False)
188
+ with gr.TabItem(label='Inpaint or Outpaint') as inpaint_tab:
189
+ inpaint_input_image = grh.Image(label='Drag above image to here', source='upload', type='numpy', tool='sketch', height=500, brush_color="#FFFFFF", elem_id='inpaint_canvas')
190
+ with gr.Row():
191
+ inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", elem_id='inpaint_additional_prompt', label='Inpaint Additional Prompt', visible=False)
192
+ outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], label='Outpaint Direction')
193
+ inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, value=modules.flags.inpaint_option_default, label='Method')
194
+ example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, label='Additional Prompt Quick List', components=[inpaint_additional_prompt], visible=False)
195
+ gr.HTML('* Powered by Fooocus Inpaint Engine <a href="https://github.com/lllyasviel/Fooocus/discussions/414" target="_blank">\U0001F4D4 Document</a>')
196
+ example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, outputs=inpaint_additional_prompt, show_progress=False, queue=False)
197
+ with gr.TabItem(label='Describe') as desc_tab:
198
+ with gr.Row():
199
+ with gr.Column():
200
+ desc_input_image = grh.Image(label='Drag any image to here', source='upload', type='numpy')
201
+ with gr.Column():
202
+ desc_method = gr.Radio(
203
+ label='Content Type',
204
+ choices=[flags.desc_type_photo, flags.desc_type_anime],
205
+ value=flags.desc_type_photo)
206
+ desc_btn = gr.Button(value='Describe this Image into Prompt')
207
+ gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/1363" target="_blank">\U0001F4D4 Document</a>')
208
+ switch_js = "(x) => {if(x){viewer_to_bottom(100);viewer_to_bottom(500);}else{viewer_to_top();} return x;}"
209
+ down_js = "() => {viewer_to_bottom();}"
210
+
211
+ input_image_checkbox.change(lambda x: gr.update(visible=x), inputs=input_image_checkbox,
212
+ outputs=image_input_panel, queue=False, show_progress=False, _js=switch_js)
213
+ ip_advanced.change(lambda: None, queue=False, show_progress=False, _js=down_js)
214
+
215
+ current_tab = gr.Textbox(value='uov', visible=False)
216
+ uov_tab.select(lambda: 'uov', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
217
+ inpaint_tab.select(lambda: 'inpaint', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
218
+ ip_tab.select(lambda: 'ip', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
219
+ desc_tab.select(lambda: 'desc', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
220
+
221
+ with gr.Column(scale=1, visible=modules.config.default_advanced_checkbox) as advanced_column:
222
+ with gr.Tab(label='Setting'):
223
+ performance_selection = gr.Radio(label='Performance',
224
+ choices=modules.flags.performance_selections,
225
+ value=modules.config.default_performance)
226
+ aspect_ratios_selection = gr.Radio(label='Aspect Ratios', choices=modules.config.available_aspect_ratios,
227
+ value=modules.config.default_aspect_ratio, info='width × height',
228
+ elem_classes='aspect_ratios')
229
+ image_number = gr.Slider(label='Image Number', minimum=1, maximum=modules.config.default_max_image_number, step=1, value=modules.config.default_image_number)
230
+ negative_prompt = gr.Textbox(label='Negative Prompt', show_label=True, placeholder="Type prompt here.",
231
+ info='Describing what you do not want to see.', lines=2,
232
+ elem_id='negative_prompt',
233
+ value=modules.config.default_prompt_negative)
234
+ seed_random = gr.Checkbox(label='Random', value=True)
235
+ image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354
236
+
237
+ def random_checked(r):
238
+ return gr.update(visible=not r)
239
+
240
+ def refresh_seed(r, seed_string):
241
+ if r:
242
+ return random.randint(constants.MIN_SEED, constants.MAX_SEED)
243
+ else:
244
+ try:
245
+ seed_value = int(seed_string)
246
+ if constants.MIN_SEED <= seed_value <= constants.MAX_SEED:
247
+ return seed_value
248
+ except ValueError:
249
+ pass
250
+ return random.randint(constants.MIN_SEED, constants.MAX_SEED)
251
+
252
+ seed_random.change(random_checked, inputs=[seed_random], outputs=[image_seed],
253
+ queue=False, show_progress=False)
254
+
255
+ if not args_manager.args.disable_image_log:
256
+ gr.HTML(f'<a href="/file={get_current_html_path()}" target="_blank">\U0001F4DA History Log</a>')
257
+
258
+ with gr.Tab(label='Style'):
259
+ style_sorter.try_load_sorted_styles(
260
+ style_names=legal_style_names,
261
+ default_selected=modules.config.default_styles)
262
+
263
+ style_search_bar = gr.Textbox(show_label=False, container=False,
264
+ placeholder="\U0001F50E Type here to search styles ...",
265
+ value="",
266
+ label='Search Styles')
267
+ style_selections = gr.CheckboxGroup(show_label=False, container=False,
268
+ choices=copy.deepcopy(style_sorter.all_styles),
269
+ value=copy.deepcopy(modules.config.default_styles),
270
+ label='Selected Styles',
271
+ elem_classes=['style_selections'])
272
+ gradio_receiver_style_selections = gr.Textbox(elem_id='gradio_receiver_style_selections', visible=False)
273
+
274
+ shared.gradio_root.load(lambda: gr.update(choices=copy.deepcopy(style_sorter.all_styles)),
275
+ outputs=style_selections)
276
+
277
+ style_search_bar.change(style_sorter.search_styles,
278
+ inputs=[style_selections, style_search_bar],
279
+ outputs=style_selections,
280
+ queue=False,
281
+ show_progress=False).then(
282
+ lambda: None, _js='()=>{refresh_style_localization();}')
283
+
284
+ gradio_receiver_style_selections.input(style_sorter.sort_styles,
285
+ inputs=style_selections,
286
+ outputs=style_selections,
287
+ queue=False,
288
+ show_progress=False).then(
289
+ lambda: None, _js='()=>{refresh_style_localization();}')
290
+
291
+ with gr.Tab(label='Model'):
292
+ with gr.Group():
293
+ with gr.Row():
294
+ base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, value=modules.config.default_base_model_name, show_label=True)
295
+ refiner_model = gr.Dropdown(label='Refiner (SDXL or SD 1.5)', choices=['None'] + modules.config.model_filenames, value=modules.config.default_refiner_model_name, show_label=True)
296
+
297
+ refiner_switch = gr.Slider(label='Refiner Switch At', minimum=0.1, maximum=1.0, step=0.0001,
298
+ info='Use 0.4 for SD1.5 realistic models; '
299
+ 'or 0.667 for SD1.5 anime models; '
300
+ 'or 0.8 for XL-refiners; '
301
+ 'or any value for switching two SDXL models.',
302
+ value=modules.config.default_refiner_switch,
303
+ visible=modules.config.default_refiner_model_name != 'None')
304
+
305
+ refiner_model.change(lambda x: gr.update(visible=x != 'None'),
306
+ inputs=refiner_model, outputs=refiner_switch, show_progress=False, queue=False)
307
+
308
+ with gr.Group():
309
+ lora_ctrls = []
310
+
311
+ for i, (n, v) in enumerate(modules.config.default_loras):
312
+ with gr.Row():
313
+ lora_model = gr.Dropdown(label=f'LoRA {i + 1}',
314
+ choices=['None'] + modules.config.lora_filenames, value=n)
315
+ lora_weight = gr.Slider(label='Weight', minimum=-2, maximum=2, step=0.01, value=v,
316
+ elem_classes='lora_weight')
317
+ lora_ctrls += [lora_model, lora_weight]
318
+
319
+ with gr.Row():
320
+ model_refresh = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', variant='secondary', elem_classes='refresh_button')
321
+ with gr.Tab(label='Advanced'):
322
+ guidance_scale = gr.Slider(label='Guidance Scale', minimum=1.0, maximum=30.0, step=0.01,
323
+ value=modules.config.default_cfg_scale,
324
+ info='Higher value means style is cleaner, vivider, and more artistic.')
325
+ sharpness = gr.Slider(label='Image Sharpness', minimum=0.0, maximum=30.0, step=0.001,
326
+ value=modules.config.default_sample_sharpness,
327
+ info='Higher value means image and texture are sharper.')
328
+ gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/117" target="_blank">\U0001F4D4 Document</a>')
329
+ dev_mode = gr.Checkbox(label='Developer Debug Mode', value=False, container=False)
330
+
331
+ with gr.Column(visible=False) as dev_tools:
332
+ with gr.Tab(label='Debug Tools'):
333
+ adm_scaler_positive = gr.Slider(label='Positive ADM Guidance Scaler', minimum=0.1, maximum=3.0,
334
+ step=0.001, value=1.5, info='The scaler multiplied to positive ADM (use 1.0 to disable). ')
335
+ adm_scaler_negative = gr.Slider(label='Negative ADM Guidance Scaler', minimum=0.1, maximum=3.0,
336
+ step=0.001, value=0.8, info='The scaler multiplied to negative ADM (use 1.0 to disable). ')
337
+ adm_scaler_end = gr.Slider(label='ADM Guidance End At Step', minimum=0.0, maximum=1.0,
338
+ step=0.001, value=0.3,
339
+ info='When to end the guidance from positive/negative ADM. ')
340
+
341
+ refiner_swap_method = gr.Dropdown(label='Refiner swap method', value='joint',
342
+ choices=['joint', 'separate', 'vae'])
343
+
344
+ adaptive_cfg = gr.Slider(label='CFG Mimicking from TSNR', minimum=1.0, maximum=30.0, step=0.01,
345
+ value=modules.config.default_cfg_tsnr,
346
+ info='Enabling Fooocus\'s implementation of CFG mimicking for TSNR '
347
+ '(effective when real CFG > mimicked CFG).')
348
+ sampler_name = gr.Dropdown(label='Sampler', choices=flags.sampler_list,
349
+ value=modules.config.default_sampler)
350
+ scheduler_name = gr.Dropdown(label='Scheduler', choices=flags.scheduler_list,
351
+ value=modules.config.default_scheduler)
352
+
353
+ generate_image_grid = gr.Checkbox(label='Generate Image Grid for Each Batch',
354
+ info='(Experimental) This may cause performance problems on some computers and certain internet conditions.',
355
+ value=False)
356
+
357
+ overwrite_step = gr.Slider(label='Forced Overwrite of Sampling Step',
358
+ minimum=-1, maximum=200, step=1,
359
+ value=modules.config.default_overwrite_step,
360
+ info='Set as -1 to disable. For developer debugging.')
361
+ overwrite_switch = gr.Slider(label='Forced Overwrite of Refiner Switch Step',
362
+ minimum=-1, maximum=200, step=1,
363
+ value=modules.config.default_overwrite_switch,
364
+ info='Set as -1 to disable. For developer debugging.')
365
+ overwrite_width = gr.Slider(label='Forced Overwrite of Generating Width',
366
+ minimum=-1, maximum=2048, step=1, value=-1,
367
+ info='Set as -1 to disable. For developer debugging. '
368
+ 'Results will be worse for non-standard numbers that SDXL is not trained on.')
369
+ overwrite_height = gr.Slider(label='Forced Overwrite of Generating Height',
370
+ minimum=-1, maximum=2048, step=1, value=-1,
371
+ info='Set as -1 to disable. For developer debugging. '
372
+ 'Results will be worse for non-standard numbers that SDXL is not trained on.')
373
+ overwrite_vary_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Vary"',
374
+ minimum=-1, maximum=1.0, step=0.001, value=-1,
375
+ info='Set as negative number to disable. For developer debugging.')
376
+ overwrite_upscale_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Upscale"',
377
+ minimum=-1, maximum=1.0, step=0.001, value=-1,
378
+ info='Set as negative number to disable. For developer debugging.')
379
+ disable_preview = gr.Checkbox(label='Disable Preview', value=False,
380
+ info='Disable preview during generation.')
381
+
382
+ with gr.Tab(label='Control'):
383
+ debugging_cn_preprocessor = gr.Checkbox(label='Debug Preprocessors', value=False,
384
+ info='See the results from preprocessors.')
385
+ skipping_cn_preprocessor = gr.Checkbox(label='Skip Preprocessors', value=False,
386
+ info='Do not preprocess images. (Inputs are already canny/depth/cropped-face/etc.)')
387
+
388
+ mixing_image_prompt_and_vary_upscale = gr.Checkbox(label='Mixing Image Prompt and Vary/Upscale',
389
+ value=False)
390
+ mixing_image_prompt_and_inpaint = gr.Checkbox(label='Mixing Image Prompt and Inpaint',
391
+ value=False)
392
+
393
+ controlnet_softness = gr.Slider(label='Softness of ControlNet', minimum=0.0, maximum=1.0,
394
+ step=0.001, value=0.25,
395
+ info='Similar to the Control Mode in A1111 (use 0.0 to disable). ')
396
+
397
+ with gr.Tab(label='Canny'):
398
+ canny_low_threshold = gr.Slider(label='Canny Low Threshold', minimum=1, maximum=255,
399
+ step=1, value=64)
400
+ canny_high_threshold = gr.Slider(label='Canny High Threshold', minimum=1, maximum=255,
401
+ step=1, value=128)
402
+
403
+ with gr.Tab(label='Inpaint'):
404
+ debugging_inpaint_preprocessor = gr.Checkbox(label='Debug Inpaint Preprocessing', value=False)
405
+ inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', value=False)
406
+ inpaint_engine = gr.Dropdown(label='Inpaint Engine',
407
+ value=modules.config.default_inpaint_engine_version,
408
+ choices=flags.inpaint_engine_versions,
409
+ info='Version of Fooocus inpaint model')
410
+ inpaint_strength = gr.Slider(label='Inpaint Denoising Strength',
411
+ minimum=0.0, maximum=1.0, step=0.001, value=1.0,
412
+ info='Same as the denoising strength in A1111 inpaint. '
413
+ 'Only used in inpaint, not used in outpaint. '
414
+ '(Outpaint always use 1.0)')
415
+ inpaint_respective_field = gr.Slider(label='Inpaint Respective Field',
416
+ minimum=0.0, maximum=1.0, step=0.001, value=0.618,
417
+ info='The area to inpaint. '
418
+ 'Value 0 is same as "Only Masked" in A1111. '
419
+ 'Value 1 is same as "Whole Image" in A1111. '
420
+ 'Only used in inpaint, not used in outpaint. '
421
+ '(Outpaint always use 1.0)')
422
+ inpaint_ctrls = [debugging_inpaint_preprocessor, inpaint_disable_initial_latent, inpaint_engine, inpaint_strength, inpaint_respective_field]
423
+
424
+ with gr.Tab(label='FreeU'):
425
+ freeu_enabled = gr.Checkbox(label='Enabled', value=False)
426
+ freeu_b1 = gr.Slider(label='B1', minimum=0, maximum=2, step=0.01, value=1.01)
427
+ freeu_b2 = gr.Slider(label='B2', minimum=0, maximum=2, step=0.01, value=1.02)
428
+ freeu_s1 = gr.Slider(label='S1', minimum=0, maximum=4, step=0.01, value=0.99)
429
+ freeu_s2 = gr.Slider(label='S2', minimum=0, maximum=4, step=0.01, value=0.95)
430
+ freeu_ctrls = [freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2]
431
+
432
+ adps = [disable_preview, adm_scaler_positive, adm_scaler_negative, adm_scaler_end, adaptive_cfg, sampler_name,
433
+ scheduler_name, generate_image_grid, overwrite_step, overwrite_switch, overwrite_width, overwrite_height,
434
+ overwrite_vary_strength, overwrite_upscale_strength,
435
+ mixing_image_prompt_and_vary_upscale, mixing_image_prompt_and_inpaint,
436
+ debugging_cn_preprocessor, skipping_cn_preprocessor, controlnet_softness,
437
+ canny_low_threshold, canny_high_threshold, refiner_swap_method]
438
+ adps += freeu_ctrls
439
+ adps += inpaint_ctrls
440
+
441
+ def dev_mode_checked(r):
442
+ return gr.update(visible=r)
443
+
444
+
445
+ dev_mode.change(dev_mode_checked, inputs=[dev_mode], outputs=[dev_tools],
446
+ queue=False, show_progress=False)
447
+
448
+ def model_refresh_clicked():
449
+ modules.config.update_all_model_names()
450
+ results = []
451
+ results += [gr.update(choices=modules.config.model_filenames), gr.update(choices=['None'] + modules.config.model_filenames)]
452
+ for i in range(5):
453
+ results += [gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()]
454
+ return results
455
+
456
+ model_refresh.click(model_refresh_clicked, [], [base_model, refiner_model] + lora_ctrls,
457
+ queue=False, show_progress=False)
458
+
459
+ performance_selection.change(lambda x: [gr.update(interactive=x != 'Extreme Speed')] * 11 +
460
+ [gr.update(visible=x != 'Extreme Speed')] * 1,
461
+ inputs=performance_selection,
462
+ outputs=[
463
+ guidance_scale, sharpness, adm_scaler_end, adm_scaler_positive,
464
+ adm_scaler_negative, refiner_switch, refiner_model, sampler_name,
465
+ scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt
466
+ ], queue=False, show_progress=False)
467
+
468
+ advanced_checkbox.change(lambda x: gr.update(visible=x), advanced_checkbox, advanced_column,
469
+ queue=False, show_progress=False) \
470
+ .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False)
471
+
472
+ def inpaint_mode_change(mode):
473
+ assert mode in modules.flags.inpaint_options
474
+
475
+ # inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
476
+ # inpaint_disable_initial_latent, inpaint_engine,
477
+ # inpaint_strength, inpaint_respective_field
478
+
479
+ if mode == modules.flags.inpaint_option_detail:
480
+ return [
481
+ gr.update(visible=True), gr.update(visible=False, value=[]),
482
+ gr.Dataset.update(visible=True, samples=modules.config.example_inpaint_prompts),
483
+ False, 'None', 0.5, 0.0
484
+ ]
485
+
486
+ if mode == modules.flags.inpaint_option_modify:
487
+ return [
488
+ gr.update(visible=True), gr.update(visible=False, value=[]),
489
+ gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
490
+ True, modules.config.default_inpaint_engine_version, 1.0, 0.0
491
+ ]
492
+
493
+ return [
494
+ gr.update(visible=False, value=''), gr.update(visible=True),
495
+ gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
496
+ False, modules.config.default_inpaint_engine_version, 1.0, 0.618
497
+ ]
498
+
499
+ inpaint_mode.input(inpaint_mode_change, inputs=inpaint_mode, outputs=[
500
+ inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
501
+ inpaint_disable_initial_latent, inpaint_engine,
502
+ inpaint_strength, inpaint_respective_field
503
+ ], show_progress=False, queue=False)
504
+
505
+ ctrls = [
506
+ prompt, negative_prompt, style_selections,
507
+ performance_selection, aspect_ratios_selection, image_number, image_seed, sharpness, guidance_scale
508
+ ]
509
+
510
+ ctrls += [base_model, refiner_model, refiner_switch] + lora_ctrls
511
+ ctrls += [input_image_checkbox, current_tab]
512
+ ctrls += [uov_method, uov_input_image]
513
+ ctrls += [outpaint_selections, inpaint_input_image, inpaint_additional_prompt]
514
+ ctrls += ip_ctrls
515
+
516
+ state_is_generating = gr.State(False)
517
+
518
+ def parse_meta(raw_prompt_txt, is_generating):
519
+ loaded_json = None
520
+ try:
521
+ if '{' in raw_prompt_txt:
522
+ if '}' in raw_prompt_txt:
523
+ if ':' in raw_prompt_txt:
524
+ loaded_json = json.loads(raw_prompt_txt)
525
+ assert isinstance(loaded_json, dict)
526
+ except:
527
+ loaded_json = None
528
+
529
+ if loaded_json is None:
530
+ if is_generating:
531
+ return gr.update(), gr.update(), gr.update()
532
+ else:
533
+ return gr.update(), gr.update(visible=True), gr.update(visible=False)
534
+
535
+ return json.dumps(loaded_json), gr.update(visible=False), gr.update(visible=True)
536
+
537
+ prompt.input(parse_meta, inputs=[prompt, state_is_generating], outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False)
538
+
539
+ load_parameter_button.click(modules.meta_parser.load_parameter_button_click, inputs=[prompt, state_is_generating], outputs=[
540
+ advanced_checkbox,
541
+ image_number,
542
+ prompt,
543
+ negative_prompt,
544
+ style_selections,
545
+ performance_selection,
546
+ aspect_ratios_selection,
547
+ overwrite_width,
548
+ overwrite_height,
549
+ sharpness,
550
+ guidance_scale,
551
+ adm_scaler_positive,
552
+ adm_scaler_negative,
553
+ adm_scaler_end,
554
+ base_model,
555
+ refiner_model,
556
+ refiner_switch,
557
+ sampler_name,
558
+ scheduler_name,
559
+ seed_random,
560
+ image_seed,
561
+ generate_button,
562
+ load_parameter_button
563
+ ] + lora_ctrls, queue=False, show_progress=False)
564
+
565
+ generate_button.click(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), [], True),
566
+ outputs=[stop_button, skip_button, generate_button, gallery, state_is_generating]) \
567
+ .then(fn=refresh_seed, inputs=[seed_random, image_seed], outputs=image_seed) \
568
+ .then(advanced_parameters.set_all_advanced_parameters, inputs=adps) \
569
+ .then(fn=generate_clicked, inputs=ctrls, outputs=[progress_html, progress_window, progress_gallery, gallery]) \
570
+ .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), gr.update(visible=False, interactive=False), False),
571
+ outputs=[generate_button, stop_button, skip_button, state_is_generating]) \
572
+ .then(fn=lambda: None, _js='playNotification').then(fn=lambda: None, _js='refresh_grid_delayed')
573
+
574
+ for notification_file in ['notification.ogg', 'notification.mp3']:
575
+ if os.path.exists(notification_file):
576
+ gr.Audio(interactive=False, value=notification_file, elem_id='audio_notification', visible=False)
577
+ break
578
+
579
+ def trigger_describe(mode, img):
580
+ if mode == flags.desc_type_photo:
581
+ from extras.interrogate import default_interrogator as default_interrogator_photo
582
+ return default_interrogator_photo(img), ["Fooocus V2", "Fooocus Enhance", "Fooocus Sharp"]
583
+ if mode == flags.desc_type_anime:
584
+ from extras.wd14tagger import default_interrogator as default_interrogator_anime
585
+ return default_interrogator_anime(img), ["Fooocus V2", "Fooocus Masterpiece"]
586
+ return mode, ["Fooocus V2"]
587
+
588
+ desc_btn.click(trigger_describe, inputs=[desc_method, desc_input_image],
589
+ outputs=[prompt, style_selections], show_progress=True, queue=True)
590
+
591
+
592
+ def dump_default_english_config():
593
+ from modules.localization import dump_english_config
594
+ dump_english_config(grh.all_components)
595
+
596
+
597
+ # dump_default_english_config()
598
+
599
+ shared.gradio_root.launch(
600
+ inbrowser=args_manager.args.in_browser,
601
+ server_name=args_manager.args.listen,
602
+ server_port=args_manager.args.port,
603
+ share=args_manager.args.share,
604
+ auth=check_auth if args_manager.args.share and auth_enabled else None,
605
+ blocked_paths=[constants.AUTH_FILENAME]
606
+ )