-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_project.py
More file actions
409 lines (340 loc) · 13.4 KB
/
test_project.py
File metadata and controls
409 lines (340 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""
Script de test pour vérifier que tous les composants du projet fonctionnent correctement
avant de pousser sur GitHub et déployer sur Streamlit
"""
import sys
import os
from pathlib import Path
import traceback
# Fix encoding for Windows
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
# Couleurs pour l'affichage
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'
def print_success(msg):
print(f"{GREEN}✅ {msg}{RESET}")
def print_error(msg):
print(f"{RED}❌ {msg}{RESET}")
def print_warning(msg):
print(f"{YELLOW}⚠️ {msg}{RESET}")
def print_info(msg):
print(f"{BLUE}ℹ️ {msg}{RESET}")
def test_imports():
"""Test 1: Vérifier que tous les imports fonctionnent"""
print("\n" + "="*60)
print("TEST 1: Vérification des imports")
print("="*60)
try:
import torch
import torchvision
import cv2
import numpy as np
import matplotlib
import seaborn
import streamlit
import sklearn
import tqdm
import PIL
print_success("Tous les packages de base sont installés")
# Test imports locaux
sys.path.append(str(Path(__file__).parent))
from src.dataset import load_cifar10_dataset, load_imagefolder_dataset
from src.train import create_model
from src.infer import predict_from_array, load_model
from src.utils import calculate_accuracy, save_checkpoint
print_success("Tous les modules locaux s'importent correctement")
return True
except ImportError as e:
print_error(f"Erreur d'import: {e}")
print_warning("Exécutez: pip install -r requirements.txt")
return False
except Exception as e:
print_error(f"Erreur inattendue: {e}")
traceback.print_exc()
return False
def test_cuda():
"""Test 2: Vérifier la disponibilité CUDA"""
print("\n" + "="*60)
print("TEST 2: Vérification CUDA")
print("="*60)
try:
import torch
if torch.cuda.is_available():
print_success(f"CUDA disponible: {torch.cuda.get_device_name(0)}")
print_info(f"Version CUDA: {torch.version.cuda}")
else:
print_warning("CUDA non disponible - l'entraînement se fera sur CPU")
return True
except Exception as e:
print_error(f"Erreur lors de la vérification CUDA: {e}")
return False
def test_dataset_loading():
"""Test 3: Tester le chargement du dataset CIFAR-10"""
print("\n" + "="*60)
print("TEST 3: Chargement du dataset CIFAR-10")
print("="*60)
try:
sys.path.append(str(Path(__file__).parent))
from src.dataset import load_cifar10_dataset
print_info("Téléchargement de CIFAR-10 (peut prendre quelques instants)...")
train_loader, val_loader, class_names = load_cifar10_dataset(
data_dir='./data',
img_size=224,
batch_size=16, # Plus petit pour le test
num_workers=0 # Éviter les problèmes de multiprocessing
)
print_success(f"Dataset chargé: {len(class_names)} classes")
print_info(f"Classes: {class_names}")
print_info(f"Train batches: {len(train_loader)}")
print_info(f"Val batches: {len(val_loader)}")
# Tester un batch
data_iter = iter(train_loader)
images, labels = next(data_iter)
print_success(f"Batch test: {images.shape}, labels: {labels.shape}")
return True
except Exception as e:
print_error(f"Erreur lors du chargement du dataset: {e}")
traceback.print_exc()
return False
def test_model_creation():
"""Test 4: Tester la création du modèle"""
print("\n" + "="*60)
print("TEST 4: Création du modèle")
print("="*60)
try:
import torch
sys.path.append(str(Path(__file__).parent))
from src.train import create_model
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print_info(f"Device: {device}")
# Test ResNet50
model, _ = create_model('resnet50', num_classes=10, pretrained=True,
freeze_backbone=True, unfreeze_last_n=0)
print_success("Modèle ResNet50 créé avec succès")
# Test forward pass
dummy_input = torch.randn(1, 3, 224, 224).to(device)
model.eval()
with torch.no_grad():
output = model(dummy_input)
print_success(f"Forward pass réussi: output shape {output.shape}")
return True
except Exception as e:
print_error(f"Erreur lors de la création du modèle: {e}")
traceback.print_exc()
return False
def test_training_step():
"""Test 5: Tester une étape d'entraînement"""
print("\n" + "="*60)
print("TEST 5: Test d'une étape d'entraînement")
print("="*60)
try:
import torch
import torch.nn as nn
sys.path.append(str(Path(__file__).parent))
from src.dataset import load_cifar10_dataset
from src.train import create_model
from src.utils import calculate_accuracy
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Charger un petit dataset
train_loader, _, class_names = load_cifar10_dataset(
data_dir='./data',
img_size=224,
batch_size=8,
num_workers=0
)
# Créer modèle
model, _ = create_model('resnet50', len(class_names), pretrained=True,
freeze_backbone=True, unfreeze_last_n=0)
# Test une étape
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
model.train()
data_iter = iter(train_loader)
images, labels = next(data_iter)
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
acc = calculate_accuracy(outputs, labels)
print_success(f"Étape d'entraînement réussie: Loss={loss.item():.4f}, Acc={acc:.2f}%")
return True
except Exception as e:
print_error(f"Erreur lors de l'étape d'entraînement: {e}")
traceback.print_exc()
return False
def test_inference():
"""Test 6: Tester l'inférence"""
print("\n" + "="*60)
print("TEST 6: Test d'inférence")
print("="*60)
try:
import torch
import numpy as np
sys.path.append(str(Path(__file__).parent))
from src.train import create_model
from src.infer import predict_from_array
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Créer un modèle et le sauvegarder temporairement
model, _ = create_model('resnet50', num_classes=10, pretrained=True,
freeze_backbone=True, unfreeze_last_n=0)
os.makedirs('./models', exist_ok=True)
test_model_path = './models/test_model.pth'
torch.save({
'state_dict': model.state_dict(),
'model_name': 'resnet50',
'num_classes': 10,
'class_names': ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
}, test_model_path)
# Test inférence
dummy_image = np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)
results = predict_from_array(dummy_image, test_model_path, topk=3, device=device)
print_success(f"Inférence réussie: {len(results)} prédictions")
for class_name, prob in results:
print_info(f" {class_name}: {prob*100:.2f}%")
# Nettoyer
if os.path.exists(test_model_path):
os.remove(test_model_path)
return True
except Exception as e:
print_error(f"Erreur lors de l'inférence: {e}")
traceback.print_exc()
return False
def test_streamlit_app():
"""Test 7: Vérifier que l'app Streamlit peut être importée"""
print("\n" + "="*60)
print("TEST 7: Vérification de l'application Streamlit")
print("="*60)
try:
app_path = Path(__file__).parent / 'app' / 'app.py'
if not app_path.exists():
print_error(f"Fichier app.py non trouvé: {app_path}")
return False
# Vérifier que le fichier peut être lu
with open(app_path, 'r', encoding='utf-8') as f:
content = f.read()
# Vérifier les imports essentiels
if 'import streamlit' in content:
print_success("Application Streamlit trouvée")
else:
print_error("Import streamlit manquant dans app.py")
return False
if 'from src.infer import' in content:
print_success("Imports locaux corrects")
else:
print_warning("Vérifiez les imports dans app.py")
print_info("Pour tester l'app: streamlit run app/app.py")
return True
except Exception as e:
print_error(f"Erreur lors de la vérification de l'app: {e}")
return False
def test_file_structure():
"""Test 8: Vérifier la structure des fichiers"""
print("\n" + "="*60)
print("TEST 8: Vérification de la structure des fichiers")
print("="*60)
required_files = [
'requirements.txt',
'README.md',
'LICENSE',
'.gitignore',
'src/__init__.py',
'src/dataset.py',
'src/train.py',
'src/infer.py',
'src/utils.py',
'app/app.py',
'scripts/convert_to_onnx.py',
'notebooks/01_EDA_images.ipynb',
'notebooks/02_training_transfer_learning.ipynb',
]
missing_files = []
for file_path in required_files:
full_path = Path(__file__).parent / file_path
if full_path.exists():
print_success(f"✓ {file_path}")
else:
print_error(f"✗ {file_path} manquant")
missing_files.append(file_path)
if missing_files:
print_warning(f"{len(missing_files)} fichier(s) manquant(s)")
return False
else:
print_success("Tous les fichiers requis sont présents")
return True
def test_onnx_conversion():
"""Test 9: Tester la conversion ONNX (optionnel)"""
print("\n" + "="*60)
print("TEST 9: Vérification du script ONNX")
print("="*60)
try:
script_path = Path(__file__).parent / 'scripts' / 'convert_to_onnx.py'
if not script_path.exists():
print_error("Script convert_to_onnx.py non trouvé")
return False
with open(script_path, 'r', encoding='utf-8') as f:
content = f.read()
if 'torch.onnx.export' in content:
print_success("Script ONNX semble correct")
else:
print_warning("Vérifiez le script ONNX")
# Vérifier les imports
try:
import onnx
print_success("Package onnx disponible")
except ImportError:
print_warning("Package onnx non installé (optionnel)")
return True
except Exception as e:
print_error(f"Erreur: {e}")
return False
def main():
"""Exécuter tous les tests"""
print("\n" + "="*60)
print("🧪 TESTS DU PROJET - Image Classification Transfer Learning")
print("="*60)
results = []
# Tests
results.append(("Imports", test_imports()))
results.append(("CUDA", test_cuda()))
results.append(("Structure fichiers", test_file_structure()))
results.append(("Chargement dataset", test_dataset_loading()))
results.append(("Création modèle", test_model_creation()))
results.append(("Étape entraînement", test_training_step()))
results.append(("Inférence", test_inference()))
results.append(("App Streamlit", test_streamlit_app()))
results.append(("Script ONNX", test_onnx_conversion()))
# Résumé
print("\n" + "="*60)
print("📊 RÉSUMÉ DES TESTS")
print("="*60)
passed = sum(1 for _, result in results if result)
total = len(results)
for test_name, result in results:
status = "✅ PASSÉ" if result else "❌ ÉCHOUÉ"
print(f"{status}: {test_name}")
print("\n" + "="*60)
if passed == total:
print_success(f"Tous les tests sont passés! ({passed}/{total})")
print_info("\nProchaines étapes:")
print_info("1. Vérifiez que .gitignore exclut bien les fichiers volumineux")
print_info("2. Testez manuellement: streamlit run app/app.py")
print_info("3. Entraînez un modèle: python src/train.py --use_cifar10 --epochs 1")
print_info("4. Poussez sur GitHub")
print_info("5. Déployez sur Streamlit Cloud")
else:
print_error(f"Certains tests ont échoué ({passed}/{total})")
print_warning("Corrigez les erreurs avant de pousser sur GitHub")
print("="*60 + "\n")
return passed == total
if __name__ == '__main__':
success = main()
sys.exit(0 if success else 1)