Charuka66 commited on
Commit
ccd2742
Β·
verified Β·
1 Parent(s): ee6cdb6

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +38 -30
main.py CHANGED
@@ -1,11 +1,10 @@
1
  from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from ultralytics import YOLO # Import the AI library
 
4
  import uvicorn
5
  import shutil
6
  import os
7
- import cv2
8
- import numpy as np
9
 
10
  app = FastAPI()
11
 
@@ -18,18 +17,25 @@ app.add_middleware(
18
  allow_headers=["*"],
19
  )
20
 
21
- # LOAD THE MODEL ONCE (At startup)
22
- # Make sure 'best.pt' is in the same folder as main.py!
23
- print("⏳ Loading AI Model...")
 
24
  try:
25
- model = YOLO("best.pt")
26
- print("βœ… Model loaded successfully!")
 
 
 
 
 
 
27
  except Exception as e:
28
  print(f"❌ Error loading model: {e}")
29
 
30
  @app.get("/")
31
  def home():
32
- return {"message": "Goyam AI Server is Running! πŸš€"}
33
 
34
  @app.post("/predict")
35
  async def predict(file: UploadFile = File(...)):
@@ -41,29 +47,31 @@ async def predict(file: UploadFile = File(...)):
41
  shutil.copyfileobj(file.file, buffer)
42
 
43
  try:
44
- # 2. RUN REAL AI PREDICTION
45
- results = model(temp_filename)
 
 
 
 
 
 
 
 
46
 
47
  # 3. Process Results
48
- # Get the first result (since we sent one image)
49
- result = results[0]
50
 
51
- # Check if any objects were detected
52
- if len(result.boxes) > 0:
53
- # Find the box with the highest confidence
54
- # box.conf is a list of confidences, we take the max
55
- best_box = max(result.boxes, key=lambda x: x.conf[0])
56
 
57
- class_id = int(best_box.cls[0])
58
- confidence_score = float(best_box.conf[0])
59
-
60
- # Get the name from the model's internal names list
61
- detected_name = result.names[class_id]
62
 
63
  # Format confidence as percentage
64
  confidence_percent = f"{int(confidence_score * 100)}%"
65
 
66
- print(f"βœ… Detected: {detected_name} ({confidence_percent})")
67
 
68
  return {
69
  "filename": file.filename,
@@ -72,12 +80,12 @@ async def predict(file: UploadFile = File(...)):
72
  "recommendation": get_recommendation(detected_name)
73
  }
74
  else:
75
- print("⚠️ No disease detected")
76
  return {
77
  "filename": file.filename,
78
- "disease": "No Disease Detected",
79
  "confidence": "0%",
80
- "recommendation": "Plant looks healthy or unclear. Try closer photo."
81
  }
82
 
83
  except Exception as e:
@@ -85,11 +93,11 @@ async def predict(file: UploadFile = File(...)):
85
  return {"error": str(e)}
86
 
87
  finally:
88
- # Clean up (Delete the temp file) regardless of success/fail
89
  if os.path.exists(temp_filename):
90
  os.remove(temp_filename)
91
 
92
- # Helper function to give advice based on disease
93
  def get_recommendation(disease_name):
94
  recommendations = {
95
  "Blast": "Use Tricyclazole 75 WP. Avoid excess nitrogen.",
@@ -101,4 +109,4 @@ def get_recommendation(disease_name):
101
  return recommendations.get(disease_name, "Consult an agricultural officer.")
102
 
103
  if __name__ == "__main__":
104
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
  from fastapi import FastAPI, File, UploadFile
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from sahi import AutoDetectionModel
4
+ from sahi.predict import get_sliced_prediction
5
  import uvicorn
6
  import shutil
7
  import os
 
 
8
 
9
  app = FastAPI()
10
 
 
17
  allow_headers=["*"],
18
  )
19
 
20
+ # ==========================================
21
+ # 🧠 LOAD SAHI MODEL
22
+ # ==========================================
23
+ print("⏳ Loading SAHI + YOLO Model...")
24
  try:
25
+ # We wrap your YOLO model inside SAHI
26
+ detection_model = AutoDetectionModel.from_pretrained(
27
+ model_type='yolov8',
28
+ model_path='best.pt', # Your trained model
29
+ confidence_threshold=0.25, # Lower threshold because SAHI is more accurate
30
+ device='cpu' # Use 'cpu' for Hugging Face free tier
31
+ )
32
+ print("βœ… SAHI Model loaded successfully!")
33
  except Exception as e:
34
  print(f"❌ Error loading model: {e}")
35
 
36
  @app.get("/")
37
  def home():
38
+ return {"message": "Goyam AI (SAHI Enabled) is Running! πŸš€"}
39
 
40
  @app.post("/predict")
41
  async def predict(file: UploadFile = File(...)):
 
47
  shutil.copyfileobj(file.file, buffer)
48
 
49
  try:
50
+ # 2. RUN SAHI SLICED PREDICTION
51
+ # This cuts the image into 512x512 blocks and checks each one
52
+ result = get_sliced_prediction(
53
+ temp_filename,
54
+ detection_model,
55
+ slice_height=512,
56
+ slice_width=512,
57
+ overlap_height_ratio=0.2,
58
+ overlap_width_ratio=0.2
59
+ )
60
 
61
  # 3. Process Results
62
+ predictions = result.object_prediction_list
 
63
 
64
+ if len(predictions) > 0:
65
+ # Find the prediction with the highest confidence score
66
+ best_pred = max(predictions, key=lambda x: x.score.value)
 
 
67
 
68
+ detected_name = best_pred.category.name
69
+ confidence_score = best_pred.score.value
 
 
 
70
 
71
  # Format confidence as percentage
72
  confidence_percent = f"{int(confidence_score * 100)}%"
73
 
74
+ print(f"βœ… Detected with SAHI: {detected_name} ({confidence_percent})")
75
 
76
  return {
77
  "filename": file.filename,
 
80
  "recommendation": get_recommendation(detected_name)
81
  }
82
  else:
83
+ print("⚠️ No disease detected (SAHI)")
84
  return {
85
  "filename": file.filename,
86
+ "disease": "Healthy / No Detection",
87
  "confidence": "0%",
88
+ "recommendation": "Plant looks healthy. Ensure regular water supply."
89
  }
90
 
91
  except Exception as e:
 
93
  return {"error": str(e)}
94
 
95
  finally:
96
+ # Clean up
97
  if os.path.exists(temp_filename):
98
  os.remove(temp_filename)
99
 
100
+ # Helper function
101
  def get_recommendation(disease_name):
102
  recommendations = {
103
  "Blast": "Use Tricyclazole 75 WP. Avoid excess nitrogen.",
 
109
  return recommendations.get(disease_name, "Consult an agricultural officer.")
110
 
111
  if __name__ == "__main__":
112
+ uvicorn.run(app, host="0.0.0.0", port=7860)