Update app.py
Browse files123456775 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291305 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661 unmodified line1681691701711721731741751761771781791801811821831841851861871883 unmodified lines192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258#!/usr/bin/env python3"""HuggingFace Spaces App for ImageNet ResNet50 ClassifierTrained from scratch to 78%+ Top-1 accuracy"""import gradio as gr75 unmodified lines# ============================================================================# MODEL LOADING# ============================================================================def load_model():"""Load the trained model (CPU-optimized for HuggingFace)"""model = ResNet50(num_classes=1000)try:# Try to load checkpointcheckpoint_path = "best_model_final.pth" # Will be uploaded separatelycheckpoint = torch.load(checkpoint_path, map_location='cpu')# Handle different checkpoint formatsif isinstance(checkpoint, dict):if 'model' in checkpoint:state_dict = checkpoint['model']elif 'state_dict' in checkpoint:state_dict = checkpoint['state_dict']else:state_dict = checkpointelse:state_dict = checkpoint# Remove 'module.' prefix if present (from DataParallel)new_state_dict = {}for k, v in state_dict.items():name = k.replace('module.', '') if k.startswith('module.') else knew_state_dict[name] = vmodel.load_state_dict(new_state_dict)print(f"✅ Model loaded successfully from {checkpoint_path}")except Exception as e:print(f"⚠️ Could not load checkpoint: {e}")print("Using randomly initialized model for demo purposes")model.eval()return model# ============================================================================# IMAGE PREPROCESSING# ============================================================================transform = transforms.Compose([5 unmodified lines# ============================================================================# IMAGENET CLASS LABELS# ============================================================================# Top 20 most common ImageNet classes for demoIMAGENET_CLASSES = {0: "tench", 1: "goldfish", 2: "great white shark", 3: "tiger shark",4: "hammerhead", 5: "electric ray", 6: "stingray", 7: "cock",8: "hen", 9: "ostrich", 10: "brambling", 11: "goldfinch",12: "house finch", 13: "junco", 14: "indigo bunting", 15: "robin",151: "Chihuahua", 207: "golden retriever", 281: "tabby cat",282: "tiger cat", 283: "Persian cat", 285: "Egyptian cat",291: "lion", 292: "tiger", 293: "jaguar", 294: "leopard",404: "airliner", 407: "container ship", 468: "cab",511: "convertible", 609: "jeep", 627: "limousine",817: "sports car", 751: "racer", 779: "school bus",555: "fire engine", 569: "garbage truck", 717: "pickup",# Add more as needed}# Load full class names if availabletry:with open('imagenet_classes.json', 'r') as f:IMAGENET_CLASSES = json.load(f)except:pass # Use default subset# ============================================================================1 unmodified line# ============================================================================def predict(image):"""Predict ImageNet class for input imageArgs:image: PIL ImageReturns:dict: Top-5 predictions with confidence scores"""if image is None:return {"error": "Please upload an image"}try:# Preprocessimg_tensor = transform(image).unsqueeze(0) # Add batch dimension# Inferencewith torch.no_grad():3 unmodified lines# Get top 5 predictionstop5_prob, top5_indices = torch.topk(probabilities, 5)# Format resultsresults = {}for i in range(5):idx = top5_indices[i].item()prob = top5_prob[i].item()class_name = IMAGENET_CLASSES.get(str(idx), f"Class {idx}")results[f"{class_name}"] = float(prob)return resultsexcept Exception as e:return {"error": f"Prediction failed: {str(e)}"}# ============================================================================# GRADIO INTERFACE# ============================================================================# Load model globallyprint("Loading model...")model = load_model()print("Model loaded successfully!")# Create Gradio interfacewith gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🔥 ImageNet ResNet50 ClassifierUpload any image and get top-5 predictions with confidence scores.""")with gr.Row():with gr.Column():image_input = gr.Image(type="pil", label="Upload Image")predict_btn = gr.Button("Classify Image", variant="primary")with gr.Column():output = gr.Label(num_top_classes=5, label="Top-5 Predictions")gr.Markdown("""### 🎯 Model Info:- **Architecture:** ResNet50 (25.5M params)- **Training:** From scratch (no pretrained weights)- **Dataset:** ImageNet (1.2M images, 1000 classes)- **Accuracy:** 77.09% Top-1 validation### 🔗 Links:- [GitHub Repository](https://github.com/Shwethaamrutha/TSAI-S8)""")# Connect buttonpredict_btn.click(fn=predict, inputs=image_input, outputs=output)# Launchif __name__ == "__main__":demo.launch()12345675 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141155 unmodified lines1211221231241251261271281291301311321331341351361371 unmodified line1391401411421431441451461471481491501511521531541551561571581593 unmodified lines163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238#!/usr/bin/env python3"""HuggingFace App for ImageNet ResNet50 Classifier - 77.09% Accuracy"""import gradio as gr75 unmodified lines# ============================================================================# LOAD MODEL# ============================================================================def load_model():model = ResNet50(num_classes=1000)try:checkpoint = torch.load("best_model_final.pth", map_location='cpu')if isinstance(checkpoint, dict):state_dict = checkpoint.get('model', checkpoint.get('state_dict', checkpoint))else:state_dict = checkpointnew_state_dict = {}for k, v in state_dict.items():name = k.replace('module.', '') if k.startswith('module.') else knew_state_dict[name] = vmodel.load_state_dict(new_state_dict)print("✅ Model loaded successfully")except Exception as e:print(f"⚠️ Could not load checkpoint: {e}")model.eval()return model# ============================================================================# PREPROCESSING# ============================================================================transform = transforms.Compose([5 unmodified lines# ============================================================================# IMAGENET CLASSES# ============================================================================IMAGENET_CLASSES = {}try:with open('imagenet_classes.json', 'r') as f:IMAGENET_CLASSES = json.load(f)except:# Fallback - create basic class mappingIMAGENET_CLASSES = {str(i): f"Class {i}" for i in range(1000)}print("⚠️ Using default class indices")# ============================================================================1 unmodified line# ============================================================================def predict(image):"""Predict ImageNet class for input image"""if image is None:# Return dummy predictions for error casereturn {"Error - No Image": 1.0,"Please upload an image": 0.0,"": 0.0," ": 0.0," ": 0.0}try:# Preprocessimg_tensor = transform(image).unsqueeze(0)# Inferencewith torch.no_grad():3 unmodified lines# Get top 5 predictionstop5_prob, top5_indices = torch.topk(probabilities, 5)# Format results - dict with string keys and float valuesresults = {}for i in range(5):idx = top5_indices[i].item()prob = top5_prob[i].item()# CRITICAL: Convert idx to string for JSON lookupclass_name = IMAGENET_CLASSES.get(str(idx), f"Class_{idx}")# Ensure float probabilityresults[class_name] = float(prob)return resultsexcept Exception as e:# Return error in valid formaterror_msg = str(e)[:80]return {f"Error: {error_msg}": 0.5,"Please try another image": 0.3,"Check console for details": 0.2,"": 0.0," ": 0.0}# ============================================================================# GRADIO INTERFACE# ============================================================================print("Loading model...")model = load_model()print("Model ready!")with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🔥 ImageNet ResNet50 Classifier**77.09% Top-1 Accuracy** - Trained from scratch on ImageNet (1.2M images, 1000 classes)Upload an image to get top-5 predictions with confidence scores.""")with gr.Row():with gr.Column():image_input = gr.Image(type="pil", label="Upload Image")predict_btn = gr.Button("Classify Image", variant="primary", size="lg")with gr.Column():output = gr.Label(num_top_classes=5, label="Top-5 Predictions")gr.Markdown("""### 📊 Model Info:- **Architecture:** ResNet50 (25.5M params)- **Training:** From scratch (no pretrained)- **Accuracy:** 77.09% Top-1- **Hardware:** 8× A100 GPUs""")predict_btn.click(fn=predict, inputs=image_input, outputs=output)gr.Markdown("""---**Links:** [GitHub Code](https://github.com/Shwethaamrutha/TSAI-S8) | [Training Details](https://github.com/Shwethaamrutha/TSAI-S8/blob/main/README.md)Built with PyTorch •""")if __name__ == "__main__":demo.launch()
app.py+52-72