Muhammad commited on
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485861 unmodified line888990919293944 unmodified lines991001011021031041051061071081091101111121131141151161171 unmodified line119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228import loggingimport osimport tempfilefrom pathlib import Pathfrom flask import Flask, jsonify, requestfrom flask_cors import CORSfrom src.config import (CLASS_MAP_PATH,CORS_ORIGINS,FLASK_DEBUG,FLASK_HOST,FLASK_PORT,FLASK_SECRET_KEY,MAX_CONTENT_LENGTH,MODEL_PATH,TOP_K_DEFAULT,TOP_K_MAX,TRAINING_SUMMARY_PATH,)from src.predict import load_model_and_classes, predict# ── Logging ───────────────────────────────────────────────────────────────────logging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s — %(message)s",)logger = logging.getLogger("gardcom.flask")# ── Flask app setup ───────────────────────────────────────────────────────────app = Flask(__name__)app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTH# FIX: Restrict CORS to configured origins instead of wildcard.# In production set the CORS_ORIGINS env var to your domain(s).CORS(app,origins=CORS_ORIGINS,max_age=3600,)# Allowed upload extensions (server-side whitelist)ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}# ── Helpers ───────────────────────────────────────────────────────────────────def _model_ready() -> bool:return MODEL_PATH.exists() and CLASS_MAP_PATH.exists()def _check_api_secret() -> bool:"""Validate the shared secret header when FLASK_SECRET_KEY is configured.Returns True (allow) when:- FLASK_SECRET_KEY is empty string (dev mode — disabled)- The X-API-Secret header matches FLASK_SECRET_KEYReturns False (deny) otherwise."""if not FLASK_SECRET_KEY:return True # Secret check disabled — development onlyprovided = request.headers.get("X-API-Secret", "")return provided == FLASK_SECRET_KEYdef _validate_image_extension(filename: str) -> bool:suffix = Path(filename).suffix.lower()return suffix in ALLOWED_EXTENSIONS# ── Routes ────────────────────────────────────────────────────────────────────@app.get("/api/health")def health():return jsonify({"status": "ok","model_ready": _model_ready(),"cors_origins": CORS_ORIGINS,})@app.get("/api/classes")1 unmodified lineif not CLASS_MAP_PATH.exists():return jsonify({"total": 0, "classes": []})import jsonwith 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))]4 unmodified linesdef stats():if TRAINING_SUMMARY_PATH.exists():import jsonwith open(TRAINING_SUMMARY_PATH, "r", encoding="utf-8") as f:return jsonify(json.load(f))return jsonify({"status": "ok", "message": "No training summary available."})@app.post("/api/predict")def predict_endpoint():# ── Auth check ────────────────────────────────────────────────────────────if not _check_api_secret():return jsonify({"error": "Forbidden"}), 403# ── Input validation ──────────────────────────────────────────────────────if "image" not in request.files:return jsonify({"error": "No image file provided"}), 4001 unmodified lineif not image or image.filename == "":return jsonify({"error": "Empty image upload"}), 400# Extension whitelist — prevents .py, .php, etc. from being savedif not _validate_image_extension(image.filename or ""):return jsonify({"error": f"Unsupported file type. Allowed: {', '.join(ALLOWED_EXTENSIONS)}"}), 415# Clamp top_k to prevent abuse (e.g. top_k=999999)try:top_k = max(1, min(int(request.form.get("top_k", TOP_K_DEFAULT)), TOP_K_MAX))except (ValueError, TypeError):top_k = TOP_K_DEFAULTplant_hint: str | None = request.form.get("plant_hint") or Noneif plant_hint:# Basic sanitization — strip control characters, limit lengthplant_hint = plant_hint.strip()[:100]if not plant_hint:plant_hint = None# ── Save to a true temp file (auto-deleted on close/crash) ────────────────suffix = Path(image.filename or "").suffix.lower() or ".jpg"if suffix not in ALLOWED_EXTENSIONS:suffix = ".jpg"tmp_path: str | None = Nonetry:# FIX: Use NamedTemporaryFile instead of a persistent uploads/ dir.# delete=False lets us pass the path to predict(); we clean up in finally.with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:tmp_path = tmp.nameimage.save(tmp)# Quick sanity check — can PIL actually open this?# Catches truncated / non-image files before predict() sees them.try:from PIL import Image as PILImagewith PILImage.open(tmp_path) as img:img.verify() # verify() must be called before load()except Exception:return jsonify({"error": "File does not appear to be a valid image."}), 415result = predict(tmp_path, top_k=top_k, plant_hint=plant_hint)return jsonify(result)except MemoryError:logger.error("Out of memory during prediction")return jsonify({"status": "error","message": "Server ran out of memory. Try a smaller image.","error": "MemoryError",}), 503except Exception as exc:logger.exception("Prediction failed: %s", exc)# Do NOT leak internal paths or stack traces to the clientreturn jsonify({"status": "error","message": "Prediction failed due to an internal error. Please try again.","error": type(exc).__name__,}), 500finally:# Always clean up the temp fileif tmp_path:try:os.remove(tmp_path)except OSError:pass# ── Startup ───────────────────────────────────────────────────────────────────if __name__ == "__main__":# Eagerly load the model so the first real request isn't slow.# If the model file doesn't exist yet we skip silently (dev mode).if _model_ready():logger.info("Pre-loading model on startup …")try:load_model_and_classes()logger.info("Model loaded successfully.")except Exception as exc:logger.warning("Model pre-load failed: %s", exc)else:logger.warning("Model file not found at %s — /api/predict will fail until ""the model is present.",MODEL_PATH,)logger.info("Starting GardCom Flask service on %s:%s debug=%s",FLASK_HOST,FLASK_PORT,FLASK_DEBUG,)logger.info("CORS origins: %s", CORS_ORIGINS)if not FLASK_SECRET_KEY:logger.warning("FLASK_SECRET_KEY is not set — API secret check is DISABLED. ""Set this env var in production.")# IMPORTANT for Hugging Face Spaces# app.run(host=FLASK_HOST, port=FLASK_PORT, debug=False)app.run(host="0.0.0.0", port=7860)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455561 unmodified line5859606162634 unmodified lines686970717273747576777879801 unmodified line828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import osimport timefrom pathlib import Pathfrom uuid import uuid4from flask import Flask, jsonify, requestfrom flask_cors import CORSfrom 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, predictapp = 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()# 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")1 unmodified lineif not CLASS_MAP_PATH.exists():return jsonify({"total": 0, "classes": []})import jsonwith 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))]4 unmodified linesdef stats():if TRAINING_SUMMARY_PATH.exists():import jsonwith 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"}), 4001 unmodified lineif not image or image.filename == "":return jsonify({"error": "Empty image upload"}), 400top_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_idimage.save(filepath)try:result = predict(str(filepath), top_k=top_k, plant_hint=plant_hint)result["image_id"] = image_idreturn jsonify(result)except Exception as e:import tracebackprint(traceback.format_exc()) # shows real error in HF Space logsreturn jsonify({"status": "error","error": str(e),"message": "Prediction failed",}), 500finally:try:os.remove(filepath)except OSError:passif __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)
app.py+45-152