Creator-090 commited on
Commit
de9af52
·
2 Parent(s): 053568ed91411e

feat: add /predict_frames endpoint and frame-based preprocessing to FastAPI service

Browse files
Files changed (2) hide show
  1. app.py +43 -0
  2. model.py +73 -0
app.py CHANGED
@@ -3,10 +3,14 @@ from fastapi import FastAPI, File, UploadFile, HTTPException
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import uvicorn
5
  from model import load_model, predict, predict_from_frames
 
6
  import time
7
  from pydantic import BaseModel
8
  from typing import List
9
  import base64
 
 
 
10
 
11
  app = FastAPI(
12
  title="ISL Recognition API",
@@ -14,20 +18,28 @@ app = FastAPI(
14
  version="1.0.0"
15
  )
16
 
 
17
  # Allow all origins (for Flutter / frontend apps)
18
  app.add_middleware(
 
 
19
  CORSMiddleware,
20
  allow_origins=["*"],
21
  allow_methods=["*"],
22
  allow_headers=["*"],
23
  )
24
 
 
25
  # Global state
26
  model = None
27
  model_loaded = False
28
  model_error = None
29
 
 
 
 
30
 
 
31
  # STARTUP
32
  @app.on_event("startup")
33
  async def startup_event():
@@ -42,7 +54,19 @@ async def startup_event():
42
  model_error = str(e)
43
  print("Model failed to load:", e)
44
 
 
 
 
 
 
 
 
 
 
 
 
45
 
 
46
  # ROOT
47
  @app.get("/")
48
  def root():
@@ -131,6 +155,7 @@ async def predict_frames_api(payload: FramesPayload):
131
  # PREDICT
132
  @app.post("/predict")
133
  async def predict_sign(file: UploadFile = File(...), top_k: int = 5):
 
134
  # Validate file type
135
  if not file.filename.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):
136
  raise HTTPException(
@@ -139,6 +164,12 @@ async def predict_sign(file: UploadFile = File(...), top_k: int = 5):
139
  )
140
 
141
  # Ensure model is ready
 
 
 
 
 
 
142
  if not model_loaded or model is None:
143
  raise HTTPException(
144
  status_code=503,
@@ -148,6 +179,15 @@ async def predict_sign(file: UploadFile = File(...), top_k: int = 5):
148
  start_time = time.time()
149
  video_bytes = await file.read()
150
 
 
 
 
 
 
 
 
 
 
151
  try:
152
  result = predict(model, video_bytes, top_k=top_k)
153
  except Exception as e:
@@ -159,8 +199,11 @@ async def predict_sign(file: UploadFile = File(...), top_k: int = 5):
159
  result["inference_time_ms"] = round((time.time() - start_time) * 1000, 2)
160
  result["filename"] = file.filename
161
 
 
162
  return result
163
 
164
 
 
165
  if __name__ == "__main__":
 
166
  uvicorn.run("app:app", host="0.0.0.0", port=7860)
 
3
  from fastapi.middleware.cors import CORSMiddleware
4
  import uvicorn
5
  from model import load_model, predict, predict_from_frames
6
+ from model import load_model, predict, predict_from_frames
7
  import time
8
  from pydantic import BaseModel
9
  from typing import List
10
  import base64
11
+ from pydantic import BaseModel
12
+ from typing import List
13
+ import base64
14
 
15
  app = FastAPI(
16
  title="ISL Recognition API",
 
18
  version="1.0.0"
19
  )
20
 
21
+ # Allow all origins (for Flutter / frontend apps)
22
  # Allow all origins (for Flutter / frontend apps)
23
  app.add_middleware(
24
+ CORSMiddleware,
25
+ allow_origins=["*"],
26
  CORSMiddleware,
27
  allow_origins=["*"],
28
  allow_methods=["*"],
29
  allow_headers=["*"],
30
  )
31
 
32
+ # Global state
33
  # Global state
34
  model = None
35
  model_loaded = False
36
  model_error = None
37
 
38
+ model_loaded = False
39
+ model_error = None
40
+
41
 
42
+ # STARTUP
43
  # STARTUP
44
  @app.on_event("startup")
45
  async def startup_event():
 
54
  model_error = str(e)
55
  print("Model failed to load:", e)
56
 
57
+ global model, model_loaded, model_error
58
+ try:
59
+ model = load_model()
60
+ model_loaded = True
61
+ model_error = None
62
+ print("Model loaded and API is ready!")
63
+ except Exception as e:
64
+ model_loaded = False
65
+ model_error = str(e)
66
+ print("Model failed to load:", e)
67
+
68
 
69
+ # ROOT
70
  # ROOT
71
  @app.get("/")
72
  def root():
 
155
  # PREDICT
156
  @app.post("/predict")
157
  async def predict_sign(file: UploadFile = File(...), top_k: int = 5):
158
+ # Validate file type
159
  # Validate file type
160
  if not file.filename.lower().endswith(('.mp4', '.mov', '.avi', '.mkv')):
161
  raise HTTPException(
 
164
  )
165
 
166
  # Ensure model is ready
167
+ if not model_loaded or model is None:
168
+ raise HTTPException(
169
+ status_code=503,
170
+ detail="Model is not ready"
171
+ )
172
+ # Ensure model is ready
173
  if not model_loaded or model is None:
174
  raise HTTPException(
175
  status_code=503,
 
179
  start_time = time.time()
180
  video_bytes = await file.read()
181
 
182
+ try:
183
+ result = predict(model, video_bytes, top_k=top_k)
184
+ except Exception as e:
185
+ raise HTTPException(
186
+ status_code=500,
187
+ detail=f"Inference error: {str(e)}"
188
+ )
189
+
190
+
191
  try:
192
  result = predict(model, video_bytes, top_k=top_k)
193
  except Exception as e:
 
199
  result["inference_time_ms"] = round((time.time() - start_time) * 1000, 2)
200
  result["filename"] = file.filename
201
 
202
+
203
  return result
204
 
205
 
206
+
207
  if __name__ == "__main__":
208
+ uvicorn.run("app:app", host="0.0.0.0", port=7860)
209
  uvicorn.run("app:app", host="0.0.0.0", port=7860)
model.py CHANGED
@@ -10,6 +10,8 @@ import tempfile
10
  import os
11
  import cv2
12
  import numpy as np
 
 
13
 
14
  # Exactly 76 classes from your notebook metadata
15
  CLASSES = [
@@ -181,6 +183,77 @@ def predict_from_frames(model, frames_list_bytes: list[bytes], top_k: int = 5):
181
  "top_k": results
182
  }
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  def predict(model, video_bytes: bytes, top_k: int = 5):
185
  """Runs inference and returns the top results"""
186
  pixel_values = preprocess_video(video_bytes).to(DEVICE)
 
10
  import os
11
  import cv2
12
  import numpy as np
13
+ import cv2
14
+ import numpy as np
15
 
16
  # Exactly 76 classes from your notebook metadata
17
  CLASSES = [
 
183
  "top_k": results
184
  }
185
 
186
+ def preprocess_frames(frames_list_bytes: list[bytes], clip_length: int = 16):
187
+ """
188
+ Processes a list of raw frame bytes (JPEG/PNG encoded) into the Swin3D model input format.
189
+ Eliminates video encoding/decoding and disk I/O.
190
+ """
191
+ image_processor = VivitImageProcessor(
192
+ do_resize=True,
193
+ size={"shortest_edge": 224},
194
+ do_center_crop=True,
195
+ crop_size={"height": 224, "width": 224},
196
+ do_rescale=True,
197
+ rescale_factor=1/255,
198
+ do_normalize=True,
199
+ image_mean=[0.5, 0.5, 0.5],
200
+ image_std=[0.5, 0.5, 0.5],
201
+ )
202
+
203
+ frames = []
204
+ for frame_bytes in frames_list_bytes:
205
+ # Decode image from bytes
206
+ nparr = np.frombuffer(frame_bytes, np.uint8)
207
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
208
+ if img is not None:
209
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
210
+ frames.append(img)
211
+
212
+ if not frames:
213
+ raise ValueError("No valid frames decoded")
214
+
215
+ # Temporal sampling/padding
216
+ if len(frames) < clip_length:
217
+ frames += [frames[-1]] * (clip_length - len(frames))
218
+ elif len(frames) > clip_length:
219
+ frames = frames[:clip_length]
220
+
221
+ # Processor expects list of numpy arrays (H, W, C)
222
+ processed = image_processor(
223
+ frames,
224
+ return_tensors='pt',
225
+ # image_processor handles (T, C, H, W) return with return_tensors='pt'
226
+ # but we need to check internal dimension order
227
+ )
228
+
229
+ pixel_values = processed['pixel_values'].squeeze(0) # (T, C, H, W)
230
+ pixel_values = pixel_values.permute(1, 0, 2, 3) # (C, T, H, W) for Swin3D
231
+
232
+ return pixel_values.unsqueeze(0)
233
+
234
+ def predict_from_frames(model, frames_list_bytes: list[bytes], top_k: int = 5):
235
+ """Runs inference from raw frame bytes"""
236
+ pixel_values = preprocess_frames(frames_list_bytes).to(DEVICE)
237
+
238
+ with torch.no_grad():
239
+ outputs = model(pixel_values)
240
+ probabilities = torch.nn.functional.softmax(outputs, dim=-1)[0]
241
+
242
+ top_probs, top_indices = torch.topk(probabilities, k=top_k)
243
+
244
+ results = []
245
+ for i in range(top_k):
246
+ results.append({
247
+ "class": CLASSES[top_indices[i].item()],
248
+ "confidence": float(top_probs[i].item())
249
+ })
250
+
251
+ return {
252
+ "prediction": results[0]["class"],
253
+ "confidence": results[0]["confidence"],
254
+ "top_k": results
255
+ }
256
+
257
  def predict(model, video_bytes: bytes, top_k: int = 5):
258
  """Runs inference and returns the top results"""
259
  pixel_values = preprocess_video(video_bytes).to(DEVICE)