PrachiY commited on
Commit
2b2fd40
·
verified ·
1 Parent(s): 97d3b50

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torchvision.transforms as transforms
4
+ from torchvision import models
5
+ from PIL import Image
6
+ import gradio as gr
7
+
8
+ # 14-class Clothing1M labels
9
+ clothing1m_classes = [
10
+ "T-shirt", "Shirt", "Knitwear", "Chiffon", "Sweater",
11
+ "Hoodie", "Windbreaker", "Jacket", "Down Coat", "Suits",
12
+ "Shawl", "Dress", "Vest", "Underwear"
13
+ ]
14
+
15
+ # Set device
16
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+ # Load model
19
+ model = models.resnet50(weights=None)
20
+ model.fc = torch.nn.Linear(model.fc.in_features, 14) # match to 14 classes
21
+ try:
22
+ model.load_state_dict(torch.load("model.pth", map_location=device))
23
+ model.to(device)
24
+ model.eval()
25
+ except Exception as e:
26
+ print("❌ Model loading failed:", e)
27
+ model = None
28
+
29
+ # Preprocessing
30
+ def preprocess_image(image):
31
+ transform = transforms.Compose([
32
+ transforms.Resize((224, 224)),
33
+ transforms.ToTensor(),
34
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
35
+ std=[0.229, 0.224, 0.225])
36
+ ])
37
+ return transform(image).unsqueeze(0).to(device)
38
+
39
+ # Prediction
40
+ def classify_image(image):
41
+ if model is None:
42
+ return "Model failed to load. Check logs."
43
+
44
+ image_tensor = preprocess_image(image)
45
+ with torch.no_grad():
46
+ output = model(image_tensor)
47
+ predicted_idx = output.argmax(dim=1).item()
48
+ return clothing1m_classes[predicted_idx] if predicted_idx < len(clothing1m_classes) else "Unknown"
49
+
50
+ # Gradio Interface
51
+ interface = gr.Interface(
52
+ fn=classify_image,
53
+ inputs=gr.Image(type="pil"),
54
+ outputs="text",
55
+ title="Clothing1M ResNet Classifier",
56
+ description="Upload an image of clothing and get the predicted category."
57
+ )
58
+
59
+ if __name__ == "__main__":
60
+ interface.launch()
61
+