venkyvicky commited on
Commit
7dbd4bf
·
verified ·
1 Parent(s): f4461ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -102
app.py CHANGED
@@ -1,106 +1,59 @@
1
- import gradio as gr
2
  import torch
3
  import torch.nn as nn
4
- import torch.nn.functional as F
5
- import torchvision.transforms as transforms
6
- from PIL import Image
7
- from ResNet_for_CC import CC_model # Import the model
8
-
9
- # Set device (CPU/GPU)
10
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
-
12
- # Load the trained CC_model
13
- model_path = "CC_net.pt"
14
- model = CC_model(num_classes1=14)
15
-
16
- # Load model weights
17
- state_dict = torch.load(model_path, map_location=device)
18
- model.load_state_dict(state_dict, strict=False)
19
- model.to(device)
20
- model.eval()
21
-
22
- # Clothing1M Class Labels
23
- class_labels = [
24
- "T-Shirt", "Shirt", "Knitwear", "Chiffon", "Sweater", "Hoodie",
25
- "Windbreaker", "Jacket", "Downcoat", "Suit", "Shawl", "Dress",
26
- "Vest", "Underwear"
27
- ]
28
-
29
- # ✅ **Updated Image Preprocessing Function**
30
- def preprocess_image(image):
31
- """Applies necessary transformations to the input image."""
32
- transform = transforms.Compose([
33
- transforms.Resize(256),
34
- transforms.CenterCrop(224),
35
- transforms.ToTensor(),
36
- transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
37
- ])
38
- return transform(image).unsqueeze(0).to(device)
39
-
40
- # ✅ **Classification Function**
41
- def classify_image(image):
42
- """Processes the input image and returns the predicted clothing category."""
43
- print("\n[INFO] Received image for classification.")
44
-
45
- try:
46
- image = Image.fromarray(image) # Ensure conversion to PIL format
47
- image = preprocess_image(image) # Apply transformations
48
- print("[INFO] Image transformed and moved to device.")
49
 
50
  with torch.no_grad():
51
- output = model(image)
52
-
53
- # ✅ Ensure output is a tensor (handle tuple case)
54
- if isinstance(output, tuple):
55
- output = output[1] # Extract the actual output tensor
56
-
57
- print(f"[DEBUG] Model output shape: {output.shape}")
58
- print(f"[DEBUG] Model output values: {output}")
59
-
60
- if output.shape[1] != 14:
61
- return f"[ERROR] Model output mismatch! Expected 14 but got {output.shape[1]}."
62
-
63
- # Convert logits to probabilities
64
- probabilities = F.softmax(output, dim=1)
65
- print(f"[DEBUG] Softmax probabilities: {probabilities}")
66
-
67
- # Get predicted class index
68
- predicted_class = torch.argmax(probabilities, dim=1).item()
69
- print(f"[INFO] Predicted class index: {predicted_class} (Class: {class_labels[predicted_class]})")
70
-
71
- # Validate and return the prediction
72
- if 0 <= predicted_class < len(class_labels):
73
- predicted_label = class_labels[predicted_class]
74
- confidence = probabilities[0][predicted_class].item() * 100
75
- return f"Predicted Class: {predicted_label} (Confidence: {confidence:.2f}%)"
76
- else:
77
- return "[ERROR] Model returned an invalid class index."
78
-
79
- except Exception as e:
80
- print(f"[ERROR] Exception during classification: {e}")
81
- return "Error in classification. Check console for details."
82
-
83
- # ✅ **Sample Images (Can be URLs or Local Paths)**
84
- sample_images = [
85
- "img1.png", # Replace with actual URLs or local paths
86
- "img2.png",
87
- "img3.png",
88
- "img4.png",
89
- "img5.png"
90
- ]
91
-
92
- # ✅ **Gradio Interface**
93
- interface = gr.Interface(
94
- fn=classify_image,
95
- inputs=gr.Image(type="numpy"),
96
- outputs="text",
97
- title="Clothing1M Image Classifier",
98
- description="Upload a clothing image, or select a sample below, and the model will classify it into one of the 14 categories.",
99
- examples=sample_images # ✅ Predefined images for users to try
100
- )
101
-
102
- # ✅ **Run the Interface**
103
- if __name__ == "__main__":
104
- print("[INFO] Launching Gradio interface...")
105
- interface.launch()
106
-
 
 
1
  import torch
2
  import torch.nn as nn
3
+ import torchvision.models as models
4
+
5
+
6
+ class ResClassifier(nn.Module):
7
+ def __init__(self, class_num=14):
8
+ super(ResClassifier, self).__init__()
9
+ self.fc1 = nn.Sequential(
10
+ nn.Linear(128, 64),
11
+ nn.BatchNorm1d(64, affine=True),
12
+ nn.ReLU(inplace=True),
13
+ nn.Dropout()
14
+ )
15
+ self.fc2 = nn.Sequential(
16
+ nn.Linear(64, 64),
17
+ nn.BatchNorm1d(64, affine=True),
18
+ nn.ReLU(inplace=True),
19
+ nn.Dropout()
20
+ )
21
+ self.fc3 = nn.Linear(64, class_num)
22
+
23
+ def forward(self, x):
24
+ fc1_emb = self.fc1(x)
25
+ fc2_emb = self.fc2(fc1_emb)
26
+ logit = self.fc3(fc2_emb)
27
+ return logit
28
+
29
+ class CC_model(nn.Module):
30
+ def __init__(self, num_classes1=14, num_classes2=None):
31
+
32
+ if num_classes2 is None:
33
+ num_classes2 = num_classes1
34
+
35
+ super(CC_model, self).__init__()
36
+ assert num_classes1 == num_classes2
37
+ self.num_classes = num_classes1
38
+ self.model_resnet = models.resnet50(weights='ResNet50_Weights.DEFAULT')
39
+ num_ftrs = self.model_resnet.fc.in_features
40
+ self.model_resnet.fc = nn.Identity()
41
+ self.classification_fc = nn.Linear(num_ftrs, num_classes1)
42
+ self.dr = nn.Linear(num_ftrs, 128)
43
+ self.fc1 = ResClassifier(num_classes1)
44
+ self.fc2 = ResClassifier(num_classes1)
45
+
46
+ def forward(self, x, detach_feature=False):
 
47
 
48
  with torch.no_grad():
49
+ feature = self.model_resnet(x)
50
+ res_out = self.classification_fc(feature)
51
+ if detach_feature:
52
+ feature = feature.detach()
53
+ dr_feature = self.dr(feature)
54
+ out1 = self.fc1(dr_feature)
55
+ out2 = self.fc2(dr_feature)
56
+ output_mean = (out1 + out2) / 2
57
+ return dr_feature, output_mean
58
+
59
+ #return dr_feature