Allex21 commited on
Commit
8542711
·
verified ·
1 Parent(s): 1bc2da2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -53
app.py CHANGED
@@ -1,55 +1,150 @@
1
- import gradio as gr
2
  import os
3
- from some_module import train_lora, process_images # ajuste de acordo com seus imports reais
4
-
5
- # Função principal de treinamento
6
- def start_training(images, model_name, trigger_word, epochs, batch_size, learning_rate, lora_r, lora_alpha, lora_dropout):
7
- # processa imagens
8
- processed = process_images(images)
9
-
10
- # chama função de treinamento LoRA
11
- result_path = train_lora(
12
- images=processed,
13
- model_name=model_name,
14
- trigger_word=trigger_word,
15
- epochs=epochs,
16
- batch_size=batch_size,
17
- learning_rate=learning_rate,
18
- lora_r=lora_r,
19
- lora_alpha=lora_alpha,
20
- lora_dropout=lora_dropout
21
- )
22
- return f"Treinamento concluído! Modelo salvo em: {result_path}"
23
-
24
- # Criação da interface Gradio com Blocks
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  with gr.Blocks() as demo:
26
- gr.Markdown("## 🎨 LoRA Image Trainer")
27
-
28
- with gr.Row():
29
- with gr.Column():
30
- images_input = gr.File(label="Selecione imagens", file_types=[".jpg", ".png"], file_types_allow_multiple=True)
31
- model_name_input = gr.Textbox(label="Modelo Base", value="Stable Diffusion 1.5")
32
- trigger_word_input = gr.Textbox(label="Trigger Word", placeholder="Ex: myStyle")
33
- with gr.Column():
34
- epochs_input = gr.Slider(5, 50, value=10, step=1, label="Épocas")
35
- batch_size_input = gr.Slider(1, 8, value=1, step=1, label="Batch Size")
36
- learning_rate_input = gr.Number(value=1e-4, label="Learning Rate")
37
- lora_r_input = gr.Slider(4, 128, value=16, step=1, label="LoRA Rank (r)")
38
- lora_alpha_input = gr.Slider(1, 128, value=32, step=1, label="LoRA Alpha")
39
- lora_dropout_input = gr.Slider(0.0, 0.5, value=0.1, step=0.01, label="LoRA Dropout")
40
-
41
- train_button = gr.Button("Iniciar Treinamento")
42
- output_text = gr.Textbox(label="Status do Treinamento")
43
-
44
- train_button.click(
45
- fn=start_training,
46
- inputs=[
47
- images_input, model_name_input, trigger_word_input,
48
- epochs_input, batch_size_input, learning_rate_input,
49
- lora_r_input, lora_alpha_input, lora_dropout_input
50
- ],
51
- outputs=output_text
52
- )
53
-
54
- # NÃO chamar demo.launch() aqui
55
- # Hugging Face detecta automaticamente a variável `demo`
 
 
1
  import os
2
+ import json
3
+ import uuid
4
+ import threading
5
+ import time
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ import zipfile
9
+
10
+ import gradio as gr
11
+ from PIL import Image
12
+ import torch
13
+
14
+ # --- Classe LoRA Trainer ---
15
+ class LoRAImageTrainer:
16
+ def __init__(self):
17
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+ self.training_jobs = {}
19
+ self.models_cache = {}
20
+
21
+ def get_available_models(self):
22
+ return [
23
+ "runwayml/stable-diffusion-v1-5",
24
+ "stabilityai/stable-diffusion-2-1",
25
+ "stabilityai/stable-diffusion-xl-base-1.0",
26
+ "CompVis/stable-diffusion-v1-4"
27
+ ]
28
+
29
+ def prepare_image_dataset(self, image_files, captions, resolution=512):
30
+ dataset = []
31
+ for img_path, caption in zip(image_files, captions):
32
+ try:
33
+ image = Image.open(img_path).convert("RGB")
34
+ dataset.append({"image": image, "caption": caption, "image_path": img_path})
35
+ except:
36
+ continue
37
+ return dataset
38
+
39
+ def simulate_training(self, job_id, model_name, dataset, r=16, lora_alpha=32, lora_dropout=0.1, num_epochs=10):
40
+ self.training_jobs[job_id]["status"] = "training"
41
+ self.training_jobs[job_id]["progress"] = 0
42
+ total_steps = num_epochs * len(dataset)
43
+ for step in range(total_steps):
44
+ time.sleep(0.2)
45
+ self.training_jobs[job_id]["progress"] = int((step + 1) / total_steps * 100)
46
+ # Simular criação do modelo
47
+ output_dir = f"./lora_models/{job_id}"
48
+ os.makedirs(output_dir, exist_ok=True)
49
+ with open(f"{output_dir}/adapter_model.safetensors", "w") as f:
50
+ f.write("Simulated LoRA model")
51
+ with open(f"{output_dir}/adapter_config.json", "w") as f:
52
+ json.dump({"model_name": model_name}, f)
53
+ self.training_jobs[job_id]["status"] = "completed"
54
+ self.training_jobs[job_id]["model_path"] = output_dir
55
+ self.training_jobs[job_id]["progress"] = 100
56
+
57
+ def start_training(self, model_name, image_files, captions, **kwargs):
58
+ job_id = str(uuid.uuid4())
59
+ dataset = self.prepare_image_dataset(image_files, captions)
60
+ self.training_jobs[job_id] = {"id": job_id, "status": "queued", "progress": 0, "model_name": model_name, "model_path": None}
61
+ thread = threading.Thread(target=self.simulate_training, args=(job_id, model_name, dataset), kwargs=kwargs)
62
+ thread.start()
63
+ return job_id
64
+
65
+ def get_training_status(self, job_id):
66
+ return self.training_jobs.get(job_id, {"error": "Job não encontrado"})
67
+
68
+ def list_trained_models(self):
69
+ models = []
70
+ lora_models_dir = Path("./lora_models")
71
+ if lora_models_dir.exists():
72
+ for model_dir in lora_models_dir.iterdir():
73
+ if model_dir.is_dir():
74
+ models.append({"id": model_dir.name, "path": str(model_dir)})
75
+ return models
76
+
77
+ def create_download_zip(self, model_path):
78
+ zip_path = f"{model_path}.zip"
79
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
80
+ for file_path in Path(model_path).rglob("*"):
81
+ if file_path.is_file():
82
+ zipf.write(file_path, arcname=file_path.name)
83
+ return zip_path
84
+
85
+ # --- Instância ---
86
+ trainer = LoRAImageTrainer()
87
+
88
+ # --- Gradio Interface ---
89
+ def start_training_wrapper(model_name, files, captions_text, trigger_word, r, lora_alpha, lora_dropout, num_epochs, learning_rate, batch_size, resolution):
90
+ if not files or len(files) < 3:
91
+ return "❌ Envie pelo menos 3 imagens para treinamento!"
92
+ image_files = [f.name for f in files]
93
+ captions = [line.strip() for line in captions_text.split("\n") if line.strip()]
94
+ while len(captions) < len(files):
95
+ captions.append(trigger_word or f"image {len(captions)+1}")
96
+ captions = captions[:len(files)]
97
+ job_id = trainer.start_training(model_name, image_files, captions)
98
+ return f"✅ Treinamento iniciado! Job ID: {job_id}"
99
+
100
+ def check_status_wrapper(job_id):
101
+ status = trainer.get_training_status(job_id.strip())
102
+ if "error" in status:
103
+ return status["error"]
104
+ return f"Status: {status['status']}\nProgresso: {status['progress']}%"
105
+
106
+ def list_models_wrapper():
107
+ models = trainer.list_trained_models()
108
+ if not models:
109
+ return "📭 Nenhum modelo encontrado."
110
+ text = ""
111
+ for m in models:
112
+ text += f"ID: {m['id']}\nPath: {m['path']}\n---\n"
113
+ return text
114
+
115
+ def download_model_wrapper(job_id):
116
+ status = trainer.get_training_status(job_id.strip())
117
+ if status.get("status") != "completed":
118
+ return None, "❌ Modelo não disponível ou treinamento não concluído."
119
+ zip_path = trainer.create_download_zip(status["model_path"])
120
+ return zip_path, "✅ Clique para baixar"
121
+
122
  with gr.Blocks() as demo:
123
+ with gr.Tab("🎯 Treinar LoRA"):
124
+ model_dropdown = gr.Dropdown(choices=trainer.get_available_models(), value="runwayml/stable-diffusion-v1-5", label="Modelo Base")
125
+ image_files = gr.File(file_types=["image"], file_count="multiple", label="Imagens")
126
+ trigger_word = gr.Textbox(label="Trigger Word")
127
+ captions_text = gr.Textbox(label="Legendas (opcional)")
128
+ train_button = gr.Button("Iniciar Treinamento")
129
+ train_output = gr.Textbox(label="Resultado")
130
+ train_button.click(start_training_wrapper, inputs=[model_dropdown, image_files, captions_text, trigger_word, 16, 32, 0.1, 10, 0.0001, 1, 512], outputs=train_output)
131
+
132
+ with gr.Tab("📊 Status do Treinamento"):
133
+ job_id_input = gr.Textbox(label="Job ID")
134
+ status_button = gr.Button("Verificar Status")
135
+ status_output = gr.Textbox(label="Status")
136
+ status_button.click(check_status_wrapper, inputs=job_id_input, outputs=status_output)
137
+
138
+ with gr.Tab("📚 Modelos e Download"):
139
+ list_button = gr.Button("Listar Modelos")
140
+ models_output = gr.Textbox(label="Modelos")
141
+ list_button.click(list_models_wrapper, outputs=models_output)
142
+ download_job_id = gr.Textbox(label="Job ID para Download")
143
+ download_button = gr.Button("Preparar Download")
144
+ download_file = gr.File(label="Download do Modelo")
145
+ download_status = gr.Textbox(label="Status Download")
146
+ download_button.click(download_model_wrapper, inputs=download_job_id, outputs=[download_file, download_status])
147
+
148
+ if __name__ == "__main__":
149
+ os.makedirs("./lora_models", exist_ok=True)
150
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)