Muhammad commited on
Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+99
- requirements.txtAdded+6
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import 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)123456flask==3.0.3flask-cors==4.0.1numpy==1.26.4pillow==10.4.0scikit-learn==1.5.1tensorflow==2.16.1app.pyAdded+99
requirements.txtAdded+6