Giftmutie commited on
Commit
e500c4c
Β·
verified Β·
1 Parent(s): a80420b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -17
app.py CHANGED
@@ -1,11 +1,11 @@
1
- from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from ultralytics import YOLO
4
  from PIL import Image
5
  import io
6
-
7
  app = FastAPI(title="AgriVision API")
8
-
9
  app.add_middleware(
10
  CORSMiddleware,
11
  allow_origins=["*"],
@@ -132,7 +132,6 @@ TREATMENTS = {
132
  "treatment": "Apply pyrethroid insecticides. Store harvested grain in airtight containers. Use hermetic storage bags and apply diatomaceous earth as a physical control."
133
  },
134
  }
135
-
136
  # ── Severity function ──────────────────────────────────────────
137
  def get_severity(confidence: float, crop_type: str) -> str:
138
  if crop_type == "Healthy":
@@ -143,51 +142,70 @@ def get_severity(confidence: float, crop_type: str) -> str:
143
  return "Medium"
144
  else:
145
  return "Low"
146
-
 
 
 
 
147
  # ── Load model once at startup ─────────────────────────────────
148
  model = YOLO("best.pt")
149
-
150
  # ── Routes ─────────────────────────────────────────────────────
151
  @app.get("/")
152
  def home():
153
  return {"status": "AgriVision API is running"}
154
-
155
  @app.post("/predict")
156
  async def predict(file: UploadFile = File(...)):
157
  # Read and process image
158
  contents = await file.read()
159
  image = Image.open(io.BytesIO(contents)).convert("RGB")
160
-
161
  # Run inference
162
  results = model.predict(image, imgsz=224, verbose=False)
163
  probs = results[0].probs
164
-
165
  # Top prediction
166
  top1_index = probs.top1
167
  top1_class = model.names[top1_index]
168
  top1_confidence = round(float(probs.top1conf), 4)
169
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  # Look up treatment and type
171
  info = TREATMENTS.get(top1_class, {
172
  "type": "Unknown",
173
  "treatment": "No treatment data available for this class."
174
  })
175
  severity = get_severity(top1_confidence, info["type"])
176
-
177
  # Top 3 predictions
178
  top3 = [
179
  {
180
- "class": model.names[i],
181
- "confidence": round(float(probs.data[i]), 4)
182
  }
183
  for i in probs.top5[:3]
184
  ]
185
-
186
  return {
187
- "prediction": top1_class,
188
  "type": info["type"],
189
- "confidence": top1_confidence,
190
  "severity": severity,
191
  "treatment": info["treatment"],
192
  "top3": top3
193
- }
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from ultralytics import YOLO
4
  from PIL import Image
5
  import io
6
+
7
  app = FastAPI(title="AgriVision API")
8
+
9
  app.add_middleware(
10
  CORSMiddleware,
11
  allow_origins=["*"],
 
132
  "treatment": "Apply pyrethroid insecticides. Store harvested grain in airtight containers. Use hermetic storage bags and apply diatomaceous earth as a physical control."
133
  },
134
  }
 
135
  # ── Severity function ──────────────────────────────────────────
136
  def get_severity(confidence: float, crop_type: str) -> str:
137
  if crop_type == "Healthy":
 
142
  return "Medium"
143
  else:
144
  return "Low"
145
+
146
+ # ── Name formatter ─────────────────────────────────────────────
147
+ def format_class_name(name: str) -> str:
148
+ return name.replace("_", " ").title()
149
+
150
  # ── Load model once at startup ─────────────────────────────────
151
  model = YOLO("best.pt")
152
+
153
  # ── Routes ─────────────────────────────────────────────────────
154
  @app.get("/")
155
  def home():
156
  return {"status": "AgriVision API is running"}
157
+
158
  @app.post("/predict")
159
  async def predict(file: UploadFile = File(...)):
160
  # Read and process image
161
  contents = await file.read()
162
  image = Image.open(io.BytesIO(contents)).convert("RGB")
163
+
164
  # Run inference
165
  results = model.predict(image, imgsz=224, verbose=False)
166
  probs = results[0].probs
167
+
168
  # Top prediction
169
  top1_index = probs.top1
170
  top1_class = model.names[top1_index]
171
  top1_confidence = round(float(probs.top1conf), 4)
172
+
173
+ # ── Invalid image detection ─────────────────────────────────
174
+ top5_probs = [float(probs.data[i]) for i in probs.top5]
175
+ top5_spread = max(top5_probs) - min(top5_probs)
176
+
177
+ if top1_confidence < 0.45 and top5_spread < 0.30:
178
+ raise HTTPException(
179
+ status_code=422,
180
+ detail={
181
+ "error": "Invalid image",
182
+ "message": "The uploaded image does not appear to be a crop or pest image. Please upload a clear photo of the crop or pest.",
183
+ "confidence": f"{round(top1_confidence * 100, 2)}%"
184
+ }
185
+ )
186
+
187
  # Look up treatment and type
188
  info = TREATMENTS.get(top1_class, {
189
  "type": "Unknown",
190
  "treatment": "No treatment data available for this class."
191
  })
192
  severity = get_severity(top1_confidence, info["type"])
193
+
194
  # Top 3 predictions
195
  top3 = [
196
  {
197
+ "class": format_class_name(model.names[i]),
198
+ "confidence": f"{round(float(probs.data[i]) * 100, 2)}%"
199
  }
200
  for i in probs.top5[:3]
201
  ]
202
+
203
  return {
204
+ "prediction": format_class_name(top1_class),
205
  "type": info["type"],
206
+ "confidence": f"{round(top1_confidence * 100, 2)}%",
207
  "severity": severity,
208
  "treatment": info["treatment"],
209
  "top3": top3
210
+ }
211
+