Upload app.py with huggingface_hub
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import torchimport torchvision.models as modelsimport gradio as grfrom huggingface_hub import hf_hub_downloadfrom PIL import Imagefrom torchvision import transforms# β Download model checkpoint from Hugging Face Hubmodel_path = hf_hub_download(repo_id="PrachiY/image-classification-model",filename="clothing1m.pth.tar")# β Load the Modeldevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")print(f"β Using device: {device}")model = models.resnet50(pretrained=False)checkpoint = torch.load(model_path, map_location=device)if "model" in checkpoint:model.load_state_dict(checkpoint["model"], strict=False)elif "state_dict" in checkpoint:model.load_state_dict(checkpoint["state_dict"], strict=False)else:model.load_state_dict(checkpoint, strict=False)# Ensure correct output layer (21 classes for Clothing1M)model.fc = torch.nn.Linear(2048, 21)model.to(device)model.eval()# β Define Clothing1M Class Labelsclass_labels = ["T-shirt", "Shirt", "Knitwear", "Chiffon", "Sweater", "Hoodie", "Windbreaker","Jacket", "Downcoat", "Suits", "Shawl", "Dress", "Vest", "Underwear","Hat", "Sock", "Jeans", "Sweatpants", "Trousers", "Shorts", "Skirt"]# β Image Preprocessingdef preprocess_image(image):transform = transforms.Compose([transforms.Resize((224, 224)),transforms.ToTensor(),transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])])image = transform(image).unsqueeze(0).to(device) # Ensure tensor is on GPU if availablereturn image# β Prediction Functiondef predict(image):image_tensor = preprocess_image(image)with torch.no_grad():output = model(image_tensor)predicted_class_idx = output.argmax(dim=1).item()if predicted_class_idx >= len(class_labels):return f"Predicted Class: Unknown (Index {predicted_class_idx} out of range)"return f"Predicted Class: {class_labels[predicted_class_idx]}"# β Gradio Interfaceinterface = gr.Interface(fn=predict,inputs=gr.Image(type="pil"),outputs="text",title="Clothing1M Image Classifier",description="Upload an image to classify it into one of 21 clothing categories.")if __name__ == "__main__":12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import torchimport torchvision.transforms as transformsimport gradio as grfrom torchvision import modelsfrom PIL import Image# Define Clothing1M class labelsclothing1m_classes = ["T-shirt", "Shirt", "Knitwear", "Chiffon", "Sweater", "Hoodie", "Windbreaker","Jacket", "Down Coat", "Suits", "Shawl", "Dress", "Vest", "Underwear", "Shorts","Trousers", "Jeans", "Leather Shoes", "Casual Shoes", "Sport Shoes", "Sandals"]# β Set devicedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")# β Load modelmodel = models.resnet50(weights=None) # Ensure correct architecturenum_ftrs = model.fc.in_featuresmodel.fc = torch.nn.Linear(num_ftrs, 21) # Match Clothing1M class countmodel.load_state_dict(torch.load("model.pth", map_location=device)) # Load weightsmodel.to(device)model.eval()# β Define image preprocessingdef preprocess_image(image):transform = transforms.Compose([transforms.Resize((224, 224)),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])return transform(image).unsqueeze(0).to(device)# β Define inference functiondef classify_image(image):image_tensor = preprocess_image(image)with torch.no_grad():output = model(image_tensor)predicted_class_idx = output.argmax(dim=1).item()predicted_class_name = clothing1m_classes[predicted_class_idx] if predicted_class_idx < len(clothing1m_classes) else "Unknown"return f"Predicted Class: {predicted_class_name}"# β Create Gradio Interfaceinterface = gr.Interface(fn=classify_image,inputs=gr.Image(type="pil"),outputs="text",title="Clothing1M Classifier",description="Upload an image of clothing and get the predicted category.")if __name__ == "__main__":
app.py+25-44