import 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() # Root route — removes the "Not Found" on HF Space UI @app.route("/") def home(): return jsonify({ "message": "GardCom 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: import traceback print(traceback.format_exc()) # shows real error in HF Space logs 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 # Hardcoded for Hugging Face Spaces (port 7860 is required) app.run(host="0.0.0.0", port=7860)