jani2904 commited on
Commit
36cb04c
·
verified ·
1 Parent(s): f6970eb

Upload 3 files

Browse files
Files changed (3) hide show
  1. NAION_Risk_Unet_v1.pth +3 -0
  2. naion_app.py +149 -0
  3. requirements.txt +5 -0
NAION_Risk_Unet_v1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a772fd6f6d3861f9945bd77b4416b5ee164659241fa83287711494f96afc5212
3
+ size 97923079
naion_app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import cv2
4
+ import numpy as np
5
+ import segmentation_models_pytorch as smp
6
+ from PIL import Image
7
+
8
+ # --- 1. MEASUREMENT ENGINE ---
9
+
10
+ def calculate_isnt_rims(mask_disc, mask_cup):
11
+ """Calculates superior rim thickness and vCDR."""
12
+ disc_coords = np.argwhere(mask_disc)
13
+ if len(disc_coords) == 0:
14
+ return 0, 0, 0
15
+
16
+ center_x = int(np.mean(disc_coords[:, 1]))
17
+
18
+ # Get vertical bounds of Disc
19
+ disc_y_coords = disc_coords[disc_coords[:, 1] == center_x][:, 0]
20
+ if len(disc_y_coords) == 0:
21
+ return 0, 0, 0
22
+ disc_top = np.min(disc_y_coords)
23
+ disc_bottom = np.max(disc_y_coords)
24
+ disc_height = disc_bottom - disc_top
25
+
26
+ # Get vertical bounds of Cup
27
+ cup_coords = np.argwhere(mask_cup)
28
+ if len(cup_coords) == 0:
29
+ center_y = int(np.mean(disc_coords[:, 0]))
30
+ rim_s = center_y - disc_top
31
+ return max(0, rim_s), 0.0, disc_height
32
+
33
+ cup_y_coords = cup_coords[cup_coords[:, 1] == center_x][:, 0]
34
+ if len(cup_y_coords) == 0:
35
+ center_y = int(np.mean(disc_coords[:, 0]))
36
+ rim_s = center_y - disc_top
37
+ return max(0, rim_s), 0.0, disc_height
38
+
39
+ cup_top = np.min(cup_y_coords)
40
+ cup_bottom = np.max(cup_y_coords)
41
+ rim_s = cup_top - disc_top
42
+ v_cdr_val = (cup_bottom - cup_top) / disc_height if disc_height > 0 else 0
43
+
44
+ return max(0, rim_s), v_cdr_val, disc_height
45
+
46
+ def calculate_vessel_density(image_rgb, mask_disc):
47
+ """Calculates vessel density in the superior quadrant."""
48
+ gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
49
+ vessels = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
50
+ cv2.THRESH_BINARY_INV, 11, 2)
51
+
52
+ disc_coords = np.argwhere(mask_disc)
53
+ if len(disc_coords) == 0: return 0
54
+
55
+ min_y, max_y = np.min(disc_coords[:, 0]), np.max(disc_coords[:, 0])
56
+ mid_y = (min_y + max_y) // 2
57
+
58
+ sup_mask = np.zeros_like(mask_disc)
59
+ sup_mask[min_y:mid_y, :] = 1
60
+ target_area = cv2.bitwise_and(mask_disc, sup_mask)
61
+
62
+ vessel_pixels = np.sum(cv2.bitwise_and(vessels, vessels, mask=target_area) > 0)
63
+ total_pixels = np.sum(target_area)
64
+
65
+ return (vessel_pixels / total_pixels) if total_pixels > 0 else 0
66
+
67
+ # --- 2. UI SETUP & MODEL LOADING ---
68
+
69
+ st.set_page_config(page_title="NAION AI Support", layout="wide")
70
+ st.title("👁️ NAION-Risk: AI Decision Support")
71
+ st.markdown("Automated anatomical and vascular profiling for Optic Nerve Head analysis.")
72
+
73
+ @st.cache_resource
74
+ def load_ai_model():
75
+ model = smp.Unet(encoder_name="resnet34", encoder_weights=None, in_channels=3, classes=2)
76
+ model.load_state_dict(torch.load("NAION_Risk_Unet_v1.pth", map_location='cpu'))
77
+ model.eval()
78
+ return model
79
+
80
+ model = load_ai_model()
81
+
82
+ # --- 3. SIDEBAR & FILE UPLOAD ---
83
+
84
+ uploaded_file = st.sidebar.file_uploader("Upload Fundus Image", type=['jpg', 'png', 'jpeg'])
85
+
86
+ if uploaded_file is not None:
87
+ # A. IMAGE LOADING
88
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
89
+ original_img = cv2.imdecode(file_bytes, 1)
90
+ original_rgb = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
91
+ h, w = original_rgb.shape[:2]
92
+
93
+ # B. AI INFERENCE
94
+ input_img = cv2.resize(original_rgb, (256, 256))
95
+ input_tensor = torch.from_numpy(input_img).transpose(0, 2).transpose(1, 2).float().unsqueeze(0) / 255.0
96
+
97
+ with torch.no_grad():
98
+ output = torch.sigmoid(model(input_tensor)).squeeze().cpu().numpy()
99
+ mask_disc_raw = (output[0] > 0.3).astype(np.uint8)
100
+ mask_cup_raw = (output[1] > 0.1).astype(np.uint8)
101
+
102
+ # C. RESCALE MASKS
103
+ mask_disc = cv2.resize(mask_disc_raw, (w, h), interpolation=cv2.INTER_NEAREST)
104
+ mask_cup = cv2.resize(mask_cup_raw, (w, h), interpolation=cv2.INTER_NEAREST)
105
+
106
+ # D. ANALYTICS
107
+ rim_s_val, vcdr_calc, disc_h = calculate_isnt_rims(mask_disc, mask_cup)
108
+ density_val = calculate_vessel_density(original_rgb, mask_disc)
109
+
110
+ # E. DASHBOARD DISPLAY
111
+ col1, col2 = st.columns(2)
112
+ with col1:
113
+ st.subheader("Clinical Source")
114
+ st.image(original_rgb, use_container_width=True)
115
+ with col2:
116
+ st.subheader("AI Analysis Overlay")
117
+ if np.sum(mask_disc) > 0:
118
+ vis_mask = np.zeros((h, w, 3), dtype=np.uint8)
119
+ vis_mask[mask_disc == 1] = [0, 255, 0] # Green Disc
120
+ vis_mask[mask_cup == 1] = [255, 0, 0] # Red Cup
121
+ blended = cv2.addWeighted(original_rgb, 0.7, vis_mask, 0.3, 0)
122
+ st.image(blended, caption="AI Detection (Green=Disc, Red=Cup)", use_container_width=True)
123
+ else:
124
+ st.error("⚠️ No Disc Detected.")
125
+
126
+ # F. LOGICAL RISK INTERPRETATION
127
+ st.markdown("---")
128
+ st.subheader("Automated Risk Metrics")
129
+
130
+ # NEW LOGIC: Only High Risk if Rim is thick AND Cup is small (< 0.2)
131
+ # We also use a percentage (Rim/Disc Height) to make it scale-independent
132
+ rim_ratio = (rim_s_val / disc_h) if disc_h > 0 else 0
133
+
134
+ is_high_risk = (rim_ratio > 0.15) and (vcdr_calc < 0.2)
135
+ risk_label = "High Risk (Crowded)" if is_high_risk else "Normal (Buffered)"
136
+ risk_color = "inverse" if is_high_risk else "normal"
137
+
138
+ m1, m2, m3 = st.columns(3)
139
+ m1.metric("Superior Rim Thickness", f"{int(rim_s_val)} px", delta=risk_label, delta_color=risk_color)
140
+ m2.metric("vCDR", f"{vcdr_calc:.2f}")
141
+ m3.metric("Superior Vessel Density", f"{density_val:.1%}")
142
+
143
+ st.markdown("### Clinical Interpretation")
144
+ if vcdr_calc == 0:
145
+ st.error("**Finding: Cupless Phenotype.** This indicates 'Mechanical Collapse' where vascular stress is immobilized by axonal crowding.")
146
+ elif vcdr_calc <= 0.2:
147
+ st.warning("**Finding: Transition Zone.** The patient is at the 'Vascular Cliff' where perfusion drops rapidly.")
148
+ else:
149
+ st.success("**Finding: Healthy Architecture.** Sufficient cup space observed to buffer mechanical pressure.")
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit
2
+ torch
3
+ torchvision
4
+ opencv-python
5
+ segmentation-models-pytorch