fixed batch error
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import io
|
| 2 |
import os
|
| 3 |
-
import time #
|
| 4 |
import numpy as np
|
| 5 |
import cv2
|
| 6 |
import tensorflow as tf
|
|
@@ -28,7 +28,7 @@ from model_utils import PredictionConfig, visualize_detections
|
|
| 28 |
|
| 29 |
app = FastAPI()
|
| 30 |
|
| 31 |
-
# Single initialization of CORS Middleware to
|
| 32 |
app.add_middleware(
|
| 33 |
CORSMiddleware,
|
| 34 |
allow_origins=["*"],
|
|
@@ -51,7 +51,7 @@ def load_model():
|
|
| 51 |
with graph.as_default():
|
| 52 |
model_eval = modellib.MaskRCNN(mode="inference", model_dir=".", config=config)
|
| 53 |
model_eval.load_weights(weights_path, by_name=True)
|
| 54 |
-
# Warm up the compilation graph
|
| 55 |
model_eval.keras_model._make_predict_function()
|
| 56 |
print("Service Ready.")
|
| 57 |
|
|
@@ -63,12 +63,12 @@ async def root():
|
|
| 63 |
async def predict(file: UploadFile = File(...)):
|
| 64 |
start_time = time.perf_counter() # Start Benchmark
|
| 65 |
|
| 66 |
-
# Direct
|
| 67 |
contents = await file.read()
|
| 68 |
nparr = np.frombuffer(contents, np.uint8)
|
| 69 |
image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 70 |
if image_bgr is None:
|
| 71 |
-
return Response(status_code=400, content="Invalid image
|
| 72 |
|
| 73 |
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
| 74 |
|
|
@@ -81,10 +81,10 @@ async def predict(file: UploadFile = File(...)):
|
|
| 81 |
print(f"[BENCHMARK-OPTIMIZED] /predict executed in: {elapsed_time:.4f} seconds (No targets found)")
|
| 82 |
return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
|
| 83 |
|
| 84 |
-
# Render
|
| 85 |
processed_img = visualize_detections(image_rgb, results)
|
| 86 |
|
| 87 |
-
#
|
| 88 |
processed_bgr = cv2.cvtColor(processed_img, cv2.COLOR_RGB2BGR)
|
| 89 |
_, buffer = cv2.imencode('.jpg', processed_bgr)
|
| 90 |
|
|
@@ -106,9 +106,9 @@ async def explain_occlusion(file: UploadFile = File(...)):
|
|
| 106 |
image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 107 |
|
| 108 |
if image_bgr is None:
|
| 109 |
-
return Response(status_code=400, content="Invalid image structure.")
|
| 110 |
|
| 111 |
-
# Native downsample via cv2 (
|
| 112 |
image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
|
| 113 |
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
| 114 |
h, w, _ = image_rgb.shape
|
|
@@ -124,7 +124,7 @@ async def explain_occlusion(file: UploadFile = File(...)):
|
|
| 124 |
|
| 125 |
baseline_score = baseline_res['scores'][0]
|
| 126 |
|
| 127 |
-
# 2.
|
| 128 |
patch_size = 64
|
| 129 |
stride = 64
|
| 130 |
|
|
@@ -134,29 +134,45 @@ async def explain_occlusion(file: UploadFile = File(...)):
|
|
| 134 |
batch_images = []
|
| 135 |
patch_indices = []
|
| 136 |
|
| 137 |
-
#
|
| 138 |
for y in y_coords:
|
| 139 |
for x in x_coords:
|
| 140 |
y_end = min(y + patch_size, h)
|
| 141 |
x_end = min(x + patch_size, w)
|
| 142 |
|
| 143 |
img_occ = image_rgb.copy()
|
| 144 |
-
img_occ[y:y_end, x:x_end, :] = 128 # Apply neutral
|
| 145 |
|
| 146 |
batch_images.append(img_occ)
|
| 147 |
patch_indices.append((y, y_end, x, x_end))
|
| 148 |
|
| 149 |
-
# 3.
|
| 150 |
-
print(f"Starting Vectorized Occlusion Analysis (
|
| 151 |
loop_start = time.perf_counter()
|
| 152 |
|
|
|
|
|
|
|
|
|
|
| 153 |
with graph.as_default():
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
loop_elapsed = time.perf_counter() - loop_start
|
| 157 |
-
print(f"[BENCHMARK-OPTIMIZED]
|
| 158 |
|
| 159 |
-
# 4. Map
|
| 160 |
sensitivity_map = np.zeros((h, w), dtype=np.float32)
|
| 161 |
|
| 162 |
for idx, res in enumerate(batch_results):
|
|
@@ -176,7 +192,7 @@ async def explain_occlusion(file: UploadFile = File(...)):
|
|
| 176 |
|
| 177 |
# 6. Final Composite Render Execution
|
| 178 |
overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
|
| 179 |
-
cv2.putText(overlay, "XAI:
|
| 180 |
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
|
| 181 |
|
| 182 |
_, buffer = cv2.imencode('.jpg', overlay)
|
|
|
|
| 1 |
import io
|
| 2 |
import os
|
| 3 |
+
import time # High-precision benchmark tracking
|
| 4 |
import numpy as np
|
| 5 |
import cv2
|
| 6 |
import tensorflow as tf
|
|
|
|
| 28 |
|
| 29 |
app = FastAPI()
|
| 30 |
|
| 31 |
+
# Single initialization of CORS Middleware to prevent multi-pass overhead
|
| 32 |
app.add_middleware(
|
| 33 |
CORSMiddleware,
|
| 34 |
allow_origins=["*"],
|
|
|
|
| 51 |
with graph.as_default():
|
| 52 |
model_eval = modellib.MaskRCNN(mode="inference", model_dir=".", config=config)
|
| 53 |
model_eval.load_weights(weights_path, by_name=True)
|
| 54 |
+
# Warm up the compilation graph execution space
|
| 55 |
model_eval.keras_model._make_predict_function()
|
| 56 |
print("Service Ready.")
|
| 57 |
|
|
|
|
| 63 |
async def predict(file: UploadFile = File(...)):
|
| 64 |
start_time = time.perf_counter() # Start Benchmark
|
| 65 |
|
| 66 |
+
# Direct low-level matrix decoding via OpenCV (Saves memory & CPU over PIL)
|
| 67 |
contents = await file.read()
|
| 68 |
nparr = np.frombuffer(contents, np.uint8)
|
| 69 |
image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 70 |
if image_bgr is None:
|
| 71 |
+
return Response(status_code=400, content="Invalid image encoding layout.")
|
| 72 |
|
| 73 |
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
| 74 |
|
|
|
|
| 81 |
print(f"[BENCHMARK-OPTIMIZED] /predict executed in: {elapsed_time:.4f} seconds (No targets found)")
|
| 82 |
return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
|
| 83 |
|
| 84 |
+
# Render segments onto the RGB frame
|
| 85 |
processed_img = visualize_detections(image_rgb, results)
|
| 86 |
|
| 87 |
+
# Convert back to BGR right before streaming to browser canvas
|
| 88 |
processed_bgr = cv2.cvtColor(processed_img, cv2.COLOR_RGB2BGR)
|
| 89 |
_, buffer = cv2.imencode('.jpg', processed_bgr)
|
| 90 |
|
|
|
|
| 106 |
image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 107 |
|
| 108 |
if image_bgr is None:
|
| 109 |
+
return Response(status_code=400, content="Invalid image layout structure.")
|
| 110 |
|
| 111 |
+
# Native downsample via cv2 (significantly faster execution speed than PIL)
|
| 112 |
image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
|
| 113 |
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
|
| 114 |
h, w, _ = image_rgb.shape
|
|
|
|
| 124 |
|
| 125 |
baseline_score = baseline_res['scores'][0]
|
| 126 |
|
| 127 |
+
# 2. Build Patch Array Parameters
|
| 128 |
patch_size = 64
|
| 129 |
stride = 64
|
| 130 |
|
|
|
|
| 134 |
batch_images = []
|
| 135 |
patch_indices = []
|
| 136 |
|
| 137 |
+
# Map grid coordinates in clean low-overhead lists
|
| 138 |
for y in y_coords:
|
| 139 |
for x in x_coords:
|
| 140 |
y_end = min(y + patch_size, h)
|
| 141 |
x_end = min(x + patch_size, w)
|
| 142 |
|
| 143 |
img_occ = image_rgb.copy()
|
| 144 |
+
img_occ[y:y_end, x:x_end, :] = 128 # Apply neutral gray mask chunk
|
| 145 |
|
| 146 |
batch_images.append(img_occ)
|
| 147 |
patch_indices.append((y, y_end, x, x_end))
|
| 148 |
|
| 149 |
+
# 3. Dynamic Batch Slicing (Prevents BATCH_SIZE Mismatch AssertionErrors)
|
| 150 |
+
print(f"Starting Vectorized Occlusion Analysis (Total patches: {len(batch_images)}, Step Size: {config.BATCH_SIZE})...")
|
| 151 |
loop_start = time.perf_counter()
|
| 152 |
|
| 153 |
+
batch_results = []
|
| 154 |
+
step = config.BATCH_SIZE
|
| 155 |
+
|
| 156 |
with graph.as_default():
|
| 157 |
+
for i in range(0, len(batch_images), step):
|
| 158 |
+
chunk = batch_images[i:i + step]
|
| 159 |
+
|
| 160 |
+
# If the final chunk is smaller than expected batch size, pad it with copies
|
| 161 |
+
if len(chunk) < step:
|
| 162 |
+
padding_size = step - len(chunk)
|
| 163 |
+
chunk.extend([batch_images[-1]] * padding_size)
|
| 164 |
+
|
| 165 |
+
chunk_res = model_eval.detect(chunk, verbose=0)
|
| 166 |
+
# Slice away the padding artifacts so data integrity stays clean
|
| 167 |
+
batch_results.extend(chunk_res[:len(chunk) - padding_size])
|
| 168 |
+
else:
|
| 169 |
+
chunk_res = model_eval.detect(chunk, verbose=0)
|
| 170 |
+
batch_results.extend(chunk_res)
|
| 171 |
|
| 172 |
loop_elapsed = time.perf_counter() - loop_start
|
| 173 |
+
print(f"[BENCHMARK-OPTIMIZED] Inference Execution Pipeline Phase: {loop_elapsed:.4f} seconds")
|
| 174 |
|
| 175 |
+
# 4. Map evaluation drops directly across sensitivity matrix grids
|
| 176 |
sensitivity_map = np.zeros((h, w), dtype=np.float32)
|
| 177 |
|
| 178 |
for idx, res in enumerate(batch_results):
|
|
|
|
| 192 |
|
| 193 |
# 6. Final Composite Render Execution
|
| 194 |
overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
|
| 195 |
+
cv2.putText(overlay, "XAI: Safe Batched Occlusion Map", (10, 20),
|
| 196 |
cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
|
| 197 |
|
| 198 |
_, buffer = cv2.imencode('.jpg', overlay)
|