File size: 14,449 Bytes
d46e66a
ee590d9
 
d46e66a
379fd8b
efa0fb6
 
 
 
 
 
 
ee590d9
d46e66a
efa0fb6
d46e66a
10aceab
 
 
d46e66a
 
 
 
 
10aceab
 
 
 
 
d46e66a
 
 
10aceab
 
 
 
 
 
f36ab4c
 
8aafabe
 
 
10aceab
 
 
 
 
 
 
 
 
8aafabe
 
 
 
a86b8d7
8aafabe
efa0fb6
f36ab4c
8aafabe
 
 
 
 
 
 
 
f36ab4c
8aafabe
 
 
10aceab
 
 
 
 
 
f36ab4c
8aafabe
 
 
efa0fb6
10aceab
 
 
 
f36ab4c
8aafabe
 
 
efa0fb6
10aceab
 
f36ab4c
8aafabe
10aceab
8aafabe
10aceab
 
 
 
 
 
 
 
 
f36ab4c
8aafabe
 
 
10aceab
efa0fb6
10aceab
f36ab4c
8aafabe
 
 
10aceab
 
 
 
 
f36ab4c
8aafabe
 
 
f36ab4c
 
efa0fb6
 
f36ab4c
 
 
 
 
 
 
8aafabe
f36ab4c
8aafabe
efa0fb6
f36ab4c
 
 
 
 
 
 
8aafabe
f36ab4c
8aafabe
f36ab4c
 
 
 
 
10aceab
f36ab4c
 
 
 
8aafabe
10aceab
8aafabe
f36ab4c
 
 
 
 
8aafabe
f36ab4c
8aafabe
f36ab4c
 
efa0fb6
 
 
 
f36ab4c
8aafabe
 
 
efa0fb6
f36ab4c
 
 
 
 
 
10aceab
f36ab4c
 
 
 
8aafabe
 
 
efa0fb6
f36ab4c
8aafabe
 
 
f36ab4c
 
efa0fb6
f36ab4c
8aafabe
f36ab4c
8aafabe
f36ab4c
 
 
 
 
 
8aafabe
f36ab4c
8aafabe
f36ab4c
 
efa0fb6
f36ab4c
 
 
 
8aafabe
f36ab4c
8aafabe
f36ab4c
 
 
 
 
8aafabe
efa0fb6
8aafabe
efa0fb6
 
f36ab4c
efa0fb6
 
 
 
f36ab4c
efa0fb6
 
f36ab4c
efa0fb6
 
 
 
 
 
 
f36ab4c
efa0fb6
 
 
 
 
 
f36ab4c
efa0fb6
 
 
 
 
 
 
 
f36ab4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10aceab
efa0fb6
10aceab
efa0fb6
 
 
10aceab
efa0fb6
 
 
 
 
 
 
 
10aceab
efa0fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
10aceab
efa0fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee590d9
0d267c5
ee590d9
 
 
 
5e468e2
ee590d9
 
 
0d267c5
5e468e2
0d267c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee590d9
 
 
 
 
 
 
 
 
 
 
 
 
0d267c5
 
 
 
 
 
 
 
 
 
 
 
 
 
ee590d9
 
 
 
0d267c5
 
 
ee590d9
 
 
 
 
0d267c5
ee590d9
0d267c5
 
 
ee590d9
4cf46e5
0d267c5
ee590d9
0d267c5
 
efa0fb6
 
 
 
 
10aceab
 
 
 
 
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import os
from io import BytesIO
from pathlib import Path
from flask import Flask, jsonify, request
from huggingface_hub import hf_hub_download
import csv
from datetime import datetime
import cv2
import torch
import torch.nn as nn
import numpy as np
from torchvision import models, transforms
from PIL import Image, ImageOps

app = Flask(__name__)

# ============================================================
# HOME
# ============================================================
@app.route("/")
def home():
    return jsonify({
        "status": "success",
        "message": "Backend is running"
    }), 200

# ============================================================
# HEALTH
# ============================================================
@app.route("/health", methods=["GET", "POST"])
def health():
    return jsonify({
        "status": "healthy"
    }), 200

# ============================================================
# MODEL 0
# ============================================================
@app.route("/model/0", methods=["GET", "POST"])
def model_0():
    # ========================================================
    # GET REQUEST
    # ========================================================
    if request.method == "GET":
        return jsonify({
            "status": "model is running",
            "model": "MobileNetV3-Small",
            "classes": [
                "Sajan",
                "UNKNOWN"
            ]
        }), 200
    try:
        # ====================================================
        # CONFIG
        # ====================================================
        SAJAN_THRESHOLD = 0.80
        device = torch.device("cpu")
        CSV_FILE = "predictions.csv"

        # ====================================================
        # DOWNLOAD HOSTED MODEL
        # ====================================================
        MODEL_PATH = hf_hub_download(
            repo_id="ajaycodeself/ml_models",
            filename="models/model0.pth",
            repo_type="space"
        )

        # ====================================================
        # LOAD CHECKPOINT
        # ====================================================
        checkpoint = torch.load(
            MODEL_PATH,
            map_location=device,
            weights_only=False
        )
        classes = checkpoint["classes"]

        # ====================================================
        # CREATE MOBILENETV3-SMALL
        # ====================================================
        model = models.mobilenet_v3_small(weights=None)
        model.classifier[3] = nn.Linear(
            model.classifier[3].in_features,
            len(classes)
        )

        # ====================================================
        # LOAD TRAINED WEIGHTS
        # ====================================================
        model.load_state_dict(checkpoint["model_state_dict"])
        model.to(device)
        model.eval()

        # ====================================================
        # PREPROCESSING
        # ====================================================
        transform = transforms.Compose([
            transforms.ToPILImage(),
            transforms.Resize((224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(
                mean=[0.485, 0.456, 0.406],
                std=[0.229, 0.224, 0.225]
            )
        ])

        # ====================================================
        # HAAR FACE DETECTOR
        # ====================================================
        face_detector = cv2.CascadeClassifier(
            cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
        )

        # ====================================================
        # CHECK IMAGE
        # ====================================================
        if "image" not in request.files:
            return jsonify({
                "status": "error",
                "message": "image is required"
            }), 400

        # ====================================================
        # READ IMAGE
        # ====================================================
        file = request.files["image"]
        image_bytes = file.read()
        image_array = np.frombuffer(image_bytes, dtype=np.uint8)
        frame = cv2.imdecode(image_array, cv2.IMREAD_COLOR)

        if frame is None:
            return jsonify({
                "status": "error",
                "message": "invalid image"
            }), 400

        # ====================================================
        # FACE DETECTION
        # ====================================================
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=6,
            minSize=(50, 50)
        )

        # ====================================================
        # NO FACE = UNKNOWN
        # ====================================================
        if len(faces) == 0:
            return jsonify({
                "status": "success",
                "prediction": "UNKNOWN",
                "confidence": 0,
                "confidence_percent": 0,
                "face_detected": False,
                "bounding_box": None
            }), 200

        # ====================================================
        # LARGEST FACE
        # ====================================================
        x, y, w, h = max(
            faces,
            key=lambda face: face[2] * face[3]
        )

        # ====================================================
        # FACE MARGIN
        # ====================================================
        margin_x = int(w * 0.15)
        margin_y = int(h * 0.15)
        x1 = max(0, x - margin_x)
        y1 = max(0, y - margin_y)
        x2 = min(frame.shape[1], x + w + margin_x)
        y2 = min(frame.shape[0], y + h + margin_y)

        # ====================================================
        # CROP FACE
        # ====================================================
        face = frame[y1:y2, x1:x2]

        if face.size == 0:
            return jsonify({
                "status": "success",
                "prediction": "UNKNOWN",
                "confidence": 0,
                "confidence_percent": 0,
                "face_detected": False,
                "bounding_box": None
            }), 200

        # ====================================================
        # PREPROCESS FACE
        # ====================================================
        tensor = transform(face).unsqueeze(0).to(device)

        # ====================================================
        # MODEL PREDICTION
        # ====================================================
        with torch.inference_mode():
            output = model(tensor)
            probabilities = torch.softmax(output, dim=1)

        # ====================================================
        # FIND SAJAN CLASS
        # ====================================================
        sajan_index = None
        for i, class_name in enumerate(classes):
            if class_name.lower() == "sajan":
                sajan_index = i
                break

        # ====================================================
        # SAJAN CONFIDENCE
        # ====================================================
        if sajan_index is not None:
            sajan_confidence = float(
                probabilities[0, sajan_index].item()
            )
        else:
            sajan_confidence = 0.0

        # ====================================================
        # FINAL DECISION
        # ====================================================
        if sajan_confidence >= SAJAN_THRESHOLD:
            prediction = "Sajan"
        else:
            prediction = "UNKNOWN"

        # ====================================================
        # CONFIDENCE
        # ====================================================
        confidence = round(sajan_confidence, 4)
        confidence_percent = round(sajan_confidence * 100, 2)

        # ====================================================
        # SAVE RESULT DIRECTLY INSIDE MODEL ROUTE
        # ====================================================
        file_exists = os.path.exists(CSV_FILE)

        with open(CSV_FILE, "a", newline="", encoding="utf-8") as f:
            writer = csv.writer(f)

            if not file_exists:
                writer.writerow([
                    "timestamp",
                    "prediction",
                    "confidence_percent",
                    "face_detected"
                ])

            writer.writerow([
                datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                prediction,
                confidence_percent,
                True
            ])

        # ====================================================
        # RESPONSE
        # ====================================================
        return jsonify({
            "status": "success",
            "prediction": prediction,
            "confidence": confidence,
            "confidence_percent": confidence_percent,
            "face_detected": True,
            "bounding_box": {
                "x": int(x1),
                "y": int(y1),
                "width": int(x2 - x1),
                "height": int(y2 - y1)
            }
        }), 200

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

# ============================================================
# GET LAST STORED MODEL 0 RESULT
# ============================================================
@app.route("/model/0/get", methods=["GET"])
def get_model_0_result():
    CSV_FILE = "predictions.csv"

    if not os.path.exists(CSV_FILE):
        return jsonify({
            "status": "success",
            "prediction": "UNKNOWN",
            "confidence_percent": 0,
            "face_detected": False,
            "source": "no_stored_result"
        }), 200

    try:
        with open(CSV_FILE, "r", encoding="utf-8") as f:
            rows = list(csv.DictReader(f))

        if not rows:
            return jsonify({
                "status": "success",
                "prediction": "UNKNOWN",
                "confidence_percent": 0,
                "face_detected": False,
                "source": "empty"
            }), 200

        last = rows[-1]

        return jsonify({
            "status": "success",
            "timestamp": last["timestamp"],
            "prediction": last["prediction"],
            "confidence_percent": float(last["confidence_percent"]),
            "face_detected": last["face_detected"].lower() == "true",
            "source": "csv"
        }), 200

    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

@app.route("/model/1", methods=["GET", "POST"])
def model_1():
    if request.method == "GET":
        return jsonify({
            "status": "model is running",
            "model": "Fruit and Vegetable Condition Classifier",
            "classes": ["healthy", "unhealthy"]
        }), 200

    model_path = Path(__file__).parent / "models" / "fruit_veg.pt"
    image_size = (224, 224)
    class_labels = ("healthy", "unhealthy")
    max_image_pixels = 25_000_000
    max_upload_bytes = 10 * 1024 * 1024

    if request.content_length and request.content_length > max_upload_bytes:
        return jsonify({"error": "Image upload exceeds the 10 MB limit."}), 413

    uploaded_image = request.files.get("image")
    if uploaded_image is None or not uploaded_image.filename:
        return jsonify({"error": "Send an image using the multipart field 'image'."}), 400

    try:
        image_data = uploaded_image.stream.read(max_upload_bytes + 1)
        if len(image_data) > max_upload_bytes:
            return jsonify({"error": "Image upload exceeds the 10 MB limit."}), 413

        with Image.open(BytesIO(image_data)) as image:
            image.verify()

        with Image.open(BytesIO(image_data)) as image:
            if image.width * image.height > max_image_pixels:
                return jsonify({"error": "Image dimensions are too large."}), 400

            image = ImageOps.exif_transpose(image).convert("RGB")
            image = image.resize(image_size, Image.Resampling.BILINEAR)

    except (OSError, ValueError) as exc:
        return jsonify({
            "status": "error",
            "message": f"Invalid image: {exc}"
        }), 400

    if not model_path.is_file():
        return jsonify({
            "status": "error",
            "message": f"Model file not found: {model_path.name}"
        }), 503

    try:
        tensor = torch.frombuffer(
            bytearray(image.tobytes()), dtype=torch.uint8
        )
        tensor = tensor.reshape(image_size[1], image_size[0], 3)
        tensor = tensor.permute(2, 0, 1).to(torch.float32).div_(255.0)
        mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
        std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
        tensor = ((tensor - mean) / std).unsqueeze(0)

        model = torch.jit.load(str(model_path), map_location="cpu")
        model.eval()
        with torch.inference_mode():
            logits = model(tensor)
            if logits.shape != (1, len(class_labels)):
                return jsonify({
                    "status": "error",
                    "message": "Model returned an unexpected output."
                }), 500

            probabilities = torch.softmax(logits, dim=1)[0]
            predicted_index = int(probabilities.argmax().item())
    except (OSError, RuntimeError, ValueError) as exc:
        return jsonify({
            "status": "error",
            "message": f"Prediction failed: {exc}"
        }), 500

    prediction = class_labels[predicted_index]

    return jsonify(
        {
            "prediction": prediction,
            "confidence_percent": 100.0
        }
    ), 200

 
# ============================================================
# START
# ============================================================
if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    app.run(
        host="0.0.0.0",
        port=port,
        debug=False
    )