Thekingbalxd commited on
Commit
3b4aa62
·
verified ·
1 Parent(s): acdd15b

Delete webui.py

Browse files
Files changed (1) hide show
  1. webui.py +0 -744
webui.py DELETED
@@ -1,744 +0,0 @@
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.style_sorter as style_sorter
15
- import modules.meta_parser
16
- import args_manager
17
- import copy
18
- import launch
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
- from modules.util import is_json
25
-
26
- def get_task(*args):
27
- args = list(args)
28
- args.pop(0)
29
-
30
- return worker.AsyncTask(args=args)
31
-
32
- def generate_clicked(task: worker.AsyncTask):
33
- import ldm_patched.modules.model_management as model_management
34
-
35
- with model_management.interrupt_processing_mutex:
36
- model_management.interrupt_processing = False
37
- # outputs=[progress_html, progress_window, progress_gallery, gallery]
38
-
39
- if len(task.args) == 0:
40
- return
41
-
42
- execution_start_time = time.perf_counter()
43
- finished = False
44
-
45
- yield gr.update(visible=True, value=modules.html.make_progress_html(1, 'Waiting for task to start ...')), \
46
- gr.update(visible=True, value=None), \
47
- gr.update(visible=False, value=None), \
48
- gr.update(visible=False)
49
-
50
- worker.async_tasks.append(task)
51
-
52
- while not finished:
53
- time.sleep(0.01)
54
- if len(task.yields) > 0:
55
- flag, product = task.yields.pop(0)
56
- if flag == 'preview':
57
-
58
- # help bad internet connection by skipping duplicated preview
59
- if len(task.yields) > 0: # if we have the next item
60
- if task.yields[0][0] == 'preview': # if the next item is also a preview
61
- # print('Skipped one preview for better internet connection.')
62
- continue
63
-
64
- percentage, title, image = product
65
- yield gr.update(visible=True, value=modules.html.make_progress_html(percentage, title)), \
66
- gr.update(visible=True, value=image) if image is not None else gr.update(), \
67
- gr.update(), \
68
- gr.update(visible=False)
69
- if flag == 'results':
70
- yield gr.update(visible=True), \
71
- gr.update(visible=True), \
72
- gr.update(visible=True, value=product), \
73
- gr.update(visible=False)
74
- if flag == 'finish':
75
- yield gr.update(visible=False), \
76
- gr.update(visible=False), \
77
- gr.update(visible=False), \
78
- gr.update(visible=True, value=product)
79
- finished = True
80
-
81
- # delete Fooocus temp images, only keep gradio temp images
82
- if args_manager.args.disable_image_log:
83
- for filepath in product:
84
- if isinstance(filepath, str) and os.path.exists(filepath):
85
- os.remove(filepath)
86
-
87
- execution_time = time.perf_counter() - execution_start_time
88
- print(f'Total time: {execution_time:.2f} seconds')
89
- return
90
-
91
-
92
- reload_javascript()
93
-
94
- title = f'Fooocus {fooocus_version.version}'
95
-
96
- if isinstance(args_manager.args.preset, str):
97
- title += ' ' + args_manager.args.preset
98
-
99
- shared.gradio_root = gr.Blocks(title=title).queue()
100
-
101
- with shared.gradio_root:
102
- currentTask = gr.State(worker.AsyncTask(args=[]))
103
- with gr.Row():
104
- with gr.Column(scale=2):
105
- with gr.Row():
106
- progress_window = grh.Image(label='Preview', show_label=True, visible=False, height=768,
107
- elem_classes=['main_view'])
108
- progress_gallery = gr.Gallery(label='Finished Images', show_label=True, object_fit='contain',
109
- height=768, visible=False, elem_classes=['main_view', 'image_gallery'])
110
- progress_html = gr.HTML(value=modules.html.make_progress_html(32, 'Progress 32%'), visible=False,
111
- elem_id='progress-bar', elem_classes='progress-bar')
112
- gallery = gr.Gallery(label='Gallery', show_label=False, object_fit='contain', visible=True, height=768,
113
- elem_classes=['resizable_area', 'main_view', 'final_gallery', 'image_gallery'],
114
- elem_id='final_gallery')
115
- with gr.Row(elem_classes='type_row'):
116
- with gr.Column(scale=17):
117
- prompt = gr.Textbox(show_label=False, placeholder="Type prompt here or paste parameters.", elem_id='positive_prompt',
118
- container=False, autofocus=True, elem_classes='type_row', lines=1024)
119
-
120
- default_prompt = modules.config.default_prompt
121
- if isinstance(default_prompt, str) and default_prompt != '':
122
- shared.gradio_root.load(lambda: default_prompt, outputs=prompt)
123
-
124
- with gr.Column(scale=3, min_width=0):
125
- generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', elem_id='generate_button', visible=True)
126
- load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", elem_classes='type_row', elem_id='load_parameter_button', visible=False)
127
- skip_button = gr.Button(label="Skip", value="Skip", elem_classes='type_row_half', visible=False)
128
- stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', elem_id='stop_button', visible=False)
129
-
130
- def stop_clicked(currentTask):
131
- import ldm_patched.modules.model_management as model_management
132
- currentTask.last_stop = 'stop'
133
- if (currentTask.processing):
134
- model_management.interrupt_current_processing()
135
- return currentTask
136
-
137
- def skip_clicked(currentTask):
138
- import ldm_patched.modules.model_management as model_management
139
- currentTask.last_stop = 'skip'
140
- if (currentTask.processing):
141
- model_management.interrupt_current_processing()
142
- return currentTask
143
-
144
- stop_button.click(stop_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False, _js='cancelGenerateForever')
145
- skip_button.click(skip_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False)
146
- with gr.Row(elem_classes='advanced_check_row'):
147
- input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, elem_classes='min_check')
148
- advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, container=False, elem_classes='min_check')
149
- with gr.Row(visible=False) as image_input_panel:
150
- with gr.Tabs():
151
- with gr.TabItem(label='Upscale or Variation') as uov_tab:
152
- with gr.Row():
153
- with gr.Column():
154
- uov_input_image = grh.Image(label='Drag above image to here', source='upload', type='numpy')
155
- with gr.Column():
156
- uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, value=flags.disabled)
157
- gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/390" target="_blank">\U0001F4D4 Document</a>')
158
- with gr.TabItem(label='Image Prompt') as ip_tab:
159
- with gr.Row():
160
- ip_images = []
161
- ip_types = []
162
- ip_stops = []
163
- ip_weights = []
164
- ip_ctrls = []
165
- ip_ad_cols = []
166
- for _ in range(flags.controlnet_image_count):
167
- with gr.Column():
168
- ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, height=300)
169
- ip_images.append(ip_image)
170
- ip_ctrls.append(ip_image)
171
- with gr.Column(visible=False) as ad_col:
172
- with gr.Row():
173
- default_end, default_weight = flags.default_parameters[flags.default_ip]
174
-
175
- ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, value=default_end)
176
- ip_stops.append(ip_stop)
177
- ip_ctrls.append(ip_stop)
178
-
179
- ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, value=default_weight)
180
- ip_weights.append(ip_weight)
181
- ip_ctrls.append(ip_weight)
182
-
183
- ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, container=False)
184
- ip_types.append(ip_type)
185
- ip_ctrls.append(ip_type)
186
-
187
- ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], outputs=[ip_stop, ip_weight], queue=False, show_progress=False)
188
- ip_ad_cols.append(ad_col)
189
- ip_advanced = gr.Checkbox(label='Advanced', value=False, container=False)
190
- 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>')
191
-
192
- def ip_advance_checked(x):
193
- return [gr.update(visible=x)] * len(ip_ad_cols) + \
194
- [flags.default_ip] * len(ip_types) + \
195
- [flags.default_parameters[flags.default_ip][0]] * len(ip_stops) + \
196
- [flags.default_parameters[flags.default_ip][1]] * len(ip_weights)
197
-
198
- ip_advanced.change(ip_advance_checked, inputs=ip_advanced,
199
- outputs=ip_ad_cols + ip_types + ip_stops + ip_weights,
200
- queue=False, show_progress=False)
201
- with gr.TabItem(label='Inpaint or Outpaint') as inpaint_tab:
202
- with gr.Row():
203
- inpaint_input_image = grh.Image(label='Drag inpaint or outpaint image to here', source='upload', type='numpy', tool='sketch', height=500, brush_color="#FFFFFF", elem_id='inpaint_canvas')
204
- inpaint_mask_image = grh.Image(label='Mask Upload', source='upload', type='numpy', height=500, visible=False)
205
-
206
- with gr.Row():
207
- inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", elem_id='inpaint_additional_prompt', label='Inpaint Additional Prompt', visible=False)
208
- outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], label='Outpaint Direction')
209
- inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, value=modules.flags.inpaint_option_default, label='Method')
210
- example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, label='Additional Prompt Quick List', components=[inpaint_additional_prompt], visible=False)
211
- gr.HTML('* Powered by Fooocus Inpaint Engine <a href="https://github.com/lllyasviel/Fooocus/discussions/414" target="_blank">\U0001F4D4 Document</a>')
212
- example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, outputs=inpaint_additional_prompt, show_progress=False, queue=False)
213
- with gr.TabItem(label='Describe') as desc_tab:
214
- with gr.Row():
215
- with gr.Column():
216
- desc_input_image = grh.Image(label='Drag any image to here', source='upload', type='numpy')
217
- with gr.Column():
218
- desc_method = gr.Radio(
219
- label='Content Type',
220
- choices=[flags.desc_type_photo, flags.desc_type_anime],
221
- value=flags.desc_type_photo)
222
- desc_btn = gr.Button(value='Describe this Image into Prompt')
223
- gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/1363" target="_blank">\U0001F4D4 Document</a>')
224
- with gr.TabItem(label='Metadata') as load_tab:
225
- with gr.Column():
226
- metadata_input_image = grh.Image(label='Drag any image generated by Fooocus here', source='upload', type='filepath')
227
- metadata_json = gr.JSON(label='Metadata')
228
- metadata_import_button = gr.Button(value='Apply Metadata')
229
-
230
- def trigger_metadata_preview(filepath):
231
- parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath)
232
-
233
- results = {}
234
- if parameters is not None:
235
- results['parameters'] = parameters
236
-
237
- if isinstance(metadata_scheme, flags.MetadataScheme):
238
- results['metadata_scheme'] = metadata_scheme.value
239
-
240
- return results
241
-
242
- metadata_input_image.upload(trigger_metadata_preview, inputs=metadata_input_image,
243
- outputs=metadata_json, queue=False, show_progress=True)
244
-
245
- switch_js = "(x) => {if(x){viewer_to_bottom(100);viewer_to_bottom(500);}else{viewer_to_top();} return x;}"
246
- down_js = "() => {viewer_to_bottom();}"
247
-
248
- input_image_checkbox.change(lambda x: gr.update(visible=x), inputs=input_image_checkbox,
249
- outputs=image_input_panel, queue=False, show_progress=False, _js=switch_js)
250
- ip_advanced.change(lambda: None, queue=False, show_progress=False, _js=down_js)
251
-
252
- current_tab = gr.Textbox(value='uov', visible=False)
253
- uov_tab.select(lambda: 'uov', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
254
- inpaint_tab.select(lambda: 'inpaint', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
255
- ip_tab.select(lambda: 'ip', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
256
- desc_tab.select(lambda: 'desc', outputs=current_tab, queue=False, _js=down_js, show_progress=False)
257
-
258
- with gr.Column(scale=1, visible=modules.config.default_advanced_checkbox) as advanced_column:
259
- with gr.Tab(label='Setting'):
260
- if not args_manager.args.disable_preset_selection:
261
- preset_selection = gr.Radio(label='Preset',
262
- choices=modules.config.available_presets,
263
- value=args_manager.args.preset if args_manager.args.preset else "initial",
264
- interactive=True)
265
- performance_selection = gr.Radio(label='Performance',
266
- choices=flags.Performance.list(),
267
- value=modules.config.default_performance)
268
- aspect_ratios_selection = gr.Radio(label='Aspect Ratios', choices=modules.config.available_aspect_ratios,
269
- value=modules.config.default_aspect_ratio, info='width × height',
270
- elem_classes='aspect_ratios')
271
- image_number = gr.Slider(label='Image Number', minimum=1, maximum=modules.config.default_max_image_number, step=1, value=modules.config.default_image_number)
272
-
273
- output_format = gr.Radio(label='Output Format',
274
- choices=flags.OutputFormat.list(),
275
- value=modules.config.default_output_format)
276
-
277
- negative_prompt = gr.Textbox(label='Negative Prompt', show_label=True, placeholder="Type prompt here.",
278
- info='Describing what you do not want to see.', lines=2,
279
- elem_id='negative_prompt',
280
- value=modules.config.default_prompt_negative)
281
- seed_random = gr.Checkbox(label='Random', value=True)
282
- image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354
283
-
284
- def random_checked(r):
285
- return gr.update(visible=not r)
286
-
287
- def refresh_seed(r, seed_string):
288
- if r:
289
- return random.randint(constants.MIN_SEED, constants.MAX_SEED)
290
- else:
291
- try:
292
- seed_value = int(seed_string)
293
- if constants.MIN_SEED <= seed_value <= constants.MAX_SEED:
294
- return seed_value
295
- except ValueError:
296
- pass
297
- return random.randint(constants.MIN_SEED, constants.MAX_SEED)
298
-
299
- seed_random.change(random_checked, inputs=[seed_random], outputs=[image_seed],
300
- queue=False, show_progress=False)
301
-
302
- def update_history_link():
303
- if args_manager.args.disable_image_log:
304
- return gr.update(value='')
305
-
306
- return gr.update(value=f'<a href="file={get_current_html_path(output_format)}" target="_blank">\U0001F4DA History Log</a>')
307
-
308
- history_link = gr.HTML()
309
- shared.gradio_root.load(update_history_link, outputs=history_link, queue=False, show_progress=False)
310
-
311
- with gr.Tab(label='Style', elem_classes=['style_selections_tab']):
312
- style_sorter.try_load_sorted_styles(
313
- style_names=legal_style_names,
314
- default_selected=modules.config.default_styles)
315
-
316
- style_search_bar = gr.Textbox(show_label=False, container=False,
317
- placeholder="\U0001F50E Type here to search styles ...",
318
- value="",
319
- label='Search Styles')
320
- style_selections = gr.CheckboxGroup(show_label=False, container=False,
321
- choices=copy.deepcopy(style_sorter.all_styles),
322
- value=copy.deepcopy(modules.config.default_styles),
323
- label='Selected Styles',
324
- elem_classes=['style_selections'])
325
- gradio_receiver_style_selections = gr.Textbox(elem_id='gradio_receiver_style_selections', visible=False)
326
-
327
- shared.gradio_root.load(lambda: gr.update(choices=copy.deepcopy(style_sorter.all_styles)),
328
- outputs=style_selections)
329
-
330
- style_search_bar.change(style_sorter.search_styles,
331
- inputs=[style_selections, style_search_bar],
332
- outputs=style_selections,
333
- queue=False,
334
- show_progress=False).then(
335
- lambda: None, _js='()=>{refresh_style_localization();}')
336
-
337
- gradio_receiver_style_selections.input(style_sorter.sort_styles,
338
- inputs=style_selections,
339
- outputs=style_selections,
340
- queue=False,
341
- show_progress=False).then(
342
- lambda: None, _js='()=>{refresh_style_localization();}')
343
-
344
- with gr.Tab(label='Model'):
345
- with gr.Group():
346
- with gr.Row():
347
- base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, value=modules.config.default_base_model_name, show_label=True)
348
- 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)
349
-
350
- refiner_switch = gr.Slider(label='Refiner Switch At', minimum=0.1, maximum=1.0, step=0.0001,
351
- info='Use 0.4 for SD1.5 realistic models; '
352
- 'or 0.667 for SD1.5 anime models; '
353
- 'or 0.8 for XL-refiners; '
354
- 'or any value for switching two SDXL models.',
355
- value=modules.config.default_refiner_switch,
356
- visible=modules.config.default_refiner_model_name != 'None')
357
-
358
- refiner_model.change(lambda x: gr.update(visible=x != 'None'),
359
- inputs=refiner_model, outputs=refiner_switch, show_progress=False, queue=False)
360
-
361
- with gr.Group():
362
- lora_ctrls = []
363
-
364
- for i, (enabled, filename, weight) in enumerate(modules.config.default_loras):
365
- with gr.Row():
366
- lora_enabled = gr.Checkbox(label='Enable', value=enabled,
367
- elem_classes=['lora_enable', 'min_check'], scale=1)
368
- lora_model = gr.Dropdown(label=f'LoRA {i + 1}',
369
- choices=['None'] + modules.config.lora_filenames, value=filename,
370
- elem_classes='lora_model', scale=5)
371
- lora_weight = gr.Slider(label='Weight', minimum=modules.config.default_loras_min_weight,
372
- maximum=modules.config.default_loras_max_weight, step=0.01, value=weight,
373
- elem_classes='lora_weight', scale=5)
374
- lora_ctrls += [lora_enabled, lora_model, lora_weight]
375
-
376
- with gr.Row():
377
- refresh_files = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', variant='secondary', elem_classes='refresh_button')
378
- with gr.Tab(label='Advanced'):
379
- guidance_scale = gr.Slider(label='Guidance Scale', minimum=1.0, maximum=30.0, step=0.01,
380
- value=modules.config.default_cfg_scale,
381
- info='Higher value means style is cleaner, vivider, and more artistic.')
382
- sharpness = gr.Slider(label='Image Sharpness', minimum=0.0, maximum=30.0, step=0.001,
383
- value=modules.config.default_sample_sharpness,
384
- info='Higher value means image and texture are sharper.')
385
- gr.HTML('<a href="https://github.com/lllyasviel/Fooocus/discussions/117" target="_blank">\U0001F4D4 Document</a>')
386
- dev_mode = gr.Checkbox(label='Developer Debug Mode', value=False, container=False)
387
-
388
- with gr.Column(visible=False) as dev_tools:
389
- with gr.Tab(label='Debug Tools'):
390
- adm_scaler_positive = gr.Slider(label='Positive ADM Guidance Scaler', minimum=0.1, maximum=3.0,
391
- step=0.001, value=1.5, info='The scaler multiplied to positive ADM (use 1.0 to disable). ')
392
- adm_scaler_negative = gr.Slider(label='Negative ADM Guidance Scaler', minimum=0.1, maximum=3.0,
393
- step=0.001, value=0.8, info='The scaler multiplied to negative ADM (use 1.0 to disable). ')
394
- adm_scaler_end = gr.Slider(label='ADM Guidance End At Step', minimum=0.0, maximum=1.0,
395
- step=0.001, value=0.3,
396
- info='When to end the guidance from positive/negative ADM. ')
397
-
398
- refiner_swap_method = gr.Dropdown(label='Refiner swap method', value=flags.refiner_swap_method,
399
- choices=['joint', 'separate', 'vae'])
400
-
401
- adaptive_cfg = gr.Slider(label='CFG Mimicking from TSNR', minimum=1.0, maximum=30.0, step=0.01,
402
- value=modules.config.default_cfg_tsnr,
403
- info='Enabling Fooocus\'s implementation of CFG mimicking for TSNR '
404
- '(effective when real CFG > mimicked CFG).')
405
- sampler_name = gr.Dropdown(label='Sampler', choices=flags.sampler_list,
406
- value=modules.config.default_sampler)
407
- scheduler_name = gr.Dropdown(label='Scheduler', choices=flags.scheduler_list,
408
- value=modules.config.default_scheduler)
409
-
410
- generate_image_grid = gr.Checkbox(label='Generate Image Grid for Each Batch',
411
- info='(Experimental) This may cause performance problems on some computers and certain internet conditions.',
412
- value=False)
413
-
414
- overwrite_step = gr.Slider(label='Forced Overwrite of Sampling Step',
415
- minimum=-1, maximum=200, step=1,
416
- value=modules.config.default_overwrite_step,
417
- info='Set as -1 to disable. For developer debugging.')
418
- overwrite_switch = gr.Slider(label='Forced Overwrite of Refiner Switch Step',
419
- minimum=-1, maximum=200, step=1,
420
- value=modules.config.default_overwrite_switch,
421
- info='Set as -1 to disable. For developer debugging.')
422
- overwrite_width = gr.Slider(label='Forced Overwrite of Generating Width',
423
- minimum=-1, maximum=2048, step=1, value=-1,
424
- info='Set as -1 to disable. For developer debugging. '
425
- 'Results will be worse for non-standard numbers that SDXL is not trained on.')
426
- overwrite_height = gr.Slider(label='Forced Overwrite of Generating Height',
427
- minimum=-1, maximum=2048, step=1, value=-1,
428
- info='Set as -1 to disable. For developer debugging. '
429
- 'Results will be worse for non-standard numbers that SDXL is not trained on.')
430
- overwrite_vary_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Vary"',
431
- minimum=-1, maximum=1.0, step=0.001, value=-1,
432
- info='Set as negative number to disable. For developer debugging.')
433
- overwrite_upscale_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Upscale"',
434
- minimum=-1, maximum=1.0, step=0.001, value=-1,
435
- info='Set as negative number to disable. For developer debugging.')
436
- disable_preview = gr.Checkbox(label='Disable Preview', value=False,
437
- info='Disable preview during generation.')
438
- disable_intermediate_results = gr.Checkbox(label='Disable Intermediate Results',
439
- value=modules.config.default_performance == flags.Performance.EXTREME_SPEED.value,
440
- interactive=modules.config.default_performance != flags.Performance.EXTREME_SPEED.value,
441
- info='Disable intermediate results during generation, only show final gallery.')
442
- disable_seed_increment = gr.Checkbox(label='Disable seed increment',
443
- info='Disable automatic seed increment when image number is > 1.',
444
- value=False)
445
- read_wildcards_in_order = gr.Checkbox(label="Read wildcards in order", value=False)
446
-
447
- if not args_manager.args.disable_metadata:
448
- save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', value=modules.config.default_save_metadata_to_images,
449
- info='Adds parameters to generated images allowing manual regeneration.')
450
- metadata_scheme = gr.Radio(label='Metadata Scheme', choices=flags.metadata_scheme, value=modules.config.default_metadata_scheme,
451
- info='Image Prompt parameters are not included. Use png and a1111 for compatibility with Civitai.',
452
- visible=modules.config.default_save_metadata_to_images)
453
-
454
- save_metadata_to_images.change(lambda x: gr.update(visible=x), inputs=[save_metadata_to_images], outputs=[metadata_scheme],
455
- queue=False, show_progress=False)
456
-
457
- with gr.Tab(label='Control'):
458
- debugging_cn_preprocessor = gr.Checkbox(label='Debug Preprocessors', value=False,
459
- info='See the results from preprocessors.')
460
- skipping_cn_preprocessor = gr.Checkbox(label='Skip Preprocessors', value=False,
461
- info='Do not preprocess images. (Inputs are already canny/depth/cropped-face/etc.)')
462
-
463
- mixing_image_prompt_and_vary_upscale = gr.Checkbox(label='Mixing Image Prompt and Vary/Upscale',
464
- value=False)
465
- mixing_image_prompt_and_inpaint = gr.Checkbox(label='Mixing Image Prompt and Inpaint',
466
- value=False)
467
-
468
- controlnet_softness = gr.Slider(label='Softness of ControlNet', minimum=0.0, maximum=1.0,
469
- step=0.001, value=0.25,
470
- info='Similar to the Control Mode in A1111 (use 0.0 to disable). ')
471
-
472
- with gr.Tab(label='Canny'):
473
- canny_low_threshold = gr.Slider(label='Canny Low Threshold', minimum=1, maximum=255,
474
- step=1, value=64)
475
- canny_high_threshold = gr.Slider(label='Canny High Threshold', minimum=1, maximum=255,
476
- step=1, value=128)
477
-
478
- with gr.Tab(label='Inpaint'):
479
- debugging_inpaint_preprocessor = gr.Checkbox(label='Debug Inpaint Preprocessing', value=False)
480
- inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', value=False)
481
- inpaint_engine = gr.Dropdown(label='Inpaint Engine',
482
- value=modules.config.default_inpaint_engine_version,
483
- choices=flags.inpaint_engine_versions,
484
- info='Version of Fooocus inpaint model')
485
- inpaint_strength = gr.Slider(label='Inpaint Denoising Strength',
486
- minimum=0.0, maximum=1.0, step=0.001, value=1.0,
487
- info='Same as the denoising strength in A1111 inpaint. '
488
- 'Only used in inpaint, not used in outpaint. '
489
- '(Outpaint always use 1.0)')
490
- inpaint_respective_field = gr.Slider(label='Inpaint Respective Field',
491
- minimum=0.0, maximum=1.0, step=0.001, value=0.618,
492
- info='The area to inpaint. '
493
- 'Value 0 is same as "Only Masked" in A1111. '
494
- 'Value 1 is same as "Whole Image" in A1111. '
495
- 'Only used in inpaint, not used in outpaint. '
496
- '(Outpaint always use 1.0)')
497
- inpaint_erode_or_dilate = gr.Slider(label='Mask Erode or Dilate',
498
- minimum=-64, maximum=64, step=1, value=0,
499
- info='Positive value will make white area in the mask larger, '
500
- 'negative value will make white area smaller.'
501
- '(default is 0, always process before any mask invert)')
502
- inpaint_mask_upload_checkbox = gr.Checkbox(label='Enable Mask Upload', value=False)
503
- invert_mask_checkbox = gr.Checkbox(label='Invert Mask', value=False)
504
-
505
- inpaint_ctrls = [debugging_inpaint_preprocessor, inpaint_disable_initial_latent, inpaint_engine,
506
- inpaint_strength, inpaint_respective_field,
507
- inpaint_mask_upload_checkbox, invert_mask_checkbox, inpaint_erode_or_dilate]
508
-
509
- inpaint_mask_upload_checkbox.change(lambda x: gr.update(visible=x),
510
- inputs=inpaint_mask_upload_checkbox,
511
- outputs=inpaint_mask_image, queue=False, show_progress=False)
512
-
513
- with gr.Tab(label='FreeU'):
514
- freeu_enabled = gr.Checkbox(label='Enabled', value=False)
515
- freeu_b1 = gr.Slider(label='B1', minimum=0, maximum=2, step=0.01, value=1.01)
516
- freeu_b2 = gr.Slider(label='B2', minimum=0, maximum=2, step=0.01, value=1.02)
517
- freeu_s1 = gr.Slider(label='S1', minimum=0, maximum=4, step=0.01, value=0.99)
518
- freeu_s2 = gr.Slider(label='S2', minimum=0, maximum=4, step=0.01, value=0.95)
519
- freeu_ctrls = [freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2]
520
-
521
- def dev_mode_checked(r):
522
- return gr.update(visible=r)
523
-
524
- dev_mode.change(dev_mode_checked, inputs=[dev_mode], outputs=[dev_tools],
525
- queue=False, show_progress=False)
526
-
527
- def refresh_files_clicked():
528
- modules.config.update_files()
529
- results = [gr.update(choices=modules.config.model_filenames)]
530
- results += [gr.update(choices=['None'] + modules.config.model_filenames)]
531
- if not args_manager.args.disable_preset_selection:
532
- results += [gr.update(choices=modules.config.available_presets)]
533
- for i in range(modules.config.default_max_lora_number):
534
- results += [gr.update(interactive=True),
535
- gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()]
536
- return results
537
-
538
- refresh_files_output = [base_model, refiner_model]
539
- if not args_manager.args.disable_preset_selection:
540
- refresh_files_output += [preset_selection]
541
- refresh_files.click(refresh_files_clicked, [], refresh_files_output + lora_ctrls,
542
- queue=False, show_progress=False)
543
-
544
- state_is_generating = gr.State(False)
545
-
546
- load_data_outputs = [advanced_checkbox, image_number, prompt, negative_prompt, style_selections,
547
- performance_selection, overwrite_step, overwrite_switch, aspect_ratios_selection,
548
- overwrite_width, overwrite_height, guidance_scale, sharpness, adm_scaler_positive,
549
- adm_scaler_negative, adm_scaler_end, refiner_swap_method, adaptive_cfg, base_model,
550
- refiner_model, refiner_switch, sampler_name, scheduler_name, seed_random, image_seed,
551
- generate_button, load_parameter_button] + freeu_ctrls + lora_ctrls
552
-
553
- if not args_manager.args.disable_preset_selection:
554
- def preset_selection_change(preset, is_generating):
555
- preset_content = modules.config.try_get_preset_content(preset) if preset != 'initial' else {}
556
- preset_prepared = modules.meta_parser.parse_meta_from_preset(preset_content)
557
-
558
- default_model = preset_prepared.get('base_model')
559
- previous_default_models = preset_prepared.get('previous_default_models', [])
560
- checkpoint_downloads = preset_prepared.get('checkpoint_downloads', {})
561
- embeddings_downloads = preset_prepared.get('embeddings_downloads', {})
562
- lora_downloads = preset_prepared.get('lora_downloads', {})
563
-
564
- preset_prepared['base_model'], preset_prepared['lora_downloads'] = launch.download_models(
565
- default_model, previous_default_models, checkpoint_downloads, embeddings_downloads, lora_downloads)
566
-
567
- if 'prompt' in preset_prepared and preset_prepared.get('prompt') == '':
568
- del preset_prepared['prompt']
569
-
570
- return modules.meta_parser.load_parameter_button_click(json.dumps(preset_prepared), is_generating)
571
-
572
- preset_selection.change(preset_selection_change, inputs=[preset_selection, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=True) \
573
- .then(fn=style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, show_progress=False) \
574
-
575
- performance_selection.change(lambda x: [gr.update(interactive=not flags.Performance.has_restricted_features(x))] * 11 +
576
- [gr.update(visible=not flags.Performance.has_restricted_features(x))] * 1 +
577
- [gr.update(interactive=not flags.Performance.has_restricted_features(x), value=flags.Performance.has_restricted_features(x))] * 1,
578
- inputs=performance_selection,
579
- outputs=[
580
- guidance_scale, sharpness, adm_scaler_end, adm_scaler_positive,
581
- adm_scaler_negative, refiner_switch, refiner_model, sampler_name,
582
- scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt, disable_intermediate_results
583
- ], queue=False, show_progress=False)
584
-
585
- output_format.input(lambda x: gr.update(output_format=x), inputs=output_format)
586
-
587
- advanced_checkbox.change(lambda x: gr.update(visible=x), advanced_checkbox, advanced_column,
588
- queue=False, show_progress=False) \
589
- .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False)
590
-
591
- def inpaint_mode_change(mode):
592
- assert mode in modules.flags.inpaint_options
593
-
594
- # inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
595
- # inpaint_disable_initial_latent, inpaint_engine,
596
- # inpaint_strength, inpaint_respective_field
597
-
598
- if mode == modules.flags.inpaint_option_detail:
599
- return [
600
- gr.update(visible=True), gr.update(visible=False, value=[]),
601
- gr.Dataset.update(visible=True, samples=modules.config.example_inpaint_prompts),
602
- False, 'None', 0.5, 0.0
603
- ]
604
-
605
- if mode == modules.flags.inpaint_option_modify:
606
- return [
607
- gr.update(visible=True), gr.update(visible=False, value=[]),
608
- gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
609
- True, modules.config.default_inpaint_engine_version, 1.0, 0.0
610
- ]
611
-
612
- return [
613
- gr.update(visible=False, value=''), gr.update(visible=True),
614
- gr.Dataset.update(visible=False, samples=modules.config.example_inpaint_prompts),
615
- False, modules.config.default_inpaint_engine_version, 1.0, 0.618
616
- ]
617
-
618
- inpaint_mode.input(inpaint_mode_change, inputs=inpaint_mode, outputs=[
619
- inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts,
620
- inpaint_disable_initial_latent, inpaint_engine,
621
- inpaint_strength, inpaint_respective_field
622
- ], show_progress=False, queue=False)
623
-
624
- ctrls = [currentTask, generate_image_grid]
625
- ctrls += [
626
- prompt, negative_prompt, style_selections,
627
- performance_selection, aspect_ratios_selection, image_number, output_format, image_seed,
628
- read_wildcards_in_order, sharpness, guidance_scale
629
- ]
630
-
631
- ctrls += [base_model, refiner_model, refiner_switch] + lora_ctrls
632
- ctrls += [input_image_checkbox, current_tab]
633
- ctrls += [uov_method, uov_input_image]
634
- ctrls += [outpaint_selections, inpaint_input_image, inpaint_additional_prompt, inpaint_mask_image]
635
- ctrls += [disable_preview, disable_intermediate_results, disable_seed_increment]
636
- ctrls += [adm_scaler_positive, adm_scaler_negative, adm_scaler_end, adaptive_cfg]
637
- ctrls += [sampler_name, scheduler_name]
638
- ctrls += [overwrite_step, overwrite_switch, overwrite_width, overwrite_height, overwrite_vary_strength]
639
- ctrls += [overwrite_upscale_strength, mixing_image_prompt_and_vary_upscale, mixing_image_prompt_and_inpaint]
640
- ctrls += [debugging_cn_preprocessor, skipping_cn_preprocessor, canny_low_threshold, canny_high_threshold]
641
- ctrls += [refiner_swap_method, controlnet_softness]
642
- ctrls += freeu_ctrls
643
- ctrls += inpaint_ctrls
644
-
645
- if not args_manager.args.disable_metadata:
646
- ctrls += [save_metadata_to_images, metadata_scheme]
647
-
648
- ctrls += ip_ctrls
649
-
650
- def parse_meta(raw_prompt_txt, is_generating):
651
- loaded_json = None
652
- if is_json(raw_prompt_txt):
653
- loaded_json = json.loads(raw_prompt_txt)
654
-
655
- if loaded_json is None:
656
- if is_generating:
657
- return gr.update(), gr.update(), gr.update()
658
- else:
659
- return gr.update(), gr.update(visible=True), gr.update(visible=False)
660
-
661
- return json.dumps(loaded_json), gr.update(visible=False), gr.update(visible=True)
662
-
663
- prompt.input(parse_meta, inputs=[prompt, state_is_generating], outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False)
664
-
665
- load_parameter_button.click(modules.meta_parser.load_parameter_button_click, inputs=[prompt, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=False)
666
-
667
- def trigger_metadata_import(filepath, state_is_generating):
668
- parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath)
669
- if parameters is None:
670
- print('Could not find metadata in the image!')
671
- parsed_parameters = {}
672
- else:
673
- metadata_parser = modules.meta_parser.get_metadata_parser(metadata_scheme)
674
- parsed_parameters = metadata_parser.parse_json(parameters)
675
-
676
- return modules.meta_parser.load_parameter_button_click(parsed_parameters, state_is_generating)
677
-
678
- metadata_import_button.click(trigger_metadata_import, inputs=[metadata_input_image, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=True) \
679
- .then(style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, show_progress=False)
680
-
681
- generate_button.click(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), [], True),
682
- outputs=[stop_button, skip_button, generate_button, gallery, state_is_generating]) \
683
- .then(fn=refresh_seed, inputs=[seed_random, image_seed], outputs=image_seed) \
684
- .then(fn=get_task, inputs=ctrls, outputs=currentTask) \
685
- .then(fn=generate_clicked, inputs=currentTask, outputs=[progress_html, progress_window, progress_gallery, gallery]) \
686
- .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), gr.update(visible=False, interactive=False), False),
687
- outputs=[generate_button, stop_button, skip_button, state_is_generating]) \
688
- .then(fn=update_history_link, outputs=history_link) \
689
- .then(fn=lambda: None, _js='playNotification').then(fn=lambda: None, _js='refresh_grid_delayed')
690
-
691
- for notification_file in ['notification.ogg', 'notification.mp3']:
692
- if os.path.exists(notification_file):
693
- gr.Audio(interactive=False, value=notification_file, elem_id='audio_notification', visible=False)
694
- break
695
-
696
- def trigger_describe(mode, img):
697
- if mode == flags.desc_type_photo:
698
- from extras.interrogate import default_interrogator as default_interrogator_photo
699
- return default_interrogator_photo(img), ["Fooocus V2", "Fooocus Enhance", "Fooocus Sharp"]
700
- if mode == flags.desc_type_anime:
701
- from extras.wd14tagger import default_interrogator as default_interrogator_anime
702
- return default_interrogator_anime(img), ["Fooocus V2", "Fooocus Masterpiece"]
703
- return mode, ["Fooocus V2"]
704
-
705
- desc_btn.click(trigger_describe, inputs=[desc_method, desc_input_image],
706
- outputs=[prompt, style_selections], show_progress=True, queue=True)
707
-
708
-
709
- def dump_default_english_config():
710
- from modules.localization import dump_english_config
711
- dump_english_config(grh.all_components)
712
-
713
-
714
- # dump_default_english_config()
715
- import subprocess
716
- import threading
717
- import time
718
- import socket
719
-
720
- def iframe_thread(port):
721
- while True:
722
- time.sleep(0.5)
723
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
724
- result = sock.connect_ex(('127.0.0.1', port))
725
- if result == 0:
726
- break
727
- sock.close()
728
- print("\nFooocus finished loading, trying to launch cloudflared (if it gets stuck here cloudflared is having issues)\n")
729
- p = subprocess.Popen(["cloudflared", "tunnel", "--url", "http://127.0.0.1:{}".format(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
730
- for line in p.stderr:
731
- l = line.decode()
732
- if "trycloudflare.com" in l:
733
- print("This is the URL to access Fooocus:", l[l.find("https"):], end='')
734
-
735
- port = 7865 # Replace with the port number used by Fooocus
736
- threading.Thread(target=iframe_thread, daemon=True, args=(port,)).start()
737
-
738
- shared.gradio_root.launch(
739
- inbrowser=args_manager.args.in_browser,
740
- server_name=args_manager.args.listen,
741
- server_port=args_manager.args.port,
742
- allowed_paths=[modules.config.path_outputs],
743
- blocked_paths=[constants.AUTH_FILENAME]
744
- )