File size: 8,414 Bytes
ff45240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Quick inference test script to verify model works before deployment

Run this before deploying to catch any issues early

"""

import torch
import torch.nn as nn
from torchvision import transforms, models
from PIL import Image
import json
import sys
from pathlib import Path

def test_model_loading():
    """Test if model loads correctly"""
    print("=" * 60)
    print("🧪 Testing Model Loading...")
    print("=" * 60)
    
    try:
        # Check if model file exists
        model_path = "model/ecoscan_model.pth"
        if not Path(model_path).exists():
            print(f"❌ Model file not found: {model_path}")
            print("   Please place your trained model in the model/ folder")
            return False
        
        print(f"✅ Found model file: {model_path}")
        
        # Check class names
        class_names_path = "model/class_names.json"
        if not Path(class_names_path).exists():
            print(f"❌ Class names file not found: {class_names_path}")
            return False
        
        with open(class_names_path, 'r') as f:
            class_names = json.load(f)
        
        print(f"✅ Found {len(class_names)} classes: {class_names}")
        
        # Load model architecture
        print("\n🏗️  Building model architecture...")
        model = models.efficientnet_b3(weights=None)
        in_features = model.classifier[1].in_features
        model.classifier = nn.Sequential(
            nn.Dropout(p=0.3, inplace=True),
            nn.Linear(in_features, len(class_names))
        )
        
        # Load weights
        print("📦 Loading weights...")
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        model.load_state_dict(torch.load(model_path, map_location=device))
        model.to(device)
        model.eval()
        
        print(f"✅ Model loaded successfully on {device}")
        
        return True
        
    except Exception as e:
        print(f"❌ Error loading model: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_inference():
    """Test inference on a dummy image"""
    print("\n" + "=" * 60)
    print("🔍 Testing Inference...")
    print("=" * 60)
    
    try:
        # Load model
        model_path = "model/ecoscan_model.pth"
        class_names_path = "model/class_names.json"
        
        with open(class_names_path, 'r') as f:
            class_names = json.load(f)
        
        model = models.efficientnet_b3(weights=None)
        in_features = model.classifier[1].in_features
        model.classifier = nn.Sequential(
            nn.Dropout(p=0.3, inplace=True),
            nn.Linear(in_features, len(class_names))
        )
        
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        model.load_state_dict(torch.load(model_path, map_location=device))
        model.to(device)
        model.eval()
        
        # Create dummy image
        print("📸 Creating test image (300x300 RGB)...")
        dummy_image = Image.new('RGB', (300, 300), color='blue')
        
        # Preprocess
        transform = transforms.Compose([
            transforms.Resize((300, 300)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], 
                               std=[0.229, 0.224, 0.225])
        ])
        
        input_tensor = transform(dummy_image).unsqueeze(0).to(device)
        
        # Run inference
        print("🚀 Running inference...")
        with torch.no_grad():
            outputs = model(input_tensor)
            probabilities = torch.nn.functional.softmax(outputs, dim=1)
            confidence, predicted = torch.max(probabilities, 1)
        
        predicted_class = class_names[predicted.item()]
        confidence_score = confidence.item()
        
        print(f"✅ Inference successful!")
        print(f"   Predicted: {predicted_class}")
        print(f"   Confidence: {confidence_score*100:.2f}%")
        
        # Show top-3 predictions
        print("\n📊 Top-3 Predictions:")
        top3_probs, top3_indices = torch.topk(probabilities[0], min(3, len(class_names)))
        for prob, idx in zip(top3_probs, top3_indices):
            print(f"   {class_names[idx.item()]}: {prob.item()*100:.2f}%")
        
        return True
        
    except Exception as e:
        print(f"❌ Error during inference: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_dependencies():
    """Test if all required packages are installed"""
    print("\n" + "=" * 60)
    print("📦 Testing Dependencies...")
    print("=" * 60)
    
    required_packages = {
        'torch': 'PyTorch',
        'torchvision': 'TorchVision',
        'PIL': 'Pillow',
        'gradio': 'Gradio',
        'cv2': 'OpenCV (cv2)',
        'numpy': 'NumPy'
    }
    
    all_installed = True
    
    for package, name in required_packages.items():
        try:
            __import__(package)
            print(f"✅ {name}")
        except ImportError:
            print(f"❌ {name} - NOT INSTALLED")
            all_installed = False
    
    return all_installed

def test_file_structure():
    """Test if project structure is correct"""
    print("\n" + "=" * 60)
    print("📂 Testing File Structure...")
    print("=" * 60)
    
    required_files = [
        "app.py",
        "requirements.txt",
        "README.md",
        "model/ecoscan_model.pth",
        "model/class_names.json"
    ]
    
    optional_files = [
        "examples/plastic_bottle.jpg",
        "examples/cardboard_box.jpg",
        "examples/glass_jar.jpg"
    ]
    
    all_present = True
    
    print("\n🔍 Required files:")
    for file_path in required_files:
        if Path(file_path).exists():
            size = Path(file_path).stat().st_size / (1024 * 1024)  # MB
            print(f"✅ {file_path} ({size:.2f} MB)")
        else:
            print(f"❌ {file_path} - MISSING")
            all_present = False
    
    print("\n🎨 Optional files:")
    for file_path in optional_files:
        if Path(file_path).exists():
            print(f"✅ {file_path}")
        else:
            print(f"⚠️  {file_path} - not found (optional)")
    
    return all_present

def main():
    """Run all tests"""
    print("\n")
    print("╔" + "=" * 58 + "╗")
    print("║" + " " * 58 + "║")
    print("║" + "  🌱 EcoScan - Pre-Deployment Testing Suite  ".center(58) + "║")
    print("║" + " " * 58 + "║")
    print("╚" + "=" * 58 + "╝")
    print("\n")
    
    tests = [
        ("File Structure", test_file_structure),
        ("Dependencies", test_dependencies),
        ("Model Loading", test_model_loading),
        ("Inference", test_inference)
    ]
    
    results = {}
    
    for test_name, test_func in tests:
        try:
            results[test_name] = test_func()
        except Exception as e:
            print(f"\n❌ Test '{test_name}' crashed: {e}")
            results[test_name] = False
    
    # Summary
    print("\n" + "=" * 60)
    print("📋 TEST SUMMARY")
    print("=" * 60)
    
    for test_name, passed in results.items():
        status = "✅ PASSED" if passed else "❌ FAILED"
        print(f"{test_name:.<40} {status}")
    
    all_passed = all(results.values())
    
    print("\n" + "=" * 60)
    if all_passed:
        print("🎉 ALL TESTS PASSED!")
        print("✅ Your app is ready for deployment!")
        print("\nNext steps:")
        print("  1. Test locally: python app.py")
        print("  2. Deploy to Hugging Face Spaces")
        print("  3. Share with the world! 🌍")
    else:
        print("⚠️  SOME TESTS FAILED")
        print("Please fix the issues above before deploying.")
        print("\nCommon fixes:")
        print("  - Install missing packages: pip install -r requirements.txt")
        print("  - Download model from Kaggle to model/ folder")
        print("  - Verify file paths match your structure")
    print("=" * 60 + "\n")
    
    return 0 if all_passed else 1

if __name__ == "__main__":
    sys.exit(main())