Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -79,13 +79,15 @@ class GatekeeperService:
|
|
| 79 |
|
| 80 |
def physics_check_hemorrhage(self, swi_path):
|
| 81 |
"""
|
| 82 |
-
|
| 83 |
-
|
| 84 |
"""
|
| 85 |
-
if not swi_path: return False, 0.0
|
| 86 |
try:
|
| 87 |
img_obj = nib.load(swi_path)
|
| 88 |
vol = img_obj.get_fdata()
|
|
|
|
|
|
|
| 89 |
|
| 90 |
# Robust Normalization
|
| 91 |
p99 = np.percentile(vol, 99)
|
|
@@ -93,35 +95,61 @@ class GatekeeperService:
|
|
| 93 |
|
| 94 |
# Physics Rule
|
| 95 |
dark_mask = vol < 0.02
|
| 96 |
-
|
| 97 |
-
# Fast Cluster Analysis
|
| 98 |
labeled_array, num_features = ndimage.label(dark_mask)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
zooms = img_obj.header.get_zooms()
|
| 102 |
-
voxel_vol = zooms[0] * zooms[1] * zooms[2]
|
| 103 |
-
|
| 104 |
-
# Vectorized counting
|
| 105 |
-
counts = np.bincount(labeled_array.ravel())
|
| 106 |
-
if len(counts) > 1:
|
| 107 |
-
cluster_volumes = counts[1:] * voxel_vol
|
| 108 |
-
else:
|
| 109 |
-
cluster_volumes = np.array([0.0])
|
| 110 |
|
| 111 |
-
#
|
| 112 |
-
#
|
| 113 |
-
|
| 114 |
-
valid_bleeds = cluster_volumes[(cluster_volumes > 5000) & (cluster_volumes < 400000)]
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
return True, max_bleed
|
| 119 |
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
print(f"Physics Check Failed: {e}")
|
| 124 |
-
return False, 0.0
|
| 125 |
|
| 126 |
def process_batch(self, file_list):
|
| 127 |
flair_path, swi_path, file_log = self.identify_sequences(file_list)
|
|
@@ -139,17 +167,17 @@ class GatekeeperService:
|
|
| 139 |
response["reasoning"].append("CRITICAL: No FLAIR sequence found.")
|
| 140 |
return response
|
| 141 |
|
| 142 |
-
# 1. Physics Check
|
| 143 |
if swi_path:
|
| 144 |
-
is_bleed, size = self.physics_check_hemorrhage(swi_path)
|
| 145 |
if is_bleed:
|
| 146 |
response["status"] = "COMPLETED"
|
| 147 |
response["triage_category"] = "HEMORRHAGE"
|
| 148 |
response["next_agent"] = "REPORT_AGENT"
|
| 149 |
-
response["reasoning"].append(f"Physics Rule:
|
| 150 |
return response
|
| 151 |
else:
|
| 152 |
-
response["reasoning"].append("Physics Rule: SWI scan clear (
|
| 153 |
|
| 154 |
# 2. AI Prediction
|
| 155 |
try:
|
|
@@ -195,7 +223,7 @@ class GatekeeperService:
|
|
| 195 |
return response
|
| 196 |
|
| 197 |
# ==========================================
|
| 198 |
-
# 3. INITIALIZATION
|
| 199 |
# ==========================================
|
| 200 |
MODEL_FILE = "gatekeeper_hybrid_trained.pth"
|
| 201 |
agent = GatekeeperService(MODEL_FILE)
|
|
|
|
| 79 |
|
| 80 |
def physics_check_hemorrhage(self, swi_path):
|
| 81 |
"""
|
| 82 |
+
ADVANCED: Uses Volume + Aspect Ratio (Shape) to distinguish
|
| 83 |
+
Hemorrhages (Blobs) from Veins (Tubes).
|
| 84 |
"""
|
| 85 |
+
if not swi_path: return False, 0.0, "N/A"
|
| 86 |
try:
|
| 87 |
img_obj = nib.load(swi_path)
|
| 88 |
vol = img_obj.get_fdata()
|
| 89 |
+
zooms = img_obj.header.get_zooms()
|
| 90 |
+
voxel_vol = zooms[0] * zooms[1] * zooms[2]
|
| 91 |
|
| 92 |
# Robust Normalization
|
| 93 |
p99 = np.percentile(vol, 99)
|
|
|
|
| 95 |
|
| 96 |
# Physics Rule
|
| 97 |
dark_mask = vol < 0.02
|
|
|
|
|
|
|
| 98 |
labeled_array, num_features = ndimage.label(dark_mask)
|
| 99 |
+
|
| 100 |
+
if num_features == 0: return False, 0.0, "Clean"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# Get Bounding Boxes for all dark spots
|
| 103 |
+
# (This is much faster than iterating pixels)
|
| 104 |
+
slices = ndimage.find_objects(labeled_array)
|
|
|
|
| 105 |
|
| 106 |
+
largest_bleed = 0.0
|
| 107 |
+
bleed_shape = "Unknown"
|
|
|
|
| 108 |
|
| 109 |
+
for i, slc in enumerate(slices):
|
| 110 |
+
if slc is None: continue
|
| 111 |
+
|
| 112 |
+
# 1. Calculate Exact Volume of this cluster
|
| 113 |
+
# We extract the cluster mask to count exact pixels
|
| 114 |
+
cluster_mask = (labeled_array[slc] == (i + 1))
|
| 115 |
+
size_mm3 = np.sum(cluster_mask) * voxel_vol
|
| 116 |
+
|
| 117 |
+
# 2. FILTER: Size (Lowered threshold to 1.5mL thanks to Shape check)
|
| 118 |
+
if 1500 < size_mm3 < 400000:
|
| 119 |
+
|
| 120 |
+
# 3. SHAPE ANALYSIS (Tubularity Check)
|
| 121 |
+
# Calculate dimensions of the bounding box
|
| 122 |
+
dz = (slc[0].stop - slc[0].start) * zooms[0]
|
| 123 |
+
dy = (slc[1].stop - slc[1].start) * zooms[1]
|
| 124 |
+
dx = (slc[2].stop - slc[2].start) * zooms[2]
|
| 125 |
+
|
| 126 |
+
dims = sorted([dx, dy, dz])
|
| 127 |
+
longest = dims[2]
|
| 128 |
+
shortest = dims[0] if dims[0] > 0 else 1.0
|
| 129 |
+
|
| 130 |
+
aspect_ratio = longest / shortest
|
| 131 |
+
|
| 132 |
+
# LOGIC:
|
| 133 |
+
# Veins are long tubes -> High Aspect Ratio (> 3.5)
|
| 134 |
+
# Bleeds are blobs -> Low Aspect Ratio (< 3.0)
|
| 135 |
+
|
| 136 |
+
if aspect_ratio < 3.5:
|
| 137 |
+
# It's a BLOB (Bleed)
|
| 138 |
+
if size_mm3 > largest_bleed:
|
| 139 |
+
largest_bleed = size_mm3
|
| 140 |
+
bleed_shape = f"Blob (Ratio {aspect_ratio:.1f})"
|
| 141 |
+
else:
|
| 142 |
+
# It's a TUBE (Vein) - Ignore
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
if largest_bleed > 0:
|
| 146 |
+
return True, largest_bleed, bleed_shape
|
| 147 |
+
|
| 148 |
+
return False, 0.0, "Veins/Noise Ignored"
|
| 149 |
|
| 150 |
except Exception as e:
|
| 151 |
print(f"Physics Check Failed: {e}")
|
| 152 |
+
return False, 0.0, "Error"
|
| 153 |
|
| 154 |
def process_batch(self, file_list):
|
| 155 |
flair_path, swi_path, file_log = self.identify_sequences(file_list)
|
|
|
|
| 167 |
response["reasoning"].append("CRITICAL: No FLAIR sequence found.")
|
| 168 |
return response
|
| 169 |
|
| 170 |
+
# 1. Physics Check (Shape-Aware)
|
| 171 |
if swi_path:
|
| 172 |
+
is_bleed, size, shape = self.physics_check_hemorrhage(swi_path)
|
| 173 |
if is_bleed:
|
| 174 |
response["status"] = "COMPLETED"
|
| 175 |
response["triage_category"] = "HEMORRHAGE"
|
| 176 |
response["next_agent"] = "REPORT_AGENT"
|
| 177 |
+
response["reasoning"].append(f"Physics Rule: {shape} signal void ({size:.0f}mm3) detected. Thrombolysis Contraindicated.")
|
| 178 |
return response
|
| 179 |
else:
|
| 180 |
+
response["reasoning"].append(f"Physics Rule: SWI scan clear. (Status: {shape}).")
|
| 181 |
|
| 182 |
# 2. AI Prediction
|
| 183 |
try:
|
|
|
|
| 223 |
return response
|
| 224 |
|
| 225 |
# ==========================================
|
| 226 |
+
# 3. INITIALIZATION
|
| 227 |
# ==========================================
|
| 228 |
MODEL_FILE = "gatekeeper_hybrid_trained.pth"
|
| 229 |
agent = GatekeeperService(MODEL_FILE)
|