File size: 13,061 Bytes
74037f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# predict.py - FoodVision Command Line Prediction Script
# ============================================================
# 
# USAGE:
# ------
# python predict.py --image path/to/food.jpg
# python predict.py --image pizza.jpg --top 5
# python predict.py --folder food_images/
# python predict.py --image burger.png --json results.json
#
# FEATURES:
# ---------
# βœ… Single image prediction
# βœ… Batch prediction on folder
# βœ… JSON output option
# βœ… Detailed or simple output modes
#
# ============================================================

import torch
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
import timm
import argparse
from pathlib import Path
import json
import sys

# ============================================================
# FOOD CLASSES (101 categories)
# ============================================================

FOOD_CLASSES = [
    "apple_pie", "baby_back_ribs", "baklava", "beef_carpaccio", "beef_tartare",
    "beet_salad", "beignets", "bibimbap", "bread_pudding", "breakfast_burrito",
    "bruschetta", "caesar_salad", "cannoli", "caprese_salad", "carrot_cake",
    "ceviche", "cheese_plate", "cheesecake", "chicken_curry", "chicken_quesadilla",
    "chicken_wings", "chocolate_cake", "chocolate_mousse", "churros", "clam_chowder",
    "club_sandwich", "crab_cakes", "creme_brulee", "croque_madame", "cup_cakes",
    "deviled_eggs", "donuts", "dumplings", "edamame", "eggs_benedict",
    "escargots", "falafel", "filet_mignon", "fish_and_chips", "foie_gras",
    "french_fries", "french_onion_soup", "french_toast", "fried_calamari", "fried_rice",
    "frozen_yogurt", "garlic_bread", "gnocchi", "greek_salad", "grilled_cheese_sandwich",
    "grilled_salmon", "guacamole", "gyoza", "hamburger", "hot_and_sour_soup",
    "hot_dog", "huevos_rancheros", "hummus", "ice_cream", "lasagna",
    "lobster_bisque", "lobster_roll_sandwich", "macaroni_and_cheese", "macarons", "miso_soup",
    "mussels", "nachos", "omelette", "onion_rings", "oysters",
    "pad_thai", "paella", "pancakes", "panna_cotta", "peking_duck",
    "pho", "pizza", "pork_chop", "poutine", "prime_rib",
    "pulled_pork_sandwich", "ramen", "ravioli", "red_velvet_cake", "risotto",
    "samosa", "sashimi", "scallops", "seaweed_salad", "shrimp_and_grits",
    "spaghetti_bolognese", "spaghetti_carbonara", "spring_rolls", "steak", "strawberry_shortcake",
    "sushi", "tacos", "takoyaki", "tiramisu", "tuna_tartare", "waffles"
]

# ============================================================
# MODEL LOADING
# ============================================================

def load_model(model_path, device):
    """
    Loads a trained model from checkpoint.
    
    Args:
        model_path: Path to .pth checkpoint file
        device: torch device ('cuda' or 'cpu')
    
    Returns:
        Loaded model in eval mode
    """
    print(f"πŸ“‚ Loading model from: {model_path}")
    
    try:
        # Load checkpoint
        checkpoint = torch.load(model_path, map_location=device)
        
        # Get model config
        model_config = checkpoint.get('model_config', {
            'model_id': 'convnextv2_base.fcmae_ft_in22k_in1k_384'
        })
        
        # Create model
        model = timm.create_model(
            model_config['model_id'],
            pretrained=False,
            num_classes=101
        )
        
        # Load weights
        model.load_state_dict(checkpoint['model_state_dict'])
        model.to(device)
        model.eval()
        
        accuracy = checkpoint.get('best_val_acc', 0)
        
        print(f"βœ… Model loaded successfully!")
        print(f"   Architecture: {model_config.get('name', 'ConvNeXt V2')}")
        if accuracy > 0:
            print(f"   Accuracy: {accuracy:.2f}%")
        
        return model
        
    except Exception as e:
        print(f"❌ Error loading model: {e}")
        sys.exit(1)

# ============================================================
# IMAGE PREPROCESSING
# ============================================================

def preprocess_image(image_path):
    """
    Loads and preprocesses an image.
    
    Args:
        image_path: Path to image file
    
    Returns:
        Preprocessed image tensor
    """
    transform = transforms.Compose([
        transforms.Resize(256),
        transforms.CenterCrop(224),
        transforms.ToTensor(),
        transforms.Normalize(
            mean=[0.485, 0.456, 0.406],
            std=[0.229, 0.224, 0.225]
        )
    ])
    
    try:
        # Load and convert image
        image = Image.open(image_path).convert('RGB')
        
        # Apply transforms
        img_tensor = transform(image).unsqueeze(0)
        
        return img_tensor
        
    except Exception as e:
        print(f"❌ Error loading image {image_path}: {e}")
        return None

# ============================================================
# PREDICTION FUNCTION
# ============================================================

def predict(model, image_tensor, device, top_k=3):
    """
    Predicts food class for a single image.
    
    Args:
        model: Trained PyTorch model
        image_tensor: Preprocessed image
        device: torch device
        top_k: Number of top predictions
    
    Returns:
        List of (class_name, confidence) tuples
    """
    with torch.no_grad():
        # Move to device
        image_tensor = image_tensor.to(device)
        
        # Forward pass
        outputs = model(image_tensor)
        probabilities = F.softmax(outputs, dim=1)
        
        # Get top-k
        top_probs, top_indices = torch.topk(probabilities, top_k)
        
        # Convert to lists
        top_probs = top_probs.cpu().numpy()[0]
        top_indices = top_indices.cpu().numpy()[0]
        
        # Format results
        results = []
        for prob, idx in zip(top_probs, top_indices):
            class_name = FOOD_CLASSES[idx]
            confidence = float(prob) * 100
            results.append((class_name, confidence))
        
        return results

# ============================================================
# OUTPUT FORMATTING
# ============================================================

def print_predictions(image_path, predictions, detailed=True):
    """
    Prints predictions in a nice format.
    
    Args:
        image_path: Path to image
        predictions: List of (class_name, confidence) tuples
        detailed: Whether to show detailed output
    """
    if detailed:
        print(f"\n{'='*60}")
        print(f"πŸ“· Image: {image_path}")
        print(f"{'='*60}")
        
        for i, (food, conf) in enumerate(predictions, 1):
            emoji = "πŸ₯‡" if i == 1 else "πŸ₯ˆ" if i == 2 else "πŸ₯‰"
            formatted_name = food.replace('_', ' ').title()
            bar_length = int(conf / 2)  # Scale to 50 chars max
            bar = 'β–ˆ' * bar_length + 'β–‘' * (50 - bar_length)
            
            print(f"\n{emoji} Rank {i}:")
            print(f"   Food: {formatted_name}")
            print(f"   Confidence: {conf:.2f}%")
            print(f"   {bar}")
        
        print(f"\n{'='*60}\n")
    else:
        # Simple output
        top_food, top_conf = predictions[0]
        formatted_name = top_food.replace('_', ' ').title()
        print(f"{image_path}: {formatted_name} ({top_conf:.1f}%)")

def save_json(image_path, predictions, output_file):
    """
    Saves predictions to JSON file.
    
    Args:
        image_path: Path to image
        predictions: List of (class_name, confidence) tuples
        output_file: Output JSON file path
    """
    result = {
        'image': str(image_path),
        'predictions': [
            {
                'rank': i,
                'food': food,
                'formatted_name': food.replace('_', ' ').title(),
                'confidence': round(conf, 2)
            }
            for i, (food, conf) in enumerate(predictions, 1)
        ],
        'top_prediction': {
            'food': predictions[0][0],
            'confidence': round(predictions[0][1], 2)
        }
    }
    
    with open(output_file, 'w') as f:
        json.dump(result, f, indent=2)
    
    print(f"πŸ’Ύ Saved results to: {output_file}")

# ============================================================
# MAIN FUNCTION
# ============================================================

def main():
    parser = argparse.ArgumentParser(
        description='FoodVision - AI-powered food classification',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python predict.py --image pizza.jpg
  python predict.py --image food.png --top 5
  python predict.py --folder food_images/
  python predict.py --image burger.jpg --simple
  python predict.py --image pasta.jpg --json output.json
        """
    )
    
    # Input options
    input_group = parser.add_mutually_exclusive_group(required=True)
    input_group.add_argument('--image', type=str, help='Path to single image')
    input_group.add_argument('--folder', type=str, help='Path to folder of images')
    
    # Model options
    parser.add_argument('--model', type=str, default='model1_best.pth',
                       help='Path to model checkpoint (default: model1_best.pth)')
    
    # Output options
    parser.add_argument('--top', type=int, default=3,
                       help='Number of top predictions to show (default: 3)')
    parser.add_argument('--simple', action='store_true',
                       help='Simple output format (one line per image)')
    parser.add_argument('--json', type=str,
                       help='Save results to JSON file')
    
    # Device option
    parser.add_argument('--cpu', action='store_true',
                       help='Force CPU usage (default: auto-detect GPU)')
    
    args = parser.parse_args()
    
    # Setup device
    if args.cpu:
        device = torch.device('cpu')
        print("πŸ’» Using CPU")
    else:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        if device.type == 'cuda':
            print(f"⚑ Using GPU: {torch.cuda.get_device_name(0)}")
        else:
            print("πŸ’» Using CPU (no GPU detected)")
    
    # Load model
    model = load_model(args.model, device)
    print()  # Blank line
    
    # Get list of images to process
    if args.image:
        image_paths = [Path(args.image)]
    else:
        # Process folder
        folder = Path(args.folder)
        image_paths = list(folder.glob('*.jpg')) + list(folder.glob('*.jpeg')) + \
                     list(folder.glob('*.png')) + list(folder.glob('*.webp'))
        
        if not image_paths:
            print(f"❌ No images found in {folder}")
            sys.exit(1)
        
        print(f"πŸ“ Found {len(image_paths)} images in {folder}\n")
    
    # Process each image
    all_results = {}
    
    for img_path in image_paths:
        # Preprocess
        img_tensor = preprocess_image(img_path)
        
        if img_tensor is None:
            continue
        
        # Predict
        predictions = predict(model, img_tensor, device, args.top)
        
        # Store results
        all_results[str(img_path)] = predictions
        
        # Print predictions
        print_predictions(img_path, predictions, detailed=not args.simple)
    
    # Save to JSON if requested
    if args.json:
        if len(all_results) == 1:
            # Single image - save simple format
            img_path, predictions = list(all_results.items())[0]
            save_json(img_path, predictions, args.json)
        else:
            # Multiple images - save batch format
            batch_results = {
                'total_images': len(all_results),
                'results': []
            }
            
            for img_path, predictions in all_results.items():
                batch_results['results'].append({
                    'image': img_path,
                    'top_prediction': {
                        'food': predictions[0][0],
                        'confidence': round(predictions[0][1], 2)
                    },
                    'all_predictions': [
                        {
                            'rank': i,
                            'food': food,
                            'confidence': round(conf, 2)
                        }
                        for i, (food, conf) in enumerate(predictions, 1)
                    ]
                })
            
            with open(args.json, 'w') as f:
                json.dump(batch_results, f, indent=2)
            
            print(f"\nπŸ’Ύ Saved batch results to: {args.json}")
    
    # Summary for batch processing
    if len(all_results) > 1:
        print(f"\n{'='*60}")
        print(f"βœ… Successfully processed {len(all_results)} images")
        print(f"{'='*60}")

# ============================================================
# RUN SCRIPT
# ============================================================

if __name__ == "__main__":
    main()