ajayduraisamy commited on
Commit
efa0fb6
·
1 Parent(s): a86b8d7
Files changed (1) hide show
  1. app.py +99 -143
app.py CHANGED
@@ -1,14 +1,19 @@
1
  import os
2
-
3
  from flask import Flask, jsonify, request
4
  from huggingface_hub import hf_hub_download
5
- app = Flask(__name__)
 
 
 
 
 
 
6
 
 
7
 
8
  # ============================================================
9
  # HOME
10
  # ============================================================
11
-
12
  @app.route("/")
13
  def home():
14
  return jsonify({
@@ -16,31 +21,24 @@ def home():
16
  "message": "Backend is running"
17
  }), 200
18
 
19
-
20
  # ============================================================
21
  # HEALTH
22
  # ============================================================
23
-
24
  @app.route("/health", methods=["GET", "POST"])
25
  def health():
26
  return jsonify({
27
  "status": "healthy"
28
  }), 200
29
 
30
-
31
  # ============================================================
32
  # MODEL 0
33
  # ============================================================
34
-
35
  @app.route("/model/0", methods=["GET", "POST"])
36
  def model_0():
37
-
38
  # ========================================================
39
  # GET REQUEST
40
  # ========================================================
41
-
42
  if request.method == "GET":
43
-
44
  return jsonify({
45
  "status": "model is running",
46
  "model": "MobileNetV3-Small",
@@ -49,31 +47,17 @@ def model_0():
49
  "UNKNOWN"
50
  ]
51
  }), 200
52
-
53
- # ========================================================
54
- # IMPORTS
55
- # ========================================================
56
-
57
- import cv2
58
- import torch
59
- import torch.nn as nn
60
- import numpy as np
61
- from torchvision import models, transforms
62
- from huggingface_hub import hf_hub_download
63
-
64
  try:
65
-
66
  # ====================================================
67
  # CONFIG
68
  # ====================================================
69
-
70
  SAJAN_THRESHOLD = 0.80
71
  device = torch.device("cpu")
 
72
 
73
  # ====================================================
74
  # DOWNLOAD HOSTED MODEL
75
  # ====================================================
76
-
77
  MODEL_PATH = hf_hub_download(
78
  repo_id="ajaycodeself/ml_models",
79
  filename="models/model0.pth",
@@ -83,23 +67,17 @@ def model_0():
83
  # ====================================================
84
  # LOAD CHECKPOINT
85
  # ====================================================
86
-
87
  checkpoint = torch.load(
88
  MODEL_PATH,
89
  map_location=device,
90
  weights_only=False
91
  )
92
-
93
  classes = checkpoint["classes"]
94
 
95
  # ====================================================
96
  # CREATE MOBILENETV3-SMALL
97
  # ====================================================
98
-
99
- model = models.mobilenet_v3_small(
100
- weights=None
101
- )
102
-
103
  model.classifier[3] = nn.Linear(
104
  model.classifier[3].in_features,
105
  len(classes)
@@ -108,18 +86,13 @@ def model_0():
108
  # ====================================================
109
  # LOAD TRAINED WEIGHTS
110
  # ====================================================
111
-
112
- model.load_state_dict(
113
- checkpoint["model_state_dict"]
114
- )
115
-
116
  model.to(device)
117
  model.eval()
118
 
119
  # ====================================================
120
  # PREPROCESSING
121
  # ====================================================
122
-
123
  transform = transforms.Compose([
124
  transforms.ToPILImage(),
125
  transforms.Resize((224, 224)),
@@ -133,18 +106,14 @@ def model_0():
133
  # ====================================================
134
  # HAAR FACE DETECTOR
135
  # ====================================================
136
-
137
  face_detector = cv2.CascadeClassifier(
138
- cv2.data.haarcascades
139
- + "haarcascade_frontalface_default.xml"
140
  )
141
 
142
  # ====================================================
143
  # CHECK IMAGE
144
  # ====================================================
145
-
146
  if "image" not in request.files:
147
-
148
  return jsonify({
149
  "status": "error",
150
  "message": "image is required"
@@ -153,23 +122,12 @@ def model_0():
153
  # ====================================================
154
  # READ IMAGE
155
  # ====================================================
156
-
157
  file = request.files["image"]
158
-
159
  image_bytes = file.read()
160
-
161
- image_array = np.frombuffer(
162
- image_bytes,
163
- dtype=np.uint8
164
- )
165
-
166
- frame = cv2.imdecode(
167
- image_array,
168
- cv2.IMREAD_COLOR
169
- )
170
 
171
  if frame is None:
172
-
173
  return jsonify({
174
  "status": "error",
175
  "message": "invalid image"
@@ -178,12 +136,7 @@ def model_0():
178
  # ====================================================
179
  # FACE DETECTION
180
  # ====================================================
181
-
182
- gray = cv2.cvtColor(
183
- frame,
184
- cv2.COLOR_BGR2GRAY
185
- )
186
-
187
  faces = face_detector.detectMultiScale(
188
  gray,
189
  scaleFactor=1.1,
@@ -194,9 +147,7 @@ def model_0():
194
  # ====================================================
195
  # NO FACE = UNKNOWN
196
  # ====================================================
197
-
198
  if len(faces) == 0:
199
-
200
  return jsonify({
201
  "status": "success",
202
  "prediction": "UNKNOWN",
@@ -209,7 +160,6 @@ def model_0():
209
  # ====================================================
210
  # LARGEST FACE
211
  # ====================================================
212
-
213
  x, y, w, h = max(
214
  faces,
215
  key=lambda face: face[2] * face[3]
@@ -218,41 +168,19 @@ def model_0():
218
  # ====================================================
219
  # FACE MARGIN
220
  # ====================================================
221
-
222
  margin_x = int(w * 0.15)
223
  margin_y = int(h * 0.15)
224
-
225
- x1 = max(
226
- 0,
227
- x - margin_x
228
- )
229
-
230
- y1 = max(
231
- 0,
232
- y - margin_y
233
- )
234
-
235
- x2 = min(
236
- frame.shape[1],
237
- x + w + margin_x
238
- )
239
-
240
- y2 = min(
241
- frame.shape[0],
242
- y + h + margin_y
243
- )
244
 
245
  # ====================================================
246
  # CROP FACE
247
  # ====================================================
248
-
249
- face = frame[
250
- y1:y2,
251
- x1:x2
252
- ]
253
 
254
  if face.size == 0:
255
-
256
  return jsonify({
257
  "status": "success",
258
  "prediction": "UNKNOWN",
@@ -265,117 +193,145 @@ def model_0():
265
  # ====================================================
266
  # PREPROCESS FACE
267
  # ====================================================
268
-
269
- tensor = transform(
270
- face
271
- ).unsqueeze(0).to(device)
272
 
273
  # ====================================================
274
  # MODEL PREDICTION
275
  # ====================================================
276
-
277
  with torch.inference_mode():
278
-
279
  output = model(tensor)
280
-
281
- probabilities = torch.softmax(
282
- output,
283
- dim=1
284
- )
285
 
286
  # ====================================================
287
  # FIND SAJAN CLASS
288
  # ====================================================
289
-
290
  sajan_index = None
291
-
292
  for i, class_name in enumerate(classes):
293
-
294
  if class_name.lower() == "sajan":
295
-
296
  sajan_index = i
297
  break
298
 
299
  # ====================================================
300
  # SAJAN CONFIDENCE
301
  # ====================================================
302
-
303
  if sajan_index is not None:
304
-
305
  sajan_confidence = float(
306
- probabilities[
307
- 0,
308
- sajan_index
309
- ].item()
310
  )
311
-
312
  else:
313
-
314
  sajan_confidence = 0.0
315
 
316
  # ====================================================
317
  # FINAL DECISION
318
  # ====================================================
319
-
320
  if sajan_confidence >= SAJAN_THRESHOLD:
321
-
322
  prediction = "Sajan"
323
-
324
  else:
325
-
326
  prediction = "UNKNOWN"
327
 
328
  # ====================================================
329
- # RESPONSE
330
  # ====================================================
 
 
331
 
332
- return jsonify({
 
 
 
333
 
334
- "status": "success",
 
335
 
336
- "prediction": prediction,
 
 
 
 
 
 
337
 
338
- "confidence": round(
339
- sajan_confidence,
340
- 4
341
- ),
342
-
343
- "confidence_percent": round(
344
- sajan_confidence * 100,
345
- 2
346
- ),
347
 
 
 
 
 
 
 
 
 
348
  "face_detected": True,
349
-
350
  "bounding_box": {
351
  "x": int(x1),
352
  "y": int(y1),
353
  "width": int(x2 - x1),
354
  "height": int(y2 - y1)
355
  }
356
-
357
  }), 200
358
 
359
  except Exception as e:
360
-
361
  return jsonify({
362
  "status": "error",
363
  "message": str(e)
364
  }), 500
365
 
366
  # ============================================================
367
- # START
368
  # ============================================================
 
 
 
369
 
370
- if __name__ == "__main__":
 
 
 
 
 
 
 
371
 
372
- port = int(
373
- os.environ.get(
374
- "PORT",
375
- 7860
376
- )
377
- )
 
 
 
 
 
 
 
 
378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  app.run(
380
  host="0.0.0.0",
381
  port=port,
 
1
  import os
 
2
  from flask import Flask, jsonify, request
3
  from huggingface_hub import hf_hub_download
4
+ import csv
5
+ from datetime import datetime
6
+ import cv2
7
+ import torch
8
+ import torch.nn as nn
9
+ import numpy as np
10
+ from torchvision import models, transforms
11
 
12
+ app = Flask(__name__)
13
 
14
  # ============================================================
15
  # HOME
16
  # ============================================================
 
17
  @app.route("/")
18
  def home():
19
  return jsonify({
 
21
  "message": "Backend is running"
22
  }), 200
23
 
 
24
  # ============================================================
25
  # HEALTH
26
  # ============================================================
 
27
  @app.route("/health", methods=["GET", "POST"])
28
  def health():
29
  return jsonify({
30
  "status": "healthy"
31
  }), 200
32
 
 
33
  # ============================================================
34
  # MODEL 0
35
  # ============================================================
 
36
  @app.route("/model/0", methods=["GET", "POST"])
37
  def model_0():
 
38
  # ========================================================
39
  # GET REQUEST
40
  # ========================================================
 
41
  if request.method == "GET":
 
42
  return jsonify({
43
  "status": "model is running",
44
  "model": "MobileNetV3-Small",
 
47
  "UNKNOWN"
48
  ]
49
  }), 200
 
 
 
 
 
 
 
 
 
 
 
 
50
  try:
 
51
  # ====================================================
52
  # CONFIG
53
  # ====================================================
 
54
  SAJAN_THRESHOLD = 0.80
55
  device = torch.device("cpu")
56
+ CSV_FILE = "predictions.csv"
57
 
58
  # ====================================================
59
  # DOWNLOAD HOSTED MODEL
60
  # ====================================================
 
61
  MODEL_PATH = hf_hub_download(
62
  repo_id="ajaycodeself/ml_models",
63
  filename="models/model0.pth",
 
67
  # ====================================================
68
  # LOAD CHECKPOINT
69
  # ====================================================
 
70
  checkpoint = torch.load(
71
  MODEL_PATH,
72
  map_location=device,
73
  weights_only=False
74
  )
 
75
  classes = checkpoint["classes"]
76
 
77
  # ====================================================
78
  # CREATE MOBILENETV3-SMALL
79
  # ====================================================
80
+ model = models.mobilenet_v3_small(weights=None)
 
 
 
 
81
  model.classifier[3] = nn.Linear(
82
  model.classifier[3].in_features,
83
  len(classes)
 
86
  # ====================================================
87
  # LOAD TRAINED WEIGHTS
88
  # ====================================================
89
+ model.load_state_dict(checkpoint["model_state_dict"])
 
 
 
 
90
  model.to(device)
91
  model.eval()
92
 
93
  # ====================================================
94
  # PREPROCESSING
95
  # ====================================================
 
96
  transform = transforms.Compose([
97
  transforms.ToPILImage(),
98
  transforms.Resize((224, 224)),
 
106
  # ====================================================
107
  # HAAR FACE DETECTOR
108
  # ====================================================
 
109
  face_detector = cv2.CascadeClassifier(
110
+ cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
 
111
  )
112
 
113
  # ====================================================
114
  # CHECK IMAGE
115
  # ====================================================
 
116
  if "image" not in request.files:
 
117
  return jsonify({
118
  "status": "error",
119
  "message": "image is required"
 
122
  # ====================================================
123
  # READ IMAGE
124
  # ====================================================
 
125
  file = request.files["image"]
 
126
  image_bytes = file.read()
127
+ image_array = np.frombuffer(image_bytes, dtype=np.uint8)
128
+ frame = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
 
 
 
 
 
 
 
 
129
 
130
  if frame is None:
 
131
  return jsonify({
132
  "status": "error",
133
  "message": "invalid image"
 
136
  # ====================================================
137
  # FACE DETECTION
138
  # ====================================================
139
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
 
 
 
 
 
140
  faces = face_detector.detectMultiScale(
141
  gray,
142
  scaleFactor=1.1,
 
147
  # ====================================================
148
  # NO FACE = UNKNOWN
149
  # ====================================================
 
150
  if len(faces) == 0:
 
151
  return jsonify({
152
  "status": "success",
153
  "prediction": "UNKNOWN",
 
160
  # ====================================================
161
  # LARGEST FACE
162
  # ====================================================
 
163
  x, y, w, h = max(
164
  faces,
165
  key=lambda face: face[2] * face[3]
 
168
  # ====================================================
169
  # FACE MARGIN
170
  # ====================================================
 
171
  margin_x = int(w * 0.15)
172
  margin_y = int(h * 0.15)
173
+ x1 = max(0, x - margin_x)
174
+ y1 = max(0, y - margin_y)
175
+ x2 = min(frame.shape[1], x + w + margin_x)
176
+ y2 = min(frame.shape[0], y + h + margin_y)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
  # ====================================================
179
  # CROP FACE
180
  # ====================================================
181
+ face = frame[y1:y2, x1:x2]
 
 
 
 
182
 
183
  if face.size == 0:
 
184
  return jsonify({
185
  "status": "success",
186
  "prediction": "UNKNOWN",
 
193
  # ====================================================
194
  # PREPROCESS FACE
195
  # ====================================================
196
+ tensor = transform(face).unsqueeze(0).to(device)
 
 
 
197
 
198
  # ====================================================
199
  # MODEL PREDICTION
200
  # ====================================================
 
201
  with torch.inference_mode():
 
202
  output = model(tensor)
203
+ probabilities = torch.softmax(output, dim=1)
 
 
 
 
204
 
205
  # ====================================================
206
  # FIND SAJAN CLASS
207
  # ====================================================
 
208
  sajan_index = None
 
209
  for i, class_name in enumerate(classes):
 
210
  if class_name.lower() == "sajan":
 
211
  sajan_index = i
212
  break
213
 
214
  # ====================================================
215
  # SAJAN CONFIDENCE
216
  # ====================================================
 
217
  if sajan_index is not None:
 
218
  sajan_confidence = float(
219
+ probabilities[0, sajan_index].item()
 
 
 
220
  )
 
221
  else:
 
222
  sajan_confidence = 0.0
223
 
224
  # ====================================================
225
  # FINAL DECISION
226
  # ====================================================
 
227
  if sajan_confidence >= SAJAN_THRESHOLD:
 
228
  prediction = "Sajan"
 
229
  else:
 
230
  prediction = "UNKNOWN"
231
 
232
  # ====================================================
233
+ # CONFIDENCE
234
  # ====================================================
235
+ confidence = round(sajan_confidence, 4)
236
+ confidence_percent = round(sajan_confidence * 100, 2)
237
 
238
+ # ====================================================
239
+ # SAVE RESULT DIRECTLY INSIDE MODEL ROUTE
240
+ # ====================================================
241
+ file_exists = os.path.exists(CSV_FILE)
242
 
243
+ with open(CSV_FILE, "a", newline="", encoding="utf-8") as f:
244
+ writer = csv.writer(f)
245
 
246
+ if not file_exists:
247
+ writer.writerow([
248
+ "timestamp",
249
+ "prediction",
250
+ "confidence_percent",
251
+ "face_detected"
252
+ ])
253
 
254
+ writer.writerow([
255
+ datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
256
+ prediction,
257
+ confidence_percent,
258
+ True
259
+ ])
 
 
 
260
 
261
+ # ====================================================
262
+ # RESPONSE
263
+ # ====================================================
264
+ return jsonify({
265
+ "status": "success",
266
+ "prediction": prediction,
267
+ "confidence": confidence,
268
+ "confidence_percent": confidence_percent,
269
  "face_detected": True,
 
270
  "bounding_box": {
271
  "x": int(x1),
272
  "y": int(y1),
273
  "width": int(x2 - x1),
274
  "height": int(y2 - y1)
275
  }
 
276
  }), 200
277
 
278
  except Exception as e:
 
279
  return jsonify({
280
  "status": "error",
281
  "message": str(e)
282
  }), 500
283
 
284
  # ============================================================
285
+ # GET LAST STORED MODEL 0 RESULT
286
  # ============================================================
287
+ @app.route("/model/0/get", methods=["GET"])
288
+ def get_model_0_result():
289
+ CSV_FILE = "predictions.csv"
290
 
291
+ if not os.path.exists(CSV_FILE):
292
+ return jsonify({
293
+ "status": "success",
294
+ "prediction": "UNKNOWN",
295
+ "confidence_percent": 0,
296
+ "face_detected": False,
297
+ "source": "no_stored_result"
298
+ }), 200
299
 
300
+ try:
301
+ with open(CSV_FILE, "r", encoding="utf-8") as f:
302
+ rows = list(csv.DictReader(f))
303
+
304
+ if not rows:
305
+ return jsonify({
306
+ "status": "success",
307
+ "prediction": "UNKNOWN",
308
+ "confidence_percent": 0,
309
+ "face_detected": False,
310
+ "source": "empty"
311
+ }), 200
312
+
313
+ last = rows[-1]
314
 
315
+ return jsonify({
316
+ "status": "success",
317
+ "timestamp": last["timestamp"],
318
+ "prediction": last["prediction"],
319
+ "confidence_percent": float(last["confidence_percent"]),
320
+ "face_detected": last["face_detected"].lower() == "true",
321
+ "source": "csv"
322
+ }), 200
323
+
324
+ except Exception as e:
325
+ return jsonify({
326
+ "status": "error",
327
+ "message": str(e)
328
+ }), 500
329
+
330
+ # ============================================================
331
+ # START
332
+ # ============================================================
333
+ if __name__ == "__main__":
334
+ port = int(os.environ.get("PORT", 7860))
335
  app.run(
336
  host="0.0.0.0",
337
  port=port,