Muhammad commited on
url fix
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import os
import time
from pathlib import Path
from uuid import uuid4
from flask import Flask, jsonify, request
from flask_cors import CORS
from src.config import (
CLASS_MAP_PATH,
FLASK_HOST,
FLASK_PORT,
MAX_CONTENT_LENGTH,
MODEL_PATH,
TOP_K_DEFAULT,
TRAINING_SUMMARY_PATH,
)
from src.predict import load_model_and_classes, predict
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTH
CORS(app)
UPLOAD_DIR = Path(__file__).resolve().parent / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
def _model_ready() -> bool:
return MODEL_PATH.exists() and CLASS_MAP_PATH.exists()
@app.get("/api/health")
def health():
return jsonify(
{
"status": "ok",
"model_ready": _model_ready(),
"timestamp": int(time.time()),
}
)
@app.get("/api/classes")
def classes():
if not CLASS_MAP_PATH.exists():
return jsonify({"total": 0, "classes": []})
import json
with open(CLASS_MAP_PATH, "r", encoding="utf-8") as f:
idx_to_class = json.load(f)
ordered = [idx_to_class[str(i)] for i in range(len(idx_to_class))]
return jsonify({"total": len(ordered), "classes": ordered})
@app.get("/api/stats")
def stats():
if TRAINING_SUMMARY_PATH.exists():
import json
with open(TRAINING_SUMMARY_PATH, "r", encoding="utf-8") as f:
return jsonify(json.load(f))
return jsonify({"status": "ok", "message": "No training summary found yet."})
@app.post("/api/predict")
def predict_endpoint():
if "image" not in request.files:
return jsonify({"error": "No image file provided"}), 400
image = request.files["image"]
if not image or image.filename == "":
return jsonify({"error": "Empty image upload"}), 400
top_k = int(request.form.get("top_k", TOP_K_DEFAULT))
plant_hint = request.form.get("plant_hint")
suffix = Path(image.filename).suffix or ".jpg"
image_id = f"{uuid4().hex}{suffix}"
filepath = UPLOAD_DIR / image_id
image.save(filepath)
try:
result = predict(str(filepath), top_k=top_k, plant_hint=plant_hint)
result["image_id"] = image_id
return jsonify(result)
except Exception as e:
return jsonify({"status": "error", "error": str(e), "message": "Prediction failed"}), 500
finally:
try:
os.remove(filepath)
except OSError:
pass
if __name__ == "__main__":
if _model_ready():
try:
load_model_and_classes()
except Exception:
pass
app.run(host=FLASK_HOST, port=FLASK_PORT, debug=True)import osimport timefrom pathlib import Pathfrom uuid import uuid4
from flask import Flask, jsonify, requestfrom flask_cors import CORS
from src.config import ( CLASS_MAP_PATH, FLASK_HOST, FLASK_PORT, MAX_CONTENT_LENGTH, MODEL_PATH, TOP_K_DEFAULT, TRAINING_SUMMARY_PATH,)from src.predict import load_model_and_classes, predict
app = Flask(__name__)app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTHCORS(app)
UPLOAD_DIR = Path(__file__).resolve().parent / "uploads"UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
def _model_ready() -> bool: return MODEL_PATH.exists() and CLASS_MAP_PATH.exists()
# ✅ FIX: Root route (this removes "Not Found")@app.route("/")def home(): return jsonify({ "message": "Plant Disease Detection API is running", "status": "success", "endpoints": { "health": "/api/health", "classes": "/api/classes", "stats": "/api/stats", "predict": "/api/predict" } })
@app.get("/api/health")def health(): return jsonify( { "status": "ok", "model_ready": _model_ready(), "timestamp": int(time.time()), } )
@app.get("/api/classes")def classes(): if not CLASS_MAP_PATH.exists(): return jsonify({"total": 0, "classes": []})
import json with open(CLASS_MAP_PATH, "r", encoding="utf-8") as f: idx_to_class = json.load(f)
ordered = [idx_to_class[str(i)] for i in range(len(idx_to_class))] return jsonify({"total": len(ordered), "classes": ordered})
@app.get("/api/stats")def stats(): if TRAINING_SUMMARY_PATH.exists(): import json with open(TRAINING_SUMMARY_PATH, "r", encoding="utf-8") as f: return jsonify(json.load(f))
return jsonify({"status": "ok", "message": "No training summary found yet."})
@app.post("/api/predict")def predict_endpoint(): if "image" not in request.files: return jsonify({"error": "No image file provided"}), 400
image = request.files["image"]
if not image or image.filename == "": return jsonify({"error": "Empty image upload"}), 400
top_k = int(request.form.get("top_k", TOP_K_DEFAULT)) plant_hint = request.form.get("plant_hint")
suffix = Path(image.filename).suffix or ".jpg" image_id = f"{uuid4().hex}{suffix}" filepath = UPLOAD_DIR / image_id
image.save(filepath)
try: result = predict(str(filepath), top_k=top_k, plant_hint=plant_hint) result["image_id"] = image_id return jsonify(result)
except Exception as e: return jsonify({ "status": "error", "error": str(e), "message": "Prediction failed" }), 500
finally: try: os.remove(filepath) except OSError: pass
if __name__ == "__main__": # Load model at startup if available if _model_ready(): try: load_model_and_classes() except Exception: pass
# IMPORTANT for Hugging Face Spaces app.run(host=FLASK_HOST, port=FLASK_PORT, debug=False)app.py+128-99