vincenzo-afk/crowd-detection
概要
Experimental Python and FastAPI crowd-monitoring system for person detection, density analysis, risk scoring, and incident alerting
開発ツールできること
- Person detection with Ultralytics YOLO and configurable confidence and Intersection over Union (IoU) thresholds.
- Track IDs, trajectories, count, occupancy percentage, grid-based density, and density heatmaps.
- Movement speed, direction entropy, compression, pressure-wave, social-distance, cluster, and restricted-zone analysis.
- Alert levels of SAFE, WARNING, DANGER, and CRITICAL, with cooldown handling in the alert engine.
計測したスター増加
- 24時間
- 0
- 7日間
- 0
- 15日間
- 履歴を収集中
- 1か月
- 履歴を収集中
期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。
README.md
オリジナルcrowd-detection
A Python and FastAPI application for real-time crowd observation, density analysis, risk scoring, and incident alerting.
Quick links: Getting started · Usage · API reference · Contributing · Report a bug
Table of Contents
- About the project
- Tech stack
- Getting started
- Usage
- API reference
- Project structure
- Features and roadmap
- Testing
- Deployment
- Contributing
- Security
- License
- Acknowledgments
- Contact and support
About the project
crowd-detection is an experimental crowd-monitoring application. The main process captures frames from a webcam, video file, or Real Time Streaming Protocol (RTSP) source, then passes them through detection, tracking, density, movement, alert, prediction, and dashboard stages. A simulation mode provides synthetic crowd states when a camera is unavailable.
The runtime is presented in the source code as CrowdSafe AI. It exposes a local FastAPI dashboard with an annotated Motion JPEG (MJPEG) stream, live WebSocket metrics, REST endpoints, and a mobile-oriented view. Runtime events are written to JSON Lines (JSONL) and SQLite, while metric history can be exported as CSV.
Safety notice: This repository is an experimental software project, not a certified life-safety system. Its risk scores, alerts, privacy behavior, and performance must be independently validated before any operational or emergency-use deployment.
Key capabilities
- Person detection with Ultralytics YOLO and configurable confidence and Intersection over Union (IoU) thresholds.
- Track IDs, trajectories, count, occupancy percentage, grid-based density, and density heatmaps.
- Movement speed, direction entropy, compression, pressure-wave, social-distance, cluster, and restricted-zone analysis.
- Alert levels of
SAFE,WARNING,DANGER, andCRITICAL, with cooldown handling in the alert engine. - Rolling risk prediction using an LSTM-backed predictor with a trend-based fallback when model inference is unavailable.
- Simulation scenarios for normal, building, dense, and panic crowd behavior.
- Optional notifications through Twilio SMS, SMTP email, and a webhook. Without credentials, SMS and email delivery are simulated by the notification pipeline.
- Incident clip recording, JSONL event logs, SQLite persistence, incident timelines, and CSV metric export.
- A local dashboard,
/mobiledashboard view, MJPEG stream, WebSocket updates, and camera-switching endpoint.
Architecture overview
flowchart LR
A[Webcam / video file / RTSP] --> B[OpenCV capture]
S[Simulation mode] --> C[Frame and detection input]
B --> C
C --> D[YOLO person detector]
D --> E[MultiTracker]
E --> F[Density and heatmaps]
E --> G[Movement and behavior analysis]
E --> H[Social distance and zone checks]
F --> I[Alert engine]
G --> I
H --> I
I --> J[Risk predictor and explainability]
I --> K[Notifications and voice alerts]
F --> L[HUD and dashboard state]
J --> L
L --> M[FastAPI REST / WebSocket / MJPEG]
I --> N[JSONL and SQLite logger]
I --> O[Incident recorder]
Tech stack
| Area | Implemented technology | Evidence |
|---|---|---|
| Language | Python; the repository does not include a packaging manifest or a pinned interpreter file | main.py, requirements.txt |
| Computer vision | OpenCV and NumPy | requirements.txt, main.py |
| Detection | Ultralytics YOLO, configured by default for yolov8n.pt and person class 0 |
config/settings.py, src/detector.py |
| Tracking and analysis | SciPy, FilterPy, custom tracking, density, movement, cluster, zone, and behavior modules | src/, requirements.txt |
| Web server | FastAPI, Uvicorn, WebSockets, Jinja2 | web/server.py, requirements.txt |
| Persistence | SQLite and JSONL session logs | src/logger.py |
| Reporting | CSV export, ReportLab, and fpdf2 dependencies | src/logger.py, requirements.txt |
| Audio | Pygame and pyttsx3; PyAudio is listed for acoustic input | requirements.txt, src/acoustic.py |
| Notifications | Twilio, SMTP, and webhook requests | src/notifications.py, config/settings.py |
The dependency file uses minimum-version specifiers rather than a lockfile. Exact resolved versions therefore depend on the Python environment and package index used during installation.
Getting started
Prerequisites
You need Python 3.9 or newer, a working C/C++ build environment for any dependency that cannot use a prebuilt wheel, and sufficient disk space for Python packages and the YOLO model. A webcam is required for live mode but not for simulation mode. The application opens a local HTTP server on port 8000 by default.
The repository currently has no Dockerfile, compose file, database migration system, or cloud deployment configuration. The supported setup path is the included shell script and Python virtual environment.
Installation
Clone the repository and run the full setup script:
git clone https://github.com/vincenzo-afk/crowd-detection.git
cd crowd-detection
chmod +x setup.sh run.sh start.sh install-quick.sh
./setup.sh
setup.sh creates venv/, installs requirements.txt, creates the runtime directories, and attempts to place yolov8n.pt in models/. If the model download cannot complete during setup, Ultralytics may attempt to download it on first use; otherwise the detector falls back to returning no detections.
For a smaller dependency set, the repository also includes install-quick.sh. It is useful for trying the simulation path, but it does not install every dependency listed in requirements.txt and is not a substitute for the full setup when all modules are required.
Environment configuration
Copy the template only when you need outbound notifications:
cp .env.example .env
The application reads the following variables. Empty notification credentials are valid; the notification pipeline then simulates SMS and email delivery instead of sending them.
| Variable | Purpose | Default |
|---|---|---|
TWILIO_ACCOUNT_SID |
Twilio account identifier | Empty |
TWILIO_AUTH_TOKEN |
Twilio authentication token | Empty |
TWILIO_FROM |
Twilio sender number | Empty |
ALERT_PHONES |
Comma-separated SMS recipients | Empty |
SMTP_HOST |
SMTP server hostname | smtp.gmail.com |
SMTP_PORT |
SMTP server port | 587 |
SMTP_USER |
SMTP username | Empty |
SMTP_PASS |
SMTP password or app password | Empty |
ALERT_EMAILS |
Comma-separated email recipients | Empty |
WEBHOOK_URL |
Optional webhook destination | Empty |
Do not commit .env, API keys, SMTP passwords, model files, databases, logs, recordings, or generated reports. The repository .gitignore excludes these runtime artifacts.
Configuration file
Runtime defaults and thresholds are centralized in config/settings.py. The most important settings include:
| Setting | Default | Meaning |
|---|---|---|
DEFAULT_SOURCE |
0 |
Default OpenCV camera index |
TARGET_FPS |
30 |
Target processing rate |
FRAME_WIDTH / FRAME_HEIGHT |
1280 / 720 |
Default frame dimensions |
YOLO_MODEL |
yolov8n.pt |
Detector model name |
YOLO_CONFIDENCE |
0.40 |
Minimum detection confidence |
MAX_CAPACITY |
100 |
Occupancy baseline |
DENSITY_GRID_ROWS / DENSITY_GRID_COLS |
4 / 6 |
Density grid dimensions |
ALERT_COOLDOWN_SECONDS |
10 |
Minimum interval between repeated alerts |
LSTM_FORECAST_STEPS |
[30, 60, 120] |
Forecast horizons in seconds |
API_HOST / API_PORT |
0.0.0.0 / 8000 |
Dashboard bind address and port |
Change thresholds only after validating their meaning for the camera geometry, venue, and operating conditions. Several measurements are normalized or pixel-based rather than calibrated physical-world units.
Usage
Start the application
The main entry point is main.py. The shell launcher activates venv/ automatically when it exists:
# Live webcam, using camera index 0 by default
./run.sh
# Synthetic crowd simulation; no camera is needed
./run.sh --sim
# A different camera index, a video file, or an RTSP URL
./run.sh --source 1
./run.sh --source path/to/video.mp4
./run.sh --source rtsp://camera-host/stream
# Run the dashboard and pipeline without an OpenCV window
./run.sh --sim --no-window
# Bind the dashboard to another port
./run.sh --sim --port 8080
The equivalent Windows-oriented launcher is:
python launch.py --sim
The command-line flags supported by main.py are:
| Flag | Description |
|---|---|
--source VALUE |
Camera index, video path, or RTSP URL. Numeric values are converted to integers. |
--sim |
Use the synthetic crowd simulator instead of a camera source. |
--no-window |
Disable the local OpenCV window and leave the web dashboard available. |
--port PORT |
Override the dashboard port; the default is 8000. |
If a live source cannot be opened, the pipeline prints a warning and switches to simulation mode. In simulation mode, the local OpenCV window accepts 1 for normal, 2 for building, 3 for dense, and 4 for panic scenarios. The q key quits the window, h hides it, and s toggles simulation mode.
Dashboard
After startup, open http://localhost:8000, or use the port supplied to --port. The dashboard renders the current annotated frame, metrics, risk score, predictions, alerts, and controls. The mobile-oriented page is available at /mobile.
The dashboard is intended for local or trusted-network use. The server does not implement authentication, authorization, rate limiting, or TLS in this repository, so do not expose it directly to the public internet without adding an appropriate security boundary.
Runtime outputs
The application creates these paths relative to the repository root:
| Path | Contents |
|---|---|
models/ |
Local model files such as yolov8n.pt |
logs/ |
Session JSONL files and exported metric CSV files |
recordings/ |
Incident MP4 clips |
reports/ |
Report output directory used by reporting modules |
crowd_safety.db |
SQLite database with events and metrics tables |
assets/ |
Runtime asset directory |
API reference
The FastAPI application is defined in web/server.py. Unless stated otherwise, all endpoints are served by the host and port configured at startup.
HTTP endpoints
| Method | Path | Description |
|---|---|---|
GET |
/ |
Renders the main dashboard. |
GET |
/mobile |
Renders the mobile-oriented dashboard. |
GET |
/stream |
Streams annotated frames as MJPEG. |
GET |
/api/status |
Returns alert level, risk score, count, density, running state, and predictions. |
GET |
/api/alerts |
Returns the current alert feed. |
POST |
/api/control/{action} |
Sets start, stop, or one of the simulation actions. |
GET |
/api/timeline |
Returns the current incident timeline or a no-incident message. |
GET |
/api/recordings |
Lists MP4 files in the recording directory. |
POST |
/api/camera/{cam_id} |
Stores the selected camera identifier in shared dashboard state. |
GET |
/static/... |
Serves static files when web/static/ exists. |
GET |
/recordings/... |
Serves files from the recording directory. |
WebSocket |
/ws |
Sends live metrics, alerts, predictions, and running state approximately every 0.5 seconds. |
The control actions implemented by the server are start, stop, sim_normal, sim_building, sim_dense, and sim_panic.
Example requests
curl http://localhost:8000/api/status
curl http://localhost:8000/api/alerts
curl http://localhost:8000/api/timeline
curl http://localhost:8000/api/recordings
curl -X POST http://localhost:8000/api/control/sim_panic
curl -X POST http://localhost:8000/api/camera/camera-2
A status response has the following shape:
{
"alert_level": "SAFE",
"risk_score": 0.0,
"count": 0,
"density": 0,
"running": false,
"predictions": {}
}
The exact metric keys evolve with the pipeline state. The WebSocket broadcaster publishes metrics, alert_level, risk_score, predictions, alert_feed, and running fields.
Project structure
crowd-detection/
├── config/
│ └── settings.py # Paths, thresholds, defaults, and notification config
├── src/
│ ├── detector.py # YOLO person detection and privacy-oriented blur
│ ├── tracker.py # Multi-object tracking and trajectories
│ ├── density.py # Count, density, occupancy, and heatmaps
│ ├── movement.py # Speed, direction, flow, and compression analysis
│ ├── alerts.py # Alert evaluation and cooldown logic
│ ├── predictor.py # LSTM risk predictor and fallback trend logic
│ ├── logger.py # JSONL, SQLite, timeline, and CSV persistence
│ ├── notifications.py # SMS, email, and webhook notification pipeline
│ ├── recorder.py # Rolling incident video buffer and MP4 output
│ └── ... # Additional analysis, UI, and integration modules
├── web/
│ ├── server.py # FastAPI application and HTTP/WebSocket routes
│ └── templates/ # Dashboard and mobile HTML templates
├── main.py # Pipeline orchestration and CLI entry point
├── launch.py # Python launcher for Windows-oriented workflows
├── setup.sh # Full virtual-environment and dependency setup
├── install-quick.sh # Minimal dependency setup
├── run.sh # Shell launcher
├── start.sh # Dependency-checking launcher
├── requirements.txt # Minimum dependency versions
├── .env.example # Optional notification configuration template
└── README.md # Project documentation
Features and roadmap
Implemented in the current codebase
- ✅ Webcam, video-file, RTSP, and synthetic simulation input paths.
- ✅ YOLO-based person detection and custom multi-object tracking.
- ✅ Density grid, occupancy, heatmap, movement, flow, and trajectory rendering.
- ✅ Alert evaluation, risk scoring, explainability, and forecast output.
- ✅ Social-distance, lost-child, cluster, restricted-zone, acoustic, weather, and behavior modules.
- ✅ Local FastAPI dashboard with MJPEG, REST, and WebSocket surfaces.
- ✅ JSONL and SQLite event persistence, metric CSV export, and incident recording.
- ✅ Optional Twilio, SMTP, webhook, and voice-alert integrations.
Known limitations
- The repository contains no automated test suite, no pinned lockfile, and no production deployment manifest.
- The web server has no authentication or authorization layer.
- Weather data is mocked in
src/weather.py; theOPENWEATHER_API_KEYentry that previously appeared in the example configuration is not used by the current implementation. - Several modules are present as integrations or analysis components but are not equivalent to a validated machine-learning model or a calibrated venue safety system.
- Live performance, detection accuracy, and alert quality depend on the camera, hardware, model availability, thresholds, and scene conditions.
- There is no formal changelog or release process yet.
Future work
Future changes should be driven by measured behavior and tests. Suitable next steps include adding deterministic unit tests for each analyzer, pinning reproducible dependency versions, adding dashboard authentication, documenting calibration procedures, and validating alerts against labeled video before operational use.
Testing
No test framework or test directory is currently included. The repository’s continuous integration workflow therefore performs safe static checks rather than claiming behavioral coverage:
python3 -m compileall -q config src web main.py launch.py
bash -n setup.sh install-quick.sh run.sh start.sh
To run the application manually without a camera, use the simulation smoke path:
./run.sh --sim --no-window
Stop it with Ctrl+C. This starts the real pipeline and dashboard, but it is not a substitute for automated tests or an accuracy evaluation.
Deployment
The supported deployment model is a local Python process on a machine with access to the selected camera or stream. For a local trusted-network deployment:
./setup.sh
./run.sh --source 0 --no-window
For a different network interface or port, adjust API_HOST and API_PORT in config/settings.py, or pass --port for the port override. The application binds to 0.0.0.0 by default, which makes the dashboard reachable on the host’s network interfaces; protect that access with a firewall, private network, reverse proxy, or other trusted boundary.
No Docker, Kubernetes, systemd, reverse-proxy, cloud, or hosted deployment configuration is included. Any such deployment should add process supervision, TLS, authentication, log retention, camera access controls, model lifecycle management, and a documented backup strategy before it is considered production-ready.
Contributing
Contributions are welcome through GitHub issues and pull requests. Before opening a pull request, explain the user-visible or maintenance problem, keep changes focused, update documentation when behavior changes, and include the validation commands you ran.
A practical local workflow is:
git checkout -b feat/short-description
./setup.sh
python3 -m compileall -q config src web main.py launch.py
bash -n setup.sh install-quick.sh run.sh start.sh
Use clear imperative commit subjects such as Improve simulation controls or Fix dashboard status response. Pull requests should describe intent, testing, configuration changes, security impact, and any breaking behavior. Do not commit credentials, generated model files, runtime databases, logs, recordings, or reports.
See CONTRIBUTING.md and the pull-request template in .github/pull_request_template.md for the repository-specific checklist.
Security
This project processes camera imagery and can send alert data to external services. Keep camera feeds, logs, recordings, database files, and notification credentials under appropriate access controls. The application performs a limited blur of the upper portion of detected bounding boxes before drawing detections, but this should not be treated as a complete privacy guarantee.
Do not expose the dashboard directly to the public internet: the current FastAPI server does not provide authentication, authorization, or TLS. Use private networking and a properly configured reverse proxy or access gateway if remote access is necessary.
Please report suspected vulnerabilities privately to the repository owner through the contact information available on the GitHub profile rather than posting exploit details in a public issue. Do not include real camera footage, credentials, phone numbers, email passwords, or private webhook URLs in issue reports.
License
No LICENSE file or license header is currently present in the repository. The project’s reuse terms therefore remain unspecified. Add a license file and copyright holder before distributing the project as open-source software.
Acknowledgments
The project uses the following open-source ecosystems and libraries: Python, OpenCV, NumPy, Ultralytics YOLO, PyTorch, FastAPI, Uvicorn, WebSockets, SciPy, FilterPy, Pandas, SQLAlchemy, ReportLab, Pygame, pyttsx3, PyAudio, Twilio, and related dependencies listed in requirements.txt.
The current Git history attributes the existing commits to Sonali. The repository owner is vincenzo-afk. No additional contributor, sponsor, or third-party asset credit is asserted here without repository evidence.
Contact and support
Use the issue tracker for reproducible bugs, feature requests, and documentation corrections. Include the commit or branch, operating system, Python version, exact command, traceback, and a minimal reproduction when possible. Please redact secrets and private video data.
References
関連プロジェクトを探す
読み込み中…