SaniaE commited on
Commit
85cd7a9
·
verified ·
1 Parent(s): 55df2c0

added timing checks

Browse files
Files changed (1) hide show
  1. app.py +92 -100
app.py CHANGED
@@ -1,21 +1,40 @@
1
  import os
2
  import io
 
3
  import cv2
4
  import numpy as np
5
- import os
 
 
 
6
  os.environ['TF_USE_LEGACY_KERAS'] = '1'
 
 
 
 
 
7
  import tf_keras as keras
8
  import tensorflow as tf
9
  from fastapi import FastAPI, UploadFile, File
 
10
  from PIL import Image
11
  from huggingface_hub import snapshot_download
12
- from fastapi.responses import StreamingResponse
13
-
14
  from object_detection.utils import label_map_util, config_util
15
  from object_detection.builders import model_builder
16
 
17
  app = FastAPI()
18
 
 
 
 
 
 
 
 
 
 
 
19
  # 1. Download Private Models
20
  HF_TOKEN = os.getenv("HF_Token")
21
  REPO_ID = "SaniaE/Car_Damage_Detection"
@@ -33,15 +52,14 @@ LABEL_MAP_PATH = os.path.join(model_dir, "object_detection_model/label_map.pbtxt
33
  CNN_MODEL_PATH = os.path.join(model_dir, "cnn_filter.h5")
34
 
35
  # 3. Load Models
36
- # Load CNN Filter
37
  cnn_filter = tf.keras.models.load_model(CNN_MODEL_PATH, compile=False)
38
 
39
- # Load Object Detection Model
40
  configs = config_util.get_configs_from_pipeline_file(PIPELINE_CONFIG)
41
  detection_model = model_builder.build(model_config=configs['model'], is_training=False)
42
  ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
43
  ckpt.restore(CHECKPOINT_PATH).expect_partial()
44
-
45
  category_index = label_map_util.create_category_index_from_labelmap(LABEL_MAP_PATH)
46
 
47
  @tf.function
@@ -51,18 +69,26 @@ def detect_fn(image):
51
  detections = detection_model.postprocess(prediction_dict, shapes)
52
  return detections
53
 
 
 
 
 
 
 
 
54
  @app.get("/")
55
  def read_root():
56
  return {"status": "Model is Online", "model_repo": REPO_ID}
57
 
58
  @app.post("/predict")
59
  async def predict(file: UploadFile = File(...)):
 
 
60
  # Read Image
61
  contents = await file.read()
62
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
63
  image_np = np.array(image_pil)
64
-
65
- # We need a BGR version for OpenCV drawing
66
  image_cv = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
67
  height, width, _ = image_cv.shape
68
 
@@ -70,7 +96,7 @@ async def predict(file: UploadFile = File(...)):
70
  img_cnn = image_pil.resize((64, 64))
71
  x = tf.keras.preprocessing.image.img_to_array(img_cnn)
72
  x = np.expand_dims(x, axis=0)
73
-
74
  cnn_pred = cnn_filter.predict(x)
75
  is_damage_labels = ['Clear', 'Damaged']
76
  status = is_damage_labels[np.argmax(cnn_pred)]
@@ -79,215 +105,181 @@ async def predict(file: UploadFile = File(...)):
79
  if status == 'Damaged':
80
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
81
  detections = detect_fn(input_tensor)
82
-
83
  scores = detections['detection_scores'][0].numpy()
84
  classes = detections['detection_classes'][0].numpy().astype(int)
85
  boxes = detections['detection_boxes'][0].numpy()
86
 
87
  for i in range(len(scores)):
88
  if scores[i] > 0.4:
89
- # TFOD Boxes are [ymin, xmin, ymax, xmax] in normalized coordinates
90
  ymin, xmin, ymax, xmax = boxes[i]
91
- (left, right, top, bottom) = (xmin * width, xmax * width,
92
- ymin * height, ymax * height)
93
-
94
- # Draw Bounding Box (Teal color to match your vibe)
95
  cv2.rectangle(image_cv, (int(left), int(top)), (int(right), int(bottom)), (255, 255, 0), 2)
96
-
97
- # Draw Label
98
  label = f"{category_index.get(classes[i] + 1, {}).get('name', 'unknown')}: {int(scores[i]*100)}%"
99
  cv2.putText(image_cv, label, (int(left), int(top) - 10),
100
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 2)
101
 
102
- # Encode the image back to JPEG
103
  _, buffer = cv2.imencode('.jpg', image_cv)
104
- return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/jpeg")
105
-
106
-
107
- def get_top_prediction(detections):
108
- """Extracts the index of the most confident detection."""
109
- scores = detections['detection_scores'][0].numpy()
110
- if len(scores) > 0 and scores[0] > 0.4:
111
- # Returns index 0 (top score) and the class ID
112
- return 0, int(detections['detection_classes'][0].numpy()[0])
113
- return None, None
114
-
115
 
 
 
 
 
 
 
116
  @app.post("/explain")
117
  async def explain(file: UploadFile = File(...)):
118
- # 1. Prepare Image
 
119
  contents = await file.read()
120
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
121
  image_np = np.array(image_pil).astype(np.float32)
122
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
123
 
124
- # 2. Gradient Tape for Saliency
125
  with tf.GradientTape() as tape:
126
  tape.watch(input_tensor)
127
-
128
- # Manually run the forward pass through the detection model
129
  image, shapes = detection_model.preprocess(input_tensor)
130
  prediction_dict = detection_model.predict(image, shapes)
131
-
132
- # 'class_predictions_with_background' is standard for TFOD SSD/FasterRCNN models
133
- # It usually has shape [1, num_anchors, num_classes]
134
  raw_scores = prediction_dict['class_predictions_with_background'][0]
135
 
136
- # We need a reference detection to know which class to compute gradients for
137
  detections = detection_model.postprocess(prediction_dict, shapes)
138
  _, top_class = get_top_prediction(detections)
139
-
140
  if top_class is None:
141
- return {"error": "No object detected with sufficient confidence to explain."}
142
-
143
- # Focus loss on the max score for that specific class across all anchors
144
  loss = tf.reduce_max(raw_scores[:, top_class])
145
 
146
- # 3. Compute Gradients
147
  grads = tape.gradient(loss, input_tensor)
148
- # Take absolute max across color channels
149
  saliency = np.max(np.abs(grads.numpy()), axis=-1)[0]
150
 
151
- # 4. Normalize and Create Heatmap
152
- # Using 95th percentile to reduce noise/outliers
153
  v_min, v_max = np.percentile(saliency, (5, 95))
154
  saliency = np.clip((saliency - v_min) / (v_max - v_min + 1e-8), 0, 1)
155
-
156
- # Create the JET heatmap (Blue = low, Red = high)
157
  heatmap = cv2.applyColorMap(np.uint8(255 * saliency), cv2.COLORMAP_JET)
158
 
159
- # 5. Overlay on original image (Convert original to BGR first)
160
  original_bgr = cv2.cvtColor(image_np.astype(np.uint8), cv2.COLOR_RGB2BGR)
161
  overlay = cv2.addWeighted(original_bgr, 0.6, heatmap, 0.4, 0)
162
-
163
- # Add text label for what we are explaining
164
  class_name = category_index.get(top_class + 1, {}).get('name', 'unknown')
165
  cv2.putText(overlay, f"Explaining: {class_name}", (10, 30),
166
  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
167
 
168
- # 6. Stream Result
169
  _, buffer = cv2.imencode('.jpg', overlay)
170
- return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/jpeg")
171
-
 
 
 
 
 
 
172
 
173
  @app.post("/explain/tiled")
174
  async def explain_tiled(file: UploadFile = File(...)):
175
- # 1. Prepare Base Image
 
176
  contents = await file.read()
177
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
178
  image_np = np.array(image_pil).astype(np.float32)
179
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
180
-
181
- # 2. Get Initial Detections to know what to "Explain"
182
  detections = detect_fn(input_tensor)
183
  scores = detections['detection_scores'][0].numpy()
184
  classes = detections['detection_classes'][0].numpy().astype(int)
185
  boxes = detections['detection_boxes'][0].numpy()
186
-
187
- # Create the Top-Left "Base" image with all boxes
188
  base_image = cv2.cvtColor(image_np.astype(np.uint8), cv2.COLOR_RGB2BGR)
189
  h_img, w_img, _ = base_image.shape
190
-
191
  for i in range(min(len(scores), 3)):
192
  if scores[i] > 0.4:
193
  ymin, xmin, ymax, xmax = boxes[i]
194
  cv2.rectangle(base_image, (int(xmin*w_img), int(ymin*h_img)),
195
- (int(xmax*w_img), int(ymax*h_img)), (255, 255, 0), 2)
196
 
197
- # 3. Generate Saliency Maps for the Top 3 detections
198
  panels = [base_image]
199
-
200
  for i in range(3):
201
  if i < len(scores) and scores[i] > 0.4:
202
  target_class = classes[i]
203
-
204
  with tf.GradientTape() as tape:
205
  tape.watch(input_tensor)
206
  image, shapes = detection_model.preprocess(input_tensor)
207
  prediction_dict = detection_model.predict(image, shapes)
208
  raw_scores = prediction_dict['class_predictions_with_background'][0]
209
- # Target the specific class at its most active anchor
210
  loss = tf.reduce_max(raw_scores[:, target_class])
211
-
212
  grads = tape.gradient(loss, input_tensor)
213
  saliency = np.max(np.abs(grads.numpy()), axis=-1)[0]
214
-
215
- # Normalize and Colorize
216
  v_min, v_max = np.percentile(saliency, (5, 95))
217
  saliency = np.clip((saliency - v_min) / (v_max - v_min + 1e-8), 0, 1)
218
  heatmap = cv2.applyColorMap(np.uint8(255 * saliency), cv2.COLORMAP_JET)
219
-
220
- # Overlay
221
  overlay = cv2.addWeighted(cv2.cvtColor(image_np.astype(np.uint8), cv2.COLOR_RGB2BGR), 0.6, heatmap, 0.4, 0)
222
-
223
- # Label the panel
224
  class_name = category_index.get(target_class + 1, {}).get('name', 'unknown')
225
  cv2.putText(overlay, f"Top {i+1}: {class_name}", (10, 30),
226
  cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
227
  panels.append(overlay)
228
  else:
229
- # Placeholder for empty slots if fewer than 3 detections exist
230
  panels.append(np.zeros_like(base_image))
231
 
232
- # 4. Assemble the 2x2 Grid
233
- # Panels are: [0:Base, 1:Top1, 2:Top2, 3:Top3]
234
  top_row = np.hstack((panels[0], panels[1]))
235
  bottom_row = np.hstack((panels[2], panels[3]))
236
  tiled_output = np.vstack((top_row, bottom_row))
237
 
238
- # 5. Stream Result
239
  _, buffer = cv2.imencode('.jpg', tiled_output)
240
- return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/jpeg")
241
-
 
 
 
 
 
 
242
 
243
  @app.post("/explain/global")
244
  async def explain_global(file: UploadFile = File(...)):
245
- # 1. Read and Prepare Image
 
246
  contents = await file.read()
247
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
248
  image_np = np.array(image_pil).astype(np.float32)
249
- # Keeping a uint8 copy for the final BGR overlay
250
  image_bgr = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
251
-
252
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
253
 
254
- # 2. Gradient Tape for Global Activation
255
  with tf.GradientTape() as tape:
256
  tape.watch(input_tensor)
257
-
258
- # Forward pass
259
  image, shapes = detection_model.preprocess(input_tensor)
260
  prediction_dict = detection_model.predict(image, shapes)
261
-
262
- # 'class_predictions_with_background' shape: [1, num_anchors, num_classes]
263
  raw_scores = prediction_dict['class_predictions_with_background'][0]
264
-
265
- # We ignore index 0 (Background/Clear) and look at all damage classes
266
- # We take the max score at each anchor point, then sum them for the global loss
267
  foreground_scores = raw_scores[:, 1:]
268
  loss = tf.reduce_sum(tf.reduce_max(foreground_scores, axis=-1))
269
 
270
- # 3. Compute and Process Gradients
271
  grads = tape.gradient(loss, input_tensor)
272
  saliency = np.max(np.abs(grads.numpy()), axis=-1)[0]
273
 
274
- # 4. Refine Saliency Visualization
275
- # Using the 95th percentile helps ignore "pixel noise" and highlights the actual damage
276
  v_min, v_max = np.percentile(saliency, (5, 95))
277
  saliency = np.clip((saliency - v_min) / (v_max - v_min + 1e-8), 0, 1)
278
 
279
- # Create the heatmap overlay
280
  heatmap = cv2.applyColorMap(np.uint8(255 * saliency), cv2.COLORMAP_JET)
281
-
282
- # Blend: 60% original image, 40% heatmap
283
- # This maintains the "Pinterest-chic" aesthetic without washing out the car details
284
  overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
285
-
286
- # 5. Add Branding/Label
287
- # Teal text to match your office setup/portfolio theme
288
  cv2.putText(overlay, "Global Model Attention", (20, 40),
289
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 0), 2)
290
 
291
- # 6. Stream Result
292
  _, buffer = cv2.imencode('.jpg', overlay)
293
- return StreamingResponse(io.BytesIO(buffer.tobytes()), media_type="image/jpeg")
 
 
 
 
 
 
 
 
1
  import os
2
  import io
3
+ import time
4
  import cv2
5
  import numpy as np
6
+
7
+ # ==========================================
8
+ # HARDWARE SCHEDULING INTERFACES (BASELINE)
9
+ # ==========================================
10
  os.environ['TF_USE_LEGACY_KERAS'] = '1'
11
+ # Initialize clean, un-throttled thread footprints for benchmarking
12
+ os.environ["OMP_NUM_THREADS"] = "2"
13
+ os.environ["TF_NUM_INTRAOP_THREADS"] = "2"
14
+ os.environ["TF_NUM_INTEROP_THREADS"] = "1"
15
+
16
  import tf_keras as keras
17
  import tensorflow as tf
18
  from fastapi import FastAPI, UploadFile, File
19
+ from fastapi.middleware.cors import CORSMiddleware
20
  from PIL import Image
21
  from huggingface_hub import snapshot_download
22
+ from fastapi.responses import StreamingResponse, Response
 
23
  from object_detection.utils import label_map_util, config_util
24
  from object_detection.builders import model_builder
25
 
26
  app = FastAPI()
27
 
28
+ # Enable smooth frontend cross-origin header interceptions
29
+ app.add_middleware(
30
+ CORSMiddleware,
31
+ allow_origins=["*"],
32
+ allow_credentials=True,
33
+ allow_methods=["*"],
34
+ allow_headers=["*"],
35
+ expose_headers=["X-Processing-Time", "X-Model-Status"]
36
+ )
37
+
38
  # 1. Download Private Models
39
  HF_TOKEN = os.getenv("HF_Token")
40
  REPO_ID = "SaniaE/Car_Damage_Detection"
 
52
  CNN_MODEL_PATH = os.path.join(model_dir, "cnn_filter.h5")
53
 
54
  # 3. Load Models
55
+ print("Loading CNN Filter...")
56
  cnn_filter = tf.keras.models.load_model(CNN_MODEL_PATH, compile=False)
57
 
58
+ print("Loading Object Detection Model...")
59
  configs = config_util.get_configs_from_pipeline_file(PIPELINE_CONFIG)
60
  detection_model = model_builder.build(model_config=configs['model'], is_training=False)
61
  ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
62
  ckpt.restore(CHECKPOINT_PATH).expect_partial()
 
63
  category_index = label_map_util.create_category_index_from_labelmap(LABEL_MAP_PATH)
64
 
65
  @tf.function
 
69
  detections = detection_model.postprocess(prediction_dict, shapes)
70
  return detections
71
 
72
+ def get_top_prediction(detections):
73
+ """Extracts the index of the most confident detection."""
74
+ scores = detections['detection_scores'][0].numpy()
75
+ if len(scores) > 0 and scores[0] > 0.4:
76
+ return 0, int(detections['detection_classes'][0].numpy()[0])
77
+ return None, None
78
+
79
  @app.get("/")
80
  def read_root():
81
  return {"status": "Model is Online", "model_repo": REPO_ID}
82
 
83
  @app.post("/predict")
84
  async def predict(file: UploadFile = File(...)):
85
+ start_time = time.perf_counter()
86
+
87
  # Read Image
88
  contents = await file.read()
89
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
90
  image_np = np.array(image_pil)
91
+
 
92
  image_cv = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
93
  height, width, _ = image_cv.shape
94
 
 
96
  img_cnn = image_pil.resize((64, 64))
97
  x = tf.keras.preprocessing.image.img_to_array(img_cnn)
98
  x = np.expand_dims(x, axis=0)
99
+
100
  cnn_pred = cnn_filter.predict(x)
101
  is_damage_labels = ['Clear', 'Damaged']
102
  status = is_damage_labels[np.argmax(cnn_pred)]
 
105
  if status == 'Damaged':
106
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
107
  detections = detect_fn(input_tensor)
 
108
  scores = detections['detection_scores'][0].numpy()
109
  classes = detections['detection_classes'][0].numpy().astype(int)
110
  boxes = detections['detection_boxes'][0].numpy()
111
 
112
  for i in range(len(scores)):
113
  if scores[i] > 0.4:
 
114
  ymin, xmin, ymax, xmax = boxes[i]
115
+ (left, right, top, bottom) = (xmin * width, xmax * width,
116
+ ymin * height, ymax * height)
 
 
117
  cv2.rectangle(image_cv, (int(left), int(top)), (int(right), int(bottom)), (255, 255, 0), 2)
 
 
118
  label = f"{category_index.get(classes[i] + 1, {}).get('name', 'unknown')}: {int(scores[i]*100)}%"
119
  cv2.putText(image_cv, label, (int(left), int(top) - 10),
120
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 2)
121
 
 
122
  _, buffer = cv2.imencode('.jpg', image_cv)
123
+ elapsed_time = time.perf_counter() - start_time
124
+ print(f"[BENCHMARK] /predict turnaround: {elapsed_time:.4f}s | Status: {status}")
 
 
 
 
 
 
 
 
 
125
 
126
+ return StreamingResponse(
127
+ io.BytesIO(buffer.tobytes()),
128
+ media_type="image/jpeg",
129
+ headers={"X-Processing-Time": f"{elapsed_time:.4f}", "X-Model-Status": status}
130
+ )
131
+
132
  @app.post("/explain")
133
  async def explain(file: UploadFile = File(...)):
134
+ start_time = time.perf_counter()
135
+
136
  contents = await file.read()
137
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
138
  image_np = np.array(image_pil).astype(np.float32)
139
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
140
 
 
141
  with tf.GradientTape() as tape:
142
  tape.watch(input_tensor)
 
 
143
  image, shapes = detection_model.preprocess(input_tensor)
144
  prediction_dict = detection_model.predict(image, shapes)
 
 
 
145
  raw_scores = prediction_dict['class_predictions_with_background'][0]
146
 
 
147
  detections = detection_model.postprocess(prediction_dict, shapes)
148
  _, top_class = get_top_prediction(detections)
149
+
150
  if top_class is None:
151
+ elapsed_time = time.perf_counter() - start_time
152
+ return Response(status_code=204, headers={"X-Processing-Time": f"{elapsed_time:.4f}"})
153
+
154
  loss = tf.reduce_max(raw_scores[:, top_class])
155
 
 
156
  grads = tape.gradient(loss, input_tensor)
 
157
  saliency = np.max(np.abs(grads.numpy()), axis=-1)[0]
158
 
 
 
159
  v_min, v_max = np.percentile(saliency, (5, 95))
160
  saliency = np.clip((saliency - v_min) / (v_max - v_min + 1e-8), 0, 1)
 
 
161
  heatmap = cv2.applyColorMap(np.uint8(255 * saliency), cv2.COLORMAP_JET)
162
 
 
163
  original_bgr = cv2.cvtColor(image_np.astype(np.uint8), cv2.COLOR_RGB2BGR)
164
  overlay = cv2.addWeighted(original_bgr, 0.6, heatmap, 0.4, 0)
165
+
 
166
  class_name = category_index.get(top_class + 1, {}).get('name', 'unknown')
167
  cv2.putText(overlay, f"Explaining: {class_name}", (10, 30),
168
  cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
169
 
 
170
  _, buffer = cv2.imencode('.jpg', overlay)
171
+ elapsed_time = time.perf_counter() - start_time
172
+ print(f"[BENCHMARK] /explain turnaround: {elapsed_time:.4f}s")
173
+
174
+ return StreamingResponse(
175
+ io.BytesIO(buffer.tobytes()),
176
+ media_type="image/jpeg",
177
+ headers={"X-Processing-Time": f"{elapsed_time:.4f}"}
178
+ )
179
 
180
  @app.post("/explain/tiled")
181
  async def explain_tiled(file: UploadFile = File(...)):
182
+ start_time = time.perf_counter()
183
+
184
  contents = await file.read()
185
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
186
  image_np = np.array(image_pil).astype(np.float32)
187
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
188
+
 
189
  detections = detect_fn(input_tensor)
190
  scores = detections['detection_scores'][0].numpy()
191
  classes = detections['detection_classes'][0].numpy().astype(int)
192
  boxes = detections['detection_boxes'][0].numpy()
193
+
 
194
  base_image = cv2.cvtColor(image_np.astype(np.uint8), cv2.COLOR_RGB2BGR)
195
  h_img, w_img, _ = base_image.shape
196
+
197
  for i in range(min(len(scores), 3)):
198
  if scores[i] > 0.4:
199
  ymin, xmin, ymax, xmax = boxes[i]
200
  cv2.rectangle(base_image, (int(xmin*w_img), int(ymin*h_img)),
201
+ (int(xmax*w_img), int(ymax*h_img)), (255, 255, 0), 2)
202
 
 
203
  panels = [base_image]
204
+
205
  for i in range(3):
206
  if i < len(scores) and scores[i] > 0.4:
207
  target_class = classes[i]
208
+
209
  with tf.GradientTape() as tape:
210
  tape.watch(input_tensor)
211
  image, shapes = detection_model.preprocess(input_tensor)
212
  prediction_dict = detection_model.predict(image, shapes)
213
  raw_scores = prediction_dict['class_predictions_with_background'][0]
 
214
  loss = tf.reduce_max(raw_scores[:, target_class])
215
+
216
  grads = tape.gradient(loss, input_tensor)
217
  saliency = np.max(np.abs(grads.numpy()), axis=-1)[0]
218
+
 
219
  v_min, v_max = np.percentile(saliency, (5, 95))
220
  saliency = np.clip((saliency - v_min) / (v_max - v_min + 1e-8), 0, 1)
221
  heatmap = cv2.applyColorMap(np.uint8(255 * saliency), cv2.COLORMAP_JET)
222
+
 
223
  overlay = cv2.addWeighted(cv2.cvtColor(image_np.astype(np.uint8), cv2.COLOR_RGB2BGR), 0.6, heatmap, 0.4, 0)
224
+
 
225
  class_name = category_index.get(target_class + 1, {}).get('name', 'unknown')
226
  cv2.putText(overlay, f"Top {i+1}: {class_name}", (10, 30),
227
  cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
228
  panels.append(overlay)
229
  else:
 
230
  panels.append(np.zeros_like(base_image))
231
 
 
 
232
  top_row = np.hstack((panels[0], panels[1]))
233
  bottom_row = np.hstack((panels[2], panels[3]))
234
  tiled_output = np.vstack((top_row, bottom_row))
235
 
 
236
  _, buffer = cv2.imencode('.jpg', tiled_output)
237
+ elapsed_time = time.perf_counter() - start_time
238
+ print(f"[BENCHMARK] /explain/tiled turnaround: {elapsed_time:.4f}s")
239
+
240
+ return StreamingResponse(
241
+ io.BytesIO(buffer.tobytes()),
242
+ media_type="image/jpeg",
243
+ headers={"X-Processing-Time": f"{elapsed_time:.4f}"}
244
+ )
245
 
246
  @app.post("/explain/global")
247
  async def explain_global(file: UploadFile = File(...)):
248
+ start_time = time.perf_counter()
249
+
250
  contents = await file.read()
251
  image_pil = Image.open(io.BytesIO(contents)).convert("RGB")
252
  image_np = np.array(image_pil).astype(np.float32)
 
253
  image_bgr = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
254
+
255
  input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
256
 
 
257
  with tf.GradientTape() as tape:
258
  tape.watch(input_tensor)
 
 
259
  image, shapes = detection_model.preprocess(input_tensor)
260
  prediction_dict = detection_model.predict(image, shapes)
 
 
261
  raw_scores = prediction_dict['class_predictions_with_background'][0]
 
 
 
262
  foreground_scores = raw_scores[:, 1:]
263
  loss = tf.reduce_sum(tf.reduce_max(foreground_scores, axis=-1))
264
 
 
265
  grads = tape.gradient(loss, input_tensor)
266
  saliency = np.max(np.abs(grads.numpy()), axis=-1)[0]
267
 
 
 
268
  v_min, v_max = np.percentile(saliency, (5, 95))
269
  saliency = np.clip((saliency - v_min) / (v_max - v_min + 1e-8), 0, 1)
270
 
 
271
  heatmap = cv2.applyColorMap(np.uint8(255 * saliency), cv2.COLORMAP_JET)
 
 
 
272
  overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
273
+
 
 
274
  cv2.putText(overlay, "Global Model Attention", (20, 40),
275
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 0), 2)
276
 
 
277
  _, buffer = cv2.imencode('.jpg', overlay)
278
+ elapsed_time = time.perf_counter() - start_time
279
+ print(f"[BENCHMARK] /explain/global turnaround: {elapsed_time:.4f}s")
280
+
281
+ return StreamingResponse(
282
+ io.BytesIO(buffer.tobytes()),
283
+ media_type="image/jpeg",
284
+ headers={"X-Processing-Time": f"{elapsed_time:.4f}"}
285
+ )