Spaces:
Runtime error
Runtime error
Commit ·
6943d4d
1
Parent(s): 5a244c5
go3
Browse files
app.py
CHANGED
|
@@ -1,7 +1,3 @@
|
|
| 1 |
-
# ============================================================================
|
| 2 |
-
# SISTEMA DE CLASSIFICAÇÃO DE IMAGENS - HUGGING FACE SPACE
|
| 3 |
-
# ============================================================================
|
| 4 |
-
|
| 5 |
import os
|
| 6 |
import shutil
|
| 7 |
import gradio as gr
|
|
@@ -19,492 +15,392 @@ import tempfile
|
|
| 19 |
import warnings
|
| 20 |
warnings.filterwarnings("ignore")
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
print(f"🖥️
|
| 25 |
-
|
| 26 |
-
# ============================================================================
|
| 27 |
-
# CONFIGURAÇÕES E VARIÁVEIS GLOBAIS
|
| 28 |
-
# ============================================================================
|
| 29 |
|
| 30 |
# Modelos disponíveis
|
| 31 |
-
|
| 32 |
-
'AlexNet': models.alexnet,
|
| 33 |
'ResNet18': models.resnet18,
|
| 34 |
-
'ResNet34': models.resnet34,
|
| 35 |
-
'ResNet50': models.resnet50,
|
| 36 |
'MobileNetV2': models.mobilenet_v2
|
| 37 |
}
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
num_classes = 2
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
# ============================================================================
|
| 55 |
-
# FUNÇÕES PRINCIPAIS
|
| 56 |
-
# ============================================================================
|
| 57 |
|
| 58 |
def setup_classes(num_classes_value):
|
| 59 |
"""Configura o número de classes e cria diretórios"""
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
def set_class_labels(
|
| 80 |
"""Define rótulos personalizados para as classes"""
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
def upload_images(class_id, images):
|
| 93 |
"""Faz upload das imagens para a classe especificada"""
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
-
def prepare_data(batch_size
|
| 114 |
"""Prepara os dados para treinamento"""
|
| 115 |
-
global train_loader, val_loader, test_loader, num_classes
|
| 116 |
-
|
| 117 |
try:
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
# Transformações
|
| 122 |
transform = transforms.Compose([
|
| 123 |
-
transforms.Resize(
|
| 124 |
transforms.ToTensor(),
|
| 125 |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 126 |
])
|
| 127 |
-
|
| 128 |
-
dataset = datasets.ImageFolder(dataset_path, transform=transform)
|
| 129 |
-
|
| 130 |
if len(dataset.classes) == 0:
|
| 131 |
return "❌ Nenhuma classe encontrada. Faça upload das imagens primeiro."
|
| 132 |
-
|
| 133 |
-
if len(dataset
|
| 134 |
-
return f"❌
|
| 135 |
-
|
| 136 |
-
#
|
| 137 |
-
if len(dataset) < 10:
|
| 138 |
-
return f"❌ Muito poucas imagens ({len(dataset)}). Adicione pelo menos 10 imagens por classe."
|
| 139 |
-
|
| 140 |
-
# Divisão dos dados: 70% treino, 20% validação, 10% teste
|
| 141 |
train_size = int(0.7 * len(dataset))
|
| 142 |
val_size = int(0.2 * len(dataset))
|
| 143 |
test_size = len(dataset) - train_size - val_size
|
| 144 |
-
|
| 145 |
train_dataset, val_dataset, test_dataset = random_split(
|
| 146 |
dataset, [train_size, val_size, test_size],
|
| 147 |
generator=torch.Generator().manual_seed(42)
|
| 148 |
)
|
| 149 |
-
|
| 150 |
-
train_loader = DataLoader(train_dataset, batch_size=int(batch_size), shuffle=True)
|
| 151 |
-
val_loader = DataLoader(val_dataset, batch_size=int(batch_size), shuffle=False)
|
| 152 |
-
test_loader = DataLoader(test_dataset, batch_size=int(batch_size), shuffle=False)
|
| 153 |
-
|
| 154 |
return f"✅ Dados preparados: {train_size} treino, {val_size} validação, {test_size} teste"
|
| 155 |
-
|
| 156 |
except Exception as e:
|
| 157 |
return f"❌ Erro na preparação: {str(e)}"
|
| 158 |
|
| 159 |
-
def start_training(model_name, epochs, lr
|
| 160 |
"""Inicia o treinamento do modelo"""
|
| 161 |
-
global model, train_loader, val_loader, device
|
| 162 |
-
|
| 163 |
-
if train_loader is None or val_loader is None:
|
| 164 |
-
return "❌ Erro: Dados não preparados. Execute a preparação dos dados primeiro."
|
| 165 |
-
|
| 166 |
try:
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
#
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
criterion = nn.CrossEntropyLoss()
|
| 179 |
-
optimizer = optim.Adam(model.parameters(), lr=float(lr))
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
results
|
| 184 |
-
|
| 185 |
-
results.append("-" * 50)
|
| 186 |
-
|
| 187 |
-
model.train()
|
| 188 |
-
|
| 189 |
for epoch in range(int(epochs)):
|
| 190 |
running_loss = 0.0
|
| 191 |
correct = 0
|
| 192 |
total = 0
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
for batch_idx, (inputs, labels) in enumerate(train_loader):
|
| 197 |
inputs, labels = inputs.to(device), labels.to(device)
|
| 198 |
-
|
| 199 |
optimizer.zero_grad()
|
| 200 |
-
outputs = model(inputs)
|
| 201 |
loss = criterion(outputs, labels)
|
| 202 |
loss.backward()
|
| 203 |
optimizer.step()
|
| 204 |
-
|
| 205 |
running_loss += loss.item()
|
| 206 |
_, predicted = torch.max(outputs.data, 1)
|
| 207 |
total += labels.size(0)
|
| 208 |
correct += (predicted == labels).sum().item()
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
epoch_loss = running_loss / len(train_loader)
|
| 212 |
epoch_acc = 100. * correct / total
|
| 213 |
-
results.append(f"
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
model_path = tempfile.NamedTemporaryFile(suffix='.pth', delete=False).name
|
| 217 |
-
torch.save(model.state_dict(), model_path)
|
| 218 |
-
results.append("-" * 50)
|
| 219 |
-
results.append(f"✅ Treinamento concluído! Modelo salvo temporariamente.")
|
| 220 |
-
|
| 221 |
return "\n".join(results)
|
| 222 |
-
|
| 223 |
except Exception as e:
|
| 224 |
return f"❌ Erro durante treinamento: {str(e)}"
|
| 225 |
|
| 226 |
def evaluate_model():
|
| 227 |
"""Avalia o modelo no conjunto de teste"""
|
| 228 |
-
global model, device, num_classes, class_labels, test_loader
|
| 229 |
-
|
| 230 |
-
if model is None:
|
| 231 |
-
return "❌ Erro: Modelo não treinado."
|
| 232 |
-
|
| 233 |
-
if test_loader is None:
|
| 234 |
-
return "❌ Erro: Conjunto de dados não preparado."
|
| 235 |
-
|
| 236 |
-
model.eval()
|
| 237 |
-
all_preds = []
|
| 238 |
-
all_labels = []
|
| 239 |
-
|
| 240 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
with torch.no_grad():
|
| 242 |
-
for inputs, labels in test_loader:
|
| 243 |
inputs, labels = inputs.to(device), labels.to(device)
|
| 244 |
-
outputs = model(inputs)
|
| 245 |
_, preds = torch.max(outputs, 1)
|
| 246 |
all_preds.extend(preds.cpu().numpy())
|
| 247 |
all_labels.extend(labels.cpu().numpy())
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
target_names = class_labels if len(class_labels) == num_classes else [f"class_{i}" for i in range(num_classes)]
|
| 251 |
-
report = classification_report(all_preds, all_labels, target_names=target_names, zero_division=0)
|
| 252 |
-
|
| 253 |
return f"📊 RELATÓRIO DE CLASSIFICAÇÃO:\n\n{report}"
|
| 254 |
-
|
| 255 |
except Exception as e:
|
| 256 |
return f"❌ Erro durante avaliação: {str(e)}"
|
| 257 |
|
| 258 |
-
def show_confusion_matrix():
|
| 259 |
-
"""Gera matriz de confusão"""
|
| 260 |
-
global model, device, num_classes, class_labels, test_loader
|
| 261 |
-
|
| 262 |
-
if model is None:
|
| 263 |
-
return None
|
| 264 |
-
|
| 265 |
-
if test_loader is None:
|
| 266 |
-
return None
|
| 267 |
-
|
| 268 |
-
model.eval()
|
| 269 |
-
all_preds = []
|
| 270 |
-
all_labels = []
|
| 271 |
-
|
| 272 |
-
with torch.no_grad():
|
| 273 |
-
for inputs, labels in test_loader:
|
| 274 |
-
inputs, labels = inputs.to(device), labels.to(device)
|
| 275 |
-
outputs = model(inputs)
|
| 276 |
-
_, preds = torch.max(outputs, 1)
|
| 277 |
-
all_preds.extend(preds.cpu().numpy())
|
| 278 |
-
all_labels.extend(labels.cpu().numpy())
|
| 279 |
-
|
| 280 |
-
cm = confusion_matrix(all_labels, all_preds)
|
| 281 |
-
labels_for_cm = class_labels if len(class_labels) == num_classes else [f"class_{i}" for i in range(num_classes)]
|
| 282 |
-
|
| 283 |
-
plt.figure(figsize=(8, 6))
|
| 284 |
-
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues",
|
| 285 |
-
xticklabels=labels_for_cm,
|
| 286 |
-
yticklabels=labels_for_cm)
|
| 287 |
-
plt.xlabel('Predições')
|
| 288 |
-
plt.ylabel('Valores Reais')
|
| 289 |
-
plt.title('Matriz de Confusão')
|
| 290 |
-
plt.tight_layout()
|
| 291 |
-
|
| 292 |
-
# Salvar em arquivo temporário
|
| 293 |
-
temp_path = tempfile.NamedTemporaryFile(suffix='.png', delete=False).name
|
| 294 |
-
plt.savefig(temp_path, dpi=150, bbox_inches='tight')
|
| 295 |
-
plt.close()
|
| 296 |
-
|
| 297 |
-
return temp_path
|
| 298 |
-
|
| 299 |
def predict_images(images):
|
| 300 |
"""Faz predições em novas imagens"""
|
| 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 |
-
except Exception as e:
|
| 342 |
-
results.append(f"❌ Erro ao processar {os.path.basename(image_path)}: {str(e)}")
|
| 343 |
-
|
| 344 |
-
return "\n".join(results)
|
| 345 |
-
|
| 346 |
-
# ============================================================================
|
| 347 |
-
# INTERFACE GRADIO
|
| 348 |
-
# ============================================================================
|
| 349 |
|
|
|
|
| 350 |
def create_interface():
|
| 351 |
-
"""Cria a interface Gradio"""
|
| 352 |
-
|
| 353 |
with gr.Blocks(title="🖼️ Classificador de Imagens", theme=gr.themes.Soft()) as demo:
|
| 354 |
-
|
| 355 |
gr.Markdown("""
|
| 356 |
-
# 🖼️ Sistema de Classificação de Imagens
|
| 357 |
-
#### Por [Ramon Mayor Martins](https://rmayormartins.github.io/)
|
| 358 |
-
|
| 359 |
-
**Instruções:**
|
| 360 |
-
1. Configure o número de classes e defina os rótulos
|
| 361 |
-
2. Faça upload das imagens para cada classe
|
| 362 |
-
3. Prepare os dados e treine o modelo
|
| 363 |
-
4. Avalie o desempenho e faça predições!
|
| 364 |
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
""")
|
| 367 |
-
|
| 368 |
with gr.Tab("1️⃣ Configuração"):
|
| 369 |
-
gr.Markdown("### 🎯 Configurar Classes")
|
| 370 |
-
|
| 371 |
-
num_classes_input = gr.Number(
|
| 372 |
-
label="Número de Classes",
|
| 373 |
-
value=2,
|
| 374 |
-
precision=0,
|
| 375 |
-
minimum=2,
|
| 376 |
-
maximum=10
|
| 377 |
-
)
|
| 378 |
-
setup_button = gr.Button("🔧 Configurar Classes", variant="primary")
|
| 379 |
-
setup_output = gr.Textbox(label="📋 Status", lines=2)
|
| 380 |
-
|
| 381 |
-
gr.Markdown("### 🏷️ Definir Rótulos")
|
| 382 |
-
|
| 383 |
-
# Campos para rótulos dinâmicos
|
| 384 |
-
label_inputs = []
|
| 385 |
-
for i in range(10):
|
| 386 |
-
label_input = gr.Textbox(
|
| 387 |
-
label=f"Rótulo da Classe {i}",
|
| 388 |
-
placeholder=f"Ex: gato, cachorro, pássaro...",
|
| 389 |
-
visible=(i < 2)
|
| 390 |
-
)
|
| 391 |
-
label_inputs.append(label_input)
|
| 392 |
-
|
| 393 |
-
set_labels_button = gr.Button("🏷️ Definir Rótulos", variant="secondary")
|
| 394 |
-
labels_output = gr.Textbox(label="📋 Status dos Rótulos")
|
| 395 |
-
|
| 396 |
-
# Atualizar visibilidade dos campos
|
| 397 |
-
def update_label_visibility(num_classes_value):
|
| 398 |
-
updates = []
|
| 399 |
-
for i in range(10):
|
| 400 |
-
updates.append(gr.update(visible=(i < int(num_classes_value))))
|
| 401 |
-
return updates
|
| 402 |
-
|
| 403 |
-
# Conectar eventos
|
| 404 |
-
setup_button.click(setup_classes, inputs=num_classes_input, outputs=setup_output)
|
| 405 |
-
num_classes_input.change(update_label_visibility, inputs=num_classes_input, outputs=label_inputs)
|
| 406 |
-
set_labels_button.click(set_class_labels, inputs=label_inputs, outputs=labels_output)
|
| 407 |
-
|
| 408 |
-
with gr.Tab("2️⃣ Upload de Imagens"):
|
| 409 |
-
gr.Markdown("### 📤 Upload de Imagens por Classe")
|
| 410 |
-
|
| 411 |
with gr.Row():
|
| 412 |
-
|
| 413 |
-
label="
|
| 414 |
-
|
| 415 |
-
|
|
|
|
|
|
|
| 416 |
)
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
upload_button = gr.Button("📤 Fazer Upload", variant="primary")
|
| 425 |
-
upload_output = gr.Textbox(label="📋 Status do Upload")
|
| 426 |
-
|
| 427 |
-
# Atualizar dropdown de classes
|
| 428 |
-
def update_class_dropdown(num_classes_value):
|
| 429 |
-
choices = []
|
| 430 |
-
for i in range(int(num_classes_value)):
|
| 431 |
-
label = class_labels[i] if i < len(class_labels) else f"Classe {i}"
|
| 432 |
-
choices.append((f"{i} - {label}", i))
|
| 433 |
-
return gr.update(choices=choices, value=0)
|
| 434 |
-
|
| 435 |
-
# Conectar eventos
|
| 436 |
-
upload_button.click(upload_images, inputs=[class_selector, images_upload], outputs=upload_output)
|
| 437 |
-
num_classes_input.change(update_class_dropdown, inputs=num_classes_input, outputs=class_selector)
|
| 438 |
-
set_labels_button.click(update_class_dropdown, inputs=num_classes_input, outputs=class_selector)
|
| 439 |
-
|
| 440 |
-
with gr.Tab("3️⃣ Preparação & Treinamento"):
|
| 441 |
-
gr.Markdown("### ⚙️ Configurar Parâmetros")
|
| 442 |
-
|
| 443 |
with gr.Row():
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
prepare_button = gr.Button("⚙️ Preparar Dados", variant="primary")
|
| 448 |
-
prepare_output = gr.Textbox(label="
|
| 449 |
-
|
| 450 |
-
gr.Markdown("### 🚀 Treinamento")
|
| 451 |
-
|
| 452 |
with gr.Row():
|
| 453 |
model_name = gr.Dropdown(
|
| 454 |
-
label="Modelo",
|
| 455 |
-
choices=list(
|
| 456 |
value="MobileNetV2"
|
| 457 |
)
|
| 458 |
-
epochs = gr.Number(label="Épocas", value=3, minimum=1, maximum=
|
| 459 |
lr = gr.Number(label="Learning Rate", value=0.001, minimum=0.0001, maximum=0.1)
|
| 460 |
-
|
| 461 |
-
train_button = gr.Button("🚀
|
| 462 |
-
train_output = gr.Textbox(label="
|
| 463 |
-
|
| 464 |
-
# Conectar eventos
|
| 465 |
-
prepare_button.click(prepare_data, inputs=[batch_size, resize_input], outputs=prepare_output)
|
| 466 |
-
train_button.click(start_training, inputs=[model_name, epochs, lr], outputs=train_output)
|
| 467 |
-
|
| 468 |
with gr.Tab("4️⃣ Avaliação"):
|
| 469 |
-
gr.
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
eval_button = gr.Button("📊 Avaliar Modelo", variant="primary")
|
| 473 |
-
cm_button = gr.Button("📈 Matriz de Confusão", variant="secondary")
|
| 474 |
-
|
| 475 |
-
eval_output = gr.Textbox(label="📋 Relatório de Avaliação", lines=15)
|
| 476 |
-
cm_output = gr.Image(label="📈 Matriz de Confusão")
|
| 477 |
-
|
| 478 |
-
# Conectar eventos
|
| 479 |
-
eval_button.click(evaluate_model, outputs=eval_output)
|
| 480 |
-
cm_button.click(show_confusion_matrix, outputs=cm_output)
|
| 481 |
-
|
| 482 |
with gr.Tab("5️⃣ Predição"):
|
| 483 |
-
gr.Markdown("### 🔮 Fazer Predições em Novas Imagens")
|
| 484 |
-
|
| 485 |
predict_images_input = gr.File(
|
| 486 |
-
label="
|
| 487 |
-
file_count="multiple",
|
| 488 |
-
type="filepath",
|
| 489 |
file_types=["image"]
|
| 490 |
)
|
| 491 |
-
predict_button = gr.Button("🔮 Predizer", variant="primary"
|
| 492 |
-
predict_output = gr.Textbox(label="
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
return demo
|
| 498 |
|
| 499 |
-
# ============================================================================
|
| 500 |
-
# EXECUÇÃO PRINCIPAL
|
| 501 |
-
# ============================================================================
|
| 502 |
-
|
| 503 |
if __name__ == "__main__":
|
| 504 |
-
print("🎯 Criando interface...")
|
| 505 |
demo = create_interface()
|
| 506 |
-
|
| 507 |
-
print("🚀 Iniciando aplicação...")
|
| 508 |
-
demo.launch()
|
| 509 |
-
|
| 510 |
-
print("✅ Sistema pronto para uso!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import shutil
|
| 3 |
import gradio as gr
|
|
|
|
| 15 |
import warnings
|
| 16 |
warnings.filterwarnings("ignore")
|
| 17 |
|
| 18 |
+
# Configuração do device
|
| 19 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 20 |
+
print(f"🖥️ Usando device: {device}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Modelos disponíveis
|
| 23 |
+
MODELS = {
|
|
|
|
| 24 |
'ResNet18': models.resnet18,
|
|
|
|
|
|
|
| 25 |
'MobileNetV2': models.mobilenet_v2
|
| 26 |
}
|
| 27 |
|
| 28 |
+
# Estado global da aplicação
|
| 29 |
+
class AppState:
|
| 30 |
+
def __init__(self):
|
| 31 |
+
self.model = None
|
| 32 |
+
self.train_loader = None
|
| 33 |
+
self.val_loader = None
|
| 34 |
+
self.test_loader = None
|
| 35 |
+
self.dataset_path = None
|
| 36 |
+
self.class_dirs = []
|
| 37 |
+
self.class_labels = []
|
| 38 |
+
self.num_classes = 2
|
| 39 |
+
|
| 40 |
+
# Instância global do estado
|
| 41 |
+
app_state = AppState()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
def setup_classes(num_classes_value):
|
| 44 |
"""Configura o número de classes e cria diretórios"""
|
| 45 |
+
try:
|
| 46 |
+
app_state.num_classes = int(num_classes_value)
|
| 47 |
+
|
| 48 |
+
# Criar diretório temporário
|
| 49 |
+
app_state.dataset_path = tempfile.mkdtemp()
|
| 50 |
+
|
| 51 |
+
# Inicializar rótulos padrão
|
| 52 |
+
app_state.class_labels = [f'classe_{i}' for i in range(app_state.num_classes)]
|
| 53 |
+
|
| 54 |
+
# Criar diretórios para cada classe
|
| 55 |
+
app_state.class_dirs = []
|
| 56 |
+
for i in range(app_state.num_classes):
|
| 57 |
+
class_dir = os.path.join(app_state.dataset_path, f'classe_{i}')
|
| 58 |
+
os.makedirs(class_dir, exist_ok=True)
|
| 59 |
+
app_state.class_dirs.append(class_dir)
|
| 60 |
+
|
| 61 |
+
choices = [(f"{i} - {app_state.class_labels[i]}", i) for i in range(app_state.num_classes)]
|
| 62 |
+
|
| 63 |
+
return (
|
| 64 |
+
f"✅ Criados {app_state.num_classes} diretórios para classes",
|
| 65 |
+
gr.Dropdown(choices=choices, value=0)
|
| 66 |
+
)
|
| 67 |
+
except Exception as e:
|
| 68 |
+
return f"❌ Erro: {str(e)}", gr.Dropdown()
|
| 69 |
|
| 70 |
+
def set_class_labels(label0, label1, label2, label3, label4):
|
| 71 |
"""Define rótulos personalizados para as classes"""
|
| 72 |
+
try:
|
| 73 |
+
labels = [label0, label1, label2, label3, label4]
|
| 74 |
+
filtered_labels = [label.strip() for label in labels if label.strip()][:app_state.num_classes]
|
| 75 |
+
|
| 76 |
+
if len(filtered_labels) != app_state.num_classes:
|
| 77 |
+
return f"❌ Erro: Forneça exatamente {app_state.num_classes} rótulos.", gr.Dropdown()
|
| 78 |
+
|
| 79 |
+
app_state.class_labels = filtered_labels
|
| 80 |
+
choices = [(f"{i} - {app_state.class_labels[i]}", i) for i in range(app_state.num_classes)]
|
| 81 |
+
|
| 82 |
+
return (
|
| 83 |
+
f"✅ Rótulos definidos: {', '.join(app_state.class_labels)}",
|
| 84 |
+
gr.Dropdown(choices=choices, value=0)
|
| 85 |
+
)
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return f"❌ Erro: {str(e)}", gr.Dropdown()
|
| 88 |
|
| 89 |
def upload_images(class_id, images):
|
| 90 |
"""Faz upload das imagens para a classe especificada"""
|
| 91 |
+
try:
|
| 92 |
+
if not images:
|
| 93 |
+
return "❌ Nenhuma imagem selecionada."
|
| 94 |
+
|
| 95 |
+
if int(class_id) >= len(app_state.class_dirs):
|
| 96 |
+
return f"❌ Classe {class_id} inválida."
|
| 97 |
+
|
| 98 |
+
class_dir = app_state.class_dirs[int(class_id)]
|
| 99 |
+
count = 0
|
| 100 |
+
|
| 101 |
+
for image in images:
|
| 102 |
+
if image is not None:
|
| 103 |
+
shutil.copy2(image, class_dir)
|
| 104 |
+
count += 1
|
| 105 |
+
|
| 106 |
+
class_name = app_state.class_labels[int(class_id)]
|
| 107 |
+
return f"✅ {count} imagens salvas na classe {class_id} ({class_name})"
|
| 108 |
+
except Exception as e:
|
| 109 |
+
return f"❌ Erro: {str(e)}"
|
| 110 |
|
| 111 |
+
def prepare_data(batch_size):
|
| 112 |
"""Prepara os dados para treinamento"""
|
|
|
|
|
|
|
| 113 |
try:
|
| 114 |
+
if not app_state.dataset_path or not os.path.exists(app_state.dataset_path):
|
| 115 |
+
return "❌ Configure as classes primeiro."
|
| 116 |
+
|
| 117 |
# Transformações
|
| 118 |
transform = transforms.Compose([
|
| 119 |
+
transforms.Resize((224, 224)),
|
| 120 |
transforms.ToTensor(),
|
| 121 |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 122 |
])
|
| 123 |
+
|
| 124 |
+
dataset = datasets.ImageFolder(app_state.dataset_path, transform=transform)
|
| 125 |
+
|
| 126 |
if len(dataset.classes) == 0:
|
| 127 |
return "❌ Nenhuma classe encontrada. Faça upload das imagens primeiro."
|
| 128 |
+
|
| 129 |
+
if len(dataset) < 6:
|
| 130 |
+
return f"❌ Muito poucas imagens ({len(dataset)}). Adicione pelo menos 2 imagens por classe."
|
| 131 |
+
|
| 132 |
+
# Divisão dos dados
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
train_size = int(0.7 * len(dataset))
|
| 134 |
val_size = int(0.2 * len(dataset))
|
| 135 |
test_size = len(dataset) - train_size - val_size
|
| 136 |
+
|
| 137 |
train_dataset, val_dataset, test_dataset = random_split(
|
| 138 |
dataset, [train_size, val_size, test_size],
|
| 139 |
generator=torch.Generator().manual_seed(42)
|
| 140 |
)
|
| 141 |
+
|
| 142 |
+
app_state.train_loader = DataLoader(train_dataset, batch_size=int(batch_size), shuffle=True)
|
| 143 |
+
app_state.val_loader = DataLoader(val_dataset, batch_size=int(batch_size), shuffle=False)
|
| 144 |
+
app_state.test_loader = DataLoader(test_dataset, batch_size=int(batch_size), shuffle=False)
|
| 145 |
+
|
| 146 |
return f"✅ Dados preparados: {train_size} treino, {val_size} validação, {test_size} teste"
|
| 147 |
+
|
| 148 |
except Exception as e:
|
| 149 |
return f"❌ Erro na preparação: {str(e)}"
|
| 150 |
|
| 151 |
+
def start_training(model_name, epochs, lr):
|
| 152 |
"""Inicia o treinamento do modelo"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
try:
|
| 154 |
+
if app_state.train_loader is None:
|
| 155 |
+
return "❌ Erro: Dados não preparados."
|
| 156 |
+
|
| 157 |
+
# Carregar modelo
|
| 158 |
+
app_state.model = MODELS[model_name](pretrained=True)
|
| 159 |
+
|
| 160 |
+
# Adaptar última camada
|
| 161 |
+
if hasattr(app_state.model, 'fc'):
|
| 162 |
+
app_state.model.fc = nn.Linear(app_state.model.fc.in_features, app_state.num_classes)
|
| 163 |
+
elif hasattr(app_state.model, 'classifier'):
|
| 164 |
+
if isinstance(app_state.model.classifier, nn.Sequential):
|
| 165 |
+
app_state.model.classifier[-1] = nn.Linear(app_state.model.classifier[-1].in_features, app_state.num_classes)
|
| 166 |
+
else:
|
| 167 |
+
app_state.model.classifier = nn.Linear(app_state.model.classifier.in_features, app_state.num_classes)
|
| 168 |
+
|
| 169 |
+
app_state.model = app_state.model.to(device)
|
| 170 |
+
|
| 171 |
criterion = nn.CrossEntropyLoss()
|
| 172 |
+
optimizer = optim.Adam(app_state.model.parameters(), lr=float(lr))
|
| 173 |
+
|
| 174 |
+
app_state.model.train()
|
| 175 |
+
|
| 176 |
+
results = [f"🚀 Treinando {model_name} por {epochs} épocas"]
|
| 177 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
for epoch in range(int(epochs)):
|
| 179 |
running_loss = 0.0
|
| 180 |
correct = 0
|
| 181 |
total = 0
|
| 182 |
+
|
| 183 |
+
for inputs, labels in app_state.train_loader:
|
|
|
|
|
|
|
| 184 |
inputs, labels = inputs.to(device), labels.to(device)
|
| 185 |
+
|
| 186 |
optimizer.zero_grad()
|
| 187 |
+
outputs = app_state.model(inputs)
|
| 188 |
loss = criterion(outputs, labels)
|
| 189 |
loss.backward()
|
| 190 |
optimizer.step()
|
| 191 |
+
|
| 192 |
running_loss += loss.item()
|
| 193 |
_, predicted = torch.max(outputs.data, 1)
|
| 194 |
total += labels.size(0)
|
| 195 |
correct += (predicted == labels).sum().item()
|
| 196 |
+
|
| 197 |
+
epoch_loss = running_loss / len(app_state.train_loader)
|
|
|
|
| 198 |
epoch_acc = 100. * correct / total
|
| 199 |
+
results.append(f"Época {epoch+1}: Loss={epoch_loss:.4f}, Acc={epoch_acc:.2f}%")
|
| 200 |
+
|
| 201 |
+
results.append("✅ Treinamento concluído!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
return "\n".join(results)
|
| 203 |
+
|
| 204 |
except Exception as e:
|
| 205 |
return f"❌ Erro durante treinamento: {str(e)}"
|
| 206 |
|
| 207 |
def evaluate_model():
|
| 208 |
"""Avalia o modelo no conjunto de teste"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
try:
|
| 210 |
+
if app_state.model is None or app_state.test_loader is None:
|
| 211 |
+
return "❌ Modelo ou dados não disponíveis."
|
| 212 |
+
|
| 213 |
+
app_state.model.eval()
|
| 214 |
+
all_preds = []
|
| 215 |
+
all_labels = []
|
| 216 |
+
|
| 217 |
with torch.no_grad():
|
| 218 |
+
for inputs, labels in app_state.test_loader:
|
| 219 |
inputs, labels = inputs.to(device), labels.to(device)
|
| 220 |
+
outputs = app_state.model(inputs)
|
| 221 |
_, preds = torch.max(outputs, 1)
|
| 222 |
all_preds.extend(preds.cpu().numpy())
|
| 223 |
all_labels.extend(labels.cpu().numpy())
|
| 224 |
+
|
| 225 |
+
report = classification_report(all_labels, all_preds, target_names=app_state.class_labels, zero_division=0)
|
|
|
|
|
|
|
|
|
|
| 226 |
return f"📊 RELATÓRIO DE CLASSIFICAÇÃO:\n\n{report}"
|
| 227 |
+
|
| 228 |
except Exception as e:
|
| 229 |
return f"❌ Erro durante avaliação: {str(e)}"
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
def predict_images(images):
|
| 232 |
"""Faz predições em novas imagens"""
|
| 233 |
+
try:
|
| 234 |
+
if app_state.model is None:
|
| 235 |
+
return "❌ Modelo não treinado."
|
| 236 |
+
|
| 237 |
+
if not images:
|
| 238 |
+
return "❌ Nenhuma imagem selecionada."
|
| 239 |
+
|
| 240 |
+
transform = transforms.Compose([
|
| 241 |
+
transforms.Resize((224, 224)),
|
| 242 |
+
transforms.ToTensor(),
|
| 243 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 244 |
+
])
|
| 245 |
+
|
| 246 |
+
app_state.model.eval()
|
| 247 |
+
results = []
|
| 248 |
+
|
| 249 |
+
for image_path in images:
|
| 250 |
+
if image_path is not None:
|
| 251 |
+
image = Image.open(image_path).convert('RGB')
|
| 252 |
+
img_tensor = transform(image).unsqueeze(0).to(device)
|
| 253 |
+
|
| 254 |
+
with torch.no_grad():
|
| 255 |
+
outputs = app_state.model(img_tensor)
|
| 256 |
+
probabilities = torch.nn.functional.softmax(outputs[0], dim=0)
|
| 257 |
+
_, predicted = torch.max(outputs, 1)
|
| 258 |
+
|
| 259 |
+
predicted_class_id = predicted.item()
|
| 260 |
+
confidence = probabilities[predicted_class_id].item() * 100
|
| 261 |
+
predicted_class_name = app_state.class_labels[predicted_class_id]
|
| 262 |
+
|
| 263 |
+
results.append(f"📸 {os.path.basename(image_path)}")
|
| 264 |
+
results.append(f" 🎯 Classe: {predicted_class_name}")
|
| 265 |
+
results.append(f" 📊 Confiança: {confidence:.2f}%")
|
| 266 |
+
results.append("-" * 40)
|
| 267 |
+
|
| 268 |
+
return "\n".join(results) if results else "❌ Nenhuma predição realizada."
|
| 269 |
+
|
| 270 |
+
except Exception as e:
|
| 271 |
+
return f"❌ Erro: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
+
# Interface Gradio
|
| 274 |
def create_interface():
|
|
|
|
|
|
|
| 275 |
with gr.Blocks(title="🖼️ Classificador de Imagens", theme=gr.themes.Soft()) as demo:
|
| 276 |
+
|
| 277 |
gr.Markdown("""
|
| 278 |
+
# 🖼️ Sistema de Classificação de Imagens
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
+
**Instruções:**
|
| 281 |
+
1. Configure as classes e rótulos
|
| 282 |
+
2. Faça upload das imagens
|
| 283 |
+
3. Prepare os dados e treine
|
| 284 |
+
4. Avalie e faça predições!
|
| 285 |
""")
|
| 286 |
+
|
| 287 |
with gr.Tab("1️⃣ Configuração"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
with gr.Row():
|
| 289 |
+
num_classes_input = gr.Number(
|
| 290 |
+
label="Número de Classes",
|
| 291 |
+
value=2,
|
| 292 |
+
minimum=2,
|
| 293 |
+
maximum=5,
|
| 294 |
+
precision=0
|
| 295 |
)
|
| 296 |
+
setup_button = gr.Button("🔧 Configurar Classes", variant="primary")
|
| 297 |
+
|
| 298 |
+
setup_output = gr.Textbox(label="Status", lines=2)
|
| 299 |
+
|
| 300 |
+
gr.Markdown("### Rótulos das Classes")
|
| 301 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
with gr.Row():
|
| 303 |
+
label0 = gr.Textbox(label="Classe 0", placeholder="Ex: gato")
|
| 304 |
+
label1 = gr.Textbox(label="Classe 1", placeholder="Ex: cachorro")
|
| 305 |
+
|
| 306 |
+
with gr.Row():
|
| 307 |
+
label2 = gr.Textbox(label="Classe 2", placeholder="Ex: pássaro", visible=False)
|
| 308 |
+
label3 = gr.Textbox(label="Classe 3", placeholder="Ex: peixe", visible=False)
|
| 309 |
+
label4 = gr.Textbox(label="Classe 4", placeholder="Ex: hamster", visible=False)
|
| 310 |
+
|
| 311 |
+
set_labels_button = gr.Button("🏷️ Definir Rótulos")
|
| 312 |
+
labels_output = gr.Textbox(label="Status dos Rótulos")
|
| 313 |
+
|
| 314 |
+
# Dropdown que será atualizado
|
| 315 |
+
class_selector = gr.Dropdown(
|
| 316 |
+
label="Selecionar Classe",
|
| 317 |
+
choices=[(f"Classe 0", 0), (f"Classe 1", 1)],
|
| 318 |
+
value=0
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
with gr.Tab("2️⃣ Upload"):
|
| 322 |
+
images_upload = gr.File(
|
| 323 |
+
label="Selecionar Imagens",
|
| 324 |
+
file_count="multiple",
|
| 325 |
+
file_types=["image"]
|
| 326 |
+
)
|
| 327 |
+
upload_button = gr.Button("📤 Fazer Upload", variant="primary")
|
| 328 |
+
upload_output = gr.Textbox(label="Status do Upload")
|
| 329 |
+
|
| 330 |
+
with gr.Tab("3️⃣ Treinamento"):
|
| 331 |
+
batch_size = gr.Number(label="Batch Size", value=8, minimum=1, maximum=32)
|
| 332 |
prepare_button = gr.Button("⚙️ Preparar Dados", variant="primary")
|
| 333 |
+
prepare_output = gr.Textbox(label="Status", lines=3)
|
| 334 |
+
|
|
|
|
|
|
|
| 335 |
with gr.Row():
|
| 336 |
model_name = gr.Dropdown(
|
| 337 |
+
label="Modelo",
|
| 338 |
+
choices=list(MODELS.keys()),
|
| 339 |
value="MobileNetV2"
|
| 340 |
)
|
| 341 |
+
epochs = gr.Number(label="Épocas", value=3, minimum=1, maximum=10)
|
| 342 |
lr = gr.Number(label="Learning Rate", value=0.001, minimum=0.0001, maximum=0.1)
|
| 343 |
+
|
| 344 |
+
train_button = gr.Button("🚀 Treinar", variant="primary")
|
| 345 |
+
train_output = gr.Textbox(label="Status do Treinamento", lines=10)
|
| 346 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
with gr.Tab("4️⃣ Avaliação"):
|
| 348 |
+
eval_button = gr.Button("📊 Avaliar", variant="primary")
|
| 349 |
+
eval_output = gr.Textbox(label="Relatório", lines=15)
|
| 350 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
with gr.Tab("5️⃣ Predição"):
|
|
|
|
|
|
|
| 352 |
predict_images_input = gr.File(
|
| 353 |
+
label="Imagens para Predição",
|
| 354 |
+
file_count="multiple",
|
|
|
|
| 355 |
file_types=["image"]
|
| 356 |
)
|
| 357 |
+
predict_button = gr.Button("🔮 Predizer", variant="primary")
|
| 358 |
+
predict_output = gr.Textbox(label="Resultados", lines=10)
|
| 359 |
+
|
| 360 |
+
# Conectar eventos
|
| 361 |
+
setup_button.click(
|
| 362 |
+
fn=setup_classes,
|
| 363 |
+
inputs=[num_classes_input],
|
| 364 |
+
outputs=[setup_output, class_selector]
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
set_labels_button.click(
|
| 368 |
+
fn=set_class_labels,
|
| 369 |
+
inputs=[label0, label1, label2, label3, label4],
|
| 370 |
+
outputs=[labels_output, class_selector]
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
upload_button.click(
|
| 374 |
+
fn=upload_images,
|
| 375 |
+
inputs=[class_selector, images_upload],
|
| 376 |
+
outputs=[upload_output]
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
prepare_button.click(
|
| 380 |
+
fn=prepare_data,
|
| 381 |
+
inputs=[batch_size],
|
| 382 |
+
outputs=[prepare_output]
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
train_button.click(
|
| 386 |
+
fn=start_training,
|
| 387 |
+
inputs=[model_name, epochs, lr],
|
| 388 |
+
outputs=[train_output]
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
eval_button.click(
|
| 392 |
+
fn=evaluate_model,
|
| 393 |
+
outputs=[eval_output]
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
predict_button.click(
|
| 397 |
+
fn=predict_images,
|
| 398 |
+
inputs=[predict_images_input],
|
| 399 |
+
outputs=[predict_output]
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
return demo
|
| 403 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
if __name__ == "__main__":
|
|
|
|
| 405 |
demo = create_interface()
|
| 406 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|