forked from dsutanto/bytetrack-counter
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d42034cb1 | ||
|
|
b463603437 | ||
|
|
29739461c2 | ||
|
|
3fbacee4ab | ||
|
|
8b20fdf9c5 | ||
|
|
b0486bcca4 | ||
|
|
f5e4b2a170 | ||
|
|
d03dfce564 | ||
|
|
2722f54989 | ||
|
|
86975ffbb6 | ||
|
|
1e2349d7ce | ||
|
|
b0e7f4bff9 | ||
|
|
2160828eff | ||
|
|
f1a8c470e9 | ||
|
|
7790a929bb | ||
|
|
857795165a | ||
|
|
36307faf13 | ||
|
|
66eb7184d2 | ||
|
|
4f41b7adf9 | ||
|
|
434125eeef | ||
|
|
7fff9482f4 | ||
|
|
d98ebf5b77 | ||
|
|
0a133b22a9 | ||
|
|
5fa17eeeff | ||
|
|
05a85c8f8f | ||
|
|
641da193d1 |
No files matched your search
@@ -1,43 +0,0 @@
|
||||
OUTPUT_DIR=/opt/jetson-counter
|
||||
DB_PATH=/opt/jetson-counter/jetson_counter.db
|
||||
STATE_FILE=/opt/jetson-counter/current_batch.json
|
||||
SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
|
||||
MODEL_PATH=/opt/jetson-counter/yolo9t.rknn
|
||||
CAMERA_NAME=CC1
|
||||
OBJECT_LABEL=ayam-potong
|
||||
CLASS_AYAM=ayam
|
||||
CLASS_TALENAN=talenan
|
||||
LINE_X=
|
||||
LINE_X_FRAC=0.5
|
||||
CROSS_DIRECTION=rtl
|
||||
IMGSZ=320
|
||||
HALF=false
|
||||
CONF=0.3
|
||||
DEVICE=0
|
||||
CORE_MASK=1
|
||||
NUM_CLASSES=2
|
||||
SCORE_SIGMOID=false
|
||||
DAILY_CUTOFF_TIME=20:00
|
||||
BATCH_TIMEOUT_SECONDS=300
|
||||
IGNORE_BATCH_LABEL_TIMEOUT_SECONDS=30
|
||||
MIN_OBJECT_PER_BATCH=60
|
||||
MIN_DURATION_PER_BATCH=60
|
||||
EXPORT_CSV=true
|
||||
CROSS_CSV=/opt/jetson-counter/batch_crossings.csv
|
||||
WARMUP_FRAMES=30
|
||||
RECONNECT_DELAY_SEC=3
|
||||
MAX_RECONNECT_ATTEMPTS=0
|
||||
FLUSH_EVERY_N_FRAMES=100
|
||||
TRACKED_PRUNE_SEC=300
|
||||
RECORD_VIDEO=false
|
||||
VIDEO_SEGMENT_SEC=3600
|
||||
OUTPUT_FPS=15
|
||||
|
||||
LIVE_STREAM_ENABLED=false
|
||||
LIVE_STREAM_FRAME_PATH=/dev/shm/jetson-counter/live_frame.jpg
|
||||
LIVE_STREAM_QUALITY=75
|
||||
LIVE_STREAM_EVERY_N=2
|
||||
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport
|
||||
tcp | fflags
|
||||
nobuffer | flags
|
||||
low_delay
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
# Copy to .env and adjust values for your deployment
|
||||
|
||||
# Paths
|
||||
OUTPUT_DIR=/opt/jetson-counter
|
||||
DB_PATH=/opt/jetson-counter/jetson_counter.db
|
||||
STATE_FILE=/opt/jetson-counter/current_batch.json
|
||||
|
||||
# Camera stream (rtsp://, http://, or file path for offline testing)
|
||||
SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
|
||||
|
||||
# RKNN model
|
||||
MODEL_PATH=/opt/jetson-counter/yolo9t.rknn
|
||||
|
||||
# Identity
|
||||
CAMERA_NAME=CC1
|
||||
OBJECT_LABEL=ayam-potong
|
||||
CLASS_AYAM=ayam
|
||||
CLASS_TALENAN=talenan
|
||||
|
||||
# Counting line: pixel position (empty = auto from LINE_X_FRAC)
|
||||
LINE_X=
|
||||
LINE_X_FRAC=0.5
|
||||
CROSS_DIRECTION=rtl
|
||||
|
||||
# Model input size
|
||||
IMGSZ=320
|
||||
|
||||
# Inference (ignored by RKNN scripts; used by Jetson/TensorRT variant)
|
||||
HALF=false
|
||||
|
||||
# Confidence threshold for detections
|
||||
CONF=0.3
|
||||
|
||||
# TensorRT device index (ignored by RKNN scripts; used by Jetson variant)
|
||||
DEVICE=0
|
||||
|
||||
# RKNN NPU core mask: 1=core0, 2=core1, 3=dual, 7=all
|
||||
CORE_MASK=1
|
||||
|
||||
# YOLO decoder: number of classes
|
||||
NUM_CLASSES=2
|
||||
|
||||
# Set to true if model outputs raw logits instead of sigmoid probabilities
|
||||
SCORE_SIGMOID=false
|
||||
|
||||
# ByteTrack parameters (counter_live_rknn_bytetrack.py only)
|
||||
TRACK_HIGH_THRESH=0.5
|
||||
TRACK_LOW_THRESH=0.1
|
||||
TRACK_MATCH_THRESH=0.8
|
||||
TRACK_BUFFER=30
|
||||
TRACK_MIN_HITS=3
|
||||
|
||||
# Batch / cutoff
|
||||
DAILY_CUTOFF_TIME=20:00
|
||||
BATCH_TIMEOUT_SECONDS=300
|
||||
IGNORE_BATCH_LABEL_TIMEOUT_SECONDS=30
|
||||
MIN_OBJECT_PER_BATCH=60
|
||||
MIN_DURATION_PER_BATCH=60
|
||||
|
||||
# CSV export
|
||||
EXPORT_CSV=true
|
||||
CROSS_CSV=/opt/jetson-counter/batch_crossings.csv
|
||||
|
||||
# Stream connection
|
||||
WARMUP_FRAMES=30
|
||||
RECONNECT_DELAY_SEC=3
|
||||
MAX_RECONNECT_ATTEMPTS=0
|
||||
|
||||
# Health logging interval
|
||||
FLUSH_EVERY_N_FRAMES=100
|
||||
|
||||
# Stale track pruning (seconds)
|
||||
TRACKED_PRUNE_SEC=300
|
||||
|
||||
# Video recording
|
||||
RECORD_VIDEO=false
|
||||
VIDEO_SEGMENT_SEC=3600
|
||||
OUTPUT_FPS=15
|
||||
|
||||
# Live stream (writes JPEG snapshot to disk for nginx)
|
||||
LIVE_STREAM_ENABLED=false
|
||||
LIVE_STREAM_FRAME_PATH=/dev/shm/jetson-counter/live_frame.jpg
|
||||
LIVE_STREAM_QUALITY=75
|
||||
LIVE_STREAM_EVERY_N=2
|
||||
|
||||
# OpenCV FFmpeg backend options (semicolon/pipe separated)
|
||||
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[codz]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py.cover
|
||||
*.lcov
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
# Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
# poetry.lock
|
||||
# poetry.toml
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||
# pdm.lock
|
||||
# pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# pixi
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||
# pixi.lock
|
||||
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||
.pixi/*
|
||||
!.pixi/config.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule*
|
||||
celerybeat.pid
|
||||
|
||||
# Redis
|
||||
*.rdb
|
||||
*.aof
|
||||
*.pid
|
||||
|
||||
# RabbitMQ
|
||||
mnesia/
|
||||
rabbitmq/
|
||||
rabbitmq-data/
|
||||
|
||||
# ActiveMQ
|
||||
activemq-data/
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.envrc
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
# .idea/
|
||||
|
||||
# Abstra
|
||||
# Abstra is an AI-powered process automation framework.
|
||||
# Ignore directories containing user credentials, local state, and settings.
|
||||
# Learn more at https://abstra.io/docs
|
||||
.abstra/
|
||||
|
||||
# Visual Studio Code
|
||||
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||
# you could uncomment the following to ignore the entire vscode folder
|
||||
# .vscode/
|
||||
# Temporary file for partial code execution
|
||||
tempCodeRunnerFile.py
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
# Marimo
|
||||
marimo/_static/
|
||||
marimo/_lsp/
|
||||
__marimo__/
|
||||
|
||||
# Streamlit
|
||||
.streamlit/secrets.toml
|
||||
|
||||
# csv and db
|
||||
*.csv
|
||||
*.db
|
||||
batch_crossings.csv
|
||||
bytetrack_counter.db
|
||||
|
||||
+5487
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
# AGENTS.md — bytetrack-counter
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Edge AI counter**: RTSP camera → YOLO RKNN (NPU) → tracking → line-crossing → SQLite + JSON state → Flask dashboard.
|
||||
- **2 counter scripts**, only 1 deployed:
|
||||
- `counter_live.py` — Jetson TensorRT variant (CUDA, NOT used on RK3588).
|
||||
- **`counter_live_rknn_bytetrack.py`** — RK3588 with ByteTrack. **This is what systemd runs.** Reference for C++ port.
|
||||
- `batch_store.py` — shared SQLite persistence + batch state machine.
|
||||
- `counter_dashboard.py` — Flask dashboard on port 5000, same DB.
|
||||
|
||||
## No build / test / lint
|
||||
|
||||
There is no build system, no test framework, no linter config, no typechecker.
|
||||
Do not try to run `pytest`, `ruff`, `mypy`, etc. — they don't exist here.
|
||||
|
||||
## How to run
|
||||
|
||||
```bash
|
||||
# Copy env (required, .env is gitignored)
|
||||
cp config.env.example .env
|
||||
|
||||
# Venv (must use system-site-packages for RKNN toolkit)
|
||||
python3 -m venv --system-site-packages venv
|
||||
source venv/bin/pip install -r requirements.txt
|
||||
|
||||
# Run counter (RK3588 only — needs rknn-toolkit-lite2 & RKNN model)
|
||||
PYTHONNOUSERSITE=1 venv/bin/python counter_live_rknn_bytetrack.py
|
||||
|
||||
# Run dashboard
|
||||
PYTHONNOUSERSITE=1 venv/bin/python counter_dashboard.py
|
||||
```
|
||||
|
||||
## Key environment & install quirks
|
||||
|
||||
- **`PYTHONNOUSERSITE=1`** is mandatory when running from the venv — without it, system/user packages leak in.
|
||||
- **`.env` is gitignored** — always copy from `config.env.example` first.
|
||||
- **`numpy<2`** is required for `rknn-toolkit-lite2` compatibility.
|
||||
- **Install path in service files is `/opt/bytetrack-counter`** (not the `/opt/jetson-counter` mentioned in README/DEPLOY). The `.env.example` also reflects `/opt/bytetrack-counter`.
|
||||
- Service user is **`root`**, not `jetson` (despite README saying otherwise).
|
||||
- Two systemd units: `bytetrack-counter.service` + `bytetrack-counter-dashboard.service`.
|
||||
- `counter_live.py` (TensorRT) is Jetson-only and won't work on RK3588.
|
||||
|
||||
## Code conventions
|
||||
|
||||
- All config lives in `.env` (dotenv), read via `os.getenv()` at module top-level in each script.
|
||||
- The 3 counter scripts duplicate ~80% of each other (drawing helpers, batch loop, etc). Changes to logic may need replication across variants.
|
||||
- `batch_store.py` has its own threading (cutoff watcher, batch timeout timer) — thread safety is via a single `state_lock`.
|
||||
- The dashboard re-creates DB tables on startup (`_ensure_db()`) independently from `batch_store.py`.
|
||||
- No formal version tracking exists anywhere in this codebase.
|
||||
@@ -0,0 +1,133 @@
|
||||
# SPEC — bytetrack-counter
|
||||
|
||||
## §G — Goal
|
||||
|
||||
RTSP camera → YOLO RKNN (NPU) → ByteTrack → line-crossing counter → SQLite + Flask dashboard.
|
||||
Count `ayam` (chicken) crossing counting line. Close batch on `talenan` (cutting-board) crossing.
|
||||
Daily cutoff @ HH:MM resets batch numbering. RK3588 hardware.
|
||||
**Reference implementation for C++ port in separate repo.**
|
||||
|
||||
## §C — Constraints
|
||||
|
||||
- Python 3.10, `rknn-toolkit-lite2` (NPU), `opencv-python` (RTSP/FFmpeg)
|
||||
- `numpy<2` (rknn-toolkit-lite2 incompatible with numpy≥2)
|
||||
- `PYTHONNOUSERSITE=1` ! set or venv breaks
|
||||
- SQLite for persistence, JSON file for active-batch state
|
||||
- Flask on port 5000, systemd supervision
|
||||
- `counter_live.py` ⊥ run on RK3588 — Jetson TensorRT artifact, ! port target
|
||||
- `counter_live_rknn_bytetrack.py` — reference for C++ port, this is what systemd runs
|
||||
- Single deployment: `counter_live_rknn_bytetrack.py` + `counter_dashboard.py`
|
||||
|
||||
## §I — Interfaces
|
||||
|
||||
### Systemd
|
||||
```
|
||||
unit: bytetrack-counter.service → `venv/bin/python counter_live_rknn_bytetrack.py`
|
||||
unit: bytetrack-counter-dashboard.service → `venv/bin/python counter_dashboard.py`
|
||||
env: PYTHONNOUSERSITE=1 ! set in both units
|
||||
env: EnvironmentFile=/opt/bytetrack-counter/.env
|
||||
user: root (not jetson)
|
||||
path: /opt/bytetrack-counter (fixed in service file)
|
||||
```
|
||||
|
||||
### `.env` config (40+ vars, gitignored)
|
||||
```
|
||||
env: SOURCE ! set → RTSP URL | file path
|
||||
env: MODEL_PATH ! set → .rknn file
|
||||
env: IMGSZ ! set → model input size (e.g. 320)
|
||||
env: CORE_MASK → NPU core mask (1=core0, 2=core1, 3=dual, 7=all)
|
||||
env: NUM_CLASSES ! match model output count
|
||||
env: CONF → detection confidence threshold (default 0.3)
|
||||
env: DAILY_CUTOFF_TIME → HH:MM, default "20:00"
|
||||
env: CROSS_DIRECTION → rtl | ltr | both (default rtl)
|
||||
env: LINE_X | LINE_X_FRAC → counting line position
|
||||
env: CLASS_AYAM → class name for counted object (index 0)
|
||||
env: CLASS_TALENAN → class name for batch-close trigger (index 1)
|
||||
env: RESET_COUNTERS_AT_CUTOFF → defined in example, ! consumed by code ? zombie
|
||||
env: MOTION_DETECTION_ENABLED | MOTION_THRESHOLD → skip inference on still frames ?
|
||||
env: TRACK_HIGH_THRESH_{0,1} | TRACK_LOW_THRESH_{0,1} | TRACK_MATCH_THRESH_{0,1} → ByteTrack params per class
|
||||
env: BATCH_TIMEOUT_SECONDS → auto-close after inactivity (default 300)
|
||||
env: IGNORE_BATCH_LABEL_TIMEOUT_SECONDS → suppress talenan close after batch start (default 30)
|
||||
env: MIN_OBJECT_PER_BATCH → min count to persist batch (default 60)
|
||||
env: MIN_DURATION_PER_BATCH → min seconds to persist batch (default 60)
|
||||
env: LIVE_STREAM_ENABLED → write annotated JPEG snapshot each N frames
|
||||
env: EXPORT_CSV → write per-crossing CSV (default true)
|
||||
```
|
||||
|
||||
### SQLite
|
||||
```
|
||||
table: batches (date, batch#, camera, label, count, start, end, created_at)
|
||||
UNIQUE(counting_date, batch_number, camera_name, object_label)
|
||||
table: daily_summaries (date, camera, label, total_count, total_batches, updated_at)
|
||||
UNIQUE(counting_date, camera_name, object_label)
|
||||
```
|
||||
|
||||
### JSON state file
|
||||
```
|
||||
path: /tmp/bytetrack_current_batch.json (default)
|
||||
schema: {counting_date, batch_number, count, start_time, last_detection_time, counted_event_ids[]}
|
||||
```
|
||||
|
||||
### Flask API
|
||||
```
|
||||
api: GET / → dashboard HTML
|
||||
api: GET /api/current-batch → {count, batch_number, counting_date, start_time, last_detection_time}
|
||||
api: GET /api/previous-batch → {date, batch#, count, start/end, duration_minutes}
|
||||
api: GET /api/summary → {today, yesterday, all_time, average_per_day, best_day}
|
||||
api: GET /api/daily-data?days=N → [ {date, total_count, total_batches, avg_per_batch} ]
|
||||
api: GET /api/day-detail/<date> → {date, total_count, total_batches, total_duration, avg_duration, batches[]}
|
||||
api: GET /api/recent-batches?limit=N → [ {date, batch#, count, start/end, duration} ]
|
||||
api: GET /api/available-dates → [ {date, total_count, total_batches} ]
|
||||
api: GET /api/export-daily-csv?days=N → .xlsx download (named csv, emits xlsx)
|
||||
api: GET /api/export-day-csv/<date> → .xlsx download (named csv, emits xlsx)
|
||||
api: GET /api/live-video → MJPEG stream from shared-memory JPEG
|
||||
```
|
||||
|
||||
## §V — Invariants
|
||||
|
||||
```
|
||||
V1: NUM_CLASSES must match model output → class 0=ayam, class 1=talenan
|
||||
V2: line crossing → prev_cx > line_x ≥ cx (rtl) | prev_cx < line_x ≤ cx (ltr)
|
||||
V3: ∀ track_id → counted at most once per batch (counted_event_ids set)
|
||||
V4: batch persisted → count ≥ MIN_OBJECT_PER_BATCH & duration ≥ MIN_DURATION_PER_BATCH
|
||||
V5: dt.time() < DAILY_CUTOFF_TIME → counting_date = today, else tomorrow
|
||||
V6: talenan crossing → close batch, but ignored ∀ IGNORE_BATCH_LABEL_TIMEOUT_SEC after batch start
|
||||
V7: batch inactivity ≥ BATCH_TIMEOUT_SECONDS → auto-close
|
||||
V8: PYTHONNOUSERSITE=1 ! set for venv isolation
|
||||
V9: .env ! exist before counter or dashboard starts
|
||||
V10: DB tables ! exist on startup (created if absent, both store & dashboard)
|
||||
V11: previous batch → last CARRY_IDS (default 50) track IDs carried forward to next batch
|
||||
V12: ∃ ! batch per (date, batch#, camera, label) — UNIQUE constraint in DB
|
||||
V13: counter & dashboard share DB path → no process-level coordination
|
||||
V14: stream disconnect → reconnect with delay (RECONNECT_DELAY_SEC), ! block main loop
|
||||
V15: model inference → letterbox-resize to IMGSZ×IMGSZ, BGR→RGB, run NPU
|
||||
V16: NMS postprocessing → iou_thr=0.45, class-aware grouping, score > CONF
|
||||
V17: tracks pruned after TRACKED_PRUNE_SEC (default 300s) without update
|
||||
V18: .env missing → scripts fail at import (os.getenv falls back to defaults, may mismatch)
|
||||
V19: stream reconnect → reset motion detection state (prev_gray = None)
|
||||
```
|
||||
|
||||
## §T — Tasks
|
||||
|
||||
```
|
||||
id|status|task|cites
|
||||
T1|.|unify install paths — README/DEPLOY/setup-venv.sh/uninstall say `/opt/jetson-counter`, service files & .env.example say `/opt/bytetrack-counter`|
|
||||
T2|.|zombie var RESET_COUNTERS_AT_CUTOFF — defined in .env.example, unused in code (confirmed by review)|
|
||||
T3|.|add version flag — no `--version` or git-derived version exists|
|
||||
T4|.|keep reference Python clean — counter_live.py is artifact; focus edits on counter_live_rknn_bytetrack.py as port source|
|
||||
T5|.|rename export routes — routes named `export-daily-csv` but emit `.xlsx`|I.flask
|
||||
T6|.|fix live-stream snapshot path — some scripts default `/dev/shm/jetson-counter/`, example says `bytetrack-counter`|
|
||||
T7|.|add dashboard health-check endpoint (no `/health` or `/api/status` exists)|
|
||||
T8|.|add model checks on startup — model class names ! validated against CLASS_AYAM/CLASS_TALENAN (TensorRT variant validates; RKNN variants do not)|
|
||||
T9|.|reset prev_gray on stream reconnect — stale gray ref causes crash or false motion|V19,B1
|
||||
T10|.|decay inf_ms toward 0 when inference skipped — stale display misleads operator|
|
||||
T11|x|reduce live-counter poll interval 2000→200ms for real-time feel|
|
||||
```
|
||||
|
||||
## §B — Bugs
|
||||
|
||||
```
|
||||
id|date|cause|fix
|
||||
B1|2026-07-29|prev_gray not reset on stream reconnect → cv2.absdiff crash or false motion|V19
|
||||
```
|
||||
|
||||
Whitespace-only changes.
|
|
Binary file not shown.
+130
-23
@@ -1,54 +1,161 @@
|
||||
# Edge RK3588 production counter — copy to .env on device
|
||||
# cp config.env.example .env && nano .env
|
||||
# =============================================================================
|
||||
# Edge RK3588 production counter + dashboard
|
||||
# Shared config for: counter_live_rknn_bytetrack.py + counter_dashboard.py
|
||||
# Copy to .env on device: cp config.env.example .env && nano .env
|
||||
# =============================================================================
|
||||
|
||||
OUTPUT_DIR=/opt/jetson-counter
|
||||
DB_PATH=/opt/jetson-counter/jetson_counter.db
|
||||
STATE_FILE=/opt/jetson-counter/current_batch.json
|
||||
# --- Core paths ---
|
||||
# Root output directory (logs, DB, video, CSV)
|
||||
OUTPUT_DIR=/opt/bytetrack-counter
|
||||
# SQLite database path for batch entries & crossing logs
|
||||
DB_PATH=/opt/bytetrack-counter/bytetrack_counter.db
|
||||
# JSON file persisting the current active batch state
|
||||
STATE_FILE=/tmp/bytetrack_current_batch.json
|
||||
|
||||
# Direct LAN camera RTSP (low latency)
|
||||
# --- Input source ---
|
||||
# RTSP / HTTP live stream, or a local video file path
|
||||
SOURCE=rtsp://user:pass@192.168.0.100:554/stream1
|
||||
# FFmpeg capture options passed to cv2.VideoCapture (RTSP low-latency flags)
|
||||
OPENCV_FFMPEG_CAPTURE_OPTIONS=rtsp_transport;tcp|fflags;nobuffer|flags;low_delay
|
||||
|
||||
# RKNN model — export'd from YOLO9t with imgsz=320
|
||||
MODEL_PATH=/opt/jetson-counter/yolo9t.rknn
|
||||
# --- RKNN model ---
|
||||
# Path to exported .rknn model (YOLO format, e.g. yolo11n.rknn)
|
||||
MODEL_PATH=/opt/models/yolo9t.rknn
|
||||
# Input image size for the model (square, e.g. 320 → 320×320)
|
||||
IMGSZ=320
|
||||
# Use FP16 inference on NPU (true/false); currently unused in ByteTrack variant
|
||||
HALF=false
|
||||
# NPU core mask: 1=core0, 2=core1, 3=core0+core1, 7=all three
|
||||
CORE_MASK=7
|
||||
# Compute device index (reserved; not used at runtime)
|
||||
DEVICE=0
|
||||
|
||||
# --- YOLO decoder ---
|
||||
# Number of object classes the model outputs (e.g. 2 = ayam + talenan)
|
||||
NUM_CLASSES=2
|
||||
# Apply sigmoid to raw class scores (true/false); set true if model head uses BCE logits
|
||||
SCORE_SIGMOID=false
|
||||
|
||||
# --- Detection ---
|
||||
# Confidence threshold – detections below this are discarded before NMS
|
||||
CONF=0.3
|
||||
|
||||
# RKNN NPU core mask: 1=core0, 2=core1, 3=core0+core1, 7=all three
|
||||
CORE_MASK=1
|
||||
# --- ByteTrack tracking ---
|
||||
# General for ayam, index 0
|
||||
# Detections with score ≥ this get priority matching in the first association stage
|
||||
TRACK_HIGH_THRESH_0=0.5
|
||||
# Detections with score between this and TRACK_HIGH_THRESH are matched in the second stage
|
||||
TRACK_LOW_THRESH_0=0.1
|
||||
# IoU threshold for the first-stage association (0–1). Higher = stricter overlap required
|
||||
TRACK_MATCH_THRESH_0=0.8
|
||||
# Frames a track survives without a match before being permanently removed
|
||||
TRACK_BUFFER_0=30
|
||||
# Minimum consecutive (or total) hits needed before a track is considered confirmed
|
||||
TRACK_MIN_HITS_0=3
|
||||
|
||||
# YOLO decoder params (must match model export)
|
||||
NUM_CLASSES=2
|
||||
NUM_KEYPOINTS=9
|
||||
REG_MAX=16
|
||||
STRIDES=8,16,32
|
||||
# For talenan, index 1
|
||||
# Detections with score ≥ this get priority matching in the first association stage
|
||||
TRACK_HIGH_THRESH_1=0.5
|
||||
# Detections with score between this and TRACK_HIGH_THRESH are matched in the second stage
|
||||
TRACK_LOW_THRESH_1=0.1
|
||||
# IoU threshold for the first-stage association (0–1). Higher = stricter overlap required
|
||||
TRACK_MATCH_THRESH_1=0.6
|
||||
# Frames a track survives without a match before being permanently removed
|
||||
TRACK_BUFFER_1=30
|
||||
# Minimum consecutive (or total) hits needed before a track is considered confirmed
|
||||
TRACK_MIN_HITS_1=3
|
||||
|
||||
CAMERA_NAME=CC1
|
||||
# --- Display ---
|
||||
# Site name shown on the dashboard header (top-right)
|
||||
SITE_NAME=ZenAi
|
||||
|
||||
# --- Object class names ---
|
||||
# Camera / location identifier shown in HUD and stored in DB
|
||||
CAMERA_NAME=ZenAi
|
||||
# Label used for batch grouping in the database
|
||||
OBJECT_LABEL=ayam-potong
|
||||
# Class name for the counted object (must match NUM_CLASSES order, index 0)
|
||||
CLASS_AYAM=ayam
|
||||
# Class name for the batch-closing trigger object (must match NUM_CLASSES order, index 1)
|
||||
CLASS_TALENAN=talenan
|
||||
|
||||
# Line crossing: rtl (default) | ltr | both
|
||||
# --- Line crossing ---
|
||||
# Direction for counting: rtl (right-to-left, default) | ltr (left-to-right) | both
|
||||
CROSS_DIRECTION=rtl
|
||||
# Fixed x-coordinate for the counting line (overrides LINE_X_FRAC if set)
|
||||
LINE_X=
|
||||
# Fraction of frame width where the counting line is drawn (default 0.5 = centre)
|
||||
LINE_X_FRAC=0.5
|
||||
|
||||
# --- Batch management ---
|
||||
# Daily cutoff time (HH:MM) – a new day's batch numbering starts after this time.
|
||||
# CUTOFF_TIME is an alias used by the dashboard; DAILY_CUTOFF_TIME takes priority in counter_live_rknn_bytetrack.py.
|
||||
DAILY_CUTOFF_TIME=20:00
|
||||
CUTOFF_TIME=20:00
|
||||
# Reset frame counter and ByteTrack track-ID counter back to 0 when the daily cutoff is reached (true/false, default: true)
|
||||
RESET_COUNTERS_AT_CUTOFF=true
|
||||
# Seconds of inactivity after which the current batch is auto-closed
|
||||
BATCH_TIMEOUT_SECONDS=300
|
||||
# Seconds a newly-opened batch ignores the talenan label before accepting a close trigger
|
||||
IGNORE_BATCH_LABEL_TIMEOUT_SECONDS=30
|
||||
# Minimum number of objects required for a batch to be saved as valid
|
||||
MIN_OBJECT_PER_BATCH=60
|
||||
# Minimum duration in seconds a batch must be open to be saved as valid
|
||||
MIN_DURATION_PER_BATCH=60
|
||||
|
||||
DASHBOARD_HOST=0.0.0.0
|
||||
DASHBOARD_PORT=5000
|
||||
SECRET_KEY=change-me-in-production
|
||||
|
||||
# --- CSV export ---
|
||||
# Write per-crossing events to a CSV file (true/false)
|
||||
EXPORT_CSV=true
|
||||
RECORD_VIDEO=false
|
||||
# Path where the crossing CSV is written
|
||||
CROSS_CSV=/opt/batch-counter/batch_crossings.csv
|
||||
|
||||
# --- Rate / performance ---
|
||||
# Enable motion detection pre-filter: skip inference on frames with no movement
|
||||
# (true/false, default: false). When enabled, frames below MOTION_THRESHOLD are
|
||||
# skipped, saving NPU/CPU load.
|
||||
MOTION_DETECTION_ENABLED=false
|
||||
# Mean absolute pixel difference threshold (0–255) to consider a frame as having
|
||||
# motion. Lower = more sensitive. Default 5.0.
|
||||
MOTION_THRESHOLD=5.0
|
||||
# Sliding window in seconds for computing the crossing rate (objects/minute)
|
||||
RATE_WINDOW_SEC=60
|
||||
# Number of frames to discard at startup to let the stream buffer stabilise
|
||||
WARMUP_FRAMES=30
|
||||
# Delay in seconds between stream reconnection attempts
|
||||
RECONNECT_DELAY_SEC=3
|
||||
# Maximum reconnection attempts (0 = infinite)
|
||||
MAX_RECONNECT_ATTEMPTS=0
|
||||
# Print status log every N processed frames
|
||||
FLUSH_EVERY_N_FRAMES=100
|
||||
# Seconds after which a tracked but unseen object is pruned from the active set
|
||||
TRACKED_PRUNE_SEC=300
|
||||
|
||||
# --- Video recording ---
|
||||
# Save annotated frames to segmented MP4 files (true/false)
|
||||
RECORD_VIDEO=false
|
||||
# Duration in seconds of each video segment file
|
||||
VIDEO_SEGMENT_SEC=3600
|
||||
# Output video FPS (fallback if source FPS is unknown or ≤ 1)
|
||||
OUTPUT_FPS=15
|
||||
|
||||
# --- Live stream snapshot ---
|
||||
# Periodically write the latest annotated frame as JPEG for an external web server
|
||||
LIVE_STREAM_ENABLED=false
|
||||
LIVE_STREAM_FRAME_PATH=/dev/shm/jetson-counter/live_frame.jpg
|
||||
# Path to the shared-memory snapshot file (served by nginx / lighttpd)
|
||||
LIVE_STREAM_FRAME_PATH=/dev/shm/byetrack-counter/live_frame.jpg
|
||||
# JPEG quality (1–100)
|
||||
LIVE_STREAM_QUALITY=75
|
||||
# Write the snapshot every N frames (lower = more frequent updates)
|
||||
LIVE_STREAM_EVERY_N=2
|
||||
|
||||
# --- Dashboard (counter_dashboard.py) ---
|
||||
# Flask secret key for session/cookie signing — change in production!
|
||||
SECRET_KEY=change-me-in-production
|
||||
# Bind address for the Flask web server
|
||||
DASHBOARD_HOST=0.0.0.0
|
||||
# Listen port for the dashboard web UI
|
||||
DASHBOARD_PORT=5000
|
||||
# Enable Flask debug mode (true/false) — auto-reloads on code changes; disable in production
|
||||
FLASK_DEBUG=false
|
||||
# Fallback name for the active-batch JSON state file used by the dashboard
|
||||
CURRENT_BATCH_PATH=/tmp/bytetrack_current_batch.json
|
||||
+420
-273
@@ -8,11 +8,13 @@ Default port 5000 (replaces frigate-counter dashboard role).
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import csv
|
||||
import time
|
||||
from io import StringIO
|
||||
from io import BytesIO
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
|
||||
from flask import Flask, render_template, jsonify, request, Response
|
||||
from werkzeug.serving import WSGIRequestHandler
|
||||
|
||||
@@ -30,25 +32,82 @@ CUTOFF_TIME = os.getenv("CUTOFF_TIME", os.getenv("DAILY_CUTOFF_TIME", "20:00"))
|
||||
|
||||
LIVE_STREAM_FRAME_PATH = os.getenv("LIVE_STREAM_FRAME_PATH", "/dev/shm/jetson-counter/live_frame.jpg")
|
||||
|
||||
SITE_NAME = os.getenv("SITE_NAME", "LIVE")
|
||||
|
||||
DASHBOARD_PORT = int(os.getenv("DASHBOARD_PORT", "5000"))
|
||||
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
|
||||
FLASK_DEBUG = os.getenv("FLASK_DEBUG", "false").lower() == "true"
|
||||
|
||||
@app.route("/api/live-video")
|
||||
def api_live_video():
|
||||
if not os.path.isfile(LIVE_STREAM_FRAME_PATH):
|
||||
return jsonify({"success": False, "error": "Live stream frame not available yet"}), 503
|
||||
|
||||
def generate():
|
||||
consecutive_fails = 0
|
||||
MAX_FAILS = 30
|
||||
while True:
|
||||
try:
|
||||
with open(LIVE_STREAM_FRAME_PATH, "rb") as f:
|
||||
jpeg = f.read()
|
||||
consecutive_fails = 0
|
||||
yield (b"--frame\r\n"
|
||||
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n")
|
||||
except FileNotFoundError:
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(1.0)
|
||||
continue
|
||||
except Exception:
|
||||
consecutive_fails += 1
|
||||
if consecutive_fails >= MAX_FAILS:
|
||||
return
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
time.sleep(0.05)
|
||||
return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
|
||||
|
||||
|
||||
def _ensure_db():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS batches (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
batch_number INTEGER NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
count INTEGER NOT NULL,
|
||||
start_time TEXT NOT NULL,
|
||||
end_time TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, batch_number, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS daily_summaries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
counting_date TEXT NOT NULL,
|
||||
camera_name TEXT NOT NULL,
|
||||
object_label TEXT NOT NULL,
|
||||
total_count INTEGER NOT NULL DEFAULT 0,
|
||||
total_batches INTEGER NOT NULL DEFAULT 0,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(counting_date, camera_name, object_label)
|
||||
)
|
||||
"""
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
_ensure_db()
|
||||
|
||||
|
||||
def get_db():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -66,7 +125,7 @@ def get_counting_date(dt=None, cutoff_str=CUTOFF_TIME):
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template("dashboard.html")
|
||||
return render_template("dashboard.html", site_name=SITE_NAME)
|
||||
|
||||
|
||||
@app.route("/api/current-batch")
|
||||
@@ -108,302 +167,390 @@ def api_current_batch():
|
||||
|
||||
@app.route("/api/previous-batch")
|
||||
def api_previous_batch():
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
SELECT counting_date, batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
if row:
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.close()
|
||||
if row:
|
||||
return jsonify(
|
||||
{
|
||||
"success": True,
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"],
|
||||
}
|
||||
)
|
||||
return jsonify({"success": False, "error": "No previous batch"}), 200
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/summary")
|
||||
def api_summary():
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
today = get_counting_date()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(total_count, 0) as total_count,
|
||||
COALESCE(total_batches, 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(today,),
|
||||
)
|
||||
today_row = cur.fetchone()
|
||||
yesterday = (datetime.strptime(today, "%Y-%m-%d").date() - timedelta(days=1)).isoformat()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(total_count, 0) as total_count,
|
||||
COALESCE(total_batches, 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(yesterday,),
|
||||
)
|
||||
yesterday_row = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as grand_total,
|
||||
COALESCE(SUM(total_batches), 0) as grand_batches,
|
||||
COUNT(DISTINCT counting_date) as total_days
|
||||
FROM daily_summaries
|
||||
"""
|
||||
)
|
||||
all_time = cur.fetchone()
|
||||
cur.execute("SELECT ROUND(AVG(total_count), 1) as avg_per_day FROM daily_summaries")
|
||||
avg = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, total_count
|
||||
FROM daily_summaries
|
||||
ORDER BY total_count DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
best = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"success": True,
|
||||
"today": {
|
||||
"date": today,
|
||||
"total_count": today_row["total_count"] if today_row else 0,
|
||||
"total_batches": today_row["total_batches"] if today_row else 0,
|
||||
},
|
||||
"yesterday": {
|
||||
"date": yesterday,
|
||||
"total_count": yesterday_row["total_count"] if yesterday_row else 0,
|
||||
"total_batches": yesterday_row["total_batches"] if yesterday_row else 0,
|
||||
},
|
||||
"all_time": {
|
||||
"grand_total": all_time["grand_total"],
|
||||
"grand_batches": all_time["grand_batches"],
|
||||
"total_days": all_time["total_days"],
|
||||
},
|
||||
"average_per_day": avg["avg_per_day"] or 0,
|
||||
"best_day": {
|
||||
"date": best["counting_date"] if best else None,
|
||||
"count": best["total_count"] if best else 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}", "today": {"date": datetime.now().date().isoformat(), "total_count": 0, "total_batches": 0}, "yesterday": {"date": "", "total_count": 0, "total_batches": 0}, "all_time": {"grand_total": 0, "grand_batches": 0, "total_days": 0}, "average_per_day": 0, "best_day": {"date": None, "count": 0}}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/daily-data")
|
||||
def api_daily_data():
|
||||
try:
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, total_count, total_batches,
|
||||
ROUND(CAST(total_count AS FLOAT) / total_batches, 1) as avg_per_batch
|
||||
FROM daily_summaries
|
||||
WHERE counting_date >= ?
|
||||
ORDER BY counting_date ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
daily_data = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
"avg_per_batch": row["avg_per_batch"] or 0,
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(daily_data)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/day-detail/<date>")
|
||||
def api_day_detail(date):
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
batches = []
|
||||
total_duration = 0
|
||||
for row in cur.fetchall():
|
||||
duration = row["duration_minutes"] or 0
|
||||
total_duration += duration
|
||||
batches.append(
|
||||
{
|
||||
"batch_number": row["batch_number"],
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": duration,
|
||||
}
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT total_count, total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
summary = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"date": date,
|
||||
"total_count": summary["total_count"] if summary else 0,
|
||||
"total_batches": summary["total_batches"] if summary else 0,
|
||||
"total_duration_minutes": round(total_duration, 1),
|
||||
"avg_duration_minutes": round(total_duration / len(batches), 1) if batches else 0,
|
||||
"batches": batches,
|
||||
}
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"date": date, "total_count": 0, "total_batches": 0, "total_duration_minutes": 0, "avg_duration_minutes": 0, "batches": [], "error": f"Database unavailable: {e}"}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/recent-batches")
|
||||
def api_recent_batches():
|
||||
try:
|
||||
limit = request.args.get("limit", 10, type=int)
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
batches = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"],
|
||||
"duration_minutes": row["duration_minutes"] or 0,
|
||||
}
|
||||
)
|
||||
return jsonify({"success": False, "error": "No previous batch"}), 200
|
||||
|
||||
|
||||
@app.route("/api/summary")
|
||||
def api_summary():
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
today = get_counting_date()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(total_count, 0) as total_count,
|
||||
COALESCE(total_batches, 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(today,),
|
||||
)
|
||||
today_row = cur.fetchone()
|
||||
yesterday = (datetime.strptime(today, "%Y-%m-%d").date() - timedelta(days=1)).isoformat()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(total_count, 0) as total_count,
|
||||
COALESCE(total_batches, 0) as total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(yesterday,),
|
||||
)
|
||||
yesterday_row = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT COALESCE(SUM(total_count), 0) as grand_total,
|
||||
COALESCE(SUM(total_batches), 0) as grand_batches,
|
||||
COUNT(DISTINCT counting_date) as total_days
|
||||
FROM daily_summaries
|
||||
"""
|
||||
)
|
||||
all_time = cur.fetchone()
|
||||
cur.execute("SELECT ROUND(AVG(total_count), 1) as avg_per_day FROM daily_summaries")
|
||||
avg = cur.fetchone()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, total_count
|
||||
FROM daily_summaries
|
||||
ORDER BY total_count DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
)
|
||||
best = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"today": {
|
||||
"date": today,
|
||||
"total_count": today_row["total_count"] if today_row else 0,
|
||||
"total_batches": today_row["total_batches"] if today_row else 0,
|
||||
},
|
||||
"yesterday": {
|
||||
"date": yesterday,
|
||||
"total_count": yesterday_row["total_count"] if yesterday_row else 0,
|
||||
"total_batches": yesterday_row["total_batches"] if yesterday_row else 0,
|
||||
},
|
||||
"all_time": {
|
||||
"grand_total": all_time["grand_total"],
|
||||
"grand_batches": all_time["grand_batches"],
|
||||
"total_days": all_time["total_days"],
|
||||
},
|
||||
"average_per_day": avg["avg_per_day"] or 0,
|
||||
"best_day": {
|
||||
"date": best["counting_date"] if best else None,
|
||||
"count": best["total_count"] if best else 0,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.route("/api/daily-data")
|
||||
def api_daily_data():
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, total_count, total_batches,
|
||||
ROUND(CAST(total_count AS FLOAT) / total_batches, 1) as avg_per_batch
|
||||
FROM daily_summaries
|
||||
WHERE counting_date >= ?
|
||||
ORDER BY counting_date ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
daily_data = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
"avg_per_batch": row["avg_per_batch"] or 0,
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(daily_data)
|
||||
|
||||
|
||||
@app.route("/api/day-detail/<date>")
|
||||
def api_day_detail(date):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
batches = []
|
||||
total_duration = 0
|
||||
for row in cur.fetchall():
|
||||
duration = row["duration_minutes"] or 0
|
||||
total_duration += duration
|
||||
batches.append(
|
||||
{
|
||||
"batch_number": row["batch_number"],
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": duration,
|
||||
}
|
||||
)
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT total_count, total_batches
|
||||
FROM daily_summaries
|
||||
WHERE counting_date = ?
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
summary = cur.fetchone()
|
||||
conn.close()
|
||||
return jsonify(
|
||||
{
|
||||
"date": date,
|
||||
"total_count": summary["total_count"] if summary else 0,
|
||||
"total_batches": summary["total_batches"] if summary else 0,
|
||||
"total_duration_minutes": round(total_duration, 1),
|
||||
"avg_duration_minutes": round(total_duration / len(batches), 1) if batches else 0,
|
||||
"batches": batches,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.route("/api/recent-batches")
|
||||
def api_recent_batches():
|
||||
limit = request.args.get("limit", 10, type=int)
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
ORDER BY end_time DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
batches = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"batch_number": row["batch_number"],
|
||||
"count": row["count"],
|
||||
"start_time": row["start_time"],
|
||||
"end_time": row["end_time"],
|
||||
"duration_minutes": row["duration_minutes"] or 0,
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(batches)
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(batches)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/available-dates")
|
||||
def api_available_dates():
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, total_count, total_batches
|
||||
FROM daily_summaries
|
||||
ORDER BY counting_date DESC
|
||||
"""
|
||||
SELECT counting_date, total_count, total_batches
|
||||
FROM daily_summaries
|
||||
ORDER BY counting_date DESC
|
||||
"""
|
||||
)
|
||||
dates = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(dates)
|
||||
)
|
||||
dates = [
|
||||
{
|
||||
"date": row["counting_date"],
|
||||
"total_count": row["total_count"],
|
||||
"total_batches": row["total_batches"],
|
||||
}
|
||||
for row in cur.fetchall()
|
||||
]
|
||||
conn.close()
|
||||
return jsonify(dates)
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify([]), 200
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
|
||||
@app.route("/api/export-daily-csv")
|
||||
def export_daily_csv():
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, total_count, total_batches,
|
||||
ROUND(CAST(total_count AS FLOAT) / NULLIF(total_batches, 0), 1) as avg_per_batch
|
||||
FROM daily_summaries
|
||||
WHERE counting_date >= ?
|
||||
ORDER BY counting_date ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
output = StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(["Date", "Total Count", "Total Batches", "Avg per Batch"])
|
||||
for row in cur.fetchall():
|
||||
writer.writerow([row["counting_date"], row["total_count"], row["total_batches"], row["avg_per_batch"] or 0])
|
||||
conn.close()
|
||||
filename = f"daily_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
|
||||
def _excel_response(wb, filename):
|
||||
output = BytesIO()
|
||||
wb.save(output)
|
||||
output.seek(0)
|
||||
return Response(
|
||||
output.getvalue(),
|
||||
mimetype="text/csv",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f"attachment; filename={filename}"},
|
||||
)
|
||||
|
||||
|
||||
def _style_header(ws, cols):
|
||||
header_font = Font(bold=True, color="FFFFFF", size=11)
|
||||
header_fill = PatternFill(start_color="2F5496", end_color="2F5496", fill_type="solid")
|
||||
thin_border = Border(
|
||||
left=Side(style="thin"), right=Side(style="thin"),
|
||||
top=Side(style="thin"), bottom=Side(style="thin"),
|
||||
)
|
||||
for col_idx, (col_letter, text) in enumerate(cols, 1):
|
||||
cell = ws.cell(row=1, column=col_idx, value=text)
|
||||
cell.font = header_font
|
||||
cell.fill = header_fill
|
||||
cell.alignment = Alignment(horizontal="center")
|
||||
cell.border = thin_border
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
|
||||
def _auto_width(ws):
|
||||
for col in ws.columns:
|
||||
max_len = 0
|
||||
col_letter = col[0].column_letter
|
||||
for cell in col:
|
||||
if cell.value is not None:
|
||||
max_len = max(max_len, len(str(cell.value)))
|
||||
ws.column_dimensions[col_letter].width = max_len + 4
|
||||
|
||||
|
||||
@app.route("/api/export-daily-csv")
|
||||
def export_daily_xlsx():
|
||||
try:
|
||||
days = request.args.get("days", 30, type=int)
|
||||
date_from = (datetime.now() - timedelta(days=days)).date().isoformat()
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT counting_date, batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date >= ?
|
||||
ORDER BY counting_date ASC, batch_number ASC
|
||||
""",
|
||||
(date_from,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Batch Details"
|
||||
_style_header(ws, [("A", "Date"), ("B", "Batch #"), ("C", "Count"), ("D", "Start Time"), ("E", "End Time"), ("F", "Duration (min)")])
|
||||
|
||||
for r_idx, row in enumerate(rows, 2):
|
||||
ws.cell(row=r_idx, column=1, value=row["counting_date"])
|
||||
ws.cell(row=r_idx, column=2, value=row["batch_number"])
|
||||
ws.cell(row=r_idx, column=3, value=row["count"])
|
||||
ws.cell(row=r_idx, column=4, value=row["start_time"])
|
||||
ws.cell(row=r_idx, column=5, value=row["end_time"])
|
||||
ws.cell(row=r_idx, column=6, value=row["duration_minutes"] or 0)
|
||||
|
||||
_auto_width(ws)
|
||||
filename = f"{SITE_NAME}_daily_records_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
|
||||
return _excel_response(wb, filename)
|
||||
|
||||
|
||||
@app.route("/api/export-day-csv/<date>")
|
||||
def export_day_csv(date):
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
output = StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(["Batch Number", "Count", "Start Time", "End Time", "Duration (min)"])
|
||||
for row in cur.fetchall():
|
||||
writer.writerow([row["batch_number"], row["count"], row["start_time"], row["end_time"], row["duration_minutes"] or 0])
|
||||
conn.close()
|
||||
return Response(
|
||||
output.getvalue(),
|
||||
mimetype="text/csv",
|
||||
headers={"Content-Disposition": f"attachment; filename=day_detail_{date}.csv"},
|
||||
)
|
||||
def export_day_xlsx(date):
|
||||
try:
|
||||
conn = get_db()
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT batch_number, count, start_time, end_time,
|
||||
ROUND((julianday(end_time) - julianday(start_time)) * 24 * 60, 1) as duration_minutes
|
||||
FROM batches
|
||||
WHERE counting_date = ?
|
||||
ORDER BY batch_number ASC
|
||||
""",
|
||||
(date,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
except sqlite3.OperationalError as e:
|
||||
return jsonify({"success": False, "error": f"Database unavailable: {e}"}), 503
|
||||
except Exception as e:
|
||||
return jsonify({"success": False, "error": str(e)}), 500
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = f"Day {date}"
|
||||
_style_header(ws, [("A", "Batch Number"), ("B", "Count"), ("C", "Start Time"), ("D", "End Time"), ("E", "Duration (min)")])
|
||||
|
||||
for r_idx, row in enumerate(rows, 2):
|
||||
ws.cell(row=r_idx, column=1, value=row["batch_number"])
|
||||
ws.cell(row=r_idx, column=2, value=row["count"])
|
||||
ws.cell(row=r_idx, column=3, value=row["start_time"])
|
||||
ws.cell(row=r_idx, column=4, value=row["end_time"])
|
||||
ws.cell(row=r_idx, column=5, value=row["duration_minutes"] or 0)
|
||||
|
||||
_auto_width(ws)
|
||||
filename = f"{SITE_NAME}_day_detail_{date}.xlsx"
|
||||
return _excel_response(wb, filename)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
WSGIRequestHandler.protocol_version = "HTTP/1.1"
|
||||
port = int(os.getenv("DASHBOARD_PORT", "5000"))
|
||||
host = os.getenv("DASHBOARD_HOST", "0.0.0.0")
|
||||
debug = os.getenv("FLASK_DEBUG", "false").lower() == "true"
|
||||
print(f"Jetson counter dashboard at http://{host}:{port}")
|
||||
print(f"Jetson counter dashboard at http://{DASHBOARD_HOST}:{DASHBOARD_PORT}")
|
||||
print(f"DB: {DB_PATH}")
|
||||
print(f"State: {CURRENT_BATCH_PATH}")
|
||||
app.run(host=host, port=port, debug=debug)
|
||||
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)
|
||||
File diff suppressed because it is too large.
Load diff
+158
-74
@@ -10,6 +10,7 @@ import csv
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from collections import deque
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
@@ -48,11 +49,18 @@ NUM_CLASSES = int(os.getenv("NUM_CLASSES", "2"))
|
||||
SCORE_SIGMOID = os.getenv("SCORE_SIGMOID", "false").lower() == "true"
|
||||
|
||||
# ByteTrack settings
|
||||
TRACK_HIGH_THRESH = float(os.getenv("TRACK_HIGH_THRESH", "0.5"))
|
||||
TRACK_LOW_THRESH = float(os.getenv("TRACK_LOW_THRESH", "0.1"))
|
||||
TRACK_MATCH_THRESH = float(os.getenv("TRACK_MATCH_THRESH", "0.8"))
|
||||
TRACK_BUFFER = int(os.getenv("TRACK_BUFFER", "30"))
|
||||
TRACK_MIN_HITS = int(os.getenv("TRACK_MIN_HITS", "3"))
|
||||
# Ayam index 0
|
||||
TRACK_HIGH_THRESH_0 = float(os.getenv("TRACK_HIGH_THRESH_0", "0.5"))
|
||||
TRACK_LOW_THRESH_0 = float(os.getenv("TRACK_LOW_THRESH_0", "0.1"))
|
||||
TRACK_MATCH_THRESH_0 = float(os.getenv("TRACK_MATCH_THRESH_0", "0.8"))
|
||||
TRACK_BUFFER_0 = int(os.getenv("TRACK_BUFFER_0", "30"))
|
||||
TRACK_MIN_HITS_0 = int(os.getenv("TRACK_MIN_HITS_0", "3"))
|
||||
# Talenan index 1
|
||||
TRACK_HIGH_THRESH_1 = float(os.getenv("TRACK_HIGH_THRESH_1", "0.5"))
|
||||
TRACK_LOW_THRESH_1 = float(os.getenv("TRACK_LOW_THRESH_1", "0.1"))
|
||||
TRACK_MATCH_THRESH_1 = float(os.getenv("TRACK_MATCH_THRESH_1", "0.6"))
|
||||
TRACK_BUFFER_1 = int(os.getenv("TRACK_BUFFER_1", "30"))
|
||||
TRACK_MIN_HITS_1 = int(os.getenv("TRACK_MIN_HITS_1", "3"))
|
||||
|
||||
DAILY_CUTOFF_TIME = os.getenv("DAILY_CUTOFF_TIME", "20:00")
|
||||
BATCH_TIMEOUT_SECONDS = float(os.getenv("BATCH_TIMEOUT_SECONDS", "300"))
|
||||
@@ -65,6 +73,7 @@ MIN_DURATION_PER_BATCH = int(os.getenv("MIN_DURATION_PER_BATCH", "60"))
|
||||
EXPORT_CSV = os.getenv("EXPORT_CSV", "true").lower() == "true"
|
||||
CROSS_CSV = os.getenv("CROSS_CSV", f"{OUTPUT_DIR}/batch_crossings.csv")
|
||||
|
||||
RATE_WINDOW_SEC = int(os.getenv("RATE_WINDOW_SEC", "60"))
|
||||
WARMUP_FRAMES = int(os.getenv("WARMUP_FRAMES", "30"))
|
||||
RECONNECT_DELAY_SEC = int(os.getenv("RECONNECT_DELAY_SEC", "3"))
|
||||
MAX_RECONNECT_ATTEMPTS = int(os.getenv("MAX_RECONNECT_ATTEMPTS", "0"))
|
||||
@@ -88,6 +97,9 @@ RTSP_FFMPEG_OPTIONS = os.getenv(
|
||||
|
||||
IS_LIVE = SOURCE.lower().startswith(("rtsp://", "http://"))
|
||||
|
||||
MOTION_DETECTION_ENABLED = os.getenv("MOTION_DETECTION_ENABLED", "false").lower() == "true"
|
||||
MOTION_THRESHOLD = float(os.getenv("MOTION_THRESHOLD", "5.0"))
|
||||
|
||||
CROSS_FLASH_FRAMES = 12
|
||||
POPUP_LIFETIME = 20
|
||||
LINE_PULSE_FRAMES = 12
|
||||
@@ -345,11 +357,13 @@ class ByteTracker:
|
||||
# --- separate detections by score ---
|
||||
if len(boxes_xyxy) > 0:
|
||||
remain = scores > self.low_thresh
|
||||
remain_orig_idx = np.where(remain)[0]
|
||||
dets = boxes_xyxy[remain]
|
||||
det_scores = scores[remain]
|
||||
is_high = det_scores > self.high_thresh
|
||||
is_low = ~is_high
|
||||
else:
|
||||
remain_orig_idx = np.zeros(0, dtype=np.int64)
|
||||
dets = np.zeros((0, 4), dtype=np.float32)
|
||||
det_scores = np.zeros(0, dtype=np.float32)
|
||||
is_high = np.zeros(0, dtype=bool)
|
||||
@@ -389,10 +403,11 @@ class ByteTracker:
|
||||
|
||||
for di, ti in matches:
|
||||
det_global = int(high_idx[di])
|
||||
orig_idx = int(remain_orig_idx[det_global])
|
||||
track_pool[ti].update(dets[det_global])
|
||||
track_pool[ti].hit_streak = max(1, track_pool[ti].hit_streak)
|
||||
matched_track_idx.add(ti)
|
||||
det_to_track[det_global] = track_pool[ti].track_id
|
||||
det_to_track[orig_idx] = track_pool[ti].track_id
|
||||
tracked_map[track_pool[ti].track_id] = track_pool[ti].get_cx()
|
||||
match_pairs_high.append((det_global, ti))
|
||||
|
||||
@@ -408,17 +423,20 @@ class ByteTracker:
|
||||
unmatched_boxes = track_boxes[unmatched_tracks]
|
||||
iou_mat = _ious_xyxy(low_dets, unmatched_boxes)
|
||||
cost_mat = 1.0 - iou_mat
|
||||
matches2 = _greedy_match(cost_mat, threshold=0.5)
|
||||
matches2 = _greedy_match(
|
||||
cost_mat, threshold=1.0 - self.match_thresh
|
||||
)
|
||||
|
||||
for di, uti in matches2:
|
||||
det_global = int(low_idx[di])
|
||||
pool_idx = unmatched_tracks[uti]
|
||||
orig_idx = int(remain_orig_idx[det_global])
|
||||
track_pool[pool_idx].update(dets[det_global])
|
||||
track_pool[pool_idx].hit_streak = max(
|
||||
1, track_pool[pool_idx].hit_streak
|
||||
)
|
||||
matched_track_idx.add(pool_idx)
|
||||
det_to_track[det_global] = track_pool[pool_idx].track_id
|
||||
det_to_track[orig_idx] = track_pool[pool_idx].track_id
|
||||
tracked_map[track_pool[pool_idx].track_id] = track_pool[
|
||||
pool_idx
|
||||
].get_cx()
|
||||
@@ -454,10 +472,11 @@ class ByteTracker:
|
||||
high_all = np.where(is_high)[0]
|
||||
matched_det_ids = set(det_to_track.keys())
|
||||
for dg in high_all:
|
||||
if int(dg) not in matched_det_ids:
|
||||
trk = KalmanBoxTracker(dets[dg])
|
||||
orig_idx = int(remain_orig_idx[int(dg)])
|
||||
if orig_idx not in matched_det_ids:
|
||||
trk = KalmanBoxTracker(dets[int(dg)])
|
||||
self.tracked_tracks.append(trk)
|
||||
det_to_track[int(dg)] = trk.track_id
|
||||
det_to_track[orig_idx] = trk.track_id
|
||||
tracked_map[trk.track_id] = trk.get_cx()
|
||||
|
||||
return tracked_map, det_to_track, lost_map
|
||||
@@ -749,61 +768,59 @@ def draw_hero_count(img, line_x, h, count, pulse_remaining=0):
|
||||
text = str(count)
|
||||
font = cv2.FONT_HERSHEY_SIMPLEX
|
||||
boost = 0.35 * (pulse_remaining / max(COUNT_PULSE_FRAMES, 1))
|
||||
font_scale, thickness = 1.6 + boost, 3
|
||||
font_scale, thickness = 1.4 + boost, 3
|
||||
(tw, th), _ = cv2.getTextSize(text, font, font_scale, thickness)
|
||||
pad = 14
|
||||
tx, ty = line_x - tw // 2, h // 2 + th // 2
|
||||
tx, ty = line_x - tw // 2, h // 3 + th // 2
|
||||
overlay_rect(
|
||||
img, tx - pad, ty - th - pad, tx + tw + pad, ty + pad // 2, C_PANEL, alpha=0.78
|
||||
img, tx - pad, ty - th - pad, tx + tw + pad, ty + pad, C_PANEL, alpha=0.78
|
||||
)
|
||||
cv2.rectangle(
|
||||
img, (tx - pad, ty - th - pad), (tx + tw + pad, ty + pad // 2), C_LINE_CORE, 2
|
||||
img, (tx - pad, ty - th - pad), (tx + tw + pad, ty + pad), C_LINE_CORE, 2
|
||||
)
|
||||
cv2.putText(img, text, (tx, ty), font, font_scale, C_GREEN, thickness, cv2.LINE_AA)
|
||||
|
||||
|
||||
def draw_hud(
|
||||
img, w, batch_num, batch_count, total_ayam, elapsed_sec, rate, camera_id, clock
|
||||
):
|
||||
bar_h = 52
|
||||
def draw_hud(img, w, batch_num, batch_count, total_ayam, elapsed_sec, rate):
|
||||
bar_h = 40
|
||||
overlay_rect(img, 0, 0, w, bar_h, C_PANEL, alpha=0.72)
|
||||
cv2.line(img, (0, bar_h), (w, bar_h), C_BORDER, 1)
|
||||
cv2.putText(
|
||||
img, "BATCH", (16, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.45, C_MUTED, 1, cv2.LINE_AA
|
||||
img, "BATCH", (14, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||||
)
|
||||
batch_label = str(batch_num) if batch_num else "\u2014"
|
||||
batch_label = str(batch_num) if batch_num else "--"
|
||||
cv2.putText(
|
||||
img,
|
||||
batch_label,
|
||||
(16, 44),
|
||||
(14, 32),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.9,
|
||||
0.55,
|
||||
C_ACCENT,
|
||||
2,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
)
|
||||
cv2.putText(
|
||||
img, "COUNT", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.45, C_MUTED, 1, cv2.LINE_AA
|
||||
img, "COUNT", (90, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||||
)
|
||||
cv2.putText(
|
||||
img,
|
||||
str(batch_count),
|
||||
(100, 44),
|
||||
(90, 32),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.9,
|
||||
0.55,
|
||||
C_GREEN,
|
||||
2,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
)
|
||||
cv2.putText(
|
||||
img, "TOTAL", (190, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.45, C_MUTED, 1, cv2.LINE_AA
|
||||
img, "TOTAL", (170, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||||
)
|
||||
cv2.putText(
|
||||
img,
|
||||
str(total_ayam),
|
||||
(190, 44),
|
||||
(170, 32),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.7,
|
||||
0.45,
|
||||
C_TEXT,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
@@ -811,9 +828,9 @@ def draw_hud(
|
||||
cv2.putText(
|
||||
img,
|
||||
"UPTIME",
|
||||
(280, 20),
|
||||
(250, 14),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.45,
|
||||
0.32,
|
||||
C_MUTED,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
@@ -821,45 +838,34 @@ def draw_hud(
|
||||
cv2.putText(
|
||||
img,
|
||||
f"{elapsed_sec / 3600:.1f}h",
|
||||
(280, 44),
|
||||
(250, 32),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.7,
|
||||
0.45,
|
||||
C_TEXT,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
)
|
||||
cv2.putText(
|
||||
img, "RATE", (380, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.45, C_MUTED, 1, cv2.LINE_AA
|
||||
img, "RATE", (340, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||||
)
|
||||
cv2.putText(
|
||||
img,
|
||||
f"{rate:.1f}/min",
|
||||
(380, 44),
|
||||
(340, 32),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.7,
|
||||
0.45,
|
||||
C_ACCENT,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
)
|
||||
# cv2.putText(img, clock, (w - 180, 36), cv2.FONT_HERSHEY_SIMPLEX, 0.55, C_TEXT, 1, cv2.LINE_AA)
|
||||
cv2.putText(
|
||||
img,
|
||||
f"CAM {camera_id}",
|
||||
(w - 180, 20),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.45,
|
||||
C_MUTED,
|
||||
1,
|
||||
cv2.LINE_AA,
|
||||
)
|
||||
|
||||
|
||||
def draw_footer(img, w, h, frame_idx, live_tag):
|
||||
def draw_footer(img, w, h, frame_idx, live_tag, inf_ms=0.0, model_name=""):
|
||||
bar_h = 28
|
||||
overlay_rect(img, 0, h - bar_h, w, h, C_PANEL, alpha=0.55)
|
||||
cv2.putText(
|
||||
img,
|
||||
f"{live_tag} | Frame {frame_idx}",
|
||||
f"{live_tag} | {model_name} | Frame {frame_idx} | Inf {inf_ms:.1f}ms",
|
||||
(12, h - 9),
|
||||
cv2.FONT_HERSHEY_SIMPLEX,
|
||||
0.45,
|
||||
@@ -982,26 +988,22 @@ def run():
|
||||
score_sigmoid=SCORE_SIGMOID,
|
||||
)
|
||||
|
||||
CLASS_IDS = {
|
||||
os.getenv("CLASS_AYAM", "ayam"): 0,
|
||||
os.getenv("CLASS_TALENAN", "talenan"): 1,
|
||||
}
|
||||
ayam_cls = CLASS_IDS[CLASS_AYAM]
|
||||
talenan_cls = CLASS_IDS[CLASS_TALENAN]
|
||||
ayam_cls = int(os.getenv("AYAM_CLASS_ID", "0"))
|
||||
talenan_cls = int(os.getenv("TALENAN_CLASS_ID", "1"))
|
||||
|
||||
ayam_tracker = ByteTracker(
|
||||
track_high_thresh=TRACK_HIGH_THRESH,
|
||||
track_low_thresh=TRACK_LOW_THRESH,
|
||||
match_thresh=TRACK_MATCH_THRESH,
|
||||
track_buffer=TRACK_BUFFER,
|
||||
min_hits=TRACK_MIN_HITS,
|
||||
track_high_thresh=TRACK_HIGH_THRESH_0,
|
||||
track_low_thresh=TRACK_LOW_THRESH_0,
|
||||
match_thresh=TRACK_MATCH_THRESH_0,
|
||||
track_buffer=TRACK_BUFFER_0,
|
||||
min_hits=TRACK_MIN_HITS_0,
|
||||
)
|
||||
talenan_tracker = ByteTracker(
|
||||
track_high_thresh=TRACK_HIGH_THRESH,
|
||||
track_low_thresh=TRACK_LOW_THRESH,
|
||||
match_thresh=TRACK_MATCH_THRESH,
|
||||
track_buffer=TRACK_BUFFER,
|
||||
min_hits=TRACK_MIN_HITS,
|
||||
track_high_thresh=TRACK_HIGH_THRESH_1,
|
||||
track_low_thresh=TRACK_LOW_THRESH_1,
|
||||
match_thresh=TRACK_MATCH_THRESH_1,
|
||||
track_buffer=TRACK_BUFFER_1,
|
||||
min_hits=TRACK_MIN_HITS_1,
|
||||
)
|
||||
|
||||
ayam_line_crossed = set()
|
||||
@@ -1014,7 +1016,10 @@ def run():
|
||||
|
||||
session_start = time.time()
|
||||
frame_idx = 0
|
||||
inf_ms = 0.0
|
||||
prev_gray = None
|
||||
video_writer = None
|
||||
crossing_times = deque()
|
||||
|
||||
cap, w, h, fps = connect_stream(SOURCE)
|
||||
if cap is None:
|
||||
@@ -1028,8 +1033,12 @@ def run():
|
||||
)
|
||||
print(f"Model: {MODEL_PATH} | imgsz={IMGSZ} | core_mask={CORE_MASK}")
|
||||
print(
|
||||
f"ByteTrack: high_thresh={TRACK_HIGH_THRESH} low_thresh={TRACK_LOW_THRESH} "
|
||||
f"match_thresh={TRACK_MATCH_THRESH} buffer={TRACK_BUFFER}"
|
||||
f"ByteTrack Index 0: high_thresh={TRACK_HIGH_THRESH_0} low_thresh={TRACK_LOW_THRESH_0} "
|
||||
f"match_thresh={TRACK_MATCH_THRESH_0} buffer={TRACK_BUFFER_0}"
|
||||
)
|
||||
print(
|
||||
f"ByteTrack Index 1: high_thresh={TRACK_HIGH_THRESH_1} low_thresh={TRACK_LOW_THRESH_1} "
|
||||
f"match_thresh={TRACK_MATCH_THRESH_1} buffer={TRACK_BUFFER_1}"
|
||||
)
|
||||
print(f"DB: {DB_PATH}")
|
||||
print(f"State: {STATE_FILE}")
|
||||
@@ -1061,7 +1070,20 @@ def run():
|
||||
mono = time.monotonic()
|
||||
ayam_crossed_frame = batch_closed_frame = batch_started_frame = False
|
||||
|
||||
detections = model(frame)
|
||||
skip_inference = False
|
||||
if MOTION_DETECTION_ENABLED:
|
||||
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||
if prev_gray is not None:
|
||||
diff = cv2.absdiff(gray, prev_gray)
|
||||
mean_diff = cv2.mean(diff)[0]
|
||||
skip_inference = mean_diff < MOTION_THRESHOLD
|
||||
prev_gray = gray
|
||||
|
||||
detections = []
|
||||
if not skip_inference:
|
||||
inf_start = time.time()
|
||||
detections = model(frame)
|
||||
inf_ms = inf_ms * 0.9 + (time.time() - inf_start) * 1000 * 0.1
|
||||
|
||||
if detections:
|
||||
ayam_boxes_xyxy = []
|
||||
@@ -1104,6 +1126,56 @@ def run():
|
||||
talenan_tracker.update(talenan_boxes_xyxy, talenan_scores)
|
||||
)
|
||||
|
||||
if os.getenv("DEBUG_TRACKING", "").lower() == "true":
|
||||
if len(ayam_boxes_xyxy) > 0 or len(talenan_boxes_xyxy) > 0:
|
||||
ayam_scores_str = (
|
||||
f" ayam scores: {ayam_scores.round(3).tolist()}"
|
||||
if len(ayam_scores) > 0
|
||||
else ""
|
||||
)
|
||||
talenan_scores_str = (
|
||||
f" talenan scores: {talenan_scores.round(3).tolist()}"
|
||||
if len(talenan_scores) > 0
|
||||
else ""
|
||||
)
|
||||
ayam_tracks_str = (
|
||||
f" ayam det→track: {dict(ayam_det_to_track)}"
|
||||
if ayam_det_to_track
|
||||
else ""
|
||||
)
|
||||
talenan_tracks_str = (
|
||||
f" talenan det→track: {dict(talenan_det_to_track)}"
|
||||
if talenan_det_to_track
|
||||
else ""
|
||||
)
|
||||
crossing_str = (
|
||||
f" ayam_line_crossed: {sorted(ayam_line_crossed)}"
|
||||
if ayam_line_crossed
|
||||
else ""
|
||||
)
|
||||
# Show cx values for one tracked object to check movement
|
||||
cx_sample = ""
|
||||
if len(ayam_cx_list) > 0 and ayam_det_to_track:
|
||||
sample_tid = list(ayam_det_to_track.values())[0]
|
||||
sample_cx = ayam_cx_list[
|
||||
list(ayam_det_to_track.keys())[0]
|
||||
]
|
||||
prev = (
|
||||
ayam_tracked.get(sample_tid, (None,))[0]
|
||||
if ayam_tracked.get(sample_tid)
|
||||
else None
|
||||
)
|
||||
cx_sample = (
|
||||
f" sample tid={sample_tid} prev_cx={prev} cx={sample_cx:.1f}"
|
||||
)
|
||||
print(
|
||||
f"[DEBUG F{frame_idx}] ayam_dets={len(ayam_boxes_xyxy)} "
|
||||
f"talenan_dets={len(talenan_boxes_xyxy)} "
|
||||
f"line_x={line_x}{ayam_scores_str}{talenan_scores_str}"
|
||||
f"{ayam_tracks_str}{talenan_tracks_str}{crossing_str}"
|
||||
f"{cx_sample}"
|
||||
)
|
||||
|
||||
# Process talenan crossings
|
||||
for di in range(len(talenan_boxes_xyxy)):
|
||||
tid = talenan_det_to_track.get(di)
|
||||
@@ -1145,6 +1217,11 @@ def run():
|
||||
crossed_line(prev_cx, cx, line_x)
|
||||
and tid not in ayam_line_crossed
|
||||
):
|
||||
if os.getenv("DEBUG_TRACKING", "").lower() == "true":
|
||||
print(
|
||||
f"[DEBUG F{frame_idx}] CROSS DETECTED: tid={tid} "
|
||||
f"prev_cx={prev_cx:.1f} → cx={cx:.1f} line_x={line_x}"
|
||||
)
|
||||
ayam_line_crossed.add(tid)
|
||||
_, started_new = store.record_ayam_crossing(tid)
|
||||
if cross_logger:
|
||||
@@ -1159,6 +1236,7 @@ def run():
|
||||
ayam_crossed_frame = True
|
||||
if started_new:
|
||||
batch_started_frame = True
|
||||
crossing_times.append(mono)
|
||||
ayam_cross_flash[tid] = CROSS_FLASH_FRAMES
|
||||
popups.append(
|
||||
{
|
||||
@@ -1216,7 +1294,9 @@ def run():
|
||||
batch_num = store.current_batch_number or 0
|
||||
batch_count = store.current_batch_count
|
||||
display_total = store.display_total()
|
||||
rate = (display_total / elapsed * 60) if elapsed > 0 else 0.0
|
||||
while crossing_times and mono - crossing_times[0] > RATE_WINDOW_SEC:
|
||||
crossing_times.popleft()
|
||||
rate = (len(crossing_times) / RATE_WINDOW_SEC * 60) if crossing_times else 0.0
|
||||
|
||||
draw_elegant_counting_line(frame, line_x, h, line_pulse)
|
||||
draw_hero_count(frame, line_x, h, batch_count, count_pulse)
|
||||
@@ -1228,12 +1308,16 @@ def run():
|
||||
display_total,
|
||||
elapsed,
|
||||
rate,
|
||||
CAMERA_NAME,
|
||||
now_str(),
|
||||
)
|
||||
draw_batch_banner(frame, w, batch_num, batch_pulse)
|
||||
draw_footer(
|
||||
frame, w, h, frame_idx, "LIVE-RKNN-BT" if IS_LIVE else "FILE-RKNN-BT"
|
||||
frame,
|
||||
w,
|
||||
h,
|
||||
frame_idx,
|
||||
"LIVE" if IS_LIVE else "FILE",
|
||||
inf_ms,
|
||||
Path(MODEL_PATH).name,
|
||||
)
|
||||
popups = draw_popups(frame, popups, frame_idx)
|
||||
|
||||
|
||||
@@ -3,3 +3,4 @@ rknn-toolkit-lite2
|
||||
opencv-python
|
||||
flask
|
||||
python-dotenv
|
||||
openpyxl
|
||||
+40
-16
@@ -561,7 +561,7 @@
|
||||
<div class="logo-icon">◆</div>
|
||||
<div>
|
||||
<h1>ZenAI APC Module</h1>
|
||||
<div class="header-sub">Edge Jetson counter — YOLO TensorRT</div>
|
||||
<div class="header-sub">Edge Nano counter — YOLO RockChip</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
@@ -571,7 +571,7 @@
|
||||
</div>
|
||||
<div class="live-chip">
|
||||
<span class="dot"></span>
|
||||
<span>Live</span>
|
||||
<span>{{ site_name }}</span>
|
||||
</div>
|
||||
<button class="theme-toggle" id="themeToggle" onclick="toggleTheme()" title="Toggle theme">☀️</button>
|
||||
</div>
|
||||
@@ -633,7 +633,7 @@
|
||||
<div class="vp-text">Live Feed Unavailable</div>
|
||||
<div class="vp-hint">Enable <code>LIVE_STREAM_ENABLED=true</code> in counter .env</div>
|
||||
</div>
|
||||
<img id="live-video-img" src="" alt="Live Feed" style="display:none;" onerror="onVideoError()" onload="onVideoLoad()" />
|
||||
<img id="live-video-img" alt="Live Feed" style="display:none;" onerror="onVideoError()" onload="onVideoLoad()" />
|
||||
<div class="video-error-overlay" id="video-error-overlay">Connection lost — retrying...</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -707,8 +707,8 @@
|
||||
<div class="toolbar-group">
|
||||
<input type="date" id="date-filter">
|
||||
<button class="btn btn-primary" onclick="filterByDate()">FILTER</button>
|
||||
<button class="btn btn-ghost" onclick="loadAllDates()">RESET</button>
|
||||
<button class="btn btn-export-btn" onclick="exportDayDetail()">EXPORT CSV</button>
|
||||
<button class="btn btn-ghost" onclick="resetFilter()">RESET</button>
|
||||
<button class="btn btn-export-btn" onclick="exportDayDetail()">EXPORT EXCEL</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="overflow-x:auto;">
|
||||
@@ -730,7 +730,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">Jetson Edge Counter — port 5000</div>
|
||||
<div class="footer">Edge Nano Counter by ZenAi</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal -->
|
||||
@@ -801,13 +801,15 @@ function updateToggleIcon() {
|
||||
}
|
||||
|
||||
let mainChart = null;
|
||||
let videoActive = false;
|
||||
let videoErrorTimer = null;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
loadSummary();
|
||||
loadCurrentBatch();
|
||||
loadChartData(7);
|
||||
loadRecentBatches();
|
||||
loadAllDates();
|
||||
resetFilter();
|
||||
|
||||
setInterval(() => {
|
||||
loadSummary();
|
||||
@@ -816,7 +818,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
|
||||
setInterval(() => {
|
||||
loadCurrentBatch();
|
||||
}, 2000);
|
||||
}, 200);
|
||||
});
|
||||
|
||||
async function loadCurrentBatch() {
|
||||
@@ -978,6 +980,10 @@ async function loadRecentBatches() {
|
||||
const batches = await res.json();
|
||||
|
||||
const container = document.getElementById('recent-batches');
|
||||
if (!batches || batches.length === 0) {
|
||||
container.innerHTML = '<div class="recent-item" style="justify-content:center;color:var(--text-secondary);font-size:10px;">No batches recorded yet</div>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = batches.map(b => `
|
||||
<div class="recent-item">
|
||||
<div class="ri-left">
|
||||
@@ -1008,6 +1014,11 @@ async function loadAllDates() {
|
||||
}
|
||||
}
|
||||
|
||||
function resetFilter() {
|
||||
document.getElementById('date-filter').value = '';
|
||||
loadAllDates();
|
||||
}
|
||||
|
||||
function renderDailyTable(dates) {
|
||||
const tbody = document.getElementById('daily-table-body');
|
||||
const currentDate = document.getElementById('current-date').textContent;
|
||||
@@ -1121,8 +1132,6 @@ document.addEventListener('keydown', (e) => {
|
||||
});
|
||||
|
||||
// --- Live Video Feed ---
|
||||
let videoActive = false;
|
||||
let videoErrorTimer = null;
|
||||
|
||||
function toggleVideo() {
|
||||
const btn = document.getElementById('videoToggle');
|
||||
@@ -1133,6 +1142,7 @@ function toggleVideo() {
|
||||
videoActive = !videoActive;
|
||||
|
||||
if (videoActive) {
|
||||
resetFilter();
|
||||
img.src = '/api/live-video?' + Date.now();
|
||||
img.style.display = 'block';
|
||||
if (placeholder) placeholder.style.display = 'none';
|
||||
@@ -1179,13 +1189,27 @@ function hideVideoError() {
|
||||
</script>
|
||||
|
||||
<script>
|
||||
function exportDayDetail() {
|
||||
const date = document.getElementById('date-filter')?.value;
|
||||
if (!date) {
|
||||
alert('Please select a date first');
|
||||
return;
|
||||
async function exportDayDetail() {
|
||||
try {
|
||||
const date = document.getElementById('date-filter')?.value;
|
||||
const url = date ? `/api/export-day-csv/${date}` : '/api/export-daily-csv';
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error('Export failed');
|
||||
const blob = await res.blob();
|
||||
const disposition = res.headers.get('Content-Disposition');
|
||||
const filename = disposition
|
||||
? decodeURIComponent(disposition.replace(/.*filename="?([^";]+)"?.*/, '$1'))
|
||||
: `export_${date || 'all'}.xlsx`;
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(a.href);
|
||||
} catch (err) {
|
||||
alert('Export error: ' + err.message);
|
||||
}
|
||||
window.location.href = `/api/export-day-csv/${date}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
Reference in new issue
Block a user