ajayduraisamy commited on
Commit
10aceab
·
1 Parent(s): 80f5d4f

Update model API deployment

Browse files
Files changed (2) hide show
  1. Dockerfile +5 -11
  2. app.py +136 -108
Dockerfile CHANGED
@@ -3,9 +3,6 @@ FROM python:3.10-slim
3
  WORKDIR /app
4
 
5
  RUN apt-get update && apt-get install -y \
6
- git \
7
- git-lfs \
8
- curl \
9
  ffmpeg \
10
  libsm6 \
11
  libxext6 \
@@ -17,16 +14,13 @@ COPY requirements.txt .
17
  RUN pip install --upgrade pip
18
  RUN pip install --no-cache-dir -r requirements.txt
19
 
20
- COPY . .
21
 
22
- # Download the REAL model file from Hugging Face
23
- RUN mkdir -p /app/models && \
24
- curl -L \
25
- "https://huggingface.co/spaces/ajaycodeself/vastu-ai/resolve/main/models/model0.pth?download=true" \
26
- -o /app/models/model0.pth
27
 
28
- # Verify model size during Docker build
29
- RUN ls -lh /app/models/model0.pth
30
 
31
  EXPOSE 7860
32
 
 
3
  WORKDIR /app
4
 
5
  RUN apt-get update && apt-get install -y \
 
 
 
6
  ffmpeg \
7
  libsm6 \
8
  libxext6 \
 
14
  RUN pip install --upgrade pip
15
  RUN pip install --no-cache-dir -r requirements.txt
16
 
17
+ COPY app.py .
18
 
19
+ # Download the hosted PyTorch model
20
+ RUN python -c "from huggingface_hub import hf_hub_download; import shutil; import os; p=hf_hub_download(repo_id='ajaycodeself/ml_models', filename='model0.pth', repo_type='space', force_download=True); shutil.copyfile(p, '/app/model0.pth'); print('MODEL SIZE:', os.path.getsize('/app/model0.pth'))"
 
 
 
21
 
22
+ # Validate the checkpoint during image build
23
+ RUN python -c "import torch; x=torch.load('/app/model0.pth', map_location='cpu', weights_only=False); print('MODEL OK:', x['classes'])"
24
 
25
  EXPOSE 7860
26
 
app.py CHANGED
@@ -1,127 +1,145 @@
1
  import os
2
 
3
  from flask import Flask, jsonify, request
4
- import cv2
5
- import torch
6
- import torch.nn as nn
7
- from torchvision import models, transforms
8
-
9
 
10
  app = Flask(__name__)
11
 
12
 
13
- # Home route
 
 
 
14
  @app.route("/")
15
  def home():
16
  return jsonify({
17
  "status": "success",
18
  "message": "Backend is running"
19
- })
 
 
 
 
 
20
 
21
- # Health check route
22
  @app.route("/health", methods=["GET", "POST"])
23
  def health():
24
- return jsonify({ "status": "healthy", }), 200
25
-
26
  return jsonify({
27
- "status": "unhealthy",
28
- "database": "disconnected",
29
- "method": request.method
30
- }), 503
31
 
 
 
 
32
 
33
  @app.route("/model/0", methods=["GET", "POST"])
34
  def model_0():
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  import cv2
37
  import torch
38
  import torch.nn as nn
39
  import numpy as np
40
  from torchvision import models, transforms
41
 
42
- # ========================================================
43
  # CONFIG
44
- # ========================================================
45
 
46
- MODEL_PATH = "models/model0.pth"
47
  SAJAN_THRESHOLD = 0.90
48
 
49
  device = torch.device("cpu")
50
 
51
- # LOAD MODEL
52
- # ========================================================
53
-
54
- checkpoint = torch.load(
55
- MODEL_PATH,
56
- map_location=device,
57
- weights_only=False
58
- )
59
-
60
- classes = checkpoint["classes"]
61
 
62
- model = models.mobilenet_v3_small(
63
- weights=None
64
- )
65
 
66
- model.classifier[3] = nn.Linear(
67
- model.classifier[3].in_features,
68
- len(classes)
69
- )
 
70
 
71
- model.load_state_dict(
72
- checkpoint["model_state_dict"]
73
- )
74
 
75
- model.to(device)
76
- model.eval()
 
 
 
77
 
78
- # ========================================================
79
- # PREPROCESSING
80
- # ========================================================
81
 
82
- transform = transforms.Compose([
83
- transforms.ToPILImage(),
84
- transforms.Resize((224, 224)),
85
- transforms.ToTensor(),
86
- transforms.Normalize(
87
- mean=[0.485, 0.456, 0.406],
88
- std=[0.229, 0.224, 0.225]
89
  )
90
- ])
91
 
92
- # ========================================================
93
- # FACE DETECTOR
94
- # ========================================================
 
95
 
96
- face_detector = cv2.CascadeClassifier(
97
- cv2.data.haarcascades +
98
- "haarcascade_frontalface_default.xml"
99
- )
100
 
101
- # ========================================================
102
- # GET REQUEST
103
- # ========================================================
104
 
105
- if request.method == "GET":
 
 
106
 
107
- return jsonify({
108
- "status": "model is running",
109
- "model": "MobileNetV3-Small",
110
- "classes": classes
111
- }), 200
 
 
 
 
112
 
113
- # ========================================================
114
- # RECEIVE IMAGE
115
- # ========================================================
116
 
117
- if "image" not in request.files:
 
 
 
118
 
119
- return jsonify({
120
- "status": "error",
121
- "message": "image is required"
122
- }), 400
123
 
124
- try:
 
 
 
 
125
 
126
  file = request.files["image"]
127
 
@@ -138,15 +156,14 @@ def model_0():
138
  )
139
 
140
  if frame is None:
141
-
142
  return jsonify({
143
  "status": "error",
144
  "message": "invalid image"
145
  }), 400
146
 
147
- # ====================================================
148
  # FACE DETECTION
149
- # ====================================================
150
 
151
  gray = cv2.cvtColor(
152
  frame,
@@ -160,32 +177,32 @@ def model_0():
160
  minSize=(50, 50)
161
  )
162
 
163
- # ====================================================
164
  # NO FACE = UNKNOWN
165
- # ====================================================
166
 
167
  if len(faces) == 0:
168
-
169
  return jsonify({
170
  "status": "success",
171
  "prediction": "UNKNOWN",
172
  "confidence": 0,
 
173
  "face_detected": False,
174
  "bounding_box": None
175
  }), 200
176
 
177
- # ====================================================
178
- # TAKE LARGEST FACE
179
- # ====================================================
180
 
181
  x, y, w, h = max(
182
  faces,
183
  key=lambda face: face[2] * face[3]
184
  )
185
 
186
- # ====================================================
187
  # FACE MARGIN
188
- # ====================================================
189
 
190
  margin_x = int(w * 0.15)
191
  margin_y = int(h * 0.15)
@@ -210,9 +227,9 @@ def model_0():
210
  y + h + margin_y
211
  )
212
 
213
- # ====================================================
214
- # CROP FACE
215
- # ====================================================
216
 
217
  face = frame[
218
  y1:y2,
@@ -220,26 +237,26 @@ def model_0():
220
  ]
221
 
222
  if face.size == 0:
223
-
224
  return jsonify({
225
  "status": "success",
226
  "prediction": "UNKNOWN",
227
  "confidence": 0,
 
228
  "face_detected": False,
229
  "bounding_box": None
230
  }), 200
231
 
232
- # ====================================================
233
  # PREPROCESS
234
- # ====================================================
235
 
236
  tensor = transform(
237
  face
238
  ).unsqueeze(0).to(device)
239
 
240
- # ====================================================
241
  # PREDICTION
242
- # ====================================================
243
 
244
  with torch.inference_mode():
245
 
@@ -250,22 +267,21 @@ def model_0():
250
  dim=1
251
  )
252
 
253
- # ====================================================
254
  # FIND SAJAN CLASS
255
- # ====================================================
256
 
257
  sajan_index = None
258
 
259
  for i, class_name in enumerate(classes):
260
 
261
  if class_name.lower() == "sajan":
262
-
263
  sajan_index = i
264
  break
265
 
266
- # ====================================================
267
  # SAJAN CONFIDENCE
268
- # ====================================================
269
 
270
  if sajan_index is not None:
271
 
@@ -280,21 +296,18 @@ def model_0():
280
 
281
  sajan_confidence = 0.0
282
 
283
- # ====================================================
284
  # FINAL DECISION
285
- # ====================================================
286
 
287
  if sajan_confidence >= SAJAN_THRESHOLD:
288
-
289
  prediction = "Sajan"
290
-
291
  else:
292
-
293
  prediction = "UNKNOWN"
294
 
295
- # ====================================================
296
  # RESPONSE
297
- # ====================================================
298
 
299
  return jsonify({
300
 
@@ -331,6 +344,21 @@ def model_0():
331
  }), 500
332
 
333
 
 
 
 
 
334
  if __name__ == "__main__":
335
- port = int(os.environ.get("PORT", 7860))
336
- app.run(host="0.0.0.0", port=port, debug=False)
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
 
3
  from flask import Flask, jsonify, request
 
 
 
 
 
4
 
5
  app = Flask(__name__)
6
 
7
 
8
+ # ============================================================
9
+ # HOME
10
+ # ============================================================
11
+
12
  @app.route("/")
13
  def home():
14
  return jsonify({
15
  "status": "success",
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: do not load the model
40
+ # --------------------------------------------------------
41
+
42
+ if request.method == "GET":
43
+ return jsonify({
44
+ "status": "model is running",
45
+ "model": "MobileNetV3-Small",
46
+ "classes": [
47
+ "Sajan",
48
+ "UNKNOWN"
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 = "model0.pth"
67
  SAJAN_THRESHOLD = 0.90
68
 
69
  device = torch.device("cpu")
70
 
71
+ try:
 
 
 
 
 
 
 
 
 
72
 
73
+ # ----------------------------------------------------
74
+ # CHECK MODEL FILE
75
+ # ----------------------------------------------------
76
 
77
+ if not os.path.exists(MODEL_PATH):
78
+ return jsonify({
79
+ "status": "error",
80
+ "message": "model0.pth not found"
81
+ }), 500
82
 
83
+ # ----------------------------------------------------
84
+ # LOAD MODEL
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
+ model = models.mobilenet_v3_small(
96
+ weights=None
 
 
 
 
 
97
  )
 
98
 
99
+ model.classifier[3] = nn.Linear(
100
+ model.classifier[3].in_features,
101
+ len(classes)
102
+ )
103
 
104
+ model.load_state_dict(
105
+ checkpoint["model_state_dict"]
106
+ )
 
107
 
108
+ model.to(device)
109
+ model.eval()
 
110
 
111
+ # ----------------------------------------------------
112
+ # PREPROCESSING
113
+ # ----------------------------------------------------
114
 
115
+ transform = transforms.Compose([
116
+ transforms.ToPILImage(),
117
+ transforms.Resize((224, 224)),
118
+ transforms.ToTensor(),
119
+ transforms.Normalize(
120
+ mean=[0.485, 0.456, 0.406],
121
+ std=[0.229, 0.224, 0.225]
122
+ )
123
+ ])
124
 
125
+ # ----------------------------------------------------
126
+ # FACE DETECTOR
127
+ # ----------------------------------------------------
128
 
129
+ face_detector = cv2.CascadeClassifier(
130
+ cv2.data.haarcascades +
131
+ "haarcascade_frontalface_default.xml"
132
+ )
133
 
134
+ # ----------------------------------------------------
135
+ # RECEIVE IMAGE
136
+ # ----------------------------------------------------
 
137
 
138
+ if "image" not in request.files:
139
+ return jsonify({
140
+ "status": "error",
141
+ "message": "image is required"
142
+ }), 400
143
 
144
  file = request.files["image"]
145
 
 
156
  )
157
 
158
  if frame is None:
 
159
  return jsonify({
160
  "status": "error",
161
  "message": "invalid image"
162
  }), 400
163
 
164
+ # ----------------------------------------------------
165
  # FACE DETECTION
166
+ # ----------------------------------------------------
167
 
168
  gray = cv2.cvtColor(
169
  frame,
 
177
  minSize=(50, 50)
178
  )
179
 
180
+ # ----------------------------------------------------
181
  # NO FACE = UNKNOWN
182
+ # ----------------------------------------------------
183
 
184
  if len(faces) == 0:
 
185
  return jsonify({
186
  "status": "success",
187
  "prediction": "UNKNOWN",
188
  "confidence": 0,
189
+ "confidence_percent": 0,
190
  "face_detected": False,
191
  "bounding_box": None
192
  }), 200
193
 
194
+ # ----------------------------------------------------
195
+ # LARGEST FACE
196
+ # ----------------------------------------------------
197
 
198
  x, y, w, h = max(
199
  faces,
200
  key=lambda face: face[2] * face[3]
201
  )
202
 
203
+ # ----------------------------------------------------
204
  # FACE MARGIN
205
+ # ----------------------------------------------------
206
 
207
  margin_x = int(w * 0.15)
208
  margin_y = int(h * 0.15)
 
227
  y + h + margin_y
228
  )
229
 
230
+ # ----------------------------------------------------
231
+ # FACE CROP
232
+ # ----------------------------------------------------
233
 
234
  face = frame[
235
  y1:y2,
 
237
  ]
238
 
239
  if face.size == 0:
 
240
  return jsonify({
241
  "status": "success",
242
  "prediction": "UNKNOWN",
243
  "confidence": 0,
244
+ "confidence_percent": 0,
245
  "face_detected": False,
246
  "bounding_box": None
247
  }), 200
248
 
249
+ # ----------------------------------------------------
250
  # PREPROCESS
251
+ # ----------------------------------------------------
252
 
253
  tensor = transform(
254
  face
255
  ).unsqueeze(0).to(device)
256
 
257
+ # ----------------------------------------------------
258
  # PREDICTION
259
+ # ----------------------------------------------------
260
 
261
  with torch.inference_mode():
262
 
 
267
  dim=1
268
  )
269
 
270
+ # ----------------------------------------------------
271
  # FIND SAJAN CLASS
272
+ # ----------------------------------------------------
273
 
274
  sajan_index = None
275
 
276
  for i, class_name in enumerate(classes):
277
 
278
  if class_name.lower() == "sajan":
 
279
  sajan_index = i
280
  break
281
 
282
+ # ----------------------------------------------------
283
  # SAJAN CONFIDENCE
284
+ # ----------------------------------------------------
285
 
286
  if sajan_index is not None:
287
 
 
296
 
297
  sajan_confidence = 0.0
298
 
299
+ # ----------------------------------------------------
300
  # FINAL DECISION
301
+ # ----------------------------------------------------
302
 
303
  if sajan_confidence >= SAJAN_THRESHOLD:
 
304
  prediction = "Sajan"
 
305
  else:
 
306
  prediction = "UNKNOWN"
307
 
308
+ # ----------------------------------------------------
309
  # RESPONSE
310
+ # ----------------------------------------------------
311
 
312
  return jsonify({
313
 
 
344
  }), 500
345
 
346
 
347
+ # ============================================================
348
+ # START
349
+ # ============================================================
350
+
351
  if __name__ == "__main__":
352
+
353
+ port = int(
354
+ os.environ.get(
355
+ "PORT",
356
+ 7860
357
+ )
358
+ )
359
+
360
+ app.run(
361
+ host="0.0.0.0",
362
+ port=port,
363
+ debug=False
364
+ )