NagashreePai commited on
Commit
8a3a43a
Β·
verified Β·
1 Parent(s): 7a0972c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -56
app.py CHANGED
@@ -5,7 +5,7 @@ from torchvision import transforms
5
  from torchvision.models import swin_t
6
  from PIL import Image
7
 
8
- # πŸ”§ Model definition
9
  class MMIM(nn.Module):
10
  def __init__(self, num_classes=36):
11
  super(MMIM, self).__init__()
@@ -22,7 +22,7 @@ class MMIM(nn.Module):
22
  features = self.backbone(x)
23
  return self.classifier(features)
24
 
25
- # βœ… Load model
26
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
  model = MMIM(num_classes=36)
28
  checkpoint = torch.load("MMIM_best.pth", map_location=device)
@@ -33,7 +33,7 @@ model.load_state_dict(filtered_checkpoint, strict=False)
33
  model.to(device)
34
  model.eval()
35
 
36
- # βœ… Class names
37
  class_names = [
38
  "Chinee apple", # class1
39
  "Black grass", # class14
@@ -74,53 +74,53 @@ class_names = [
74
  "Snake weed",
75
  ]
76
 
77
- # πŸ“˜ Weed info dictionary
78
  weed_info = {
79
- "Chinee apple": "🌳 Invasive shrub. Control by uprooting or herbicide treatment.",
80
- "Black grass": "🌾 Infests cereal crops. Remove before seed shedding.",
81
- "Charlock": "🟑 Common weed in oilseed crops. Responds to early herbicide.",
82
- "Cleavers": "πŸͺ» Sticky climbing weed. Control before flowering.",
83
- "Common Chickweed": "🌱 Fast-spreading groundcover weed. Avoid soil disturbance.",
84
- "Common Wheat": "🌾 May appear as weed in rotation crops.",
85
- "Fat Hen": "🌿 Broadleaf weed. Competes heavily with crops.",
86
- "Lanthana": "🌺 Invasive ornamental plant, toxic to livestock.",
87
- "Loose Silky bent": "🌾 Grass weed affecting wheat fields.",
88
- "Maize": "🌽 Sometimes emerges as volunteer weed post-harvest.",
89
- "Scentless Mayweed": "🌼 Strong competitor in cereals. Shallow-rooted.",
90
- "Shepherds Purse": "πŸ‘œ Common weed in cool seasons. Heart-shaped pods.",
91
- "Small-Flowered Cranesbill": "🌸 Low-growing, thrives in dry areas.",
92
- "Sugar beet": "πŸ§ƒ Appears as volunteer in crop fields.",
93
- "Carpetweeds": "🧢 Low mat-forming weed. Easy to remove manually.",
94
- "Crabgrass": "πŸ¦€ Summer annual grass. Thrives in disturbed soil.",
95
- "Eclipta": "🌿 Moisture-loving herbaceous weed.",
96
- "Goosegrass": "πŸͺΆ Mat-forming weed, tough to hand-pull.",
97
- "Negative": "❌ No weed confidently detected. Please recheck input.",
98
- "Morningglory": "🌸 Climbing vine, chokes crops quickly.",
99
- "Nutsedge": "🌰 Grass-like weed with tubers. Hard to control.",
100
- "Palmer Amarnath": "πŸ”₯ Highly aggressive and herbicide-resistant.",
101
- "Prickly Sida": "🟀 Hairy, thorny stems. Requires early control.",
102
- "Purslane": "πŸͺ΄ Succulent weed, common in warm climates.",
103
- "Ragweed": "🀧 Allergen-producing weed. Kill before flowering.",
104
- "Sicklepod": "🌿 Toxic to livestock. Control before pod set.",
105
- "SpottedSpurge": "πŸ”΄ Low-growing. Releases milky sap.",
106
- "SpurredAnoda": "⚑ Fast-growing summer annual. Common in cotton.",
107
- "Swinecress": "🐷 Strong odor. Grows in compacted soils.",
108
- "Parkinsonia": "🌲 Woody shrub. Mechanical removal advised.",
109
- "Waterhemp": "πŸ’§ Fast-growing amaranth. Glyphosate-resistant strains exist.",
110
- "Parthenium": "☠️ Toxic and invasive. Avoid contact.",
111
- "Prickly acacia": "🌡 Thorny shrub. Displaces native plants.",
112
- "Rubber vine": "πŸͺ’ Woody climber. Toxic and invasive.",
113
- "Siam weed": "πŸŽ‹ Highly invasive in tropical zones.",
114
- "Snake weed": "🐍 Woody perennial, toxic to livestock."
115
  }
116
 
117
- # πŸ” Transform
118
  transform = transforms.Compose([
119
  transforms.Resize((224, 224)),
120
  transforms.ToTensor()
121
  ])
122
 
123
- # πŸ” Prediction function
124
  def predict(img):
125
  img = img.convert('RGB')
126
  img_tensor = transform(img).unsqueeze(0).to(device)
@@ -134,35 +134,35 @@ def predict(img):
134
  confidence = conf.item() * 100
135
 
136
  if predicted_class.lower() == "negative":
137
- label = f"⚠️ Predicted as: Negative\nConfidence: {confidence:.2f}%"
138
  elif confidence < 60:
139
- label = f"❌ Low confidence. Possibly Not a Weed\nConfidence: {confidence:.2f}%"
140
  else:
141
- label = f"βœ… Predicted class: {predicted_class}\nConfidence: {confidence:.2f}%"
142
 
143
- info = weed_info.get(predicted_class, "ℹ️ No additional info available.")
144
- return f"{label}\n\nπŸ“˜ Info: {info}"
145
 
146
- # ℹ️ App description
147
  about_markdown = """
148
- ### 🌿 Weed Classifier β€” Swin Transformer + MMIM
149
  This tool predicts weed species from images using a Vision Transformer backbone trained with multi-masked image modeling.
150
 
151
- - βœ… Shows confidence scores
152
- - ❌ Flags uncertain or non-weed predictions
153
- - πŸ“˜ Displays weed info after prediction
154
- - πŸ“Έ Upload an image
155
 
156
  > Tip: Use clear, focused weed images for better results.
157
  """
158
 
159
- # 🎨 Gradio Interface
160
  interface = gr.Interface(
161
  fn=predict,
162
  inputs=gr.Image(type="pil", label="Upload an Image"),
163
  outputs=gr.Textbox(label="Prediction"),
164
- title="🌱 Weed Image Classifier",
165
- description="A Swin Transformer-based app to classify 36 weed species. Built using Multi-Masked Image Modeling (MMIM).",
166
  article=about_markdown
167
  )
168
 
 
5
  from torchvision.models import swin_t
6
  from PIL import Image
7
 
8
+ # Model definition
9
  class MMIM(nn.Module):
10
  def __init__(self, num_classes=36):
11
  super(MMIM, self).__init__()
 
22
  features = self.backbone(x)
23
  return self.classifier(features)
24
 
25
+ # Load model
26
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
  model = MMIM(num_classes=36)
28
  checkpoint = torch.load("MMIM_best.pth", map_location=device)
 
33
  model.to(device)
34
  model.eval()
35
 
36
+ # Class names
37
  class_names = [
38
  "Chinee apple", # class1
39
  "Black grass", # class14
 
74
  "Snake weed",
75
  ]
76
 
77
+ # Weed info dictionary
78
  weed_info = {
79
+ "Chinee apple": " Invasive shrub. Control by uprooting or herbicide treatment.",
80
+ "Black grass": " Infests cereal crops. Remove before seed shedding.",
81
+ "Charlock": " Common weed in oilseed crops. Responds to early herbicide.",
82
+ "Cleavers": " Sticky climbing weed. Control before flowering.",
83
+ "Common Chickweed": " Fast-spreading groundcover weed. Avoid soil disturbance.",
84
+ "Common Wheat": " May appear as weed in rotation crops.",
85
+ "Fat Hen": " Broadleaf weed. Competes heavily with crops.",
86
+ "Lanthana": " Invasive ornamental plant, toxic to livestock.",
87
+ "Loose Silky bent": " Grass weed affecting wheat fields.",
88
+ "Maize": " Sometimes emerges as volunteer weed post-harvest.",
89
+ "Scentless Mayweed": " Strong competitor in cereals. Shallow-rooted.",
90
+ "Shepherds Purse": " Common weed in cool seasons. Heart-shaped pods.",
91
+ "Small-Flowered Cranesbill": " Low-growing, thrives in dry areas.",
92
+ "Sugar beet": " Appears as volunteer in crop fields.",
93
+ "Carpetweeds": " Low mat-forming weed. Easy to remove manually.",
94
+ "Crabgrass": " Summer annual grass. Thrives in disturbed soil.",
95
+ "Eclipta": " Moisture-loving herbaceous weed.",
96
+ "Goosegrass": " Mat-forming weed, tough to hand-pull.",
97
+ "Negative": " No weed confidently detected. Please recheck input.",
98
+ "Morningglory": " Climbing vine, chokes crops quickly.",
99
+ "Nutsedge": " Grass-like weed with tubers. Hard to control.",
100
+ "Palmer Amarnath": " Highly aggressive and herbicide-resistant.",
101
+ "Prickly Sida": " Hairy, thorny stems. Requires early control.",
102
+ "Purslane": " Succulent weed, common in warm climates.",
103
+ "Ragweed": " Allergen-producing weed. Kill before flowering.",
104
+ "Sicklepod": " Toxic to livestock. Control before pod set.",
105
+ "SpottedSpurge": " Low-growing. Releases milky sap.",
106
+ "SpurredAnoda": " Fast-growing summer annual. Common in cotton.",
107
+ "Swinecress": " Strong odor. Grows in compacted soils.",
108
+ "Parkinsonia": " Woody shrub. Mechanical removal advised.",
109
+ "Waterhemp": " Fast-growing amaranth. Glyphosate-resistant strains exist.",
110
+ "Parthenium": " Toxic and invasive. Avoid contact.",
111
+ "Prickly acacia": " Thorny shrub. Displaces native plants.",
112
+ "Rubber vine": " Woody climber. Toxic and invasive.",
113
+ "Siam weed": " Highly invasive in tropical zones.",
114
+ "Snake weed": " Woody perennial, toxic to livestock."
115
  }
116
 
117
+ # Transform
118
  transform = transforms.Compose([
119
  transforms.Resize((224, 224)),
120
  transforms.ToTensor()
121
  ])
122
 
123
+ # Prediction function
124
  def predict(img):
125
  img = img.convert('RGB')
126
  img_tensor = transform(img).unsqueeze(0).to(device)
 
134
  confidence = conf.item() * 100
135
 
136
  if predicted_class.lower() == "negative":
137
+ label = f" Predicted as: Negative\nConfidence: {confidence:.2f}%"
138
  elif confidence < 60:
139
+ label = f" Low confidence. Possibly Not a Weed\nConfidence: {confidence:.2f}%"
140
  else:
141
+ label = f" Predicted class: {predicted_class}\nConfidence: {confidence:.2f}%"
142
 
143
+ info = weed_info.get(predicted_class, " No additional info available.")
144
+ return f"{label}\n\n Info: {info}"
145
 
146
+ # App description
147
  about_markdown = """
148
+ ### Weed Classifier β€” Swin Transformer + MMIM
149
  This tool predicts weed species from images using a Vision Transformer backbone trained with multi-masked image modeling.
150
 
151
+ - Shows confidence scores
152
+ - Flags uncertain or non-weed predictions
153
+ - Displays weed info after prediction
154
+ - Upload an image
155
 
156
  > Tip: Use clear, focused weed images for better results.
157
  """
158
 
159
+ # Gradio Interface
160
  interface = gr.Interface(
161
  fn=predict,
162
  inputs=gr.Image(type="pil", label="Upload an Image"),
163
  outputs=gr.Textbox(label="Prediction"),
164
+ title=" Weed Image Classifier",
165
+ description="A Self- Spervised Learning model for weed image classification.",
166
  article=about_markdown
167
  )
168