Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,11 +1,10 @@
|
|
| 1 |
from fastapi import FastAPI, File, UploadFile
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
-
from
|
|
|
|
| 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 |
-
#
|
| 22 |
-
#
|
| 23 |
-
|
|
|
|
| 24 |
try:
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
except Exception as e:
|
| 28 |
print(f"β Error loading model: {e}")
|
| 29 |
|
| 30 |
@app.get("/")
|
| 31 |
def home():
|
| 32 |
-
return {"message": "Goyam AI
|
| 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
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
# 3. Process Results
|
| 48 |
-
|
| 49 |
-
result = results[0]
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 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 |
-
|
| 58 |
-
confidence_score =
|
| 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": "
|
| 79 |
"confidence": "0%",
|
| 80 |
-
"recommendation": "Plant looks healthy
|
| 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
|
| 89 |
if os.path.exists(temp_filename):
|
| 90 |
os.remove(temp_filename)
|
| 91 |
|
| 92 |
-
# Helper function
|
| 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=
|
|
|
|
| 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)
|