Compare commits

...
17 Commits
Author SHA1 Message Date
proitlab fccc285ab3 Add OUTPUT_DIR browser + copy-on-load with progress to upload dashboard
LOAD MP4 on an OUTPUT_DIR file copies it into UPLOAD_DIR (chunked,
progress via /api/copy-progress) before spawning RECOUNT_CMD; collision
in UPLOAD_DIR fails with 400. New read-only folder-grouped browser
mirrors recounting_dashboard.py. Docs updated.
2026-08-13 13:33:26 +07:00
proitlab 634d649069 Fix STREAM toggle: auto-on preview only once per session, manual OFF persists 2026-08-10 15:41:06 +07:00
proitlab d9493ece5a STOP: host-wide /proc sweep guarantees zero RECOUNT_CMD processes remain 2026-08-10 12:19:06 +07:00
proitlab 2606de9e78 Document LOAD MP4 / .continue recount flow in SPEC, AGENTS, env example 2026-08-10 10:59:26 +07:00
proitlab 3624993189 Add LOAD MP4 button flow before START RECOUNT in upload templates 2026-08-10 10:56:50 +07:00
proitlab 5f39d47df8 Split recount flow: /api/load-mp4 spawns, /api/start-recount signals .continue 2026-08-10 10:50:07 +07:00
proitlab 6be017c4f0 Auto-on live preview when recount starts (all recounting templates) 2026-08-10 09:53:55 +07:00
proitlab 6043197d72 Fix recount stop: kill whole process group, not just shell 2026-08-05 10:29:41 +07:00
proitlab d909bc85bd Add bytetrack-recounting-upload-dashboard.service for port 5003 2026-08-05 10:27:43 +07:00
proitlab 763bcab3a6 Open cross-dashboard header links in same tab 2026-08-05 08:21:46 +07:00
proitlab 3ac73f6fd9 Add Lamborghini-themed upload recounting dashboard as default template 2026-08-05 08:10:20 +07:00
proitlab 89673db0bf Add cross-dashboard header links (UPLOAD_DASHBOARD_URL, LIVE_DASHBOARD_URL) 2026-08-05 07:58:00 +07:00
proitlab 99e126de1b Keep local file selection in applyState across all recounting dashboards 2026-08-05 01:10:00 +07:00
proitlab 5df224116d Keep file selection when /api/state reports no active recount 2026-08-05 01:00:00 +07:00
proitlab f01601d1d7 Parse batch number and date from upload filename for live API lookup 2026-08-05 00:49:39 +07:00
proitlab 14ebfb7779 Keep original filename on upload, remove timestamp prefix 2026-08-05 00:41:44 +07:00
proitlab 79656cd661 Add upload progress bar to recounting upload dashboard 2026-08-05 00:39:47 +07:00
13 changed files with 1881 additions and 178 deletions

No files matched your search

+11 -1
View File
@@ -9,6 +9,7 @@
- `batch_store.py` — shared SQLite persistence + batch state machine.
- `counter_dashboard.py` — Flask dashboard on port 5000, same DB.
- `recounting_dashboard.py` — Flask recounting dashboard on port 5002, consumes live + recount APIs.
- `recounting_dashboard_upload.py` — Flask upload+recount dashboard on port 5003; uploads MP4 first, then **LOAD MP4** spawns `RECOUNT_CMD` (process loads and pauses), then **START RECOUNT** touches `{SHM_DIR}/.continue` to begin counting.
## No build / test / lint
@@ -30,6 +31,9 @@ PYTHONNOUSERSITE=1 venv/bin/python counter_live_rknn_bytetrack.py
# Run dashboard
PYTHONNOUSERSITE=1 venv/bin/python counter_dashboard.py
# Run upload recounting dashboard
PYTHONNOUSERSITE=1 venv/bin/python recounting_dashboard_upload.py
```
## Key environment & install quirks
@@ -39,9 +43,15 @@ PYTHONNOUSERSITE=1 venv/bin/python counter_dashboard.py
- **`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`.
- Three systemd units: `bytetrack-counter.service`, `bytetrack-counter-dashboard.service`, and `bytetrack-recounting-upload-dashboard.service` (upload recounting dashboard, port 5003).
- `counter_live.py` (TensorRT) is Jetson-only and won't work on RK3588.
- **Reset flow**: `POST /api/reset` → deletes state JSON + touches `{SHM_DIR}/.reset`. `batch_store._check_reset_signal()` watches this marker and clears in-memory state on next crossing.
- **Recount continue flow** (upload dashboard, port 5003): `POST /api/load-mp4 {path}` kills the old process, spawns `RECOUNT_CMD` (loads + pauses), and POSTs `/api/reset` to the recount node. `POST /api/start-recount` (no body, requires a loaded file) touches `{SHM_DIR}/.continue`; the C++ process consumes that marker to begin counting. The dashboard never clears the marker.
- **OUTPUT_DIR browser + copy-on-load** (upload dashboard, port 5003): `GET /api/mp4-files` lists MP4s from `OUTPUT_DIR` folder-grouped (mirrors `recounting_dashboard.py`'s `/api/mp4-files` shape). Selecting one and pressing LOAD MP4 makes `POST /api/load-mp4` copy it into `UPLOAD_DIR` first (chunked, progress reported via `GET /api/copy-progress` → `{active,name,total,done,pct}`, frontend polls every 250 ms to drive the progress bar). Name collision in `UPLOAD_DIR` → 400 error (no overwrite). The OUTPUT_DIR browser is read-only (no delete).
- **Recount STOP sweep**: `POST /api/stop-recount` kills the tracked process group (`killpg` TERM→5s→KILL) then sweeps the host via `/proc` for any process whose argv matches the `RECOUNT_CMD` binary name (basename of the first token, so it also catches orphans from a dashboard restart); TERM→`_SWEEP_GRACE_SEC`→KILL with `_SWEEP_MAX_RETRIES` retries, all under `_recount_lock`. Returns `{success, killed, remaining}`; `remaining` is 0 in the normal path, and survivors (e.g. D-state) are logged rather than force-hanging.
- **Upload filename contract**: uploads are expected as `batch_XX_YYYYMMDD_HHmmSS.mp4` (XX = batch number, timestamp = date). `recounting_dashboard_upload.py` parses both to query the live API's `/api/day-detail/<YYYY-MM-DD>` for the recorded count.
- **`RECOUNT_CMD`** in the upload dashboard is a template with a `{path}` placeholder, e.g. `bytetrack-counter-cpp config.env --source {path}`; the uploaded file path is `shlex.quote()`d before substitution, and the command is spawned by **LOAD MP4** (loads + pauses until `.continue` is touched).
- **Cross-dashboard header links**: `UPLOAD_DASHBOARD_URL` (live → upload dashboard, `counter_dashboard.py`) and `LIVE_DASHBOARD_URL` (upload → live dashboard, `recounting_dashboard_upload.py`); empty value hides the header link.
## Code conventions
+45 -2
View File
@@ -13,10 +13,10 @@ Daily cutoff @ HH:MM resets batch numbering. RK3588 hardware.
- `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 (dashboard) + 5002 (recounting), systemd supervision
- Flask on port 5000 (dashboard) + 5002 (recounting) + 5003 (upload recounting), 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` + `recounting_dashboard.py`
- Single deployment: `counter_live_rknn_bytetrack.py` + `counter_dashboard.py` + `recounting_dashboard.py` + `recounting_dashboard_upload.py`
- `go2rtc` ! running for recounting MP4 streaming (port 1984)
## §I — Interfaces
@@ -54,6 +54,7 @@ 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)
env: UPLOAD_DASHBOARD_URL → header link to upload recounting dashboard (default empty → hidden)
### Recounting dashboard config
```
@@ -63,6 +64,16 @@ env: RECOUNT_API_URL → base URL of recounting counter API (second node)
env: GO2RTC_API_URL → go2rtc REST API (default http://localhost:1984)
env: GO2RTC_STREAM_NAME → go2rtc stream name for recount preview (default "recount")
```
### Upload recounting dashboard config
```
env: RECOUNTING_UPLOAD_PORT → port for upload UI (default 5003)
env: UPLOAD_DIR → dir for uploaded MP4s (default <repo>/uploads)
env: OUTPUT_DIR → dir scanned for "From Output Directory" browser (default /opt/bytetrack-counter)
env: RECOUNT_CMD → replay command template with {path} placeholder (default "bytetrack-counter config.env --source {path}")
env: RECOUNTING_UPLOAD_TEMPLATE → template (default recounting_upload_lamborghini.html)
env: LIVE_DASHBOARD_URL → header link to live counter dashboard (default empty → hidden)
```
```
### SQLite
@@ -107,6 +118,25 @@ api: GET /api/download-mp4?file=<path> → download selected MP4
api: POST /api/start-recount {path} → reset recount counter + launch ffmpeg RTSP, return {stream_url}
api: POST /api/stop-recount → kill ffmpeg + clear current file
```
### Upload recounting dashboard
```
api: GET / → upload recounting HTML (template via RECOUNTING_UPLOAD_TEMPLATE env var)
api: POST /api/upload → multipart .mp4 (≤512MB), saved as original filename in UPLOAD_DIR; returns {name, path, size}
api: GET /api/uploads → list uploaded MP4s sorted by mtime desc → [ {name, path, size, mtime} ]
api: GET /api/mp4-files → list OUTPUT_DIR MP4s grouped by folder (date), files sorted by batch # → [ {folder, files:[{name, path, size, mtime}]} ]
api: GET /api/copy-progress → {active:false} idle | {active, name, total, done, pct} during an in-progress copy
api: POST /api/delete-upload {path} → delete uploaded MP4 (path restricted to UPLOAD_DIR)
api: POST /api/load-mp4 {path} → if path outside UPLOAD_DIR: collision check (same-name in UPLOAD_DIR → 400), else copy (chunked, progress-reporting) into UPLOAD_DIR first; then kill old process, spawn RECOUNT_CMD (copied path shlex-quoted) paused, reset recount API; returns copied path
api: POST /api/start-recount → require loaded file, touch {SHM_DIR}/.continue to signal C++ process to begin counting
api: POST /api/stop-recount → killpg tracked group + host-wide /proc sweep of RECOUNT_CMD binary (TERM→grace→KILL, verify loop); returns {success, killed, remaining}
api: GET /api/state → {streaming, file, file_name, stream_url, batch_number, batch_date}
api: GET /api/proxy-stream → proxy MJPEG from RECOUNT_API_URL:/api/live-video (same-origin)
api: GET /api/live-progress → proxy to LIVE_API_URL:/api/current-batch
api: GET /api/recount-progress → proxy to RECOUNT_API_URL:/api/current-batch
api: GET /api/batch-result?file=<path> → parse batch num + date (YYYY-MM-DD) from filename batch_XX_YYYYMMDD_HHmmSS.mp4, query live API /api/day-detail/<date>, fallback recent-batches
api: GET /api/download-mp4?file=<path> → download selected MP4
```
```
## §V — Invariants
@@ -132,6 +162,12 @@ 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)
V20: reset → delete STATE_FILE + touch {SHM_DIR}/.reset; batch_store._check_reset_signal() watches marker & clears in-memory state before next crossing
V21: upload filename batch_XX_YYYYMMDD_HHmmSS.mp4 → batch# + date parsed; batch-result queries /api/day-detail/<YYYY-MM-DD> on live API
V22: preview auto-on once per streaming session — enablePreview() on START RECOUNT + applyState streaming branch guarded by previewAutoOn flag; manual toggle persists until next session (flag reset only on stop); img.onerror retries cache-busted src while streaming
V23: .continue marker flow — LOAD MP4 spawns RECOUNT_CMD paused; START RECOUNT touches {SHM_DIR}/.continue; C++ process consumes marker to begin counting; dashboard never clears it (LOAD alone does not count)
V24: STOP → killpg tracked group then host-wide /proc sweep of RECOUNT_CMD binary (basename of first token); sweep runs under _recount_lock, TERM→_SWEEP_GRACE_SEC→KILL, bounded retries; returns {success, killed, remaining} with remaining==0 in normal path; survivors (D-state) logged, never force-hang
V25: LOAD MP4 on an OUTPUT_DIR file → copy into UPLOAD_DIR (original untouched); copy runs server-side, chunked, reports {done,total} to _copy_progress under _copy_lock; name collision in UPLOAD_DIR → 400 error, no overwrite
V26: OUTPUT_DIR browser → read-only, folder-grouped via /api/mp4-files (mirrors 5002 shape); no delete button on OUTPUT_DIR rows
```
## §T — Tasks
@@ -152,6 +188,12 @@ T11|x|reduce live-counter poll interval 2000→200ms for real-time feel|
T12|x|add recounting dashboard — dual-API counter panels, MP4 browser, go2rtc streaming|
T13|x|add template system — DASHBOARD_TEMPLATE env var selects dashboard.html|lamborghini|tesla|
T14|x|harden reset API — separate SHM marker creation from state file cleanup; return 500 on SHM failure|V20
T15|x|add upload recounting dashboard — MP4 upload, progress bar, RECOUNT_CMD replay|V21
T16|x|add cross-dashboard header links — UPLOAD_DASHBOARD_URL (live→upload) & LIVE_DASHBOARD_URL (upload→live)|I.config
T17|x|auto-on live preview when recount running — enablePreview() on START + applyState; onerror retry while streaming|V22
T18|x|split recount flow — /api/load-mp4 spawns paused RECOUNT_CMD, /api/start-recount touches {SHM_DIR}/.continue; C++ consumes marker|V23
T19|x|hard-kill STOP — sweep all RECOUNT_CMD-binary processes via /proc, verify remaining==0, report killed/remaining|V24
T20|x|add OUTPUT_DIR browser to upload dashboard — /api/mp4-files listing, copy-on-load with progress polling into UPLOAD_DIR, collision guard|V25,V26
```
## §B — Bugs
@@ -159,5 +201,6 @@ T14|x|harden reset API — separate SHM marker creation from state file cleanup;
```
id|date|cause|fix
B1|2026-07-29|prev_gray not reset on stream reconnect → cv2.absdiff crash or false motion|V19
B2|2026-08-10|applyState re-ran enablePreview() every 1s poll, overriding manual STREAM toggle (OFF flipped back to ON)|V22
```
@@ -0,0 +1,34 @@
[Unit]
Description=Edge Counter Recounting Upload Dashboard (Flask, port 5003)
Documentation=file:///opt/bytetrack-counter/DEPLOY.md
After=network-online.target bytetrack-counter-dashboard.service
Wants=network-online.target bytetrack-counter-dashboard.service
[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/opt/bytetrack-counter
EnvironmentFile=/opt/bytetrack-counter/.env
Environment=PATH=/opt/bytetrack-counter/venv/bin:/usr/local/bin:/usr/bin:/bin
Environment=PYTHONNOUSERSITE=1
Environment=FLASK_DEBUG=false
ExecStart=/opt/bytetrack-counter/venv/bin/python recounting_dashboard_upload.py
TimeoutStopSec=15
KillSignal=SIGTERM
Restart=on-failure
RestartSec=5
StartLimitInterval=60s
StartLimitBurst=3
NoNewPrivileges=true
ProtectHome=true
PrivateTmp=false
[Install]
WantedBy=multi-user.target
+12 -5
View File
@@ -159,6 +159,8 @@ SECRET_KEY=change-me-in-production
DASHBOARD_HOST=0.0.0.0
# Listen port for the dashboard web UI
DASHBOARD_PORT=5000
# URL of the upload recounting dashboard (recounting_dashboard_upload.py); empty hides the header link
UPLOAD_DASHBOARD_URL=http://localhost:5003
# 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
@@ -183,8 +185,13 @@ RECOUNT_STREAM_NAME=stream_1
RECOUNTING_UPLOAD_PORT=5003
# Directory where uploaded MP4 files are stored
UPLOAD_DIR=/opt/bytetrack-counter/uploads
# Command to launch the recounting counter process (placeholder, fill in real command).
# {path} is substituted with the absolute path of the uploaded MP4 file.
RECOUNT_CMD=bytetrack-counter config.env --source {path}
# Template file for the upload dashboard: "recounting_upload.html" (default)
RECOUNTING_UPLOAD_TEMPLATE=recounting_upload.html
# Directory scanned for the "From Output Directory" file browser (folder-grouped MP4s).
# Selecting one of those files and pressing LOAD MP4 copies it into UPLOAD_DIR first.
OUTPUT_DIR=/opt/bytetrack-counter
# Command launched by LOAD MP4 (bytetrack-counter-cpp); {path} is the uploaded MP4.
# The process loads + pauses until START RECOUNT touches {SHM_DIR}/.continue.
RECOUNT_CMD=bytetrack-counter-cpp config.env --source {path}
# Template file for the upload dashboard: "recounting_upload_lamborghini.html" (default) or "recounting_upload.html"
RECOUNTING_UPLOAD_TEMPLATE=recounting_upload_lamborghini.html
# URL of the live counter dashboard (counter_dashboard.py); empty hides the header link
LIVE_DASHBOARD_URL=http://localhost:5000
+2 -1
View File
@@ -40,6 +40,7 @@ SHM_DIR = os.getenv("SHM_DIR", "/dev/shm/bytetrack-counter")
SITE_NAME = os.getenv("SITE_NAME", "LIVE")
TEMPLATE = os.getenv("DASHBOARD_TEMPLATE", "dashboard.html")
UPLOAD_DASHBOARD_URL = os.getenv("UPLOAD_DASHBOARD_URL", "")
DASHBOARD_PORT = int(os.getenv("DASHBOARD_PORT", "5000"))
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
@@ -132,7 +133,7 @@ def get_counting_date(dt=None, cutoff_str=CUTOFF_TIME):
@app.route("/")
def index():
return render_template(TEMPLATE, site_name=SITE_NAME)
return render_template(TEMPLATE, site_name=SITE_NAME, upload_dashboard_url=UPLOAD_DASHBOARD_URL)
@app.route("/api/current-batch")
+271 -48
View File
@@ -8,6 +8,8 @@ import logging
import os
import re
import shlex
import shutil
import signal
import subprocess
import threading
import time
@@ -31,11 +33,13 @@ app.config["MAX_CONTENT_LENGTH"] = 512 * 1024 * 1024 # 512 MB
REPO_ROOT = Path(__file__).resolve().parent
UPLOAD_DIR = Path(os.getenv("UPLOAD_DIR", str(REPO_ROOT / "uploads")))
OUTPUT_DIR = Path(os.getenv("OUTPUT_DIR", "/opt/bytetrack-counter"))
LIVE_API_URL = os.getenv("LIVE_API_URL", "http://localhost:5000")
RECOUNT_API_URL = os.getenv("RECOUNT_API_URL", "http://localhost:5001")
SITE_NAME = os.getenv("SITE_NAME", "RECOUNT")
TEMPLATE = os.getenv("RECOUNTING_UPLOAD_TEMPLATE", "recounting_upload.html")
TEMPLATE = os.getenv("RECOUNTING_UPLOAD_TEMPLATE", "recounting_upload_lamborghini.html")
LIVE_DASHBOARD_URL = os.getenv("LIVE_DASHBOARD_URL", "")
DASHBOARD_PORT = int(os.getenv("RECOUNTING_UPLOAD_PORT", "5003"))
DASHBOARD_HOST = os.getenv("DASHBOARD_HOST", "0.0.0.0")
@@ -43,20 +47,30 @@ FLASK_DEBUG = os.getenv("FLASK_DEBUG", "false").lower() == "true"
RECOUNT_CMD = os.getenv("RECOUNT_CMD", "bytetrack-counter config.env --source {path}")
SHM_DIR = os.getenv("SHM_DIR", "/dev/shm/bytetrack-counter")
_CONTINUE_FLAG = Path(f"{SHM_DIR}/.continue")
_SWEEP_GRACE_SEC = 5
_SWEEP_MAX_RETRIES = 3
_http_session = requests.Session()
_http_session.timeout = 3
_FILENAME_RE = re.compile(r"batch[_-]?(\d+)", re.IGNORECASE)
_FILENAME_RE = re.compile(r"batch[_-]?(\d+)[_-](\d{8})[_-]\d{6}", re.IGNORECASE)
_recount_proc = None
_recount_lock = threading.Lock()
_current_file = None
_copy_progress = {}
_copy_lock = threading.Lock()
def _parse_filename(filename):
m = _FILENAME_RE.search(filename)
if m:
return int(m.group(1)), None
raw = m.group(2)
return int(m.group(1)), f"{raw[:4]}-{raw[4:6]}-{raw[6:8]}"
return None, None
@@ -72,13 +86,85 @@ def _api_get(base_url, path, default=None):
def _stop_recount_locked():
global _recount_proc
if _recount_proc:
proc = _recount_proc
_recount_proc = None
if proc is None:
return
try:
pgid = os.getpgid(proc.pid)
except (ProcessLookupError, PermissionError):
return
try:
os.killpg(pgid, signal.SIGTERM)
except (ProcessLookupError, PermissionError):
pass
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
try:
_recount_proc.kill()
_recount_proc.wait(timeout=3)
os.killpg(pgid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
try:
proc.wait(timeout=3)
except Exception:
pass
_recount_proc = None
except Exception:
pass
def _recount_binary_name():
if not RECOUNT_CMD:
return "bytetrack-counter-cpp"
try:
first = shlex.split(RECOUNT_CMD)[0]
except (ValueError, IndexError):
return "bytetrack-counter-cpp"
return Path(first).name or "bytetrack-counter-cpp"
def _iter_matching_pids(binary):
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
try:
with open(f"/proc/{entry}/cmdline", "rb") as f:
raw = f.read().split(b"\x00")
except (FileNotFoundError, PermissionError, ProcessLookupError):
continue
args = [t.decode(errors="ignore") for t in raw if t]
for token in args:
for piece in token.split():
if Path(piece).name == binary:
yield int(entry)
break
else:
continue
break
def _sweep_recount_processes(binary):
killed = 0
for _ in range(_SWEEP_MAX_RETRIES):
pids = list(_iter_matching_pids(binary))
if not pids:
break
for pid in pids:
if pid not in list(_iter_matching_pids(binary)):
continue
try:
os.kill(pid, signal.SIGTERM)
killed += 1
except (ProcessLookupError, PermissionError):
pass
time.sleep(_SWEEP_GRACE_SEC)
for pid in list(_iter_matching_pids(binary)):
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
time.sleep(1)
return killed, len(list(_iter_matching_pids(binary)))
def _folder_date(filepath, base):
@@ -91,7 +177,7 @@ def _folder_date(filepath, base):
@app.route("/")
def index():
return render_template(TEMPLATE, site_name=SITE_NAME, upload_dir=str(UPLOAD_DIR))
return render_template(TEMPLATE, site_name=SITE_NAME, upload_dir=str(UPLOAD_DIR), output_dir=str(OUTPUT_DIR), live_dashboard_url=LIVE_DASHBOARD_URL)
@app.route("/api/live-progress")
@@ -125,6 +211,55 @@ def api_uploads():
return jsonify(files)
@app.route("/api/mp4-files")
def api_mp4_files():
folders = {}
output = Path(OUTPUT_DIR)
if not output.exists():
return jsonify([])
for d in sorted(output.iterdir(), reverse=True):
if not d.is_dir():
continue
folder_name = d.name
mp4s = sorted(d.glob("*.mp4"), key=lambda p: _parse_filename(p.name)[0] or 0)
if not mp4s:
continue
files = []
for f in mp4s:
st = f.stat()
files.append({
"name": f.name,
"path": str(f),
"size": st.st_size,
"mtime": datetime.fromtimestamp(st.st_mtime).isoformat(),
})
folders[folder_name] = files
result = []
for folder, files in sorted(folders.items(), reverse=True):
result.append({"folder": folder, "files": files})
return jsonify(result)
@app.route("/api/copy-progress")
def api_copy_progress():
with _copy_lock:
p = dict(_copy_progress)
if not p or not p.get("active"):
return jsonify({"active": False})
total = p.get("total") or 0
done = p.get("done") or 0
pct = round(done * 100.0 / total) if total else 0
return jsonify({
"active": True,
"name": p.get("name"),
"total": total,
"done": done,
"pct": pct,
})
@app.route("/api/upload", methods=["POST"])
def api_upload():
if "file" not in request.files:
@@ -136,9 +271,7 @@ def api_upload():
return jsonify({"success": False, "error": "Only .mp4 files allowed"}), 400
Path(UPLOAD_DIR).mkdir(parents=True, exist_ok=True)
safe = secure_filename(f.filename)
ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
dest_name = f"{ts}_{safe}"
dest_name = secure_filename(f.filename)
dest_path = Path(UPLOAD_DIR) / dest_name
f.save(str(dest_path))
@@ -164,27 +297,7 @@ def api_delete_upload():
return jsonify({"success": True})
@app.route("/api/start-recount", methods=["POST"])
def start_recount():
global _recount_proc, _current_file
data = request.get_json(force=True) or {}
upload_path = data.get("path", "")
if not upload_path:
return jsonify({"success": False, "error": "Missing 'path'"}), 400
if not os.path.isfile(upload_path):
return jsonify({"success": False, "error": f"File not found: {upload_path}"}), 404
with _recount_lock:
_stop_recount_locked()
_current_file = upload_path
cmd_str = RECOUNT_CMD.replace("{path}", shlex.quote(str(upload_path)))
try:
_recount_proc = subprocess.Popen(cmd_str, shell=True)
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Recount started: {cmd_str}")
except Exception as e:
_current_file = None
return jsonify({"success": False, "error": f"Failed to start: {e}"}), 500
def _reset_recount_api():
try:
resp = _http_session.post(f"{RECOUNT_API_URL}/api/reset", timeout=5)
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Recount reset: {RECOUNT_API_URL}/api/reset → {resp.status_code}")
@@ -195,6 +308,85 @@ def start_recount():
except Exception as e:
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Recount reset: {RECOUNT_API_URL}/api/reset → error: {e}")
def _spawn_recount_locked(upload_path):
global _recount_proc
cmd_str = RECOUNT_CMD.replace("{path}", shlex.quote(str(upload_path)))
_recount_proc = subprocess.Popen(cmd_str, shell=True, start_new_session=True)
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Recount loaded: {cmd_str}")
def _copy_file_with_progress(src, dest):
global _copy_progress
total = os.path.getsize(src)
done = 0
with _copy_lock:
_copy_progress = {
"active": True,
"name": Path(src).name,
"total": total,
"done": 0,
"error": None,
}
try:
with open(src, "rb") as fsrc, open(dest, "wb") as fdst:
while True:
buf = fsrc.read(1024 * 1024)
if not buf:
break
fdst.write(buf)
done += len(buf)
with _copy_lock:
_copy_progress["done"] = done
shutil.copystat(src, dest)
except Exception as e:
with _copy_lock:
_copy_progress["error"] = str(e)
raise
finally:
with _copy_lock:
_copy_progress["active"] = False
@app.route("/api/load-mp4", methods=["POST"])
def load_mp4():
global _current_file
data = request.get_json(force=True) or {}
src_path = data.get("path", "")
if not src_path:
return jsonify({"success": False, "error": "Missing 'path'"}), 400
if not os.path.isfile(src_path):
return jsonify({"success": False, "error": f"File not found: {src_path}"}), 404
src_path = str(Path(src_path).resolve())
upload_path = src_path
if Path(src_path).parent != Path(UPLOAD_DIR).resolve():
dest_path = str(Path(UPLOAD_DIR) / Path(src_path).name)
if os.path.exists(dest_path):
return jsonify({
"success": False,
"error": f"{Path(dest_path).name} already exists in uploads, delete it first",
}), 400
Path(UPLOAD_DIR).mkdir(parents=True, exist_ok=True)
try:
_copy_file_with_progress(src_path, dest_path)
except Exception as e:
with _copy_lock:
err = _copy_progress.get("error") or str(e)
return jsonify({"success": False, "error": f"Copy failed: {err}"}), 500
upload_path = dest_path
with _recount_lock:
_stop_recount_locked()
_current_file = upload_path
try:
_spawn_recount_locked(upload_path)
except Exception as e:
_current_file = None
return jsonify({"success": False, "error": f"Failed to start: {e}"}), 500
_reset_recount_api()
return jsonify({
"success": True,
"stream_url": "/api/proxy-stream",
@@ -203,13 +395,41 @@ def start_recount():
})
@app.route("/api/start-recount", methods=["POST"])
def start_recount():
with _recount_lock:
current = _current_file
if not current:
return jsonify({"success": False, "error": "Load an MP4 first"}), 400
try:
Path(SHM_DIR).mkdir(parents=True, exist_ok=True)
_CONTINUE_FLAG.touch(exist_ok=True)
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Recount continue: {_CONTINUE_FLAG}")
except Exception as e:
return jsonify({"success": False, "error": f"Failed to signal: {e}"}), 500
return jsonify({
"success": True,
"stream_url": "/api/proxy-stream",
"file": Path(current).name,
"path": current,
})
@app.route("/api/stop-recount", methods=["POST"])
def stop_recount():
global _current_file
with _recount_lock:
_stop_recount_locked()
_current_file = None
return jsonify({"success": True})
killed, remaining = _sweep_recount_processes(_recount_binary_name())
stamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
if remaining:
print(f"[{stamp}] Recount stop: killed {killed}, remaining {remaining} (SIGKILL could not reap)")
else:
print(f"[{stamp}] Recount stop: killed {killed}, remaining {remaining}")
return jsonify({"success": True, "killed": killed, "remaining": remaining})
@app.route("/api/state")
@@ -256,9 +476,13 @@ def api_proxy_stream():
def api_batch_result():
fpath = request.args.get("file", "")
filename = Path(fpath).name
batch_num, _ = _parse_filename(filename)
batch_num, date_str = _parse_filename(filename)
if batch_num is None:
return jsonify({"success": False, "error": "Cannot parse batch number from filename"}), 200
if not date_str:
date_str = _folder_date(fpath, Path(UPLOAD_DIR))
if not date_str:
return jsonify({"success": False, "error": "Cannot determine date from filename"}), 200
def _match_in_batches(batches):
for b in batches:
@@ -266,20 +490,18 @@ def api_batch_result():
return b
return None
date_str = _folder_date(fpath, Path(UPLOAD_DIR))
if date_str:
data = _api_get(LIVE_API_URL, f"/api/day-detail/{date_str}")
if data:
b = _match_in_batches(data.get("batches", []))
if b:
return jsonify({
"success": True,
"batch_number": batch_num,
"date": date_str,
"count": b["count"],
"start_time": b.get("start_time"),
"end_time": b.get("end_time"),
})
data = _api_get(LIVE_API_URL, f"/api/day-detail/{date_str}")
if data:
b = _match_in_batches(data.get("batches", []))
if b:
return jsonify({
"success": True,
"batch_number": batch_num,
"date": date_str,
"count": b["count"],
"start_time": b.get("start_time"),
"end_time": b.get("end_time"),
})
recent = _api_get(LIVE_API_URL, "/api/recent-batches?limit=100")
if recent:
@@ -312,5 +534,6 @@ if __name__ == "__main__":
print(f"Live API: {LIVE_API_URL}")
print(f"Recount API: {RECOUNT_API_URL}")
print(f"Upload dir: {UPLOAD_DIR}")
print(f"Output dir: {OUTPUT_DIR}")
print(f"Recount command: {RECOUNT_CMD}")
app.run(host=DASHBOARD_HOST, port=DASHBOARD_PORT, debug=FLASK_DEBUG)
+1
View File
@@ -575,6 +575,7 @@
<span class="date-val" id="current-date">--</span>
Counting Day
</div>
{% if upload_dashboard_url %}<a class="live-chip" href="{{ upload_dashboard_url }}" style="text-decoration:none;">RECOUNT UPLOAD</a>{% endif %}
<div class="live-chip">
<span class="dot"></span>
<span>{{ site_name }}</span>
+1
View File
@@ -408,6 +408,7 @@
<span class="date-val" id="current-date">--</span>
Counting Day
</div>
{% if upload_dashboard_url %}<a class="live-chip" href="{{ upload_dashboard_url }}" style="text-decoration:none;">RECOUNT UPLOAD</a>{% endif %}
<div class="live-chip">
<span class="dot"></span>
<span>{{ site_name }}</span>
+1
View File
@@ -418,6 +418,7 @@
<span class="date-val" id="current-date">--</span>
Counting Day
</div>
{% if upload_dashboard_url %}<a class="live-chip" href="{{ upload_dashboard_url }}" style="text-decoration:none;">RECOUNT UPLOAD</a>{% endif %}
<div class="live-chip">
<span class="dot"></span>
<span>{{ site_name }}</span>
+27 -24
View File
@@ -449,6 +449,7 @@
let selectedFile = null;
let streaming = false;
let streamUrl = '';
let previewAutoOn = false;
document.addEventListener('DOMContentLoaded', () => {
loadRecountProgress();
@@ -471,37 +472,23 @@ async function syncState() {
function applyState(data) {
if (!data) return;
if (data.file) {
selectedFile = data.file;
document.getElementById('btn-start').disabled = data.streaming;
document.getElementById('btn-download').disabled = false;
} else {
selectedFile = null;
batchResultLoaded = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-download').disabled = true;
document.getElementById('live-title').innerHTML = '&#9673; Live Counter';
document.getElementById('live-count').textContent = '--';
document.getElementById('live-label').textContent = 'Objects Counted';
document.getElementById('live-batch').textContent = '--';
document.getElementById('live-time').textContent = '--';
document.getElementById('live-status').textContent = 'no file selected';
document.getElementById('live-status').className = 'counter-status disconnected';
}
if (data.streaming && data.file) {
streaming = true;
streamUrl = data.stream_url;
selectedFile = data.file;
document.getElementById('btn-stop').disabled = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-download').disabled = false;
document.getElementById('btn-start').textContent = 'STREAMING';
document.getElementById('btn-start').classList.add('btn-ghost');
document.getElementById('video-status').innerHTML =
'<span style="width:6px;height:6px;border-radius:50%;background:var(--accent4);box-shadow:0 0 6px var(--accent4);animation:blink 1.5s ease-in-out infinite;"></span> streaming ' + (data.file_name || '');
document.getElementById('video-status').className = 'video-status connected';
if (!previewAutoOn) enablePreview();
loadBatchResult(data.file);
} else if (!data.streaming && data.file) {
} else if (data.file && selectedFile === data.file) {
previewAutoOn = false;
loadBatchResult(data.file);
}
}
@@ -685,6 +672,7 @@ async function startRecount() {
document.getElementById('video-status').innerHTML =
'<span style="width:6px;height:6px;border-radius:50%;background:var(--accent4);box-shadow:0 0 6px var(--accent4);animation:blink 1.5s ease-in-out infinite;"></span> streaming ' + data.file;
document.getElementById('video-status').className = 'video-status connected';
enablePreview();
} catch (err) {
alert('Error: ' + err.message);
btnStart.disabled = false;
@@ -702,6 +690,7 @@ async function stopRecount() {
streaming = false;
streamUrl = '';
selectedFile = null;
previewAutoOn = false;
batchResultLoaded = false;
const img = document.getElementById('stream-img');
@@ -748,11 +737,7 @@ function togglePreview() {
btn.textContent = 'STREAM OFF';
btn.classList.remove('active');
} else {
img.src = streamUrl + '?' + Date.now();
img.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('active');
enablePreview();
}
}
@@ -767,6 +752,24 @@ function resetVideoToggle() {
btn.classList.remove('active');
}
function enablePreview() {
const btn = document.getElementById('videoToggle');
const img = document.getElementById('stream-img');
const placeholder = document.getElementById('video-placeholder');
if (!streamUrl) return;
previewAutoOn = true;
img.onerror = function() {
if (streaming && streamUrl) {
img.src = streamUrl + '?' + Date.now();
}
};
img.src = streamUrl + '?' + Date.now();
img.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('active');
}
let lastRecountCount = null;
let lastRecountTime = null;
+27 -12
View File
@@ -371,6 +371,7 @@
let selectedFile = null;
let streaming = false;
let streamUrl = '';
let previewAutoOn = false;
document.addEventListener('DOMContentLoaded', () => {
loadRecountProgress();
@@ -393,25 +394,23 @@ async function syncState() {
function applyState(data) {
if (!data) return;
if (data.file) {
selectedFile = data.file;
document.getElementById('btn-start').disabled = data.streaming;
document.getElementById('btn-download').disabled = false;
}
if (data.streaming && data.file) {
streaming = true;
streamUrl = data.stream_url;
selectedFile = data.file;
document.getElementById('btn-stop').disabled = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-download').disabled = false;
document.getElementById('btn-start').textContent = 'STREAMING';
document.getElementById('btn-start').classList.add('btn-ghost');
document.getElementById('video-status').innerHTML =
'<span style="width:5px;height:5px;background:var(--success);display:inline-block;"></span> streaming ' + (data.file_name || '');
document.getElementById('video-status').className = 'video-status connected';
if (!previewAutoOn) enablePreview();
loadBatchResult(data.file);
} else if (!data.streaming && data.file) {
} else if (data.file && selectedFile === data.file) {
previewAutoOn = false;
loadBatchResult(data.file);
}
}
@@ -599,6 +598,7 @@ async function startRecount() {
document.getElementById('video-status').innerHTML =
'<span style="width:5px;height:5px;background:var(--success);display:inline-block;"></span> streaming ' + data.file;
document.getElementById('video-status').className = 'video-status connected';
enablePreview();
} catch (err) {
alert('Error: ' + err.message);
btnStart.disabled = false;
@@ -613,6 +613,7 @@ async function stopRecount() {
streaming = false;
streamUrl = '';
selectedFile = null;
previewAutoOn = false;
batchResultLoaded = false;
const img = document.getElementById('stream-img');
@@ -659,11 +660,7 @@ function togglePreview() {
btn.textContent = 'STREAM OFF';
btn.classList.remove('active');
} else {
img.src = streamUrl + '?' + Date.now();
img.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('active');
enablePreview();
}
}
@@ -678,6 +675,24 @@ function resetVideoToggle() {
btn.classList.remove('active');
}
function enablePreview() {
const btn = document.getElementById('videoToggle');
const img = document.getElementById('stream-img');
const placeholder = document.getElementById('video-placeholder');
if (!streamUrl) return;
previewAutoOn = true;
img.onerror = function() {
if (streaming && streamUrl) {
img.src = streamUrl + '?' + Date.now();
}
};
img.src = streamUrl + '?' + Date.now();
img.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('active');
}
// --- Recount counter ---
let lastRecountCount = null;
+340 -85
View File
@@ -301,6 +301,38 @@
.file-list {
flex: 1; overflow-y: auto; max-height: 300px;
}
.output-panel {
background: var(--glass);
backdrop-filter: blur(24px); -webkit-backdrop-filter: blur(24px);
border: 1px solid var(--border-glow); border-radius: var(--radius);
padding: 20px;
display: flex; flex-direction: column;
}
.output-panel .fp-header {
display: flex; align-items: center; justify-content: space-between;
margin-bottom: 12px;
}
.output-list {
flex: 1; overflow-y: auto; max-height: 300px;
}
.folder-header {
display: flex; align-items: center; gap: 8px;
padding: 8px 12px; margin-bottom: 4px;
background: var(--cell-bg);
border: 1px solid var(--cell-border); border-radius: 8px;
cursor: pointer;
font-size: 10px; letter-spacing: 1px;
color: var(--text-primary);
transition: border-color 0.2s, background 0.2s;
}
.folder-header:hover { border-color: var(--border-glow); background: var(--card-bg); }
.folder-header .folder-arrow {
display: inline-block; color: var(--accent2); font-size: 10px;
transition: transform 0.2s;
}
.folder-header.open .folder-arrow { transform: rotate(90deg); }
.folder-body { display: none; padding-left: 8px; }
.folder-body.open { display: block; }
.file-item {
display: flex; align-items: center; justify-content: space-between;
padding: 10px 12px; margin-bottom: 4px;
@@ -349,6 +381,32 @@
.upload-status.success { color: var(--accent4); }
.upload-status.error { color: var(--accent3); }
.upload-progress {
display: none;
width: 100%;
height: 6px;
background: var(--cell-bg);
border: 1px solid var(--cell-border);
border-radius: 3px;
margin-top: 10px;
overflow: hidden;
}
.upload-progress .upload-progress-bar {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--accent), var(--accent2));
border-radius: 3px;
transition: width 0.15s ease;
}
.upload-progress-percent {
display: none;
font-size: 8px;
color: var(--text-secondary);
letter-spacing: 1px;
text-align: center;
margin-top: 4px;
}
.btn {
font-family: 'Orbitron', sans-serif; font-size: 10px; letter-spacing: 2px;
padding: 8px 16px; border-radius: 7px; cursor: pointer; font-weight: 600;
@@ -406,6 +464,7 @@
</div>
</div>
<div class="header-right">
{% if live_dashboard_url %}<a class="live-chip live-chip-green" href="{{ live_dashboard_url }}" style="text-decoration:none;">LIVE DASHBOARD</a>{% endif %}
<div class="live-chip live-chip-green">
<span class="dot"></span>
<span>LIVE</span>
@@ -457,7 +516,7 @@
<div class="video-container" id="video-container">
<div class="video-placeholder" id="video-placeholder">
<div class="vp-icon">&#9654;</div>
<div class="vp-text">Upload an MP4 and start recount</div>
<div class="vp-text">Upload an MP4, then LOAD and START recount</div>
<div class="vp-hint">Preview via recount node live feed</div>
</div>
<img id="stream-img" alt="Stream" style="display:none;" />
@@ -482,6 +541,10 @@
<button class="btn btn-ghost" id="btn-upload" onclick="uploadFile()">UPLOAD</button>
</div>
<div class="upload-progress" id="upload-progress">
<div class="upload-progress-bar" id="upload-progress-bar"></div>
</div>
<div class="upload-progress-percent" id="upload-progress-percent"></div>
<div class="upload-status" id="upload-status"></div>
<input type="file" id="upload-file-input" accept=".mp4" style="display:none"
@@ -494,6 +557,9 @@
</div>
<div class="btn-row">
<button class="btn btn-ghost" id="btn-load" onclick="loadMp4()" disabled>
&#9655; LOAD MP4
</button>
<button class="btn btn-primary" id="btn-start" onclick="startRecount()" disabled>
&#9654; START RECOUNT
</button>
@@ -510,6 +576,20 @@
</div>
</div>
<div class="output-panel">
<div class="fp-header">
<span class="section-title" style="margin-bottom:0;font-size:11px;">&#9673; From Output Directory</span>
<button class="btn btn-ghost" onclick="loadOutputFiles()" style="font-size:8px;padding:4px 8px;">
<i class="fas fa-sync-alt"></i>
</button>
</div>
<div class="file-list output-list" id="output-list">
<div style="font-size:10px;color:var(--text-secondary);text-align:center;padding:20px;">
No files found
</div>
</div>
</div>
<div class="footer">{{ site_name }} Recounting Upload Dashboard</div>
</div>
@@ -517,16 +597,21 @@
let selectedFile = null;
let streaming = false;
let streamUrl = '';
let previewAutoOn = false;
let loaded = false;
let started = false;
let pendingUploadFile = null;
let batchResultLoaded = false;
document.addEventListener('DOMContentLoaded', () => {
loadRecountProgress();
loadUploads();
loadOutputFiles();
syncState();
setInterval(loadRecountProgress, 500);
setInterval(loadUploads, 30000);
setInterval(loadOutputFiles, 30000);
setInterval(syncState, 1000);
var drop = document.getElementById('upload-drop');
@@ -558,6 +643,14 @@ function setPendingFile(file) {
document.getElementById('pending-filename').classList.add('has-file');
document.getElementById('upload-status').textContent = '';
document.getElementById('upload-status').className = 'upload-status';
showUploadProgress(false);
}
function showUploadProgress(show) {
document.getElementById('upload-progress').style.display = show ? 'block' : 'none';
document.getElementById('upload-progress-percent').style.display = show ? 'block' : 'none';
document.getElementById('upload-progress-bar').style.width = '0%';
document.getElementById('upload-progress-percent').textContent = '';
}
function showUploadStatus(msg, cls) {
@@ -566,7 +659,7 @@ function showUploadStatus(msg, cls) {
el.className = 'upload-status ' + (cls || '');
}
async function uploadFile() {
function uploadFile() {
if (!pendingUploadFile) {
showUploadStatus('Pick a file first', 'error');
return;
@@ -575,41 +668,68 @@ async function uploadFile() {
btn.disabled = true;
btn.textContent = 'UPLOADING...';
showUploadStatus('Uploading...', '');
try {
var form = new FormData();
form.append('file', pendingUploadFile);
var res = await fetch('/api/upload', { method: 'POST', body: form });
var data = await res.json();
if (!data.success) {
showUploadStatus(data.error || 'Upload failed', 'error');
btn.disabled = false;
btn.textContent = 'UPLOAD';
return;
showUploadProgress(true);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var pct = Math.round((e.loaded / e.total) * 100);
document.getElementById('upload-progress-bar').style.width = pct + '%';
document.getElementById('upload-progress-percent').textContent = pct + '%';
}
showUploadStatus('Upload complete: ' + data.name, 'success');
selectedFile = data.path;
document.getElementById('btn-start').disabled = false;
document.getElementById('btn-download').disabled = false;
document.getElementById('btn-delete').disabled = false;
document.getElementById('pending-filename').textContent = 'no file chosen';
document.getElementById('pending-filename').classList.remove('has-file');
pendingUploadFile = null;
loadUploads();
loadBatchResult(data.path);
} catch (err) {
showUploadStatus('Upload error: ' + err.message, 'error');
}
btn.disabled = false;
btn.textContent = 'UPLOAD';
};
xhr.onload = function() {
showUploadProgress(false);
try {
var data = JSON.parse(xhr.responseText);
if (!data.success) {
showUploadStatus(data.error || 'Upload failed', 'error');
btn.disabled = false;
btn.textContent = 'UPLOAD';
return;
}
showUploadStatus('Upload complete: ' + data.name, 'success');
selectedFile = data.path;
renderButtons();
document.getElementById('pending-filename').textContent = 'no file chosen';
document.getElementById('pending-filename').classList.remove('has-file');
pendingUploadFile = null;
loadUploads();
loadBatchResult(data.path);
} catch (err) {
showUploadStatus('Upload error: ' + err.message, 'error');
}
btn.disabled = false;
btn.textContent = 'UPLOAD';
};
xhr.onerror = function() {
showUploadProgress(false);
showUploadStatus('Upload error: network error', 'error');
btn.disabled = false;
btn.textContent = 'UPLOAD';
};
xhr.onabort = function() {
showUploadProgress(false);
showUploadStatus('Upload aborted', '');
btn.disabled = false;
btn.textContent = 'UPLOAD';
};
var form = new FormData();
form.append('file', pendingUploadFile);
xhr.send(form);
}
function selectFile(path, name) {
if (selectedFile === path) {
selectedFile = null;
batchResultLoaded = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-download').disabled = true;
document.getElementById('btn-delete').disabled = true;
renderButtons();
document.getElementById('live-title').innerHTML = '&#9673; Live Counter';
document.getElementById('live-count').textContent = '--';
document.getElementById('live-label').textContent = 'Objects Counted';
@@ -621,9 +741,7 @@ function selectFile(path, name) {
return;
}
selectedFile = path;
document.getElementById('btn-start').disabled = false;
document.getElementById('btn-download').disabled = false;
document.getElementById('btn-delete').disabled = false;
renderButtons();
updateFileSelection();
loadBatchResult(path);
}
@@ -669,6 +787,52 @@ async function loadUploads() {
}
}
function toggleFolder(fid) {
var hdr = document.getElementById(fid + '-hdr');
var body = document.getElementById(fid);
if (hdr) hdr.classList.toggle('open');
if (body) body.classList.toggle('open');
}
async function loadOutputFiles() {
var container = document.getElementById('output-list');
try {
var res = await fetch('/api/mp4-files');
var folders = await res.json();
if (!folders || folders.length === 0) {
container.innerHTML = '<div style="font-size:10px;color:var(--text-secondary);text-align:center;padding:20px;">No MP4 files found</div>';
return;
}
container.innerHTML = folders.map(function(g, gi) {
var fid = 'ofolder-' + gi;
return '<div class="folder-header" id="' + fid + '-hdr" onclick="toggleFolder(\'' + fid + '\')">' +
'<span class="folder-arrow">&#9654;</span>' +
'<i class="fas fa-folder" style="color:var(--accent2);"></i>' +
'<span>' + g.folder + '</span>' +
'<span style="font-size:8px;color:var(--text-secondary);">(' + g.files.length + ')</span>' +
'</div>' +
'<div class="folder-body" id="' + fid + '">' +
g.files.map(function(f) {
var sel = selectedFile === f.path;
var str = streaming && selectedFile === f.path;
var cls = 'file-item';
if (str) cls += ' streaming';
else if (sel) cls += ' selected';
return '<div class="' + cls + '" onclick="event.stopPropagation(); selectFile(\'' +
f.path.replace(/'/g, "\\'") + '\', \'' + f.name.replace(/'/g, "\\'") + '\')" data-path="' +
f.path.replace(/"/g, '&quot;') + '">' +
'<span class="fi-icon">' + (str ? '&#9673;' : '&#9654;') + '</span>' +
'<span class="fi-name">' + f.name + '</span>' +
'<span class="fi-size">' + formatSize(f.size) + '</span>' +
'</div>';
}).join('') +
'</div>';
}).join('');
} catch (err) {
console.error('Failed to load output files:', err);
}
}
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
@@ -676,8 +840,103 @@ function formatSize(bytes) {
return (bytes / 1073741824).toFixed(1) + ' GB';
}
async function startRecount() {
function renderButtons() {
var btnLoad = document.getElementById('btn-load');
var btnStart = document.getElementById('btn-start');
var btnStop = document.getElementById('btn-stop');
var btnDownload = document.getElementById('btn-download');
var btnDelete = document.getElementById('btn-delete');
btnLoad.disabled = !(selectedFile && !loaded);
if (loaded && !started) {
btnStart.disabled = false;
btnStart.textContent = '\u25b6 START RECOUNT';
btnStart.classList.remove('btn-ghost');
} else if (started) {
btnStart.disabled = true;
btnStart.textContent = 'STREAMING';
btnStart.classList.add('btn-ghost');
} else {
btnStart.disabled = true;
btnStart.textContent = '\u25b6 START RECOUNT';
btnStart.classList.remove('btn-ghost');
}
btnStop.disabled = !streaming;
btnDownload.disabled = !selectedFile;
btnDelete.disabled = !selectedFile;
}
async function loadMp4() {
if (!selectedFile) return;
var btnLoad = document.getElementById('btn-load');
btnLoad.disabled = true;
btnLoad.textContent = 'LOADING...';
var pollTimer = null;
try {
var req = fetch('/api/load-mp4', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: selectedFile })
});
pollTimer = setInterval(async function() {
try {
var pr = await fetch('/api/copy-progress');
var p = await pr.json();
if (p.active) {
showCopyProgress(p.pct, p.done, p.total, p.name);
}
} catch (err) {}
}, 250);
var res = await req;
var data = await res.json();
clearInterval(pollTimer);
pollTimer = null;
hideCopyProgress();
if (!data.success) {
alert('Failed: ' + (data.error || 'unknown'));
renderButtons();
return;
}
streamUrl = data.stream_url;
selectedFile = data.path;
streaming = true;
loaded = true;
started = false;
showUploadStatus('LOADED ' + data.file + ' \u2014 press START RECOUNT', 'success');
renderButtons();
syncState();
} catch (err) {
if (pollTimer) clearInterval(pollTimer);
hideCopyProgress();
alert('Error: ' + err.message);
renderButtons();
} finally {
btnLoad.textContent = '\u25b6 LOAD MP4';
}
}
function showCopyProgress(pct, done, total, name) {
document.getElementById('upload-progress').style.display = 'block';
document.getElementById('upload-progress-percent').style.display = 'block';
document.getElementById('upload-progress-bar').style.width = pct + '%';
document.getElementById('upload-progress-percent').textContent = pct + '%';
document.getElementById('upload-status').textContent =
'Copying ' + name + ' \u2014 ' + formatSize(done) + ' / ' + formatSize(total);
}
function hideCopyProgress() {
document.getElementById('upload-progress').style.display = 'none';
document.getElementById('upload-progress-percent').style.display = 'none';
document.getElementById('upload-progress-bar').style.width = '0%';
document.getElementById('upload-progress-percent').textContent = '';
}
async function startRecount() {
if (!selectedFile || !loaded) return;
var btnStart = document.getElementById('btn-start');
btnStart.disabled = true;
btnStart.textContent = 'CONNECTING...';
@@ -691,31 +950,28 @@ async function startRecount() {
try {
var res = await fetch('/api/start-recount', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: selectedFile })
method: 'POST'
});
var data = await res.json();
if (!data.success) {
alert('Failed: ' + (data.error || 'unknown'));
btnStart.disabled = false;
btnStart.textContent = '\u25b6 START RECOUNT';
renderButtons();
return;
}
streamUrl = data.stream_url;
streaming = true;
selectedFile = data.path;
loaded = true;
started = true;
document.getElementById('btn-stop').disabled = false;
btnStart.textContent = 'STREAMING';
btnStart.classList.add('btn-ghost');
renderButtons();
document.getElementById('video-status').innerHTML =
'<span style="width:6px;height:6px;border-radius:50%;background:var(--accent4);box-shadow:0 0 6px var(--accent4);animation:blink 1.5s ease-in-out infinite;"></span> streaming ' + data.file;
document.getElementById('video-status').className = 'video-status connected';
enablePreview();
} catch (err) {
alert('Error: ' + err.message);
btnStart.disabled = false;
btnStart.textContent = '\u25b6 START RECOUNT';
renderButtons();
}
}
@@ -729,6 +985,9 @@ async function stopRecount() {
streaming = false;
streamUrl = '';
selectedFile = null;
previewAutoOn = false;
loaded = false;
started = false;
batchResultLoaded = false;
var img = document.getElementById('stream-img');
@@ -737,15 +996,7 @@ async function stopRecount() {
img.style.display = 'none';
if (placeholder) placeholder.style.display = '';
var btnStart = document.getElementById('btn-start');
var btnStop = document.getElementById('btn-stop');
btnStart.disabled = true;
btnStart.textContent = '\u25b6 START RECOUNT';
btnStart.classList.remove('btn-ghost');
btnStop.disabled = true;
document.getElementById('btn-download').disabled = true;
document.getElementById('btn-delete').disabled = true;
renderButtons();
document.getElementById('video-status').innerHTML =
'<span style="width:6px;height:6px;border-radius:50%;background:var(--text-secondary);"></span> stopped';
@@ -775,11 +1026,7 @@ function togglePreview() {
btn.textContent = 'STREAM OFF';
btn.classList.remove('active');
} else {
img.src = streamUrl + '?' + Date.now();
img.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('active');
enablePreview();
}
}
@@ -794,6 +1041,24 @@ function resetVideoToggle() {
btn.classList.remove('active');
}
function enablePreview() {
var btn = document.getElementById('videoToggle');
var img = document.getElementById('stream-img');
var placeholder = document.getElementById('video-placeholder');
if (!streamUrl) return;
previewAutoOn = true;
img.onerror = function() {
if (streaming && streamUrl) {
img.src = streamUrl + '?' + Date.now();
}
};
img.src = streamUrl + '?' + Date.now();
img.style.display = 'block';
if (placeholder) placeholder.style.display = 'none';
btn.textContent = 'STREAM ON';
btn.classList.add('active');
}
async function syncState() {
try {
var res = await fetch('/api/state');
@@ -804,38 +1069,30 @@ async function syncState() {
function applyState(data) {
if (!data) return;
if (data.file) {
selectedFile = data.file;
document.getElementById('btn-start').disabled = data.streaming;
document.getElementById('btn-download').disabled = false;
document.getElementById('btn-delete').disabled = false;
} else {
selectedFile = null;
batchResultLoaded = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-download').disabled = true;
document.getElementById('btn-delete').disabled = true;
document.getElementById('live-title').innerHTML = '&#9673; Live Counter';
document.getElementById('live-count').textContent = '--';
document.getElementById('live-label').textContent = 'Objects Counted';
document.getElementById('live-batch').textContent = '--';
document.getElementById('live-time').textContent = '--';
document.getElementById('live-status').textContent = 'no file selected';
document.getElementById('live-status').className = 'counter-status disconnected';
}
if (data.streaming && data.file) {
streaming = true;
streamUrl = data.stream_url;
document.getElementById('btn-stop').disabled = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-start').textContent = 'STREAMING';
document.getElementById('btn-start').classList.add('btn-ghost');
selectedFile = data.file;
loaded = true;
renderButtons();
document.getElementById('video-status').innerHTML =
'<span style="width:6px;height:6px;border-radius:50%;background:var(--accent4);box-shadow:0 0 6px var(--accent4);animation:blink 1.5s ease-in-out infinite;"></span> streaming ' + (data.file_name || '');
document.getElementById('video-status').className = 'video-status connected';
if (!previewAutoOn) enablePreview();
loadBatchResult(data.file);
} else if (!data.streaming && data.file) {
} else if (data.file && selectedFile === data.file) {
previewAutoOn = false;
loaded = false;
started = false;
renderButtons();
loadBatchResult(data.file);
} else if (!data.streaming) {
previewAutoOn = false;
loaded = false;
started = false;
renderButtons();
}
}
@@ -898,9 +1155,7 @@ async function deleteUploadRecord(fpath) {
if (selectedFile === fpath) {
selectedFile = null;
batchResultLoaded = false;
document.getElementById('btn-start').disabled = true;
document.getElementById('btn-download').disabled = true;
document.getElementById('btn-delete').disabled = true;
renderButtons();
document.getElementById('live-title').innerHTML = '&#9673; Live Counter';
document.getElementById('live-count').textContent = '--';
document.getElementById('live-label').textContent = 'Objects Counted';
File diff suppressed because it is too large. Load diff