Spaces:
Sleeping

File size: 3,225 Bytes
4c3e1fb
4a530ee
4c3e1fb
4a530ee
4c3e1fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a530ee
4c3e1fb
4a530ee
 
4c3e1fb
edf99f8
4c3e1fb
 
 
 
4a530ee
 
 
 
 
 
 
 
 
 
 
 
 
edf99f8
4c3e1fb
 
 
4a530ee
 
 
 
 
4c3e1fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a530ee
4c3e1fb
 
 
 
 
 
 
 
 
 
 
4a530ee
 
4c3e1fb
4a530ee
 
 
 
edf99f8
4a530ee
 
 
4c3e1fb
 
4a530ee
 
 
4c3e1fb
edf99f8
4a530ee
 
4c3e1fb
 
 
4a530ee
 
 
 
4c3e1fb
edf99f8
4c3e1fb
 
 
 
4a530ee
 
 
62313e9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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)