-
Notifications
You must be signed in to change notification settings - Fork 11
/
webui.py
1509 lines (1268 loc) · 58.1 KB
/
webui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tempfile
import traceback
import gradio as gr
import time
import os
from pathlib import Path
from huggingface_hub import hf_hub_download, HfApi
import ollama
import json
from functools import partial
import mlx.core as mx
import gc
from functools import lru_cache
import requests
from bs4 import BeautifulSoup
import re
import subprocess
from mflux.config.config import Config, ConfigControlnet
from mflux.flux.flux import Flux1
from mflux.controlnet.flux_controlnet import Flux1Controlnet
from tqdm import tqdm
from huggingface_hub import HfApi, HfFolder
from PIL import Image
from mflux.ui.cli.parsers import CommandLineParser
import base64
from io import BytesIO
import numpy as np
LORA_DIR = os.path.join(os.path.dirname(__file__), "lora")
OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "output")
os.makedirs(OUTPUT_DIR, exist_ok=True)
MODELS_DIR = os.path.join(os.path.dirname(__file__), "models")
os.makedirs(MODELS_DIR, exist_ok=True)
flux_cache = {}
def get_lora_choices():
return [name for name, _ in get_available_lora_files()]
class CustomModelConfig:
def __init__(self, model_name, alias, num_train_steps, max_sequence_length):
self.model_name = model_name
self.alias = alias
self.num_train_steps = num_train_steps
self.max_sequence_length = max_sequence_length
@staticmethod
def from_alias(alias):
return get_custom_model_config(alias)
MODELS = {
"dev": CustomModelConfig("AITRADER/MFLUXUI.1-dev", "dev", 1000, 512),
"schnell": CustomModelConfig("AITRADER/MFLUXUI.1-schnell", "schnell", 1000, 256),
"dev-8-bit": CustomModelConfig("AITRADER/MFLUX.1-dev-8-bit", "dev-8-bit", 1000, 512),
"dev-4-bit": CustomModelConfig("AITRADER/MFLUX.1-dev-4-bit", "dev-4-bit", 1000, 512),
"schnell-8-bit": CustomModelConfig("AITRADER/MFLUX.1-schnell-8-bit", "schnell-8-bit", 1000, 256),
"schnell-4-bit": CustomModelConfig("AITRADER/MFLUX.1-schnell-4-bit", "schnell-4-bit", 1000, 256),
}
def get_custom_model_config(model_alias):
config = MODELS.get(model_alias)
if config is None:
raise ValueError(f"Invalid model alias: {model_alias}. Available aliases are: {', '.join(MODELS.keys())}")
return config
from huggingface_hub import snapshot_download
def download_and_save_model(hf_model_name, alias, num_train_steps, max_sequence_length):
try:
local_dir = os.path.join(MODELS_DIR, alias)
snapshot_download(repo_id=hf_model_name, local_dir=local_dir, local_dir_use_symlinks=False)
new_config = CustomModelConfig(hf_model_name, alias, num_train_steps, max_sequence_length)
get_custom_model_config.__globals__['models'][alias] = new_config
return f"Model {hf_model_name} succesvol gedownload en opgeslagen als {alias}"
except Exception as e:
return f"Fout bij het downloaden van het model: {str(e)}"
flux_cache = {}
def download_and_save_model(hf_model_name, alias, num_train_steps, max_sequence_length):
try:
model_dir = os.path.join(MODELS_DIR, alias)
os.makedirs(model_dir, exist_ok=True)
downloaded_files = snapshot_download(repo_id=hf_model_name, local_dir=model_dir)
new_config = CustomModelConfig(hf_model_name, alias, num_train_steps, max_sequence_length)
get_custom_model_config.__globals__['models'][alias] = new_config
return f"Model {hf_model_name} successfully downloaded and saved as {alias} in {model_dir}. Downloaded files: {len(downloaded_files)}"
except Exception as e:
return f"Error: {str(e)}"
def get_or_create_flux(model, quantize, path, lora_paths_tuple, lora_scales_tuple, is_controlnet=False):
lora_paths = list(lora_paths_tuple) if lora_paths_tuple else None
lora_scales = list(lora_scales_tuple) if lora_scales_tuple else None
FluxClass = Flux1Controlnet if is_controlnet else Flux1
base_model = model.replace("-8-bit", "").replace("-4-bit", "")
try:
custom_config = get_custom_model_config(base_model)
if base_model in ["dev", "schnell", "dev-8-bit", "dev-4-bit", "schnell-8-bit", "schnell-4-bit"]:
model_path = None
else:
model_path = os.path.join(MODELS_DIR, base_model)
except ValueError:
custom_config = CustomModelConfig(base_model, base_model, 1000, 512)
model_path = os.path.join(MODELS_DIR, base_model)
if "-8-bit" in model:
quantize = 8
elif "-4-bit" in model:
quantize = 4
flux = FluxClass(
model_config=custom_config,
quantize=quantize,
local_path=model_path,
lora_paths=lora_paths,
lora_scales=lora_scales,
)
return flux
def get_available_lora_files():
lora_files = []
for root, dirs, files in os.walk(LORA_DIR):
for file in files:
if file.endswith(".safetensors"):
display_name = os.path.splitext(file)[0]
lora_files.append((display_name, os.path.join(root, file)))
lora_files.sort(key=lambda x: x[0].lower())
return lora_files
def get_available_models():
standard_models = ["schnell-4-bit", "schnell-8-bit", "dev-4-bit", "dev-8-bit", "schnell", "dev"]
custom_models = [f.name for f in Path(MODELS_DIR).iterdir() if f.is_dir()]
return standard_models + custom_models
def ensure_llama_model(model_name):
try:
ollama.pull(model_name)
return True
except Exception:
return False
def load_ollama_settings():
try:
with open('ollama_settings.json', 'r') as f:
settings = json.load(f)
except FileNotFoundError:
_, default_model = get_available_ollama_models()
settings = {'model': default_model}
settings['system_prompt'] = read_system_prompt()
return settings
def create_ollama_settings():
settings = load_ollama_settings()
available_models, _ = get_available_ollama_models()
ollama_model = gr.Dropdown(
choices=available_models,
value=settings['model'],
label="Ollama Model"
)
system_prompt = gr.Textbox(
label="System Prompt", lines=10, value=settings['system_prompt']
)
save_button = gr.Button("Save Ollama Settings")
return [ollama_model, system_prompt, save_button]
def save_settings(model, prompt):
save_ollama_settings(model, prompt)
gr.Info("Settings saved!")
model_update = gr.update(choices=get_available_ollama_models(), value=model)
return gr.update(open=False)
def enhance_prompt(prompt, ollama_model, system_prompt):
print(f"prompt={prompt}, model={ollama_model}, system_prompt={system_prompt}")
try:
response = ollama.generate(
model=ollama_model,
prompt=f"Enhance this prompt for an image generation AI: {prompt}",
system=system_prompt,
options={"temperature": 0.7}
)
enhanced_prompt = response['response'].strip()
gr.Info(f"Prompt successfully improved with model {ollama_model}.")
return enhanced_prompt
except Exception as e:
gr.Error(f"Error while improving prompt: {str(e)}")
return prompt
def print_memory_usage(label):
try:
active_memory = mx.metal.get_active_memory() / 1e6
peak_memory = mx.metal.get_peak_memory() / 1e6
print(f"{label} - Active memory: {active_memory:.2f} MB, Peak memory: {peak_memory:.2f} MB")
except AttributeError:
print(f"{label} - Unable to get memory usage information")
def generate_image_gradio(
prompt, model, seed, height, width, steps, guidance, lora_files, metadata, ollama_model, system_prompt
):
print(f"\n--- Generating image (Advanced) ---")
print(f"Model: {model}")
print(f"Prompt: {prompt}")
print(f"Adjusted Dimensions: {height}x{width}")
print(f"Steps: {steps}")
print(f"Guidance: {guidance}")
print(f"LoRA files: {lora_files}")
print_memory_usage("Before generation")
start_time = time.time()
try:
valid_loras = process_lora_files(lora_files)
lora_paths = valid_loras if valid_loras else None
lora_scales = [1.0] * len(valid_loras) if valid_loras else None
seed = None if seed == "" else int(seed)
if not steps or steps.strip() == "":
base_model = model.replace("-4-bit", "").replace("-8-bit", "")
if "schnell" in base_model:
steps = 4
elif "dev" in base_model:
steps = 20
else:
steps = 20
else:
steps = int(steps)
flux = get_or_create_flux(model, None, None, lora_paths, lora_scales)
print_memory_usage("After creating flux")
timestamp = int(time.time())
output_filename = f"generated_{timestamp}.png"
output_path = os.path.join(OUTPUT_DIR, output_filename)
image = flux.generate_image(
seed=int(time.time()) if seed is None else seed,
prompt=prompt,
config=Config(
num_inference_steps=steps,
height=height,
width=width,
guidance=guidance,
),
)
image.save(output_path)
print_memory_usage("After generating image")
print_memory_usage("After saving image")
del flux
del image
gc.collect()
force_mlx_cleanup()
end_time = time.time()
generation_time = end_time - start_time
print(f"Generation time: {generation_time:.2f} seconds")
return output_path, output_filename, prompt
except Exception as e:
print(f"Error generating image: {str(e)}")
traceback.print_exc()
return None, None, prompt
finally:
force_mlx_cleanup()
gc.collect()
def generate_image_controlnet_gradio(
prompt,
control_image,
model,
seed,
height,
width,
steps,
guidance,
controlnet_strength,
lora_files,
metadata,
save_canny,
ollama_model,
system_prompt
):
print(f"\n--- Generating image (ControlNet) ---")
print(f"Received parameters:")
print(f"- prompt: {prompt}")
print(f"- model: {model}")
print(f"- seed: {seed}")
print(f"- height: {height}")
print(f"- width: {width}")
print(f"- steps: {steps}")
print(f"- guidance: {guidance}")
print(f"- controlnet_strength: {controlnet_strength}")
print(f"- lora_files: {lora_files}")
print(f"- save_canny: {save_canny}")
print_memory_usage("Before generation")
start_time = time.time()
generated_image = None
canny_image_to_return = None
try:
valid_loras = process_lora_files(lora_files)
lora_paths = valid_loras if valid_loras else None
lora_scales = [1.0] * len(valid_loras) if valid_loras else None
seed = None if seed == "" else int(seed)
steps = None if steps == "" else int(steps)
if steps is None:
steps = 4 if "schnell" in model else 14
flux = get_or_create_flux(
model,
None,
None,
lora_paths,
lora_scales,
is_controlnet=True
)
timestamp = int(time.time())
control_image_path = os.path.join(OUTPUT_DIR, f"control_image_{timestamp}.png")
output_path = os.path.join(OUTPUT_DIR, f"generated_controlnet_{timestamp}.png")
control_image.save(control_image_path)
generated_image = flux.generate_image(
seed=int(time.time()) if seed is None else seed,
prompt=prompt,
controlnet_image_path=control_image_path,
config=ConfigControlnet(
num_inference_steps=steps,
height=height,
width=width,
guidance=guidance,
controlnet_strength=controlnet_strength,
),
output=output_path,
controlnet_save_canny=save_canny
)
canny_image = None
if save_canny:
canny_path = output_path.replace('.png', '_controlnet_canny.png')
if os.path.exists(canny_path):
canny_image = Image.open(canny_path)
print(f"Canny image geladen van {canny_path}")
else:
print(f"Canny image niet gevonden op {canny_path}")
print_memory_usage("After generating image")
generated_image.image.save(output_path)
print(f"Generation completed in {time.time() - start_time:.2f}s")
return generated_image.image, "Generation successful!", prompt, canny_image
except Exception as e:
print(f"\nError in ControlNet generation: {str(e)}")
print(f"Full traceback:")
traceback.print_exc()
return None, f"Error: {str(e)}", prompt, None
finally:
if 'control_image_path' in locals() and os.path.exists(control_image_path):
os.remove(control_image_path)
if flux:
del flux
if generated_image:
del generated_image
gc.collect()
force_mlx_cleanup()
def process_lora_files(selected_loras):
if not selected_loras:
return []
lora_files = get_available_lora_files()
if not lora_files:
return []
lora_dict = dict(lora_files)
valid_loras = []
for lora in selected_loras:
if lora in lora_dict:
valid_loras.append(lora_dict[lora])
return valid_loras
def save_quantized_model_gradio(model, quantize):
quantize = int(quantize)
try:
custom_config = get_custom_model_config(model)
except ValueError:
custom_config = CustomModelConfig(model, model, 1000, 512)
model_path = os.path.join(MODELS_DIR, model)
flux = Flux1(
model_config=custom_config,
quantize=quantize,
local_path=model_path
)
save_path = os.path.join(MODELS_DIR, f"{model}-{quantize}-bit")
flux.save_model(save_path)
updated_models = get_updated_models()
return (
gr.update(choices=updated_models),
gr.update(choices=updated_models),
gr.update(choices=updated_models),
gr.update(choices=[m for m in updated_models if not m.endswith("-4-bit") and not m.endswith("-8-bit")]),
f"Model gekwantiseerd en opgeslagen als {save_path}"
)
def simple_generate_image(prompt, model, image_format, lora_files, ollama_model, system_prompt):
print(f"\n--- Generating image ---")
print(f"Model: {model}")
print(f"Prompt: {prompt}")
print(f"Image Format: {image_format}")
print(f"LoRA files: {lora_files}")
print_memory_usage("Before generation")
start_time = time.time()
try:
width, height = map(int, image_format.split('(')[1].split(')')[0].split('x'))
valid_loras = process_lora_files(lora_files)
lora_paths = valid_loras if valid_loras else None
lora_scales = [1.0] * len(valid_loras) if valid_loras else None
if "dev" in model:
steps = 20
else:
steps = 4
flux = get_or_create_flux(model, None, None, lora_paths, lora_scales)
timestamp = int(time.time())
output_filename = f"generated_simple_{timestamp}.png"
output_path = os.path.join(OUTPUT_DIR, output_filename)
image = flux.generate_image(
seed=int(time.time()),
prompt=prompt,
config=Config(
num_inference_steps=steps,
height=height,
width=width,
guidance=7.5,
),
)
print_memory_usage("After generating image")
image.image.save(output_path)
print_memory_usage("After saving image")
del flux
del image
gc.collect()
force_mlx_cleanup()
print_memory_usage("After cleanup")
end_time = time.time()
generation_time = end_time - start_time
print(f"Generation time: {generation_time:.2f} seconds")
return output_path, output_filename, prompt
except Exception as e:
print(f"Error in image generation: {str(e)}")
return None, None, prompt
finally:
force_mlx_cleanup()
gc.collect()
def get_available_ollama_models():
try:
models = ollama.list()
available_models = [model['name'] for model in models['models']]
return available_models, available_models[0] if available_models else None
except Exception as e:
print(f"Error fetching Ollama models: {e}")
return [], None
def save_ollama_settings(model, system_prompt):
with open('ollama_settings.json', 'w') as f:
json.dump({'model': model}, f)
with open('system_prompt.md', 'w') as f:
f.write(system_prompt)
def read_system_prompt():
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
system_prompt_path = os.path.join(script_dir, 'system_prompt.md')
with open(system_prompt_path, 'r') as file:
return file.read()
except FileNotFoundError:
print("system_prompt.md niet gevonden. Een lege prompt wordt gebruikt.")
return ""
def clear_flux_cache():
global flux_cache
flux_cache.clear()
gc.collect()
try:
mx.metal.reset_peak_memory()
mx.eval(mx.zeros(1))
if hasattr(mx, 'clear_memory_pool'):
mx.clear_memory_pool()
if hasattr(mx, 'metal') and hasattr(mx.metal, 'device_reset'):
mx.metal.device_reset()
except AttributeError as e:
print(f"Waarschuwing: Sommige MLX geheugenbeheerfuncties zijn niet beschikbaar: {e}")
gc.collect()
print_memory_usage("After clearing flux cache")
def force_mlx_cleanup():
mx.eval(mx.zeros(1))
if hasattr(mx.metal, 'clear_cache'):
mx.metal.clear_cache()
if hasattr(mx.metal, 'reset_peak_memory'):
mx.metal.reset_peak_memory()
gc.collect()
def update_guidance_visibility(model):
return gr.update(visible="dev" in model)
def save_api_key(api_key, key_type="civitai"):
config_path = os.path.join(os.path.dirname(__file__), "config.json")
config = {}
if os.path.exists(config_path):
with open(config_path, "r") as f:
config = json.load(f)
config[f"{key_type}_api_key"] = api_key
with open(config_path, "w") as f:
json.dump(config, f)
return "API key saved successfully"
def load_api_key(key_type="civitai"):
config_path = os.path.join(os.path.dirname(__file__), "config.json")
if os.path.exists(config_path):
with open(config_path, "r") as f:
config = json.load(f)
return config.get(f"{key_type}_api_key", "")
return ""
def download_lora_model(page_url, api_key):
def slugify(value):
value = str(value)
value = re.sub('[^\w\s-]', '', value).strip().lower()
value = re.sub('[-\s]+', '-', value)
return value
if not api_key:
return gr.update(), gr.update(), gr.update(), "Error: API key is missing"
try:
print(f"Starting download process for URL: {page_url}")
model_id_match = re.search(r'/models/(\d+)', page_url)
if not model_id_match:
return gr.update(), gr.update(), gr.update(), f"Error: Could not extract model ID from the URL: {page_url}"
model_id = model_id_match.group(1)
api_url = f"https://civitai.com/api/v1/models/{model_id}"
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
response = requests.get(api_url, headers=headers)
response.raise_for_status()
model_data = response.json()
if not model_data.get('modelVersions'):
return gr.update(), gr.update(), gr.update(), "Error: No model versions found"
model_name = model_data.get('name', f"model_{model_id}")
latest_version = model_data['modelVersions'][0]
version_name = latest_version.get('name', 'unknown_version')
model_name_slug = slugify(model_name)
version_name_slug = slugify(version_name)
filename = f"{model_name_slug}-{version_name_slug}.safetensors"
file_path = os.path.join(LORA_DIR, filename)
download_url = latest_version['downloadUrl']
print(f"Download URL: {download_url}")
download_response = requests.get(download_url, headers=headers, stream=True)
download_response.raise_for_status()
total_size = int(download_response.headers.get('content-length', 0))
print(f"Saving to: {file_path}")
print(f"Total size: {total_size} bytes")
with open(file_path, 'wb') as file, tqdm(
desc=filename,
total=total_size,
unit='iB',
unit_scale=True,
unit_divisor=1024,
) as progress_bar:
for data in download_response.iter_content(chunk_size=8192):
size = file.write(data)
progress_bar.update(size)
print(f"Download completed successfully: {filename}")
updated_lora_files = get_updated_lora_files()
return (
gr.update(choices=updated_lora_files),
gr.update(choices=updated_lora_files),
gr.update(choices=updated_lora_files),
f"Download completed successfully: {filename}"
)
except requests.exceptions.RequestException as e:
error_message = f"Network error during download: {str(e)}"
if hasattr(e, 'response') and e.response is not None:
error_message += f"\nStatus code: {e.response.status_code}"
error_message += f"\nResponse content: {e.response.text[:500]}..."
print(f"Error: {error_message}")
return gr.update(), gr.update(), gr.update(), error_message
except Exception as e:
error_message = f"Unexpected error during download: {str(e)}"
print(f"Error: {error_message}")
return gr.update(), gr.update(), gr.update(), error_message
def get_updated_lora_files():
lora_files = []
for root, dirs, files in os.walk(LORA_DIR):
for file in files:
if file.endswith(".safetensors") or file.endswith(".ckpt"):
lora_files.append(file)
return lora_files
def get_updated_models():
predefined_models = ["schnell-4-bit", "dev-4-bit", "schnell-8-bit", "dev-8-bit", "schnell", "dev"]
custom_models = [f.name for f in Path(MODELS_DIR).iterdir() if f.is_dir()]
custom_models = [m for m in custom_models if m not in predefined_models]
custom_models.sort(key=str.lower)
all_models = predefined_models + custom_models
return all_models
def download_and_save_model(hf_model_name, alias, num_train_steps, max_sequence_length, api_key):
try:
login_result = login_huggingface(api_key)
if "Error" in login_result:
return gr.update(), gr.update(), gr.update(), gr.update(), login_result
model_dir = os.path.join(MODELS_DIR, alias)
os.makedirs(model_dir, exist_ok=True)
downloaded_files = snapshot_download(repo_id=hf_model_name, local_dir=model_dir, use_auth_token=api_key)
new_config = CustomModelConfig(hf_model_name, alias, num_train_steps, max_sequence_length)
get_custom_model_config.__globals__['models'][alias] = new_config
print(f"Model {hf_model_name} successfully downloaded and saved as {alias}")
updated_models = get_updated_models()
return (
gr.update(choices=updated_models),
gr.update(choices=updated_models),
gr.update(choices=updated_models),
gr.update(choices=[m for m in updated_models if not m.endswith("-4-bit") and not m.endswith("-8-bit")]),
f"Model {hf_model_name} successfully downloaded and saved as {alias}"
)
except Exception as e:
error_message = f"Error downloading model: {str(e)}"
print(f"Error: {error_message}")
return gr.update(), gr.update(), gr.update(), gr.update(), error_message
def load_hf_api_key():
try:
with open('hf_api_key.json', 'r') as f:
settings = json.load(f)
return settings.get('api_key', '')
except FileNotFoundError:
return ''
def save_hf_api_key(api_key):
return save_api_key(api_key, "huggingface")
def login_huggingface(api_key):
try:
api = HfApi()
api.set_access_token(api_key)
HfFolder.save_token(api_key)
return "Successfully logged in to Hugging Face"
except Exception as e:
return f"Error logging in to Hugging Face: {str(e)}"
def download_lora_model_huggingface(model_name, hf_api_key):
if not model_name:
return gr.update(), gr.update(), gr.update(), "Error: Model name is missing"
try:
api = HfApi(token=hf_api_key if hf_api_key else None)
if '/' in model_name:
owner, repo_name = model_name.split('/', 1)
else:
repo_name = model_name
files = api.list_repo_files(repo_id=model_name)
safetensors_files = [f for f in files if f.endswith(".safetensors")]
if not safetensors_files:
return gr.update(), gr.update(), gr.update(), f"Error: No .safetensors files found in the repository '{model_name}'"
downloaded_files = []
for filename in safetensors_files:
local_file_path = hf_hub_download(
repo_id=model_name,
filename=filename,
local_dir=LORA_DIR,
use_auth_token=hf_api_key,
force_download=True
)
if repo_name in os.path.basename(filename):
new_filename = os.path.basename(filename)
else:
new_filename = f"{repo_name}-{os.path.basename(filename)}"
if not new_filename.endswith('.safetensors'):
new_filename = f"{new_filename}.safetensors"
new_file_path = os.path.join(LORA_DIR, new_filename)
os.rename(local_file_path, new_file_path)
downloaded_files.append(new_filename)
print(f"Download completed: {', '.join(downloaded_files)}")
updated_lora_files = get_updated_lora_files()
return (
gr.update(choices=updated_lora_files),
gr.update(choices=updated_lora_files),
gr.update(choices=updated_lora_files),
f"Download completed: {', '.join(downloaded_files)}"
)
except Exception as e:
error_message = f"Error downloading LoRA from HuggingFace: {str(e)}"
print(f"Error: {error_message}")
return gr.update(), gr.update(), gr.update(), error_message
def generate_image_i2i_gradio(
prompt,
init_image,
init_image_strength,
model,
seed,
width,
height,
steps,
guidance,
lora_files,
lora_scale,
metadata,
ollama_model,
system_prompt
):
if init_image is None:
return None, None, prompt
if not isinstance(init_image, Image.Image):
init_image = Image.fromarray(init_image)
width = int(width - (width % 16))
height = int(height - (height % 16))
init_image = init_image.resize((width, height))
if not steps or steps.strip() == "":
base_model = model.replace("-4-bit", "").replace("-8-bit", "")
steps = 4 if "schnell" in base_model else 20
else:
steps = int(steps)
if init_image_strength is not None and init_image_strength < 1.0:
num_inference_steps = int(steps / (1 - init_image_strength))
else:
num_inference_steps = steps
num_inference_steps = max(1, num_inference_steps)
if not seed or seed.strip() == "":
seed = int(time.time()) % 4294967295
else:
seed = int(seed)
width = width - (width % 16)
height = height - (height % 16)
init_image = init_image.resize((width, height))
print(f"\n--- Generating image (Image-to-Image) ---")
print(f"Model: {model}")
print(f"Prompt: {prompt}")
print(f"Init Image Strength: {init_image_strength}")
print(f"Adjusted Dimensions: {width}x{height}")
print(f"Desired Steps: {steps}")
print(f"Adjusted num_inference_steps: {num_inference_steps}")
print(f"Guidance: {guidance}")
print(f"LoRA files: {lora_files}")
print(f"LoRA Scale: {lora_scale}")
print_memory_usage("Before generation")
start_time = time.time()
valid_loras = process_lora_files(lora_files)
lora_paths = valid_loras if valid_loras else None
lora_scales = [lora_scale] * len(valid_loras) if valid_loras else None
flux = get_or_create_flux(
model,
None,
None,
lora_paths,
lora_scales
)
print_memory_usage("After creating flux")
timestamp = int(time.time())
output_filename = f"generated_i2i_{timestamp}.png"
output_path = os.path.join(OUTPUT_DIR, output_filename)
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp:
init_image.save(temp.name)
init_image_path = temp.name
config = Config(
num_inference_steps=num_inference_steps,
guidance=guidance,
height=height,
width=width,
init_image_path=init_image_path,
init_image_strength=init_image_strength
)
image = flux.generate_image(
seed=seed,
prompt=prompt,
config=config
)
image.image.save(output_path)
os.remove(init_image_path)
duration = time.time() - start_time
print(f"Image generated in {duration:.2f} seconds. Saved as {output_filename}")
print_memory_usage("After saving image")
clear_flux_cache()
force_mlx_cleanup()
return image.image, output_filename, prompt
def refresh_lora_choices():
return gr.update(choices=[name for name, _ in get_available_lora_files()])
demo = None
def refresh_lora_choices():
return gr.update(choices=[name for name, _ in get_available_lora_files()])
def update_dimensions_on_image_change(image):
if image is not None:
width, height = image.size
return (
gr.update(value=width),
gr.update(value=height),
width,
height,
gr.update(value=1.0),
)
else:
return (
gr.update(value=None),
gr.update(value=None),
None,
None,
gr.update(value=1.0),
)
def update_dimensions_on_scale_change(scale_factor, original_width, original_height):
if original_width is not None and original_height is not None:
new_width = int(original_width * float(scale_factor))
new_height = int(original_height * float(scale_factor))
return gr.update(value=new_width), gr.update(value=new_height)
else:
return gr.update(value=None), gr.update(value=None)
def update_height_with_aspect_ratio(width, image):
if not image or not width:
return gr.update(value=None)
original_width, original_height = image.size
aspect_ratio = original_height / original_width
new_height = int(float(width) * aspect_ratio)
return gr.update(value=new_height)
def update_width_with_aspect_ratio(height, image):
if not image or not height:
return gr.update(value=None)
original_width, original_height = image.size
aspect_ratio = original_width / original_height
new_width = int(float(height) * aspect_ratio)
return gr.update(value=new_width)
def scale_dimensions(image, scale_factor):
if image is not None and scale_factor is not None:
width, height = image.size
new_width = int(width * float(scale_factor))
new_height = int(height * float(scale_factor))
return new_width, new_height
else:
return None, None
def create_ui():
with gr.Blocks(css="""
.refresh-button {
background-color: white !important;
border: 1px solid #ccc !important;
color: black !important;
padding: 0px 8px !important;
height: 38px !important;
margin-left: -10px !important;
}
.refresh-button:hover {
background-color: #f0f0f0 !important;
}
""") as demo:
with gr.Tabs():
with gr.TabItem("MFLUX Easy", id=0):
with gr.Row():
with gr.Column():
with gr.Group():
prompt_simple = gr.Textbox(label="Prompt", lines=2)
with gr.Accordion("⚙️ Ollama Settings", open=False) as ollama_section_simple:
ollama_components_simple = create_ollama_settings()
with gr.Row():
enhance_ollama_simple = gr.Button("Enhance prompt with Ollama")
ollama_components_simple[2].click(
fn=save_settings,
inputs=[ollama_components_simple[0], ollama_components_simple[1]],
outputs=[ollama_section_simple]
)
model_simple = gr.Dropdown(
choices=get_updated_models(),
label="Model",
value="schnell-4-bit",
allow_custom_value=True
)
image_format = gr.Dropdown(
choices=[
"Portrait (576x1024)",
"Landscape (1024x576)",
"Background (1920x1080)",
"Square (1024x1024)",
"Poster (1080x1920)",
"Wide Screen (2560x1440)",