Allex21 commited on
Commit
81d438f
·
verified ·
1 Parent(s): ef6a2b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -58
app.py CHANGED
@@ -1,25 +1,10 @@
1
  # app.py
2
- # ⚠️ NÃO REMOVA: Força instalação de pacotes críticos antes de qualquer import
3
-
4
  import os
5
- import shutil
6
-
7
- ])
8
- print("✅ Pacotes essenciais instalados!")
9
- except Exception as e:
10
- print(f"❌ Falha na instalação forçada: {e}")
11
-
12
- # Executa apenas uma vez por sessão
13
- if not os.path.exists("/tmp/packages_installed"):
14
- install_packages()
15
- with open("/tmp/packages_installed", "w") as f:
16
- f.write("ok")
17
-
18
- # Agora sim, imports seguros
19
  import gradio as gr
20
  from preprocess import process_dataset
21
  import subprocess
22
  import zipfile
 
23
  import time
24
 
25
  def train_lora_interface(
@@ -33,15 +18,14 @@ def train_lora_interface(
33
  yield "❌ Por favor, defina um nome para o conceito (ex: brenda)."
34
  return
35
  if not description.strip():
36
- yield "❌ Por favor, adicione uma descrição base (ex: mulher, 30 anos, cabelo cacheado)."
37
  return
38
 
39
  concept_name = concept_name.strip().replace(" ", "_")
40
  full_description = f"{description.strip()}, {concept_name}"
41
 
42
- yield f"🏷️ Treinando conceito: '{concept_name}' → Prompt: [photo of {concept_name}]"
43
 
44
- # Pasta de trabalho
45
  dataset_dir = "processed_data"
46
  os.makedirs(dataset_dir, exist_ok=True)
47
 
@@ -64,43 +48,40 @@ def train_lora_interface(
64
  yield "❌ Arquivo não é um ZIP válido."
65
  return
66
 
67
- yield "📦 Descompactando ZIP..."
68
  with zipfile.ZipFile(zip_file, 'r') as z:
69
  z.extractall(dataset_dir)
70
  yield f"✅ ZIP extraído! {len(z.namelist())} arquivos."
71
 
72
- else: # Múltiplas imagens
73
  image_files = dataset_input if isinstance(dataset_input, list) else [dataset_input]
74
- yield f"🖼️ Recebidas {len(image_files)} imagens. Copiando..."
75
 
76
  for uploaded_file in image_files:
77
  if hasattr(uploaded_file, 'name'):
78
- src_path = uploaded_file.name
79
- filename = os.path.basename(src_path)
80
- dest_path = os.path.join(dataset_dir, filename)
81
- shutil.copy(src_path, dest_path) # Usa copy, não rename
82
- else:
83
- yield f"⚠️ Arquivo inválido: {uploaded_file}"
84
 
85
  yield f"✅ {len(image_files)} imagens copiadas."
86
 
87
- # --- ETAPA 2: Verifica imagens e gera legendas ---
88
- image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
89
- image_files = [f for f in os.listdir(dataset_dir) if f.lower().endswith(image_extensions)]
90
-
91
- if len(image_files) == 0:
92
- yield "❌ Nenhuma imagem encontrada. Envie arquivos válidos."
93
  return
94
 
95
- yield f"📝 Aplicando legenda base: '{full_description}'"
96
 
97
- for img_name in image_files:
98
- txt_path = os.path.join(dataset_dir, os.path.splitext(img_name)[0] + ".txt")
99
- if not os.path.exists(txt_path):
100
- with open(txt_path, "w", encoding="utf-8") as f:
101
  f.write(full_description)
102
 
103
- yield "🔍 Legendas aplicadas com sucesso!"
104
 
105
  # --- ETAPA 3: Treinamento ---
106
  output_dir = "lora-output"
@@ -119,11 +100,9 @@ def train_lora_interface(
119
 
120
  if hub_token:
121
  os.environ["HF_TOKEN"] = hub_token
122
- cmd.append("--push_to_hub")
123
- cmd.append("--hub_model_id")
124
- cmd.append(f"{concept_name}-lora")
125
 
126
- yield "🔥 Iniciando treinamento LoRA... Isso pode levar alguns minutos."
127
 
128
  try:
129
  process = subprocess.Popen(
@@ -145,22 +124,22 @@ def train_lora_interface(
145
 
146
  if process.returncode == 0:
147
  yield f"""
148
- 🎉 TREINAMENTO CONCLUÍDO!
149
 
150
  🔹 Use no prompt: `photo of {concept_name} in the forest`
151
  🔹 Modelo salvo em: `{output_dir}`
152
  {'🔹 Publicado no Hub!' if hub_token else ''}
153
  """
154
  else:
155
- yield f"❌ Treinamento falhou. Código: {process.returncode}\nLogs:\n{log_output[-1000:]}"
156
 
157
  except Exception as e:
158
- yield f"💥 Erro ao executar treinamento: {str(e)}"
159
 
160
- # --- Interface Gradio ---
161
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
162
  gr.Markdown("# 🎨 Treinador de LoRA - Hugging Face")
163
- gr.Markdown("Treine seu próprio modelo com nome, descrição e imagens!")
164
 
165
  with gr.Row():
166
  input_type = gr.Radio(
@@ -176,21 +155,21 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
176
  file_count="multiple"
177
  )
178
 
179
- gr.Markdown("### 🔖 Identidade do Personagem/Conceito")
180
  with gr.Row():
181
  concept_name = gr.Textbox(
182
  label="Nome do Conceito (ex: brenda)",
183
- placeholder="Ex: brenda, cyborg_x, estilo_pintura",
184
  value=""
185
  )
186
  with gr.Row():
187
  description = gr.Textbox(
188
- label="Descrição Base (ex: woman, curly hair, realistic)",
189
- placeholder="Ex: young black woman, warm smile, detailed face",
190
  lines=2
191
  )
192
 
193
- gr.Markdown("### ⚙️ Configurações do Treinamento")
194
  with gr.Row():
195
  model_name = gr.Dropdown(
196
  ["runwayml/stable-diffusion-v1-5"],
@@ -201,10 +180,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
201
  learning_rate = gr.Number(value=1e-4, label="Taxa de Aprendizado")
202
  num_epochs = gr.Slider(1, 30, value=10, step=1, label="Épocas")
203
 
204
- hub_token = gr.Textbox(label="🔐 Token do Hugging Face (opcional)", type="password")
205
 
206
  btn = gr.Button("🚀 Iniciar Treinamento", variant="primary")
207
- output = gr.Textbox(label="📦 Logs e Resultado", lines=12)
208
 
209
  btn.click(
210
  train_lora_interface,
@@ -215,8 +194,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
215
  outputs=output
216
  )
217
 
218
- # Ativa suporte a yield
219
  demo.queue()
220
-
221
  if __name__ == "__main__":
222
  demo.launch()
 
1
  # app.py
 
 
2
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import gradio as gr
4
  from preprocess import process_dataset
5
  import subprocess
6
  import zipfile
7
+ import shutil
8
  import time
9
 
10
  def train_lora_interface(
 
18
  yield "❌ Por favor, defina um nome para o conceito (ex: brenda)."
19
  return
20
  if not description.strip():
21
+ yield "❌ Por favor, adicione uma descrição base."
22
  return
23
 
24
  concept_name = concept_name.strip().replace(" ", "_")
25
  full_description = f"{description.strip()}, {concept_name}"
26
 
27
+ yield f"🏷️ Treinando: '{concept_name}'"
28
 
 
29
  dataset_dir = "processed_data"
30
  os.makedirs(dataset_dir, exist_ok=True)
31
 
 
48
  yield "❌ Arquivo não é um ZIP válido."
49
  return
50
 
51
+ yield "📦 Descompactando..."
52
  with zipfile.ZipFile(zip_file, 'r') as z:
53
  z.extractall(dataset_dir)
54
  yield f"✅ ZIP extraído! {len(z.namelist())} arquivos."
55
 
56
+ else:
57
  image_files = dataset_input if isinstance(dataset_input, list) else [dataset_input]
58
+ yield f"🖼️ Copiando {len(image_files)} imagens..."
59
 
60
  for uploaded_file in image_files:
61
  if hasattr(uploaded_file, 'name'):
62
+ src = uploaded_file.name
63
+ dest = os.path.join(dataset_dir, os.path.basename(src))
64
+ shutil.copy(src, dest)
 
 
 
65
 
66
  yield f"✅ {len(image_files)} imagens copiadas."
67
 
68
+ # --- ETAPA 2: Gera legendas ---
69
+ exts = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
70
+ images = [f for f in os.listdir(dataset_dir) if f.lower().endswith(exts)]
71
+
72
+ if len(images) == 0:
73
+ yield "❌ Nenhuma imagem encontrada!"
74
  return
75
 
76
+ yield f"📝 Aplicando legenda: '{full_description}'"
77
 
78
+ for img in images:
79
+ txt = os.path.join(dataset_dir, os.path.splitext(img)[0] + ".txt")
80
+ if not os.path.exists(txt):
81
+ with open(txt, "w", encoding="utf-8") as f:
82
  f.write(full_description)
83
 
84
+ yield "🔍 Legendas prontas!"
85
 
86
  # --- ETAPA 3: Treinamento ---
87
  output_dir = "lora-output"
 
100
 
101
  if hub_token:
102
  os.environ["HF_TOKEN"] = hub_token
103
+ cmd += ["--push_to_hub", "--hub_model_id", f"{concept_name}-lora"]
 
 
104
 
105
+ yield "🔥 Iniciando treinamento..."
106
 
107
  try:
108
  process = subprocess.Popen(
 
124
 
125
  if process.returncode == 0:
126
  yield f"""
127
+ 🎉 SUCESSO!
128
 
129
  🔹 Use no prompt: `photo of {concept_name} in the forest`
130
  🔹 Modelo salvo em: `{output_dir}`
131
  {'🔹 Publicado no Hub!' if hub_token else ''}
132
  """
133
  else:
134
+ yield f"❌ Falha no treinamento. Código: {process.returncode}\nLogs:\n{log_output[-1000:]}"
135
 
136
  except Exception as e:
137
+ yield f"💥 Erro: {str(e)}"
138
 
139
+ # --- Interface ---
140
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
141
  gr.Markdown("# 🎨 Treinador de LoRA - Hugging Face")
142
+ gr.Markdown("Treine personagens, estilos ou objetos personalizados.")
143
 
144
  with gr.Row():
145
  input_type = gr.Radio(
 
155
  file_count="multiple"
156
  )
157
 
158
+ gr.Markdown("### 🔖 Identidade do Personagem")
159
  with gr.Row():
160
  concept_name = gr.Textbox(
161
  label="Nome do Conceito (ex: brenda)",
162
+ placeholder="Ex: brenda, cyborg_x",
163
  value=""
164
  )
165
  with gr.Row():
166
  description = gr.Textbox(
167
+ label="Descrição Base (ex: woman, curly hair)",
168
+ placeholder="Ex: young black woman, realistic style",
169
  lines=2
170
  )
171
 
172
+ gr.Markdown("### ⚙️ Configurações")
173
  with gr.Row():
174
  model_name = gr.Dropdown(
175
  ["runwayml/stable-diffusion-v1-5"],
 
180
  learning_rate = gr.Number(value=1e-4, label="Taxa de Aprendizado")
181
  num_epochs = gr.Slider(1, 30, value=10, step=1, label="Épocas")
182
 
183
+ hub_token = gr.Textbox(label="🔐 Token do HF (opcional)", type="password")
184
 
185
  btn = gr.Button("🚀 Iniciar Treinamento", variant="primary")
186
+ output = gr.Textbox(label="📦 Logs", lines=12)
187
 
188
  btn.click(
189
  train_lora_interface,
 
194
  outputs=output
195
  )
196
 
 
197
  demo.queue()
 
198
  if __name__ == "__main__":
199
  demo.launch()