SaniaE commited on
Commit
883e5dd
·
verified ·
1 Parent(s): 544b83f

optimized for loading bar support

Browse files
Files changed (1) hide show
  1. app.py +89 -79
app.py CHANGED
@@ -1,27 +1,26 @@
1
  import io
2
  import os
3
  import time
 
 
4
  import numpy as np
5
  import cv2
 
 
 
 
 
 
 
6
  import tensorflow as tf
7
  from fastapi import FastAPI, File, UploadFile
8
  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
- # ==========================================
13
- # HARDWARE ENGINE OPTIMIZATIONS (CPU BOOST)
14
- # ==========================================
15
- tf.config.threading.set_intra_op_parallelism_threads(4)
16
- tf.config.threading.set_inter_op_parallelism_threads(2)
17
- os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
18
- os.environ["KMP_AFFINITY"] = "granularity=fine,verbose,compact,1,0"
19
-
20
- # 1. Run environment fixes immediately
21
  import patches
22
  patches.apply_fixes()
23
 
24
- # 2. Setup Hub and Downloads
25
  REPO_ID = "SaniaE/MRCNN_Petrol_Pump_Segmentation"
26
  FILENAME = "mask_rcnn_petrol station_0080.h5"
27
  token = os.getenv("HF_Token")
@@ -29,7 +28,6 @@ token = os.getenv("HF_Token")
29
  snapshot_download(repo_id=REPO_ID, allow_patterns=["mrcnn/*"], local_dir=".", token=token)
30
  patches.patch_model_file()
31
 
32
- # 3. Import Mask R-CNN after patching
33
  import mrcnn.model as modellib
34
  from model_utils import PredictionConfig, visualize_detections
35
 
@@ -43,7 +41,6 @@ app.add_middleware(
43
  allow_headers=["*"],
44
  )
45
 
46
- # Global state
47
  config = PredictionConfig()
48
  graph = tf.get_default_graph()
49
  model_eval = None
@@ -71,7 +68,7 @@ async def predict(file: UploadFile = File(...)):
71
  nparr = np.frombuffer(contents, np.uint8)
72
  image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
73
  if image_bgr is None:
74
- return Response(status_code=400, content="Invalid image encoding layout.")
75
 
76
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
77
 
@@ -87,87 +84,100 @@ async def predict(file: UploadFile = File(...)):
87
  _, buffer = cv2.imencode('.jpg', processed_bgr)
88
 
89
  elapsed_time = time.perf_counter() - start_time
90
- print(f"[BENCHMARK-ENGINE] /predict total turnaround: {elapsed_time:.4f} seconds")
91
  return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
92
 
93
  @app.post("/explain/occlusion")
94
  async def explain_occlusion(file: UploadFile = File(...)):
95
- start_time = time.perf_counter()
96
-
97
  contents = await file.read()
98
  nparr = np.frombuffer(contents, np.uint8)
99
  image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
100
  if image_bgr is None:
101
- return Response(status_code=400, content="Invalid image layout structure.")
102
 
103
- # Keeping exact 256x256 requirements intact
104
  image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
105
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
106
  h, w, _ = image_rgb.shape
107
 
108
- with graph.as_default():
109
- baseline_res = model_eval.detect([image_rgb], verbose=0)[0]
110
-
111
- if len(baseline_res['scores']) == 0:
112
- elapsed_time = time.perf_counter() - start_time
113
- return Response(status_code=204, headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
114
 
115
- baseline_score = baseline_res['scores'][0]
116
-
117
- # Target parameters maintained: 16 total patches
118
- patch_size = 64
119
- stride = 64
120
-
121
- batch_images = []
122
- patch_indices = []
123
-
124
- for y in range(0, h, stride):
125
- for x in range(0, w, stride):
126
- y_end = min(y + patch_size, h)
127
- x_end = min(x + patch_size, w)
128
 
129
- img_occ = image_rgb.copy()
130
- img_occ[y:y_end, x:x_end, :] = 128
 
131
 
132
- batch_images.append(img_occ)
133
- patch_indices.append((y, y_end, x, x_end))
134
 
135
- print(f"Starting Engine-Optimized Occlusion Analysis (Total patches: {len(batch_images)})...")
136
- loop_start = time.perf_counter()
137
-
138
- batch_results = []
139
-
140
- # Safe single-thread loop boosted by low-level thread allocations
141
- with graph.as_default():
142
- for img in batch_images:
143
- res = model_eval.detect([img], verbose=0)[0]
144
- batch_results.append(res)
145
 
146
- loop_elapsed = time.perf_counter() - loop_start
147
- print(f"[BENCHMARK-ENGINE] Stable Inference Loop Execution: {loop_elapsed:.4f} seconds")
148
-
149
- # Map evaluation updates to visual fields
150
- sensitivity_map = np.zeros((h, w), dtype=np.float32)
151
- for idx, res in enumerate(batch_results):
152
- current_score = res['scores'][0] if len(res['scores']) > 0 else 0
153
- drop = max(0.0, baseline_score - current_score)
154
- y, y_end, x, x_end = patch_indices[idx]
155
- sensitivity_map[y:y_end, x:x_end] = drop
156
-
157
- # Smooth out Heatmap
158
- sens_max = np.max(sensitivity_map)
159
- if sens_max > 0:
160
- sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (sens_max - np.min(sensitivity_map) + 1e-8)
161
- sensitivity_map = cv2.GaussianBlur(sensitivity_map, (15, 15), 0)
162
-
163
- heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
164
- overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
165
- cv2.putText(overlay, "XAI: Engine-Optimized Map", (10, 20),
166
- cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1, cv2.LINE_AA)
167
-
168
- _, buffer = cv2.imencode('.jpg', overlay)
169
-
170
- elapsed_time = time.perf_counter() - start_time
171
- print(f"[BENCHMARK-ENGINE] /explain/occlusion total turnaround: {elapsed_time:.4f} seconds\n")
172
-
173
- return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import io
2
  import os
3
  import time
4
+ import json
5
+ import base64
6
  import numpy as np
7
  import cv2
8
+
9
+ # 1. HARDWARE THREAD PINNING (Prevents CPU degradation during container load spikes)
10
+ os.environ["OMP_NUM_THREADS"] = "4"
11
+ os.environ["TF_NUM_INTEROP_THREADS"] = "2"
12
+ os.environ["TF_NUM_INTRAOP_THREADS"] = "4"
13
+ os.environ["TF_ENABLE_MKL_NATIVE_FORMAT"] = "1"
14
+
15
  import tensorflow as tf
16
  from fastapi import FastAPI, File, UploadFile
17
  from fastapi.middleware.cors import CORSMiddleware
18
  from fastapi.responses import StreamingResponse, Response
19
  from huggingface_hub import hf_hub_download, snapshot_download, login
20
 
 
 
 
 
 
 
 
 
 
21
  import patches
22
  patches.apply_fixes()
23
 
 
24
  REPO_ID = "SaniaE/MRCNN_Petrol_Pump_Segmentation"
25
  FILENAME = "mask_rcnn_petrol station_0080.h5"
26
  token = os.getenv("HF_Token")
 
28
  snapshot_download(repo_id=REPO_ID, allow_patterns=["mrcnn/*"], local_dir=".", token=token)
29
  patches.patch_model_file()
30
 
 
31
  import mrcnn.model as modellib
32
  from model_utils import PredictionConfig, visualize_detections
33
 
 
41
  allow_headers=["*"],
42
  )
43
 
 
44
  config = PredictionConfig()
45
  graph = tf.get_default_graph()
46
  model_eval = None
 
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.")
72
 
73
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
74
 
 
84
  _, buffer = cv2.imencode('.jpg', processed_bgr)
85
 
86
  elapsed_time = time.perf_counter() - start_time
87
+ print(f"[BENCHMARK] /predict turnaround: {elapsed_time:.4f} seconds")
88
  return StreamingResponse(io.BytesIO(buffer), media_type="image/jpeg", headers={"X-Inference-Time": f"{elapsed_time:.4f}"})
89
 
90
  @app.post("/explain/occlusion")
91
  async def explain_occlusion(file: UploadFile = File(...)):
 
 
92
  contents = await file.read()
93
  nparr = np.frombuffer(contents, np.uint8)
94
  image_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
95
  if image_bgr is None:
96
+ return Response(status_code=400, content="Invalid image sequence layout.")
97
 
98
+ # Maintained 256x256 resolution baseline structure
99
  image_bgr = cv2.resize(image_bgr, (256, 256), interpolation=cv2.INTER_AREA)
100
  image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
101
  h, w, _ = image_rgb.shape
102
 
103
+ async def progress_streamer():
104
+ start_time = time.perf_counter()
 
 
 
 
105
 
106
+ with graph.as_default():
107
+ baseline_res = model_eval.detect([image_rgb], verbose=0)[0]
 
 
 
 
 
 
 
 
 
 
 
108
 
109
+ if len(baseline_res['scores']) == 0:
110
+ yield json.dumps({"status": "error", "message": "No stable objects detected to run XAI explanation."}) + "\n"
111
+ return
112
 
113
+ baseline_score = baseline_res['scores'][0]
 
114
 
115
+ # 2. OPTIMIZATION: Proportional sub-patch reduction (32x32 pixels)
116
+ patch_size = 32
117
+ stride = 32
 
 
 
 
 
 
 
118
 
119
+ patch_images = []
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
+
127
+ img_occ = image_rgb.copy()
128
+ img_occ[y:y_end, x:x_end, :] = 128
129
+
130
+ patch_images.append(img_occ)
131
+ patch_indices.append((y, y_end, x, x_end))
132
+
133
+ total_patches = len(patch_images)
134
+ batch_results = []
135
+
136
+ # 3. STREAMING LOOP: Emits incremental execution metrics safely
137
+ with graph.as_default():
138
+ for idx, img in enumerate(patch_images):
139
+ res = model_eval.detect([img], verbose=0)[0]
140
+ batch_results.append(res)
141
+
142
+ # Calculate progress step tracking
143
+ progress_percentage = int(((idx + 1) / total_patches) * 100)
144
+
145
+ # Yield data chunk ending with a distinct newline character \n
146
+ yield json.dumps({"status": "processing", "progress": progress_percentage}) + "\n"
147
+
148
+ # 4. Heatmap compilation logic
149
+ sensitivity_map = np.zeros((h, w), dtype=np.float32)
150
+ for idx, res in enumerate(batch_results):
151
+ current_score = res['scores'][0] if len(res['scores']) > 0 else 0
152
+ drop = max(0.0, baseline_score - current_score)
153
+ y, y_end, x, x_end = patch_indices[idx]
154
+ sensitivity_map[y:y_end, x:x_end] = drop
155
+
156
+ sens_max = np.max(sensitivity_map)
157
+ if sens_max > 0:
158
+ sensitivity_map = (sensitivity_map - np.min(sensitivity_map)) / (sens_max - np.min(sensitivity_map) + 1e-8)
159
+ sensitivity_map = cv2.GaussianBlur(sensitivity_map, (11, 11), 0)
160
+
161
+ heatmap = cv2.applyColorMap(np.uint8(255 * sensitivity_map), cv2.COLORMAP_JET)
162
+ overlay = cv2.addWeighted(image_bgr, 0.6, heatmap, 0.4, 0)
163
+
164
+ # Upscale presentation layer gracefully for the web client interface dashboard
165
+ upscaled_output = cv2.resize(overlay, (512, 512), interpolation=cv2.INTER_CUBIC)
166
+ cv2.putText(upscaled_output, "XAI: Optimized Grid Audit", (15, 30),
167
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
168
+
169
+ _, buffer = cv2.imencode('.jpg', upscaled_output)
170
+ encoded_image = base64.b64encode(buffer).decode('utf-8')
171
+ elapsed_time = time.perf_counter() - start_time
172
+
173
+ print(f"[BENCHMARK-OPTIMIZED] Final full turnaround: {elapsed_time:.4f} seconds")
174
+
175
+ # Emit final package termination payload
176
+ yield json.dumps({
177
+ "status": "complete",
178
+ "progress": 100,
179
+ "image": f"data:image/jpeg;base64,{encoded_image}",
180
+ "time": f"{elapsed_time:.2f}s"
181
+ }) + "\n"
182
+
183
+ return StreamingResponse(progress_streamer(), media_type="application/x-ndjson")