Charuka66 commited on
Commit
7994462
Β·
verified Β·
1 Parent(s): 8385446

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +24 -64
main.py CHANGED
@@ -17,66 +17,23 @@ app.add_middleware(
17
  )
18
 
19
  # ==========================================
20
- # 🧠 LOAD MODELS (Classification Only!)
21
  # ==========================================
22
  print("⏳ Loading Models...")
23
 
24
  try:
25
  # 1. Disease Classification Model (Your ultra-smart 96.8% brain)
26
  disease_model = YOLO('best.pt')
27
- print("βœ… Goyam Disease Classifier loaded!")
28
  except Exception as e:
29
- print(f"❌ Error loading Disease Model: {e}")
30
-
31
- try:
32
- # 2. Plant Gatekeeper (ImageNet 1000-class classifier)
33
- gatekeeper_model = YOLO('yolov8n-cls.pt')
34
- print("βœ… Plant Gatekeeper loaded!")
35
- except Exception as e:
36
- print(f"❌ Error loading Gatekeeper: {e}")
37
 
 
 
38
 
39
  # ==========================================
40
- # πŸ›‘οΈ THE BULLETPROOF GATEKEEPER (Allowlist)
41
  # ==========================================
42
- def is_likely_plant(image_path):
43
- """
44
- STRICT ALLOWLIST LOGIC:
45
- We check the top 5 things the AI thinks it sees.
46
- If NONE of them are related to nature, agriculture, or plants, we reject the photo.
47
- """
48
- try:
49
- results = gatekeeper_model(image_path, verbose=False)
50
-
51
- # Get the top 5 predicted classes
52
- top5_indices = results[0].probs.top5
53
- top5_names = [results[0].names[i].lower() for i in top5_indices]
54
-
55
- print(f"🧐 Gatekeeper sees: {top5_names}")
56
-
57
- # βœ… ALLOW LIST: Botanical, agricultural, and nature terms
58
- allowed_keywords = [
59
- 'plant', 'leaf', 'grass', 'flower', 'tree', 'fern', 'moss', 'weed',
60
- 'crop', 'agriculture', 'field', 'greenhouse', 'pot', 'earth', 'soil',
61
- 'vegetation', 'forest', 'valley', 'daisy', 'corn', 'acorn', 'paddy'
62
- ]
63
-
64
- # Check if ANY of the top 5 predictions contain our allowed keywords
65
- for predicted_item in top5_names:
66
- for good_word in allowed_keywords:
67
- if good_word in predicted_item:
68
- print(f"βœ… Passed: Gatekeeper verified plant matter ('{predicted_item}')")
69
- return True
70
-
71
- # If the loop finishes and didn't find a single nature word, reject it!
72
- print(f"🚫 Blocked: No agricultural or plant features detected.")
73
- return False
74
-
75
- except Exception as e:
76
- print(f"⚠️ Gatekeeper Error: {e}")
77
- return True # Fail-safe: let it pass if the gatekeeper crashes
78
-
79
-
80
  def get_recommendation(disease_name):
81
  recommendations = {
82
  "Leaf Blast": "Use Tricyclazole 75 WP. Avoid applying excess nitrogen fertilizer.",
@@ -90,10 +47,9 @@ def get_recommendation(disease_name):
90
  return value
91
  return "Consult your local agricultural extension officer for treatment."
92
 
93
-
94
  @app.get("/")
95
  def home():
96
- return {"message": "Goyam AI is Running! πŸš€"}
97
 
98
  @app.post("/predict")
99
  async def predict(
@@ -108,18 +64,7 @@ async def predict(
108
  with open(temp_filename, "wb") as buffer:
109
  shutil.copyfileobj(file.file, buffer)
110
 
111
- # πŸ›‘ STEP 1: RUN THE STRICT GATEKEEPER
112
- if not is_likely_plant(temp_filename):
113
- return {
114
- "filename": file.filename,
115
- "disease": "Invalid Image",
116
- "confidence": "0%",
117
- "recommendation": "This image does not appear to be a plant or paddy field. Please upload a clear photo of a rice leaf.",
118
- "latitude": float(latitude) if latitude else None,
119
- "longitude": float(longitude) if longitude else None
120
- }
121
-
122
- # βœ… STEP 2: RUN DISEASE CLASSIFICATION
123
  results = disease_model(temp_filename, verbose=False)
124
 
125
  # Extract the highest probability prediction
@@ -127,6 +72,21 @@ async def predict(
127
  confidence_score = float(results[0].probs.top1conf)
128
  detected_name = results[0].names[top_idx]
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  response_data = {
131
  "filename": file.filename,
132
  "disease": detected_name,
@@ -139,7 +99,7 @@ async def predict(
139
  return response_data
140
 
141
  except Exception as e:
142
- print(f"❌ API Error: {e}")
143
  return {"error": str(e)}
144
 
145
  finally:
 
17
  )
18
 
19
  # ==========================================
20
+ # LOAD MODELS (Classification Only!)
21
  # ==========================================
22
  print("⏳ Loading Models...")
23
 
24
  try:
25
  # 1. Disease Classification Model (Your ultra-smart 96.8% brain)
26
  disease_model = YOLO('best.pt')
27
+ print(" Goyam Disease Classifier loaded!")
28
  except Exception as e:
29
+ print(f" Error loading Disease Model: {e}")
 
 
 
 
 
 
 
30
 
31
+ # Note: The ImageNet Gatekeeper was removed due to macro-photography hallucinations.
32
+ # We now use a Confidence Threshold architecture.
33
 
34
  # ==========================================
35
+ # RECOMMENDATION MAPPING
36
  # ==========================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def get_recommendation(disease_name):
38
  recommendations = {
39
  "Leaf Blast": "Use Tricyclazole 75 WP. Avoid applying excess nitrogen fertilizer.",
 
47
  return value
48
  return "Consult your local agricultural extension officer for treatment."
49
 
 
50
  @app.get("/")
51
  def home():
52
+ return {"message": "Goyam AI is Running! "}
53
 
54
  @app.post("/predict")
55
  async def predict(
 
64
  with open(temp_filename, "wb") as buffer:
65
  shutil.copyfileobj(file.file, buffer)
66
 
67
+ # STEP 1: RUN THE EXPERT DISEASE MODEL
 
 
 
 
 
 
 
 
 
 
 
68
  results = disease_model(temp_filename, verbose=False)
69
 
70
  # Extract the highest probability prediction
 
72
  confidence_score = float(results[0].probs.top1conf)
73
  detected_name = results[0].names[top_idx]
74
 
75
+ # STEP 2: THE CONFIDENCE THRESHOLD GATEKEEPER
76
+ # If your model is less than 50% sure, it's probably looking at a car, a dog, or a random object.
77
+ if confidence_score < 0.50:
78
+ print(f" Blocked: Confidence too low ({confidence_score*100:.1f}%). Likely not a clear paddy leaf.")
79
+ return {
80
+ "filename": file.filename,
81
+ "disease": "Invalid Image",
82
+ "confidence": f"{int(confidence_score * 100)}%",
83
+ "recommendation": "This image does not appear to be a clear photo of a paddy field. Please upload a focused photo of a rice leaf.",
84
+ "latitude": float(latitude) if latitude else None,
85
+ "longitude": float(longitude) if longitude else None
86
+ }
87
+
88
+ # STEP 3: SUCCESSFUL DIAGNOSIS
89
+ print(f" Passed: Diagnosed {detected_name} with {confidence_score*100:.1f}% confidence.")
90
  response_data = {
91
  "filename": file.filename,
92
  "disease": detected_name,
 
99
  return response_data
100
 
101
  except Exception as e:
102
+ print(f" API Error: {e}")
103
  return {"error": str(e)}
104
 
105
  finally: