-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_server.py
More file actions
882 lines (720 loc) · 30.2 KB
/
web_server.py
File metadata and controls
882 lines (720 loc) · 30.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
"""
Web Dashboard Server for Fall Detection System.
Video Sources: Intel RealSense D435i (RGB + Depth) or Webcam fallback.
Depth Features: RANSAC floor plane, height-above-floor, fall detection.
Endpoints:
- GET / : HTML dashboard
- GET /video : MJPEG RGB stream
- GET /depth : MJPEG Depth stream (colorized)
- WS /ws : Real-time data WebSocket
"""
import asyncio
import time
import threading
from datetime import datetime
from pathlib import Path
from typing import Optional, List, Dict, Generator
from dataclasses import dataclass
import cv2
import numpy as np
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
from pydantic import BaseModel
import uvicorn
# RealSense
try:
import pyrealsense2 as rs
REALSENSE_AVAILABLE = True
except ImportError:
REALSENSE_AVAILABLE = False
rs = None
import sys
sys.path.insert(0, str(Path(__file__).parent))
from core.inference_backend import create_inference_backend
from core.pose_estimator import PoseEstimator
from core.quality import QualityAssessor
from core.features import FeatureExtractor
from core.classifier import PoseClassifier, RiskState
from core.temporal import TemporalAnalyzer
from core.depth_processor import DepthProcessor, DepthFeatures, FallDetectionResult
from core.recording_manager import RecordingManager, get_scenarios, SCENARIOS
# ============================================================================
# FRAME DATA
# ============================================================================
@dataclass
class FrameData:
frame: np.ndarray # RGB/BGR
depth_raw: Optional[np.ndarray] # Depth in mm (uint16)
depth_colorized: Optional[np.ndarray] # Depth colorized (BGR)
width: int
height: int
timestamp: float
# ============================================================================
# CAMERA ROTATION UTILITIES
# ============================================================================
# Valid rotation angles
VALID_ROTATIONS = [0, 90, 180, 270]
# Global rotation setting (can be changed at runtime)
CAMERA_ROTATION = 0
def rotate_frame(frame: np.ndarray, angle: int) -> np.ndarray:
"""
Rotate a frame by the specified angle.
Args:
frame: Input frame (BGR or depth)
angle: Rotation angle (0, 90, 180, 270)
Returns:
Rotated frame
"""
if angle == 0 or frame is None:
return frame
elif angle == 90:
return cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
elif angle == 180:
return cv2.rotate(frame, cv2.ROTATE_180)
elif angle == 270:
return cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
else:
return frame
def apply_rotation_to_frame_data(fd: FrameData, angle: int) -> FrameData:
"""
Apply rotation to all frames in FrameData and update dimensions.
Args:
fd: Original FrameData
angle: Rotation angle (0, 90, 180, 270)
Returns:
New FrameData with rotated frames and corrected dimensions
"""
if angle == 0:
return fd
rotated_frame = rotate_frame(fd.frame, angle)
rotated_depth_raw = rotate_frame(fd.depth_raw, angle) if fd.depth_raw is not None else None
rotated_depth_colorized = rotate_frame(fd.depth_colorized, angle) if fd.depth_colorized is not None else None
# Update dimensions for 90/270 rotations
if angle in [90, 270]:
new_width = fd.height
new_height = fd.width
else:
new_width = fd.width
new_height = fd.height
return FrameData(
frame=rotated_frame,
depth_raw=rotated_depth_raw,
depth_colorized=rotated_depth_colorized,
width=new_width,
height=new_height,
timestamp=fd.timestamp
)
def set_camera_rotation(angle: int) -> bool:
"""
Set the global camera rotation angle.
Args:
angle: Rotation angle (must be 0, 90, 180, or 270)
Returns:
True if valid angle, False otherwise
"""
global CAMERA_ROTATION
if angle in VALID_ROTATIONS:
CAMERA_ROTATION = angle
print(f"[Camera] Rotation set to {angle}°")
return True
return False
def get_camera_rotation() -> int:
"""Get current camera rotation angle."""
return CAMERA_ROTATION
# ============================================================================
# REALSENSE SOURCE (RGB + DEPTH at correct resolutions)
# ============================================================================
class RealSenseSource:
"""
Intel RealSense D435i:
- Color: 1280x720 @30fps BGR
- Depth: 848x480 @30fps z16 (aligned to color)
"""
def __init__(self):
self.pipeline = None
self.align = None
self.colorizer = None
self.intrinsics = None
self._running = False
self.color_w, self.color_h = 1280, 720
self.depth_w, self.depth_h = 848, 480
def start(self) -> bool:
if not REALSENSE_AVAILABLE:
print("[RealSense] pyrealsense2 not available")
return False
try:
self.pipeline = rs.pipeline()
config = rs.config()
# Color at 1280x720
config.enable_stream(rs.stream.color, self.color_w, self.color_h, rs.format.bgr8, 30)
# Depth at 848x480 (better quality than 1280x720 for D435i)
config.enable_stream(rs.stream.depth, self.depth_w, self.depth_h, rs.format.z16, 30)
profile = self.pipeline.start(config)
# Align depth to color
self.align = rs.align(rs.stream.color)
# Colorizer
self.colorizer = rs.colorizer()
self.colorizer.set_option(rs.option.color_scheme, 0) # Jet
# Get depth intrinsics (after alignment, use color intrinsics)
color_profile = profile.get_stream(rs.stream.color)
self.intrinsics = color_profile.as_video_stream_profile().get_intrinsics()
device = profile.get_device()
name = device.get_info(rs.camera_info.name)
print(f"[RealSense] Connected: {name}")
print(f"[RealSense] Color: {self.color_w}x{self.color_h} | Depth: {self.depth_w}x{self.depth_h}")
self._running = True
return True
except Exception as e:
print(f"[RealSense] Failed: {e}")
return False
def get_frame(self) -> Optional[FrameData]:
if not self._running or not self.pipeline:
return None
try:
frames = self.pipeline.wait_for_frames(timeout_ms=1000)
aligned = self.align.process(frames)
color_frame = aligned.get_color_frame()
depth_frame = aligned.get_depth_frame()
if not color_frame:
return None
color = np.asanyarray(color_frame.get_data())
depth_raw = None
depth_colorized = None
if depth_frame:
depth_raw = np.asanyarray(depth_frame.get_data())
depth_colorized = np.asanyarray(self.colorizer.colorize(depth_frame).get_data())
return FrameData(
frame=color,
depth_raw=depth_raw,
depth_colorized=depth_colorized,
width=self.color_w,
height=self.color_h,
timestamp=time.time()
)
except Exception as e:
print(f"[RealSense] Frame error: {e}")
return None
def frames(self) -> Generator[FrameData, None, None]:
while self._running:
fd = self.get_frame()
if fd:
yield fd
def stop(self):
self._running = False
if self.pipeline:
try:
self.pipeline.stop()
except:
pass
print("[RealSense] Stopped")
class WebcamSource:
"""Fallback webcam (no depth)."""
def __init__(self, camera_index: int = 0):
self.camera_index = camera_index
self.cap = None
self._running = False
self.width, self.height = 1280, 720
def start(self) -> bool:
try:
self.cap = cv2.VideoCapture(self.camera_index)
if not self.cap.isOpened():
return False
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)
self.width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"[Webcam] {self.width}x{self.height}")
self._running = True
return True
except:
return False
def get_frame(self) -> Optional[FrameData]:
if not self._running or not self.cap:
return None
ret, frame = self.cap.read()
if not ret:
return None
return FrameData(
frame=frame,
depth_raw=None,
depth_colorized=None,
width=self.width,
height=self.height,
timestamp=time.time()
)
def frames(self) -> Generator[FrameData, None, None]:
while self._running:
fd = self.get_frame()
if fd:
yield fd
def stop(self):
self._running = False
if self.cap:
self.cap.release()
print("[Webcam] Stopped")
def create_video_source(use_realsense: bool = True, camera_index: int = 0):
if use_realsense:
src = RealSenseSource()
if src.start():
return src
print("[Source] RealSense failed, trying webcam...")
src = WebcamSource(camera_index)
if src.start():
return src
raise RuntimeError("No video source")
# ============================================================================
# GLOBAL STATE
# ============================================================================
class DetectionState:
def __init__(self):
self.lock = threading.Lock()
self.frame: Optional[np.ndarray] = None
self.depth: Optional[np.ndarray] = None
self.frame_width: int = 1280
self.frame_height: int = 720
self.keypoints: List[Dict] = []
self.state: str = "ANALYZING"
self.position: str = "unknown"
self.confidence: float = 0.0
self.risk_score: float = 0.0
self.quality_score: float = 0.0
self.fps: float = 0.0
self.log: List[Dict] = []
self.is_confirmed: bool = False
# Depth features (enhanced for dashboard)
self.hip_height_m: Optional[float] = None
self.floor_quality: float = 0.0
self.plane_confidence: float = 0.0
self.vertical_drop_m: float = 0.0
self.center_mass_height_m: Optional[float] = None # NEW
self.depth_mode: str = "none"
self.fall_reason: str = ""
self.consecutive_risk_frames: int = 0
self.depth_debug_info: str = "" # DEBUG: RANSAC status
# Hip height history for graph (last 60 frames)
self.hip_height_history: List[float] = [] # Smoothed
self.hip_height_raw_history: List[float] = [] # Raw
def update(self, **kwargs):
with self.lock:
for k, v in kwargs.items():
if hasattr(self, k):
setattr(self, k, v)
def get_json(self) -> Dict:
with self.lock:
return {
"state": self.state,
"position": self.position,
"confidence": round(self.confidence, 2),
"risk_score": round(self.risk_score, 2),
"quality_score": round(self.quality_score, 2),
"fps": round(self.fps, 1),
"frame_width": self.frame_width,
"frame_height": self.frame_height,
"keypoints": self.keypoints[:],
"log": self.log[:8],
# Depth features (enhanced)
"hip_height_m": round(self.hip_height_m, 3) if self.hip_height_m else None,
"floor_quality": round(self.floor_quality, 2),
"plane_confidence": round(self.plane_confidence, 2),
"vertical_drop_m": round(self.vertical_drop_m, 3),
"center_mass_height_m": round(self.center_mass_height_m, 3) if self.center_mass_height_m else None,
"depth_mode": self.depth_mode,
"fall_reason": self.fall_reason,
"consecutive_risk_frames": self.consecutive_risk_frames,
"depth_debug_info": self.depth_debug_info,
"hip_height_history": self.hip_height_history[-60:],
"hip_height_raw_history": self.hip_height_raw_history[-60:],
}
def get_rgb_jpeg(self) -> Optional[bytes]:
with self.lock:
if self.frame is None:
return None
_, jpg = cv2.imencode('.jpg', self.frame, [cv2.IMWRITE_JPEG_QUALITY, 85])
return jpg.tobytes()
def get_depth_jpeg(self) -> Optional[bytes]:
with self.lock:
if self.depth is None:
return None
_, jpg = cv2.imencode('.jpg', self.depth, [cv2.IMWRITE_JPEG_QUALITY, 85])
return jpg.tobytes()
STATE = DetectionState()
RECORDER = RecordingManager()
DEPTH_PROCESSOR: Optional[DepthProcessor] = None # Set in detection_loop
# ============================================================================
# DETECTION LOOP WITH DEPTH
# ============================================================================
def map_state_with_depth(
risk_state: RiskState,
is_confirmed: bool,
risk_score: float,
depth_features: DepthFeatures,
config: Dict
) -> tuple:
"""
Map state using depth evidence.
Returns: (state_str, is_confirmed, risk_score, reason)
"""
hip_thresh = config.get('hip_floor_thresh_m', 0.30)
persistence_thresh = config.get('persistence_confirm_s', 1.0)
drop_thresh = config.get('drop_thresh_m', 0.35)
vel_thresh = config.get('vel_thresh_mps', 0.60)
min_floor_quality = config.get('min_floor_quality', 0.55)
min_depth_ratio = config.get('min_depth_valid_ratio', 0.50)
sofa_min = config.get('sofa_min_height_m', 0.35)
sofa_max = config.get('sofa_max_height_m', 0.80)
reason_parts = []
# Check if depth is reliable
if depth_features.depth_mode == "none" or depth_features.floor_quality < min_floor_quality:
# Fallback: use 2D only, but cannot confirm RED
if risk_state == RiskState.NEEDS_HELP:
return ("ANALYZING", False, risk_score, "DEPTH_UNRELIABLE_FALLBACK")
elif risk_state == RiskState.OK:
return ("OK", is_confirmed, risk_score, "2D_OK")
else:
return ("ANALYZING", False, risk_score, "DEPTH_UNRELIABLE")
# Depth is reliable
hip_h = depth_features.hip_height_m
# Check if on elevated surface (sofa/bed = OK)
if hip_h is not None and sofa_min <= hip_h <= sofa_max:
if depth_features.vertical_drop_m < drop_thresh:
# On sofa/bed, no fall event
reason_parts.append("ON_ELEVATED_SURFACE")
return ("OK", True, 0.15, " + ".join(reason_parts))
# Check for floor contact
on_floor = False
if hip_h is not None and hip_h < hip_thresh:
if depth_features.floor_contact_time_s >= persistence_thresh:
on_floor = True
reason_parts.append("FLOOR_CONTACT_PERSISTENT")
# Check for drop event
had_drop = False
if depth_features.vertical_drop_m > drop_thresh:
reason_parts.append(f"DROP_EVENT({depth_features.vertical_drop_m:.2f}m)")
had_drop = True
if depth_features.vertical_velocity_mps > vel_thresh:
reason_parts.append(f"FAST_DESCENT({depth_features.vertical_velocity_mps:.2f}m/s)")
had_drop = True
# Decision
if on_floor:
if had_drop:
reason_parts.append("FALL_CONFIRMED")
return ("FALL", True, 0.95, " + ".join(reason_parts))
else:
reason_parts.append("FLOOR_POSTURE_NO_DROP")
return ("FALL", True, 0.85, " + ".join(reason_parts))
# Not on floor
if risk_state == RiskState.OK:
return ("OK", True, risk_score, "DEPTH_OK")
return ("ANALYZING", False, risk_score, "ANALYZING")
def detection_loop(use_realsense: bool = True, camera_index: int = 0):
"""Detection loop with depth integration."""
global STATE
source = create_video_source(use_realsense, camera_index)
# Config
config_dir = Path(__file__).parent / 'config'
thresholds_path = config_dir / 'thresholds.yaml'
# Load depth config
depth_config = {}
if thresholds_path.exists():
import yaml
with open(thresholds_path) as f:
cfg = yaml.safe_load(f)
if 'depth' in cfg:
depth_config = cfg['depth']
# Initialize depth processor
depth_processor = DepthProcessor(
camera_height_m=0.63,
sample_window=depth_config.get('depth_sample_win', 7),
min_floor_quality=depth_config.get('min_floor_quality', 0.55),
temporal_window_s=depth_config.get('temporal_window_s', 1.2),
)
# Set global reference for API access
global DEPTH_PROCESSOR
DEPTH_PROCESSOR = depth_processor
# Set intrinsics if RealSense
if isinstance(source, RealSenseSource) and source.intrinsics:
depth_processor.set_intrinsics(source.intrinsics)
# Detection components
backend = create_inference_backend('ultralytics', model_path='yolo11n-pose.pt')
backend.warmup()
estimator = PoseEstimator(backend=backend, config_path=str(thresholds_path) if thresholds_path.exists() else None)
quality_assessor = QualityAssessor(config_path=str(thresholds_path) if thresholds_path.exists() else None)
feature_extractor = FeatureExtractor(config_path=str(thresholds_path) if thresholds_path.exists() else None)
classifier = PoseClassifier(config_path=str(thresholds_path) if thresholds_path.exists() else None)
temporal = TemporalAnalyzer(config_path=str(thresholds_path) if thresholds_path.exists() else None)
log_buffer = []
last_state = None
fps_history = []
last_time = time.time()
print("[Detection] Loop started with depth processing")
try:
for fd in source.frames():
now = time.time()
dt = now - last_time
last_time = now
if dt > 0:
fps_history.append(1.0 / dt)
if len(fps_history) > 30:
fps_history.pop(0)
fps = sum(fps_history) / max(len(fps_history), 1)
# Apply camera rotation to all frames
fd = apply_rotation_to_frame_data(fd, CAMERA_ROTATION)
STATE.update(
frame=fd.frame.copy(),
depth=fd.depth_colorized.copy() if fd.depth_colorized is not None else None,
frame_width=fd.width,
frame_height=fd.height,
fps=fps
)
# Pose estimation
pose = estimator.estimate(fd.frame, frame_shape=(fd.height, fd.width))
if pose is None:
STATE.update(
keypoints=[],
state="ANALYZING",
position="unknown",
hip_height_m=None,
floor_quality=0.0,
depth_mode="none"
)
continue
# Keypoints JSON
kp_json = [
{"x": round(k[0], 1), "y": round(k[1], 1), "c": round(k[2], 2)} if k else {"x": 0, "y": 0, "c": 0}
for k in pose.keypoints
]
# 2D analysis (still needed for torso_angle and quality)
quality = quality_assessor.assess(pose.keypoints, pose.bbox, (fd.height, fd.width))
features = feature_extractor.extract(pose.keypoints, pose.bbox, (fd.height, fd.width))
# Get torso angle for depth classifier
torso_angle = features.torso_angle if features else 90.0
# SIMPLIFIED: Use depth-based classification when available
depth_features = DepthFeatures()
fall_result = FallDetectionResult()
if fd.depth_raw is not None:
# NEW API: returns both features and classification
depth_features, fall_result = depth_processor.process(
fd.depth_raw,
pose.keypoints,
fd.timestamp,
torso_angle=torso_angle
)
# Determine final state from simplified RANSAC-based rules
if depth_features.depth_mode == "plane":
# Use depth-based classification (SIMPLIFIED RULES)
if fall_result.risk_level == "FALL_CONFIRMED":
frontend_state = "FALL"
confirmed = True
elif fall_result.risk_level == "HIGH_RISK":
frontend_state = "ANALYZING"
confirmed = False
else:
frontend_state = "OK"
confirmed = True
reason = fall_result.reason
else:
# Fallback to 2D rules when no depth
classification = classifier.classify(features, quality, feature_extractor.is_extreme_geometry(features))
bbox_center = pose.get_bbox_center()
temporal_result = temporal.update(classification, quality.score, bbox_center, fd.timestamp)
if temporal_result.confirmed_state == RiskState.NEEDS_HELP:
frontend_state = "FALL"
confirmed = True
elif temporal_result.confirmed_state == RiskState.RISK:
frontend_state = "ANALYZING"
confirmed = False
else:
frontend_state = "OK"
confirmed = True
reason = "2D_FALLBACK"
# Log on state change
if frontend_state != last_state:
ts = datetime.now().strftime("%H:%M:%S")
if frontend_state == "OK":
log_buffer.insert(0, {"text": "Postura correcta", "level": "ok", "t": ts})
elif frontend_state == "FALL":
log_buffer.insert(0, {"text": f"CAÍDA: {reason}", "level": "danger", "t": ts})
else:
log_buffer.insert(0, {"text": f"Analizando: {reason}", "level": "warn", "t": ts})
log_buffer = log_buffer[:8]
last_state = frontend_state
STATE.update(
keypoints=kp_json,
state=frontend_state,
position=features.internal_pose if hasattr(features, 'internal_pose') else "unknown",
confidence=fall_result.confidence if fall_result else quality.score,
risk_score=fall_result.confidence if fall_result else 0.0,
quality_score=quality.score,
is_confirmed=confirmed,
log=log_buffer,
hip_height_m=depth_features.hip_height_m,
floor_quality=depth_features.floor_quality,
plane_confidence=depth_features.plane_confidence,
vertical_drop_m=depth_features.vertical_drop_m,
depth_mode=depth_features.depth_mode,
fall_reason=fall_result.reason if fall_result else "",
consecutive_risk_frames=fall_result.consecutive_risk_frames if fall_result else 0,
depth_debug_info=depth_features.debug_info if hasattr(depth_features, 'debug_info') else "",
center_mass_height_m=depth_features.center_mass_height_m,
hip_height_history=depth_processor.get_hip_height_history(),
hip_height_raw_history=depth_processor.get_hip_height_raw_history()
)
finally:
source.stop()
# ============================================================================
# FASTAPI
# ============================================================================
app = FastAPI(title="Fall Detection")
@app.get("/", response_class=HTMLResponse)
async def index():
html_path = Path(__file__).parent / "web" / "index.html"
if html_path.exists():
return HTMLResponse(content=html_path.read_text(encoding="utf-8"))
return HTMLResponse("<h1>index.html not found</h1>", status_code=404)
@app.get("/video")
async def video_feed():
def gen():
while True:
jpg = STATE.get_rgb_jpeg()
if jpg:
yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + jpg + b'\r\n'
time.sleep(0.033)
return StreamingResponse(gen(), media_type="multipart/x-mixed-replace; boundary=frame")
@app.get("/depth")
async def depth_feed():
def gen():
while True:
jpg = STATE.get_depth_jpeg()
if jpg:
yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + jpg + b'\r\n'
time.sleep(0.033)
return StreamingResponse(gen(), media_type="multipart/x-mixed-replace; boundary=frame")
@app.websocket("/ws")
async def ws(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = STATE.get_json()
# Include recording status and camera rotation
data["recording"] = RECORDER.get_status()
data["camera_rotation"] = get_camera_rotation()
await websocket.send_json(data)
await asyncio.sleep(0.066)
except WebSocketDisconnect:
pass
# ============================================================================
# RECORDING API
# ============================================================================
class RecordingStartRequest(BaseModel):
scenario: str
notes: str = ""
@app.get("/api/recording/scenarios")
async def get_recording_scenarios():
"""Get available recording scenarios."""
return JSONResponse(content={"scenarios": SCENARIOS})
@app.get("/api/recording/status")
async def get_recording_status():
"""Get current recording status."""
return JSONResponse(content=RECORDER.get_status())
@app.post("/api/recording/start")
async def start_recording(request: RecordingStartRequest):
"""Start recording a .bag file."""
result = RECORDER.start_recording(
scenario=request.scenario,
notes=request.notes
)
status_code = 200 if result.get("success") else 400
return JSONResponse(content=result, status_code=status_code)
@app.post("/api/recording/stop")
async def stop_recording():
"""Stop the current recording."""
result = RECORDER.stop_recording()
status_code = 200 if result.get("success") else 400
return JSONResponse(content=result, status_code=status_code)
@app.post("/api/floor/reset")
async def reset_floor_plane():
"""Reset floor plane calibration."""
global DEPTH_PROCESSOR
if DEPTH_PROCESSOR is None:
return JSONResponse(
content={"success": False, "error": "Depth processor not initialized"},
status_code=400
)
DEPTH_PROCESSOR.reset_floor_plane()
return JSONResponse(content={"success": True, "message": "Floor plane reset"})
@app.get("/api/floor/status")
async def get_floor_status():
"""Get floor tracking status."""
global DEPTH_PROCESSOR
if DEPTH_PROCESSOR is None:
return JSONResponse(content={"has_base_plane": False, "stable_frames": 0})
return JSONResponse(content=DEPTH_PROCESSOR.get_floor_status())
# ============================================================================
# CAMERA ROTATION API
# ============================================================================
class RotationRequest(BaseModel):
angle: int
@app.get("/api/camera/rotation")
async def get_rotation():
"""Get current camera rotation angle."""
return JSONResponse(content={
"angle": get_camera_rotation(),
"valid_angles": VALID_ROTATIONS
})
@app.post("/api/camera/rotation")
async def set_rotation(request: RotationRequest):
"""Set camera rotation angle (0, 90, 180, 270)."""
if set_camera_rotation(request.angle):
return JSONResponse(content={
"success": True,
"angle": request.angle
})
return JSONResponse(
content={"success": False, "error": f"Invalid angle. Must be one of {VALID_ROTATIONS}"},
status_code=400
)
# ============================================================================
# MAIN
# ============================================================================
def main():
import argparse
import signal
import sys
parser = argparse.ArgumentParser()
parser.add_argument("--no-realsense", action="store_true")
parser.add_argument("--camera", type=int, default=0)
parser.add_argument("--port", type=int, default=8000)
args = parser.parse_args()
# Start detection in background thread
detection_thread = threading.Thread(
target=detection_loop,
args=(not args.no_realsense, args.camera),
daemon=True
)
detection_thread.start()
print(f"\n{'='*50}")
print("Fall Detection Web Dashboard")
print(f"{'='*50}")
print(f"Dashboard: http://localhost:{args.port}")
print(f"RGB: http://localhost:{args.port}/video")
print(f"Depth: http://localhost:{args.port}/depth")
print(f"{'='*50}")
print("Press Ctrl+C to stop\n")
# Create uvicorn server with config
config = uvicorn.Config(app, host="0.0.0.0", port=args.port, log_level="warning")
server = uvicorn.Server(config)
# Run server in a separate thread so main thread can catch Ctrl+C
server_thread = threading.Thread(target=server.run, daemon=True)
server_thread.start()
# Wait for Ctrl+C in main thread
try:
while server_thread.is_alive():
server_thread.join(timeout=0.5)
except KeyboardInterrupt:
print("\n[Server] Shutting down...")
# Force exit to ensure all threads stop
print("[Server] Stopped")
import os
os._exit(0)
if __name__ == "__main__":
main()