asrcoddeploy commited on
Commit
996d929
·
verified ·
1 Parent(s): eab8672

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import torch
4
+ import torch.nn as nn
5
+ import numpy as np
6
+ from torchvision import transforms
7
+ import os
8
+ import time
9
+
10
+ # --- 1. MODEL ARCHITECTURE ---
11
+ class LDobjModel(nn.Module):
12
+ def __init__(self):
13
+ super(LDobjModel, self).__init__()
14
+ self.enc1 = self.conv_block(3, 16); self.pool1 = nn.MaxPool2d(2)
15
+ self.enc2 = self.conv_block(16, 32); self.pool2 = nn.MaxPool2d(2)
16
+ self.bottleneck = self.conv_block(32, 64)
17
+ self.up1 = nn.ConvTranspose2d(64, 32, 2, 2)
18
+ self.dec1 = self.conv_block(64, 32)
19
+ self.up2 = nn.ConvTranspose2d(32, 16, 2, 2)
20
+ self.dec2 = self.conv_block(32, 16)
21
+ self.final = nn.Sequential(nn.Conv2d(16, 1, 1), nn.Sigmoid())
22
+
23
+ def conv_block(self, in_c, out_c):
24
+ return nn.Sequential(nn.Conv2d(in_c, out_c, 3, 1, 1), nn.ReLU(),
25
+ nn.Conv2d(out_c, out_c, 3, 1, 1), nn.ReLU())
26
+
27
+ def forward(self, x):
28
+ e1 = self.enc1(x); e2 = self.enc2(self.pool1(e1))
29
+ b = self.bottleneck(self.pool2(e2))
30
+ d1 = torch.cat((e2, self.up1(b)), dim=1); d1 = self.dec1(d1)
31
+ d2 = torch.cat((e1, self.up2(d1)), dim=1); d2 = self.dec2(d2)
32
+ return self.final(d2)
33
+
34
+ # --- 2. INITIALIZATION ---
35
+ device = torch.device('cpu')
36
+ model = LDobjModel().to(device)
37
+ if os.path.exists('LDobj_weights.pth'):
38
+ model.load_state_dict(torch.load('LDobj_weights.pth', map_location=device))
39
+ model.eval()
40
+
41
+ transform = transforms.Compose([
42
+ transforms.ToPILImage(),
43
+ transforms.Resize((288, 800)),
44
+ transforms.ToTensor()
45
+ ])
46
+
47
+ # --- 3. ROBUST PROCESSING LOGIC (Temporal Smoothing) ---
48
+ def analyze_video(input_video_path, sensitivity, required_frames, progress=gr.Progress()):
49
+ if not input_video_path:
50
+ return None, "⚠️ Please upload a video first."
51
+
52
+ start_time = time.time()
53
+
54
+ cap = cv2.VideoCapture(input_video_path)
55
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
56
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
57
+ fps = cap.get(cv2.CAP_PROP_FPS)
58
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
59
+
60
+ raw_output = "temp_raw.mp4"
61
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
62
+ out = cv2.VideoWriter(raw_output, fourcc, fps, (width, height))
63
+ morph_kernel = np.ones((5, 5), np.uint8)
64
+
65
+ drift_threshold = width * (sensitivity / 100.0)
66
+ frame_count = 0
67
+ alerts_triggered = 0
68
+
69
+ # NEW: Temporal variables to track sustained drift
70
+ consecutive_drift_frames = 0
71
+ is_currently_alerting = False
72
+
73
+ while cap.isOpened():
74
+ ret, frame = cap.read()
75
+ if not ret: break
76
+
77
+ frame_count += 1
78
+ if frame_count % 5 == 0:
79
+ progress(frame_count / total_frames, desc=f"Analyzing Frame {frame_count}/{total_frames}")
80
+
81
+ # AI Prediction
82
+ input_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
83
+ img_tensor = transform(input_img).unsqueeze(0).to(device)
84
+ with torch.no_grad():
85
+ pred = model(img_tensor).squeeze().numpy()
86
+
87
+ # Mask Cleaning
88
+ mask = (pred > 0.5).astype(np.uint8)
89
+ mask_full = cv2.resize(mask, (width, height), interpolation=cv2.INTER_NEAREST)
90
+ mask_full = cv2.morphologyEx(mask_full, cv2.MORPH_OPEN, morph_kernel)
91
+
92
+ # ---------------------------------------------------------
93
+ # NEW DEPARTURE LOGIC: Must be sustained to trigger
94
+ # ---------------------------------------------------------
95
+ moments = cv2.moments(mask_full[int(height*0.75):, :])
96
+ detected_drift_this_frame = False
97
+
98
+ if moments["m00"] > 0:
99
+ cx = int(moments["m10"] / moments["m00"])
100
+ if abs(cx - width // 2) > drift_threshold:
101
+ detected_drift_this_frame = True
102
+
103
+ # Temporal Smoothing Counters
104
+ if detected_drift_this_frame:
105
+ consecutive_drift_frames += 1
106
+ else:
107
+ # If the car centers itself, decrease the counter (cool down)
108
+ consecutive_drift_frames = max(0, consecutive_drift_frames - 2)
109
+
110
+ # Trigger the actual UI Alert ONLY if it meets the required frame count
111
+ if consecutive_drift_frames >= required_frames:
112
+ is_currently_alerting = True
113
+ elif consecutive_drift_frames == 0:
114
+ is_currently_alerting = False
115
+
116
+ # Draw the alert
117
+ if is_currently_alerting:
118
+ alerts_triggered += 1
119
+ overlay = frame.copy()
120
+ overlay[mask_full > 0] = (0, 0, 255)
121
+ frame = cv2.addWeighted(frame, 0.7, overlay, 0.3, 0)
122
+
123
+ # Serious UI Overlay
124
+ cv2.rectangle(frame, (0, 0), (width, 120), (0, 0, 0), -1)
125
+ cv2.putText(frame, "CRITICAL: SUSTAINED DEPARTURE", (30, 80),
126
+ cv2.FONT_HERSHEY_DUPLEX, 1.5, (0, 0, 255), 3)
127
+ # Draw a visual warning border around the whole video
128
+ cv2.rectangle(frame, (0, 0), (width, height), (0, 0, 255), 10)
129
+
130
+ out.write(frame)
131
+
132
+ cap.release()
133
+ out.release()
134
+
135
+ progress(0.95, desc="Optimizing Video for Web...")
136
+ web_output = "ldobj_final.mp4"
137
+ os.system(f"ffmpeg -y -i {raw_output} -c:v libx264 -preset fast -pix_fmt yuv420p -movflags +faststart {web_output}")
138
+
139
+ process_time = time.time() - start_time
140
+ avg_fps = frame_count / process_time if process_time > 0 else 0
141
+
142
+ telemetry_report = (
143
+ f"✅ Analysis Complete\n"
144
+ f"------------------------\n"
145
+ f"⏱️ Processing Time: {process_time:.1f} sec\n"
146
+ f"🚀 AI Speed: {avg_fps:.1f} FPS\n"
147
+ f"🚨 Critical Alert Frames: {alerts_triggered}"
148
+ )
149
+
150
+ return web_output, telemetry_report
151
+
152
+ # --- 4. ULTIMATE FRONTEND DESIGN ---
153
+ custom_css = """
154
+ #video-in, #video-out { min-height: 450px; border-radius: 10px; border: 1px solid #333; }
155
+ .gradio-container { max-width: 1200px !important; margin: auto; }
156
+ .glow-title { color: #ff4a4a; text-shadow: 0px 0px 15px rgba(255, 74, 74, 0.5); text-align: center; margin-bottom: 5px; }
157
+ .sub-title { text-align: center; color: #888; margin-top: 0px; margin-bottom: 30px; }
158
+ """
159
+
160
+ with gr.Blocks() as app:
161
+ gr.HTML("<h1 class='glow-title'>🛡️ LDobj ADAS Command Center</h1>")
162
+ gr.HTML("<h3 class='sub-title'>Advanced Driver Assistance System • Neural Lane Tracking</h3>")
163
+
164
+ with gr.Group():
165
+ with gr.Row():
166
+ with gr.Column(scale=4):
167
+ gr.Markdown("### 1. Input Source")
168
+ video_in = gr.Video(label="Dashcam Feed", elem_id="video-in")
169
+
170
+ gr.Markdown("### 2. Serious Alert Parameters")
171
+ sensitivity_slider = gr.Slider(
172
+ minimum=5, maximum=30, value=12, step=1,
173
+ label="Drift Distance Threshold (%)",
174
+ info="How far off-center the car must be before it's considered drifting."
175
+ )
176
+ frames_slider = gr.Slider(
177
+ minimum=1, maximum=30, value=7, step=1,
178
+ label="Sustained Drift Timer (Frames)",
179
+ info="How many consecutive frames the car must be drifting before triggering the CRITICAL alert (prevents glitchy flashing)."
180
+ )
181
+
182
+ run_btn = gr.Button("INITIALIZE SCAN", variant="primary", size="lg")
183
+
184
+ with gr.Column(scale=5):
185
+ gr.Markdown("### Live Output Feed")
186
+ video_out = gr.Video(label="LDobj Processed Feed", interactive=False, autoplay=True, elem_id="video-out")
187
+
188
+ gr.Markdown("### System Telemetry")
189
+ telemetry_out = gr.Textbox(label="Analytics Console", lines=6, interactive=False)
190
+
191
+ run_btn.click(
192
+ fn=analyze_video,
193
+ inputs=[video_in, sensitivity_slider, frames_slider],
194
+ outputs=[video_out, telemetry_out]
195
+ )
196
+
197
+ if __name__ == "__main__":
198
+ app.launch(
199
+ theme=gr.themes.Glass(primary_hue="red"),
200
+ css=custom_css,
201
+ footer_links=[]
202
+ )