Munzali commited on
Commit
4400aad
·
verified ·
1 Parent(s): aa8b2b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -25
app.py CHANGED
@@ -5,8 +5,14 @@ import torchvision.models as models
5
  from torchvision import transforms
6
  from PIL import Image
7
  import os
 
 
 
 
 
8
 
9
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
 
10
 
11
  CLASS_NAMES = ["bacterial", "blast", "brownspot", "healthy", "tungro"]
12
 
@@ -46,6 +52,7 @@ TRANSFORMS = transforms.Compose([
46
  ])
47
 
48
  def load_model():
 
49
  model = models.efficientnet_b0(weights=None)
50
  model.classifier = nn.Sequential(
51
  nn.Dropout(p=0.3),
@@ -53,37 +60,41 @@ def load_model():
53
  )
54
 
55
  model_path = os.getenv("MODEL_PATH", "efficientnet_b0_best.pth")
56
- checkpoint = torch.load(
57
- model_path,
58
- map_location=DEVICE
59
- )
 
 
 
60
  model.load_state_dict(checkpoint["model_state_dict"])
61
  model.to(DEVICE)
62
  model.eval()
 
63
  return model
64
 
65
  model = load_model()
66
 
67
  def predict(image: Image.Image):
68
- if image is None:
69
- return "Please upload an image.", {}
70
-
71
  tensor = TRANSFORMS(image).unsqueeze(0).to(DEVICE)
72
-
73
  with torch.no_grad():
74
  outputs = model(tensor)
75
  probs = torch.softmax(outputs, dim=1)[0]
76
  idx = probs.argmax().item()
77
-
78
  predicted = CLASS_NAMES[idx]
79
  info = DISEASE_INFO[predicted]
80
  confidence = float(probs[idx])
81
-
82
  all_probs = {
83
  CLASS_NAMES[i]: float(probs[i])
84
  for i in range(len(CLASS_NAMES))
85
  }
86
-
87
  result = f"""
88
  ## {info['full_name']}
89
  | Field | Value |
@@ -95,6 +106,7 @@ def predict(image: Image.Image):
95
  """
96
  return result, all_probs
97
 
 
98
  demo = gr.Interface(
99
  fn=predict,
100
  inputs=gr.Image(type="pil", label="Upload rice leaf image"),
@@ -107,22 +119,15 @@ demo = gr.Interface(
107
  "Upload a rice leaf image to detect disease using EfficientNet-B0. "
108
  "Detects: Bacterial Blight, Rice Blast, Brown Spot, Tungro, or Healthy."
109
  ),
110
- theme=gr.themes.Soft(),
111
  )
112
 
113
  if __name__ == "__main__":
114
  port = int(os.getenv("PORT", 7860))
 
115
 
116
- # For Hugging Face Spaces, use this configuration
117
- try:
118
- demo.launch(
119
- server_name="0.0.0.0",
120
- server_port=port,
121
- share=False # Set to False for HF Spaces
122
- )
123
- except:
124
- # Fallback for newer Gradio versions
125
- demo.launch(
126
- server_port=port,
127
- share=False
128
- )
 
5
  from torchvision import transforms
6
  from PIL import Image
7
  import os
8
+ import sys
9
+
10
+ print("Starting Rice Disease Classifier...")
11
+ print(f"Python version: {sys.version}")
12
+ print(f"Gradio version: {gr.__version__}")
13
 
14
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
15
+ print(f"Using device: {DEVICE}")
16
 
17
  CLASS_NAMES = ["bacterial", "blast", "brownspot", "healthy", "tungro"]
18
 
 
52
  ])
53
 
54
  def load_model():
55
+ print("Loading model...")
56
  model = models.efficientnet_b0(weights=None)
57
  model.classifier = nn.Sequential(
58
  nn.Dropout(p=0.3),
 
60
  )
61
 
62
  model_path = os.getenv("MODEL_PATH", "efficientnet_b0_best.pth")
63
+ print(f"Loading model from: {model_path}")
64
+
65
+ if not os.path.exists(model_path):
66
+ print(f"ERROR: Model file {model_path} not found!")
67
+ return None
68
+
69
+ checkpoint = torch.load(model_path, map_location=DEVICE)
70
  model.load_state_dict(checkpoint["model_state_dict"])
71
  model.to(DEVICE)
72
  model.eval()
73
+ print("Model loaded successfully!")
74
  return model
75
 
76
  model = load_model()
77
 
78
  def predict(image: Image.Image):
79
+ if image is None or model is None:
80
+ return "Please upload an image or model not loaded.", {}
81
+
82
  tensor = TRANSFORMS(image).unsqueeze(0).to(DEVICE)
83
+
84
  with torch.no_grad():
85
  outputs = model(tensor)
86
  probs = torch.softmax(outputs, dim=1)[0]
87
  idx = probs.argmax().item()
88
+
89
  predicted = CLASS_NAMES[idx]
90
  info = DISEASE_INFO[predicted]
91
  confidence = float(probs[idx])
92
+
93
  all_probs = {
94
  CLASS_NAMES[i]: float(probs[i])
95
  for i in range(len(CLASS_NAMES))
96
  }
97
+
98
  result = f"""
99
  ## {info['full_name']}
100
  | Field | Value |
 
106
  """
107
  return result, all_probs
108
 
109
+ # Gradio 3.50.2 compatible interface
110
  demo = gr.Interface(
111
  fn=predict,
112
  inputs=gr.Image(type="pil", label="Upload rice leaf image"),
 
119
  "Upload a rice leaf image to detect disease using EfficientNet-B0. "
120
  "Detects: Bacterial Blight, Rice Blast, Brown Spot, Tungro, or Healthy."
121
  ),
 
122
  )
123
 
124
  if __name__ == "__main__":
125
  port = int(os.getenv("PORT", 7860))
126
+ print(f"Starting server on port {port}...")
127
 
128
+ # Use this format for Gradio 3.50.2
129
+ demo.launch(
130
+ server_name="0.0.0.0",
131
+ server_port=port,
132
+ share=True
133
+ )