nftnik commited on
Commit
651b8c4
·
verified ·
1 Parent(s): ebc49ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -70
app.py CHANGED
@@ -1,53 +1,25 @@
1
  import os
2
- import sys
3
  import random
 
 
4
  import torch
5
- from pathlib import Path
6
- from PIL import Image
7
  import gradio as gr
8
  from huggingface_hub import hf_hub_download
9
  import spaces
10
- from typing import Union, Sequence, Mapping, Any
11
-
12
- # 1. Configuração de Caminhos e Imports
13
- current_dir = os.path.dirname(os.path.abspath(__file__))
14
- comfyui_path = os.path.join(current_dir, "ComfyUI")
15
- sys.path.append(comfyui_path)
16
-
17
- # 2. Imports do ComfyUI
18
- import folder_paths
19
- from nodes import NODE_CLASS_MAPPINGS, init_extra_nodes
20
-
21
- # 3. Configuração de Diretórios
22
- BASE_DIR = os.path.dirname(os.path.realpath(__file__))
23
- output_dir = os.path.join(BASE_DIR, "output")
24
- models_dir = os.path.join(BASE_DIR, "models")
25
- os.makedirs(output_dir, exist_ok=True)
26
- os.makedirs(models_dir, exist_ok=True)
27
- folder_paths.set_output_directory(output_dir)
28
-
29
- # 4. Diagnóstico CUDA
30
- print("Python version:", sys.version)
31
- print("Torch version:", torch.__version__)
32
- print("CUDA disponível:", torch.cuda.is_available())
33
- print("Quantidade de GPUs:", torch.cuda.device_count())
34
- if torch.cuda.is_available():
35
- print("GPU atual:", torch.cuda.get_device_name(0))
36
-
37
- # 5. Inicialização do ComfyUI
38
- print("Inicializando ComfyUI...")
39
- init_extra_nodes()
40
 
41
- # 6. Helper Functions
42
  def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
43
  try:
44
  return obj[index]
45
  except KeyError:
46
  return obj["result"][index]
47
 
48
- # 7. Download de Modelos
49
  def download_models():
50
- print("Baixando modelos...")
51
  models = [
52
  ("black-forest-labs/FLUX.1-Redux-dev", "flux1-redux-dev.safetensors", "style_models"),
53
  ("comfyanonymous/flux_text_encoders", "t5xxl_fp16.safetensors", "text_encoders"),
@@ -63,46 +35,55 @@ def download_models():
63
  os.makedirs(model_dir, exist_ok=True)
64
  print(f"Baixando {filename} de {repo_id}...")
65
  hf_hub_download(repo_id=repo_id, filename=filename, local_dir=model_dir)
66
- # Adicionar o diretório ao folder_paths
67
  folder_paths.add_model_folder_path(model_type, model_dir)
68
  except Exception as e:
69
  print(f"Erro ao baixar {filename} de {repo_id}: {str(e)}")
70
  continue
71
 
72
- # 8. Download e Inicialização dos Modelos
73
- download_models()
74
-
75
- print("Inicializando modelos...")
76
- with torch.inference_mode():
77
- # CLIP
78
- dualcliploader = NODE_CLASS_MAPPINGS["DualCLIPLoader"]()
79
- dualcliploader_357 = dualcliploader.load_clip(
80
- clip_name1="t5xxl_fp16.safetensors",
81
- clip_name2="ViT-L-14-TEXT-detail-improved-hiT-GmP-HF.safetensors",
82
- type="flux"
83
- )
84
-
85
- # CLIP Vision
86
- clipvisionloader = NODE_CLASS_MAPPINGS["CLIPVisionLoader"]()
87
- clip_vision = clipvisionloader.load_clip(
88
- clip_name="model.safetensors"
89
- )
90
-
91
- # Style Model
92
- stylemodelloader = NODE_CLASS_MAPPINGS["StyleModelLoader"]()
93
- stylemodelloader_441 = stylemodelloader.load_style_model(
94
- style_model_name="flux1-redux-dev.safetensors"
95
- )
96
 
97
- # VAE
98
- vaeloader = NODE_CLASS_MAPPINGS["VAELoader"]()
99
- vaeloader_359 = vaeloader.load_vae(
100
- vae_name="ae.safetensors"
101
- )
102
 
103
- # 9. Função de Geração
104
- @spaces.GPU
105
- def generate_image(prompt, input_image, lora_weight, guidance, downsampling_factor, weight, seed, width, height, batch_size, steps, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  try:
107
  with torch.inference_mode():
108
  # Codificar texto
@@ -176,7 +157,7 @@ def generate_image(prompt, input_image, lora_weight, guidance, downsampling_fact
176
  print(f"Erro ao gerar imagem: {str(e)}")
177
  return None
178
 
179
- # 10. Interface Gradio
180
  with gr.Blocks() as app:
181
  gr.Markdown("# FLUX Redux Image Generator")
182
 
 
1
  import os
 
2
  import random
3
+ import sys
4
+ from typing import Sequence, Mapping, Any, Union
5
  import torch
 
 
6
  import gradio as gr
7
  from huggingface_hub import hf_hub_download
8
  import spaces
9
+ from comfy import model_management
10
+ from nodes import NODE_CLASS_MAPPINGS
11
+ from PIL import Image
12
+ from folder_paths import folder_paths
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # Helper function to get values from objects
15
  def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
16
  try:
17
  return obj[index]
18
  except KeyError:
19
  return obj["result"][index]
20
 
21
+ # Download models from Hugging Face
22
  def download_models():
 
23
  models = [
24
  ("black-forest-labs/FLUX.1-Redux-dev", "flux1-redux-dev.safetensors", "style_models"),
25
  ("comfyanonymous/flux_text_encoders", "t5xxl_fp16.safetensors", "text_encoders"),
 
35
  os.makedirs(model_dir, exist_ok=True)
36
  print(f"Baixando {filename} de {repo_id}...")
37
  hf_hub_download(repo_id=repo_id, filename=filename, local_dir=model_dir)
 
38
  folder_paths.add_model_folder_path(model_type, model_dir)
39
  except Exception as e:
40
  print(f"Erro ao baixar {filename} de {repo_id}: {str(e)}")
41
  continue
42
 
43
+ # Configuração de Diretórios
44
+ BASE_DIR = os.path.dirname(os.path.realpath(__file__))
45
+ output_dir = os.path.join(BASE_DIR, "output")
46
+ models_dir = os.path.join(BASE_DIR, "models")
47
+ os.makedirs(output_dir, exist_ok=True)
48
+ os.makedirs(models_dir, exist_ok=True)
49
+ folder_paths.set_output_directory(output_dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ # Download and load models
52
+ download_models()
 
 
 
53
 
54
+ # Load models globally
55
+ intconstant = NODE_CLASS_MAPPINGS["INTConstant"]()
56
+ dualcliploader = NODE_CLASS_MAPPINGS["DualCLIPLoader"]()
57
+ dualcliploader_357 = dualcliploader.load_clip(
58
+ clip_name1="t5xxl_fp16.safetensors",
59
+ clip_name2="ViT-L-14-TEXT-detail-improved-hiT-GmP-HF.safetensors",
60
+ type="flux"
61
+ )
62
+ clipvisionloader = NODE_CLASS_MAPPINGS["CLIPVisionLoader"]()
63
+ clip_vision = clipvisionloader.load_clip(
64
+ clip_name="model.safetensors"
65
+ )
66
+ stylemodelloader = NODE_CLASS_MAPPINGS["StyleModelLoader"]()
67
+ stylemodelloader_441 = stylemodelloader.load_style_model(
68
+ style_model_name="flux1-redux-dev.safetensors"
69
+ )
70
+ vaeloader = NODE_CLASS_MAPPINGS["VAELoader"]()
71
+ vaeloader_359 = vaeloader.load_vae(
72
+ vae_name="ae.safetensors"
73
+ )
74
+
75
+ # Pre-load models
76
+ model_loaders = [dualcliploader_357, vaeloader_359, clip_vision, stylemodelloader_441]
77
+ valid_models = [
78
+ getattr(loader[0], 'patcher', loader[0])
79
+ for loader in model_loaders
80
+ if not isinstance(loader[0], dict) and not isinstance(getattr(loader[0], 'patcher', None), dict)
81
+ ]
82
+ model_management.load_models_gpu(valid_models)
83
+
84
+ # Function to generate images
85
+ @spaces.GPU(duration=60) # Adjust duration as needed
86
+ def generate_image(prompt, input_image, lora_weight, guidance, downsampling_factor, weight, seed, width, height, batch_size, steps):
87
  try:
88
  with torch.inference_mode():
89
  # Codificar texto
 
157
  print(f"Erro ao gerar imagem: {str(e)}")
158
  return None
159
 
160
+ # Gradio Interface
161
  with gr.Blocks() as app:
162
  gr.Markdown("# FLUX Redux Image Generator")
163