Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,38 @@
|
|
| 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(
|
|
@@ -24,7 +52,7 @@ def train_lora_interface(
|
|
| 24 |
concept_name = concept_name.strip().replace(" ", "_")
|
| 25 |
full_description = f"{description.strip()}, {concept_name}"
|
| 26 |
|
| 27 |
-
yield f"🏷️ Treinando conceito: '{concept_name}'"
|
| 28 |
|
| 29 |
# Pasta de trabalho
|
| 30 |
dataset_dir = "processed_data"
|
|
@@ -41,15 +69,14 @@ def train_lora_interface(
|
|
| 41 |
except Exception as e:
|
| 42 |
yield f"⚠️ Erro ao limpar: {e}"
|
| 43 |
|
| 44 |
-
# --- ETAPA 1: Processar entrada
|
| 45 |
if input_type == "Upload de ZIP":
|
| 46 |
-
# dataset_input é uma lista? Pega o primeiro item
|
| 47 |
zip_file = dataset_input[0] if isinstance(dataset_input, list) else dataset_input
|
| 48 |
|
| 49 |
if not zipfile.is_zipfile(zip_file):
|
| 50 |
yield "❌ Arquivo não é um ZIP válido."
|
| 51 |
return
|
| 52 |
-
|
| 53 |
yield "📦 Descompactando ZIP..."
|
| 54 |
with zipfile.ZipFile(zip_file, 'r') as z:
|
| 55 |
z.extractall(dataset_dir)
|
|
@@ -60,30 +87,26 @@ def train_lora_interface(
|
|
| 60 |
yield f"🖼️ Recebidas {len(image_files)} imagens. Copiando..."
|
| 61 |
|
| 62 |
for uploaded_file in image_files:
|
| 63 |
-
# O Gradio dá um objeto com .name (caminho completo)
|
| 64 |
if hasattr(uploaded_file, 'name'):
|
| 65 |
src_path = uploaded_file.name
|
| 66 |
filename = os.path.basename(src_path)
|
| 67 |
dest_path = os.path.join(dataset_dir, filename)
|
| 68 |
-
|
| 69 |
-
# COPIA (não renomeia) porque /tmp é somente leitura
|
| 70 |
-
shutil.copy(src_path, dest_path)
|
| 71 |
else:
|
| 72 |
yield f"⚠️ Arquivo inválido: {uploaded_file}"
|
| 73 |
|
| 74 |
-
yield f"✅ {len(image_files)} imagens copiadas
|
| 75 |
|
| 76 |
-
# --- ETAPA 2: Verifica e gera legendas ---
|
| 77 |
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
|
| 78 |
image_files = [f for f in os.listdir(dataset_dir) if f.lower().endswith(image_extensions)]
|
| 79 |
|
| 80 |
if len(image_files) == 0:
|
| 81 |
-
yield "❌ Nenhuma imagem encontrada. Envie
|
| 82 |
return
|
| 83 |
|
| 84 |
-
yield f"📝
|
| 85 |
|
| 86 |
-
# Gera .txt com descrição + conceito
|
| 87 |
for img_name in image_files:
|
| 88 |
txt_path = os.path.join(dataset_dir, os.path.splitext(img_name)[0] + ".txt")
|
| 89 |
if not os.path.exists(txt_path):
|
|
@@ -113,7 +136,7 @@ def train_lora_interface(
|
|
| 113 |
cmd.append("--hub_model_id")
|
| 114 |
cmd.append(f"{concept_name}-lora")
|
| 115 |
|
| 116 |
-
yield "🔥 Iniciando treinamento LoRA... Isso pode levar minutos."
|
| 117 |
|
| 118 |
try:
|
| 119 |
process = subprocess.Popen(
|
|
@@ -142,15 +165,15 @@ def train_lora_interface(
|
|
| 142 |
{'🔹 Publicado no Hub!' if hub_token else ''}
|
| 143 |
"""
|
| 144 |
else:
|
| 145 |
-
yield f"❌
|
| 146 |
|
| 147 |
except Exception as e:
|
| 148 |
-
yield f"💥 Erro
|
| 149 |
|
| 150 |
# --- Interface Gradio ---
|
| 151 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 152 |
gr.Markdown("# 🎨 Treinador de LoRA - Hugging Face")
|
| 153 |
-
gr.Markdown("Treine
|
| 154 |
|
| 155 |
with gr.Row():
|
| 156 |
input_type = gr.Radio(
|
|
@@ -170,13 +193,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 170 |
with gr.Row():
|
| 171 |
concept_name = gr.Textbox(
|
| 172 |
label="Nome do Conceito (ex: brenda)",
|
| 173 |
-
placeholder="Ex: brenda,
|
| 174 |
value=""
|
| 175 |
)
|
| 176 |
with gr.Row():
|
| 177 |
description = gr.Textbox(
|
| 178 |
-
label="Descrição Base (ex: woman, curly hair,
|
| 179 |
-
placeholder="Ex: young black woman,
|
| 180 |
lines=2
|
| 181 |
)
|
| 182 |
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# ⚠️ NÃO REMOVA: Força instalação de pacotes críticos antes de qualquer import
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
import os
|
| 6 |
+
import shutil
|
| 7 |
+
|
| 8 |
+
def install_packages():
|
| 9 |
+
print("🔧 Forçando reinstalação de diffusers e huggingface_hub...")
|
| 10 |
+
try:
|
| 11 |
+
subprocess.check_call([
|
| 12 |
+
sys.executable, "-m", "pip", "install",
|
| 13 |
+
"--force-reinstall",
|
| 14 |
+
"diffusers>=0.26.0",
|
| 15 |
+
"huggingface-hub>=0.20.0",
|
| 16 |
+
"accelerate",
|
| 17 |
+
"peft",
|
| 18 |
+
"torch==2.3.0",
|
| 19 |
+
"transformers==4.40.0"
|
| 20 |
+
])
|
| 21 |
+
print("✅ Pacotes essenciais instalados!")
|
| 22 |
+
except Exception as e:
|
| 23 |
+
print(f"❌ Falha na instalação forçada: {e}")
|
| 24 |
+
|
| 25 |
+
# Executa apenas uma vez por sessão
|
| 26 |
+
if not os.path.exists("/tmp/packages_installed"):
|
| 27 |
+
install_packages()
|
| 28 |
+
with open("/tmp/packages_installed", "w") as f:
|
| 29 |
+
f.write("ok")
|
| 30 |
+
|
| 31 |
+
# Agora sim, imports seguros
|
| 32 |
import gradio as gr
|
| 33 |
from preprocess import process_dataset
|
| 34 |
import subprocess
|
| 35 |
import zipfile
|
|
|
|
| 36 |
import time
|
| 37 |
|
| 38 |
def train_lora_interface(
|
|
|
|
| 52 |
concept_name = concept_name.strip().replace(" ", "_")
|
| 53 |
full_description = f"{description.strip()}, {concept_name}"
|
| 54 |
|
| 55 |
+
yield f"🏷️ Treinando conceito: '{concept_name}' → Prompt: [photo of {concept_name}]"
|
| 56 |
|
| 57 |
# Pasta de trabalho
|
| 58 |
dataset_dir = "processed_data"
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
yield f"⚠️ Erro ao limpar: {e}"
|
| 71 |
|
| 72 |
+
# --- ETAPA 1: Processar entrada ---
|
| 73 |
if input_type == "Upload de ZIP":
|
|
|
|
| 74 |
zip_file = dataset_input[0] if isinstance(dataset_input, list) else dataset_input
|
| 75 |
|
| 76 |
if not zipfile.is_zipfile(zip_file):
|
| 77 |
yield "❌ Arquivo não é um ZIP válido."
|
| 78 |
return
|
| 79 |
+
|
| 80 |
yield "📦 Descompactando ZIP..."
|
| 81 |
with zipfile.ZipFile(zip_file, 'r') as z:
|
| 82 |
z.extractall(dataset_dir)
|
|
|
|
| 87 |
yield f"🖼️ Recebidas {len(image_files)} imagens. Copiando..."
|
| 88 |
|
| 89 |
for uploaded_file in image_files:
|
|
|
|
| 90 |
if hasattr(uploaded_file, 'name'):
|
| 91 |
src_path = uploaded_file.name
|
| 92 |
filename = os.path.basename(src_path)
|
| 93 |
dest_path = os.path.join(dataset_dir, filename)
|
| 94 |
+
shutil.copy(src_path, dest_path) # Usa copy, não rename
|
|
|
|
|
|
|
| 95 |
else:
|
| 96 |
yield f"⚠️ Arquivo inválido: {uploaded_file}"
|
| 97 |
|
| 98 |
+
yield f"✅ {len(image_files)} imagens copiadas."
|
| 99 |
|
| 100 |
+
# --- ETAPA 2: Verifica imagens e gera legendas ---
|
| 101 |
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
|
| 102 |
image_files = [f for f in os.listdir(dataset_dir) if f.lower().endswith(image_extensions)]
|
| 103 |
|
| 104 |
if len(image_files) == 0:
|
| 105 |
+
yield "❌ Nenhuma imagem encontrada. Envie arquivos válidos."
|
| 106 |
return
|
| 107 |
|
| 108 |
+
yield f"📝 Aplicando legenda base: '{full_description}'"
|
| 109 |
|
|
|
|
| 110 |
for img_name in image_files:
|
| 111 |
txt_path = os.path.join(dataset_dir, os.path.splitext(img_name)[0] + ".txt")
|
| 112 |
if not os.path.exists(txt_path):
|
|
|
|
| 136 |
cmd.append("--hub_model_id")
|
| 137 |
cmd.append(f"{concept_name}-lora")
|
| 138 |
|
| 139 |
+
yield "🔥 Iniciando treinamento LoRA... Isso pode levar alguns minutos."
|
| 140 |
|
| 141 |
try:
|
| 142 |
process = subprocess.Popen(
|
|
|
|
| 165 |
{'🔹 Publicado no Hub!' if hub_token else ''}
|
| 166 |
"""
|
| 167 |
else:
|
| 168 |
+
yield f"❌ Treinamento falhou. Código: {process.returncode}\nLogs:\n{log_output[-1000:]}"
|
| 169 |
|
| 170 |
except Exception as e:
|
| 171 |
+
yield f"💥 Erro ao executar treinamento: {str(e)}"
|
| 172 |
|
| 173 |
# --- Interface Gradio ---
|
| 174 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 175 |
gr.Markdown("# 🎨 Treinador de LoRA - Hugging Face")
|
| 176 |
+
gr.Markdown("Treine seu próprio modelo com nome, descrição e imagens!")
|
| 177 |
|
| 178 |
with gr.Row():
|
| 179 |
input_type = gr.Radio(
|
|
|
|
| 193 |
with gr.Row():
|
| 194 |
concept_name = gr.Textbox(
|
| 195 |
label="Nome do Conceito (ex: brenda)",
|
| 196 |
+
placeholder="Ex: brenda, cyborg_x, estilo_pintura",
|
| 197 |
value=""
|
| 198 |
)
|
| 199 |
with gr.Row():
|
| 200 |
description = gr.Textbox(
|
| 201 |
+
label="Descrição Base (ex: woman, curly hair, realistic)",
|
| 202 |
+
placeholder="Ex: young black woman, warm smile, detailed face",
|
| 203 |
lines=2
|
| 204 |
)
|
| 205 |
|