SaniaE commited on
Commit
2018891
·
verified ·
1 Parent(s): 3fc1076

updated app

Browse files
Files changed (1) hide show
  1. app.py +30 -49
app.py CHANGED
@@ -9,6 +9,7 @@ from fastapi.middleware.cors import CORSMiddleware
9
  from fastapi.responses import StreamingResponse, Response
10
  from huggingface_hub import hf_hub_download, snapshot_download, login
11
 
 
12
  tf.config.threading.set_intra_op_parallelism_threads(4)
13
  tf.config.threading.set_inter_op_parallelism_threads(2)
14
  os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
@@ -24,7 +25,7 @@ snapshot_download(repo_id=REPO_ID, allow_patterns=["mrcnn/*"], local_dir=".", to
24
  patches.patch_model_file()
25
 
26
  import mrcnn.model as modellib
27
- from mrcnn.model import mold_image, compose_image_meta
28
  from model_utils import PredictionConfig, visualize_detections
29
 
30
  app = FastAPI()
@@ -105,68 +106,42 @@ async def explain_occlusion(file: UploadFile = File(...)):
105
  return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
106
 
107
  baseline_score = baseline_res['scores'][0]
108
- target_class_id = baseline_res['class_ids'][0]
109
-
110
- print(f"\n[XAI-DEBUG] Baseline Target Class ID: {target_class_id}, Score: {baseline_score:.4f}")
111
-
112
- molded_base = mold_image(np.array([image_rgb]), config)
113
- molded_base = molded_base[0]
114
- gray_molded_value = 128 - config.MEAN_PIXEL[:3]
115
 
116
  patch_size = 64
117
  stride = 64
118
 
119
- molded_patches = []
120
  patch_indices = []
121
 
122
  for y in range(0, h, stride):
123
  for x in range(0, w, stride):
124
  y_end = min(y + patch_size, h)
125
  x_end = min(x + patch_size, w)
126
- img_occ = molded_base.copy()
127
- img_occ[y:y_end, x:x_end, :] = gray_molded_value
128
- molded_patches.append(img_occ)
 
 
129
  patch_indices.append((y, y_end, x, x_end))
130
 
131
- scores_list = []
 
132
 
 
 
 
133
  with graph.as_default():
134
- keras_model = model_eval.keras_model
135
- meta = compose_image_meta(
136
- image_id=0,
137
- original_image_shape=image_rgb.shape,
138
- image_shape=(h, w, 3),
139
- window=(0, 0, h, w),
140
- scale=1.0,
141
- active_class_ids=np.ones(config.NUM_CLASSES, dtype=np.int32)
142
- )
143
- image_metas = np.array([meta])
144
- anchors = np.expand_dims(model_eval.anchors, axis=0)
145
-
146
- for idx, img in enumerate(molded_patches):
147
- molded_images = np.expand_dims(img, axis=0)
148
- outputs = keras_model.predict([molded_images, image_metas, anchors], verbose=0)
149
- detections = outputs[0][0]
150
-
151
- # Diagnostic telemetry extraction
152
- max_overall_score = np.max(detections[:, 5])
153
- max_score_idx = np.argmax(detections[:, 5])
154
- class_at_max = detections[max_score_idx, 4]
155
-
156
- valid_indices = np.where(detections[:, 4] == target_class_id)[0]
157
- if len(valid_indices) > 0:
158
- top_score = detections[valid_indices[0], 5]
159
- else:
160
- top_score = 0.0
161
-
162
- scores_list.append(top_score)
163
-
164
- # Print metrics for the first 4 patches to verify matrix alignment
165
- if idx < 4:
166
- print(f" -> Patch {idx}: Max Score In Tensor={max_overall_score:.4f} (Class {int(class_at_max)}), Extracted Score for Target Class={top_score:.4f}")
167
 
 
 
 
 
168
  sensitivity_map = np.zeros((h, w), dtype=np.float32)
169
- for idx, current_score in enumerate(scores_list):
 
170
  drop = max(0.0, baseline_score - current_score)
171
  y, y_end, x, x_end = patch_indices[idx]
172
  sensitivity_map[y:y_end, x:x_end] = drop
@@ -178,6 +153,12 @@ async def explain_occlusion(file: UploadFile = File(...)):
178
 
179
  heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
180
  overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
181
-
 
 
182
  _, buffer = cv2.imencode('.jpg', overlay)
183
- return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg")
 
 
 
 
 
9
  from fastapi.responses import StreamingResponse, Response
10
  from huggingface_hub import hf_hub_download, snapshot_download, login
11
 
12
+ # Hardware thread configurations
13
  tf.config.threading.set_intra_op_parallelism_threads(4)
14
  tf.config.threading.set_inter_op_parallelism_threads(2)
15
  os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
 
25
  patches.patch_model_file()
26
 
27
  import mrcnn.model as modellib
28
+ from mrcnn.model import mold_image
29
  from model_utils import PredictionConfig, visualize_detections
30
 
31
  app = FastAPI()
 
106
  return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
107
 
108
  baseline_score = baseline_res['scores'][0]
 
 
 
 
 
 
 
109
 
110
  patch_size = 64
111
  stride = 64
112
 
113
+ patch_images = []
114
  patch_indices = []
115
 
116
  for y in range(0, h, stride):
117
  for x in range(0, w, stride):
118
  y_end = min(y + patch_size, h)
119
  x_end = min(x + patch_size, w)
120
+
121
+ img_occ = image_rgb.copy()
122
+ img_occ[y:y_end, x:x_end, :] = 128
123
+
124
+ patch_images.append(img_occ)
125
  patch_indices.append((y, y_end, x, x_end))
126
 
127
+ print(f"Starting Stable Pre-processed Occlusion Analysis (Total patches: {len(patch_images)})...")
128
+ loop_start = time.perf_counter()
129
 
130
+ batch_results = []
131
+
132
+ # Run inferences using the top-level stable wrapper path
133
  with graph.as_default():
134
+ for img in patch_images:
135
+ res = model_eval.detect([img], verbose=0)[0]
136
+ batch_results.append(res)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
+ loop_elapsed = time.perf_counter() - loop_start
139
+ print(f"[BENCHMARK-STABLE] Clean Loop Execution Phase: {loop_elapsed:.4f} seconds")
140
+
141
+ # Re-build your sensitivity mapping safely
142
  sensitivity_map = np.zeros((h, w), dtype=np.float32)
143
+ for idx, res in enumerate(batch_results):
144
+ current_score = res['scores'][0] if len(res['scores']) > 0 else 0
145
  drop = max(0.0, baseline_score - current_score)
146
  y, y_end, x, x_end = patch_indices[idx]
147
  sensitivity_map[y:y_end, x:x_end] = drop
 
153
 
154
  heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
155
  overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
156
+ cv2.putText(overlay, "XAI: Stable Pre-processed Map", (10, 20),
157
+ cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
158
+
159
  _, buffer = cv2.imencode('.jpg', overlay)
160
+
161
+ elapsed_time = time.perf_counter() - start_time
162
+ print(f"[BENCHMARK-STABLE] Total turnaround: {elapsed_time:.4f} seconds\n")
163
+
164
+ return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})