ajayduraisamy commited on
Commit
8aafabe
·
1 Parent(s): dfd2e3e

Fix hosted model path

Browse files
Files changed (1) hide show
  1. app.py +80 -65
app.py CHANGED
@@ -35,11 +35,12 @@ def health():
35
  @app.route("/model/0", methods=["GET", "POST"])
36
  def model_0():
37
 
38
- # --------------------------------------------------------
39
- # GET: do not load the model
40
- # --------------------------------------------------------
41
 
42
  if request.method == "GET":
 
43
  return jsonify({
44
  "status": "model is running",
45
  "model": "MobileNetV3-Small",
@@ -49,44 +50,39 @@ def model_0():
49
  ]
50
  }), 200
51
 
52
- # --------------------------------------------------------
53
- # Imports
54
- # --------------------------------------------------------
55
 
56
  import cv2
57
  import torch
58
  import torch.nn as nn
59
  import numpy as np
60
  from torchvision import models, transforms
 
61
 
62
- # --------------------------------------------------------
63
- # CONFIG
64
- # --------------------------------------------------------
65
 
66
- MODEL_PATH = hf_hub_download(
67
- repo_id="ajaycodeself/ml_models",
68
- filename="model0.pth",
69
- repo_type="space"
70
- )
71
- SAJAN_THRESHOLD = 0.90
72
 
73
- device = torch.device("cpu")
 
74
 
75
- try:
 
 
76
 
77
- # ----------------------------------------------------
78
- # CHECK MODEL FILE
79
- # ----------------------------------------------------
80
-
81
- if not os.path.exists(MODEL_PATH):
82
- return jsonify({
83
- "status": "error",
84
- "message": "model0.pth not found"
85
- }), 500
86
 
87
- # ----------------------------------------------------
88
- # LOAD MODEL
89
- # ----------------------------------------------------
90
 
91
  checkpoint = torch.load(
92
  MODEL_PATH,
@@ -96,6 +92,10 @@ def model_0():
96
 
97
  classes = checkpoint["classes"]
98
 
 
 
 
 
99
  model = models.mobilenet_v3_small(
100
  weights=None
101
  )
@@ -105,6 +105,10 @@ def model_0():
105
  len(classes)
106
  )
107
 
 
 
 
 
108
  model.load_state_dict(
109
  checkpoint["model_state_dict"]
110
  )
@@ -112,9 +116,9 @@ def model_0():
112
  model.to(device)
113
  model.eval()
114
 
115
- # ----------------------------------------------------
116
  # PREPROCESSING
117
- # ----------------------------------------------------
118
 
119
  transform = transforms.Compose([
120
  transforms.ToPILImage(),
@@ -126,25 +130,30 @@ def model_0():
126
  )
127
  ])
128
 
129
- # ----------------------------------------------------
130
- # FACE DETECTOR
131
- # ----------------------------------------------------
132
 
133
  face_detector = cv2.CascadeClassifier(
134
- cv2.data.haarcascades +
135
- "haarcascade_frontalface_default.xml"
136
  )
137
 
138
- # ----------------------------------------------------
139
- # RECEIVE IMAGE
140
- # ----------------------------------------------------
141
 
142
  if "image" not in request.files:
 
143
  return jsonify({
144
  "status": "error",
145
  "message": "image is required"
146
  }), 400
147
 
 
 
 
 
148
  file = request.files["image"]
149
 
150
  image_bytes = file.read()
@@ -160,14 +169,15 @@ def model_0():
160
  )
161
 
162
  if frame is None:
 
163
  return jsonify({
164
  "status": "error",
165
  "message": "invalid image"
166
  }), 400
167
 
168
- # ----------------------------------------------------
169
  # FACE DETECTION
170
- # ----------------------------------------------------
171
 
172
  gray = cv2.cvtColor(
173
  frame,
@@ -181,11 +191,12 @@ def model_0():
181
  minSize=(50, 50)
182
  )
183
 
184
- # ----------------------------------------------------
185
  # NO FACE = UNKNOWN
186
- # ----------------------------------------------------
187
 
188
  if len(faces) == 0:
 
189
  return jsonify({
190
  "status": "success",
191
  "prediction": "UNKNOWN",
@@ -195,18 +206,18 @@ def model_0():
195
  "bounding_box": None
196
  }), 200
197
 
198
- # ----------------------------------------------------
199
  # LARGEST FACE
200
- # ----------------------------------------------------
201
 
202
  x, y, w, h = max(
203
  faces,
204
  key=lambda face: face[2] * face[3]
205
  )
206
 
207
- # ----------------------------------------------------
208
  # FACE MARGIN
209
- # ----------------------------------------------------
210
 
211
  margin_x = int(w * 0.15)
212
  margin_y = int(h * 0.15)
@@ -231,9 +242,9 @@ def model_0():
231
  y + h + margin_y
232
  )
233
 
234
- # ----------------------------------------------------
235
- # FACE CROP
236
- # ----------------------------------------------------
237
 
238
  face = frame[
239
  y1:y2,
@@ -241,6 +252,7 @@ def model_0():
241
  ]
242
 
243
  if face.size == 0:
 
244
  return jsonify({
245
  "status": "success",
246
  "prediction": "UNKNOWN",
@@ -250,17 +262,17 @@ def model_0():
250
  "bounding_box": None
251
  }), 200
252
 
253
- # ----------------------------------------------------
254
- # PREPROCESS
255
- # ----------------------------------------------------
256
 
257
  tensor = transform(
258
  face
259
  ).unsqueeze(0).to(device)
260
 
261
- # ----------------------------------------------------
262
- # PREDICTION
263
- # ----------------------------------------------------
264
 
265
  with torch.inference_mode():
266
 
@@ -271,21 +283,22 @@ def model_0():
271
  dim=1
272
  )
273
 
274
- # ----------------------------------------------------
275
  # FIND SAJAN CLASS
276
- # ----------------------------------------------------
277
 
278
  sajan_index = None
279
 
280
  for i, class_name in enumerate(classes):
281
 
282
  if class_name.lower() == "sajan":
 
283
  sajan_index = i
284
  break
285
 
286
- # ----------------------------------------------------
287
  # SAJAN CONFIDENCE
288
- # ----------------------------------------------------
289
 
290
  if sajan_index is not None:
291
 
@@ -300,18 +313,21 @@ def model_0():
300
 
301
  sajan_confidence = 0.0
302
 
303
- # ----------------------------------------------------
304
  # FINAL DECISION
305
- # ----------------------------------------------------
306
 
307
  if sajan_confidence >= SAJAN_THRESHOLD:
 
308
  prediction = "Sajan"
 
309
  else:
 
310
  prediction = "UNKNOWN"
311
 
312
- # ----------------------------------------------------
313
  # RESPONSE
314
- # ----------------------------------------------------
315
 
316
  return jsonify({
317
 
@@ -347,7 +363,6 @@ def model_0():
347
  "message": str(e)
348
  }), 500
349
 
350
-
351
  # ============================================================
352
  # START
353
  # ============================================================
 
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",
 
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.90
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",
80
+ repo_type="space"
81
+ )
 
 
 
 
82
 
83
+ # ====================================================
84
+ # LOAD CHECKPOINT
85
+ # ====================================================
86
 
87
  checkpoint = torch.load(
88
  MODEL_PATH,
 
92
 
93
  classes = checkpoint["classes"]
94
 
95
+ # ====================================================
96
+ # CREATE MOBILENETV3-SMALL
97
+ # ====================================================
98
+
99
  model = models.mobilenet_v3_small(
100
  weights=None
101
  )
 
105
  len(classes)
106
  )
107
 
108
+ # ====================================================
109
+ # LOAD TRAINED WEIGHTS
110
+ # ====================================================
111
+
112
  model.load_state_dict(
113
  checkpoint["model_state_dict"]
114
  )
 
116
  model.to(device)
117
  model.eval()
118
 
119
+ # ====================================================
120
  # PREPROCESSING
121
+ # ====================================================
122
 
123
  transform = transforms.Compose([
124
  transforms.ToPILImage(),
 
130
  )
131
  ])
132
 
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"
151
  }), 400
152
 
153
+ # ====================================================
154
+ # READ IMAGE
155
+ # ====================================================
156
+
157
  file = request.files["image"]
158
 
159
  image_bytes = file.read()
 
169
  )
170
 
171
  if frame is None:
172
+
173
  return jsonify({
174
  "status": "error",
175
  "message": "invalid image"
176
  }), 400
177
 
178
+ # ====================================================
179
  # FACE DETECTION
180
+ # ====================================================
181
 
182
  gray = cv2.cvtColor(
183
  frame,
 
191
  minSize=(50, 50)
192
  )
193
 
194
+ # ====================================================
195
  # NO FACE = UNKNOWN
196
+ # ====================================================
197
 
198
  if len(faces) == 0:
199
+
200
  return jsonify({
201
  "status": "success",
202
  "prediction": "UNKNOWN",
 
206
  "bounding_box": None
207
  }), 200
208
 
209
+ # ====================================================
210
  # LARGEST FACE
211
+ # ====================================================
212
 
213
  x, y, w, h = max(
214
  faces,
215
  key=lambda face: face[2] * face[3]
216
  )
217
 
218
+ # ====================================================
219
  # FACE MARGIN
220
+ # ====================================================
221
 
222
  margin_x = int(w * 0.15)
223
  margin_y = int(h * 0.15)
 
242
  y + h + margin_y
243
  )
244
 
245
+ # ====================================================
246
+ # CROP FACE
247
+ # ====================================================
248
 
249
  face = frame[
250
  y1:y2,
 
252
  ]
253
 
254
  if face.size == 0:
255
+
256
  return jsonify({
257
  "status": "success",
258
  "prediction": "UNKNOWN",
 
262
  "bounding_box": None
263
  }), 200
264
 
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
 
 
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
 
 
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
 
 
363
  "message": str(e)
364
  }), 500
365
 
 
366
  # ============================================================
367
  # START
368
  # ============================================================