Upload app.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import 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")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)
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]) ]) return transform(image).unsqueeze(0).to(device)
# ✅ 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__": interface.launch()app.pyAdded+69