feat: platform detection parity + download/processing progress bars

Alignment with karung_counter_semarang (recount consistency):
- box_conf 0.35, truck_conf 0.45, suppress_sack_box 0.4
- detector/tracker run at min(sack_conf, box_conf) so 0.35 boxes survive
  inference; _apply_class_confs gates box/box_conf, sack/sack_conf
- _apply_min_area guardrail: sack/box 1500, truck 5000 px2
- 168 tests pass (+5)
This commit is contained in:
jetson committed 2026-10-13 11:30:04 +07:00
1 parent 2efcdb2316
commit ce604b0574
10 files changed
+382 -14

No files matched your search

+4 -2
View File
@@ -295,8 +295,10 @@ def download(job_id, filename):
return "File not found", 404
if not os.path.isfile(file_path):
return "File not found", 404
compressed = _compress_for_download(file_path)
return send_file(compressed or file_path, as_attachment=True)
send_path = _compress_for_download(file_path) or file_path
resp = send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path))
resp.headers["Content-Length"] = str(os.path.getsize(send_path))
return resp
@app.route("/api/videos")
+10 -3
View File
@@ -4,12 +4,19 @@
# Missing keys fall back to built-in defaults — partial files are fine.
detection:
sack_conf: 0.4 # detector confidence for sack/box
truck_conf: 0.5 # truck detector confidence
sack_conf: 0.4 # detector confidence for sack
box_conf: 0.35 # detector confidence for box
truck_conf: 0.45 # truck detector confidence
# Per-class minimum bbox area (px^2) — drops tiny false positives.
min_bbox_area:
sack: 1500
box: 1500
truck: 5000
iou:
dedup: 0.5 # cross-model duplicate merge threshold
suppress_sack_box: 0.5 # drop sack overlapping a box (box label wins)
suppress_sack_box: 0.4 # drop sack overlapping a box (box label wins)
synthetic: 0.3 # synthetic track ID matching
sticky_truck: 0.3 # keep previous main truck pick
+8 -2
View File
@@ -17,11 +17,17 @@ CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.y
DEFAULTS: dict = {
"detection": {
"sack_conf": 0.4,
"truck_conf": 0.5,
"box_conf": 0.35,
"truck_conf": 0.45,
},
"min_bbox_area": {
"sack": 1500,
"box": 1500,
"truck": 5000,
},
"iou": {
"dedup": 0.5,
"suppress_sack_box": 0.5,
"suppress_sack_box": 0.4,
"synthetic": 0.3,
"sticky_truck": 0.3,
},
+52 -4
View File
@@ -152,6 +152,7 @@ def run_pipeline(
"""
cfg = load_config()
sack_conf = sack_conf if sack_conf is not None else cfg["detection"]["sack_conf"]
box_conf = cfg["detection"]["box_conf"]
truck_conf = truck_conf if truck_conf is not None else cfg["detection"]["truck_conf"]
detect_interval = detect_interval if detect_interval is not None else cfg["pipeline"]["detect_interval"]
truck_det_interval = truck_det_interval if truck_det_interval is not None else cfg["pipeline"]["truck_det_interval"]
@@ -171,6 +172,12 @@ def run_pipeline(
model_config.known_classes if model_config.known_classes else None
)
# Run inference at the lowest per-class conf so box TPs in
# [box_conf, sack_conf) survive; per-class gating happens later.
effective_detector_conf = (
min(sack_conf, box_conf) if not effective_filter or "box" in effective_filter else sack_conf
)
# Check onnxruntime for .onnx models
if model_config.path.endswith(".onnx"):
try:
@@ -183,7 +190,7 @@ def run_pipeline(
shared_model = YOLO(model_config.path)
detector = BaseDetector(
shared_model, conf=sack_conf, class_filter=effective_filter
shared_model, conf=effective_detector_conf, class_filter=effective_filter
)
# Truck detector — skip if fixed zone
@@ -199,7 +206,7 @@ def run_pipeline(
shared_model, conf=truck_conf, class_filter=("truck",)
)
tracker = ByteTrackTracker(shared_model, conf=sack_conf)
tracker = ByteTrackTracker(shared_model, conf=effective_detector_conf)
stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
@@ -300,6 +307,8 @@ def run_pipeline(
tracked_sacks = _suppress_sacks_under_boxes(
tracked_sacks, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked_sacks = _apply_class_confs(tracked_sacks, sack_conf, box_conf)
tracked_sacks = _apply_min_area(tracked_sacks, cfg["min_bbox_area"])
counter.update(countable_detections(tracked_sacks))
# Annotate frame
@@ -433,6 +442,29 @@ def _suppress_sacks_under_boxes(dets, iou_threshold=0.5):
or not any(_compute_iou(d.bbox, b.bbox) > iou_threshold for b in boxes)]
def _apply_class_confs(dets, sack_conf, box_conf):
"""Per-class confidence gate — box may sit below sack_conf.
ponytail: truck untouched (truck detector already gates at truck_conf).
"""
out = []
for d in dets:
if d.class_name == "box" and d.confidence < box_conf:
continue
if d.class_name == "sack" and d.confidence < sack_conf:
continue
out.append(d)
return out
def _apply_min_area(dets, areas):
"""Drop dets whose bbox area is under the per-class minimum."""
return [
d for d in dets
if (d.bbox[2] - d.bbox[0]) * (d.bbox[3] - d.bbox[1]) >= areas.get(d.class_name, 0)
]
def run_merged_pipeline(
video_path: str,
model_configs: list[ModelConfig],
@@ -474,6 +506,7 @@ def run_merged_pipeline(
"""
cfg = load_config()
sack_conf = sack_conf if sack_conf is not None else cfg["detection"]["sack_conf"]
box_conf = cfg["detection"]["box_conf"]
truck_conf = truck_conf if truck_conf is not None else cfg["detection"]["truck_conf"]
detect_interval = detect_interval if detect_interval is not None else cfg["pipeline"]["detect_interval"]
truck_det_interval = truck_det_interval if truck_det_interval is not None else cfg["pipeline"]["truck_det_interval"]
@@ -504,7 +537,12 @@ def run_merged_pipeline(
)
model = YOLO(mcfg.path)
eff_filter = (class_filters or {}).get(mcfg.stem) or mcfg.known_classes or None
detectors.append(BaseDetector(model, conf=sack_conf, class_filter=eff_filter))
# Inference at lowest per-class conf so box TPs in [box_conf, sack_conf)
# survive; per-class gating happens later.
det_conf = (
min(sack_conf, box_conf) if not eff_filter or "box" in eff_filter else sack_conf
)
detectors.append(BaseDetector(model, conf=det_conf, class_filter=eff_filter))
# Truck detector — skip if fixed zone
truck_det = None
@@ -521,7 +559,15 @@ def run_merged_pipeline(
# Single tracker using first model's weights
tracker_model = YOLO(model_configs[0].path)
tracker = ByteTrackTracker(tracker_model, conf=sack_conf)
primary_eff = (
(class_filters or {}).get(model_configs[0].stem)
or model_configs[0].known_classes
or None
)
effective_detector_conf = (
min(sack_conf, box_conf) if not primary_eff or "box" in primary_eff else sack_conf
)
tracker = ByteTrackTracker(tracker_model, conf=effective_detector_conf)
stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
@@ -645,6 +691,8 @@ def run_merged_pipeline(
tracked = _suppress_sacks_under_boxes(
tracked, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked = _apply_class_confs(tracked, sack_conf, box_conf)
tracked = _apply_min_area(tracked, cfg["min_bbox_area"])
# Count using only detections with track_id (tracker results)
counter.update(countable_detections([d for d in tracked if d.track_id is not None]))
+107 -1
View File
@@ -413,6 +413,78 @@ function escapeHtml(str) {
return div.innerHTML;
}
/* ============================================================
Download progress — delegated handler on [data-download-bar]
Streams the response so the bar can track bytes received.
============================================================ */
function downloadFormatBytes(bytes) {
if (bytes === 0) return '0 B';
var k = 1024;
var sizes = ['B', 'KB', 'MB', 'GB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
document.addEventListener('click', function (e) {
var link = e.target.closest ? e.target.closest('[data-download-bar]') : null;
if (!link) return;
if (typeof fetch !== 'function' || typeof ReadableStream === 'undefined') return; // let anchor navigate
e.preventDefault();
var card = link.closest('.result-card') || link.parentElement;
var bar = card ? card.querySelector('[data-download-progress]') : null;
var fill = bar ? bar.querySelector('.download-progress-fill') : null;
var text = bar ? bar.querySelector('.download-progress-text') : null;
function fallback() {
if (bar) bar.hidden = true;
window.location.href = link.href;
}
if (!bar || !fill || !text) return fallback();
bar.hidden = false;
fill.style.width = '0%';
text.textContent = '0%';
fetch(link.href)
.then(function (res) {
if (!res.ok) throw new Error('HTTP ' + res.status);
var total = parseInt(res.headers.get('Content-Length') || '', 10);
if (!isFinite(total) || total <= 0) total = 0;
var reader = res.body.getReader();
var received = 0;
var chunks = [];
function pump() {
return reader.read().then(function (result) {
if (result.done) return;
chunks.push(result.value);
received += result.value.length;
var pct = total ? Math.min(100, Math.round((received / total) * 100)) : null;
if (pct !== null) fill.style.width = pct + '%';
text.textContent = total
? pct + '% (' + downloadFormatBytes(received) + ' / ' + downloadFormatBytes(total) + ')'
: downloadFormatBytes(received) + ' downloaded';
return pump();
});
}
return pump().then(function () {
var blob = new Blob(chunks);
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = decodeURIComponent(link.href.split('/').pop() || 'download');
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () {
URL.revokeObjectURL(url);
bar.hidden = true;
}, 1500);
});
})
.catch(fallback);
});
function initStatusPage(jobId, initialStatus) {
var statusBadge = document.getElementById('status-badge');
var progressFill = document.getElementById('progress-fill');
@@ -429,6 +501,8 @@ function initStatusPage(jobId, initialStatus) {
var videoFallback = document.getElementById('video-fallback');
var progressRegion = document.getElementById('progress-section');
var progressPhase = document.getElementById('progress-phase');
var progressEta = document.getElementById('progress-eta');
var statusAnnouncer = document.getElementById('status-announcer');
var cancelBtn = document.getElementById('cancel-btn');
var terminalStates = ['COMPLETED', 'FAILED', 'CANCELLED'];
@@ -515,6 +589,7 @@ function initStatusPage(jobId, initialStatus) {
if (connectionLostIndicator) { connectionLostIndicator.style.display = 'none'; connectionLostIndicator = null; }
updateProgressBar(data.progress || 0);
updateStatusBadge(data.status);
updateProgressPhase(data);
updateModelName(data.current_model);
updateResults(data.results);
updateError(data.error);
@@ -564,6 +639,36 @@ function initStatusPage(jobId, initialStatus) {
}
}
/* --- Update phase + ETA line --- */
function updateProgressPhase(data) {
if (progressPhase) {
var phase = 'Processing';
if (data.status === 'PENDING') phase = 'Queued';
else if (data.status === 'COMPLETED') phase = 'Done';
else if (data.status === 'RUNNING') phase = data.current_model || 'Processing';
else if (data.status === 'FAILED') phase = 'Failed';
else if (data.status === 'CANCELLED') phase = 'Cancelled';
progressPhase.textContent = phase;
}
// Total frames not exposed by the API — ETA falls back to the frame
// counter plus the FPS already shown in the live-preview header.
if (progressEta) {
if (data.status === 'RUNNING' && data.live_frame) {
var eta = 'frame ' + data.live_frame;
if (data.live_fps > 0) eta += ' · ' + data.live_fps.toFixed(1) + ' FPS';
progressEta.textContent = eta;
} else if (data.status === 'PENDING') {
progressEta.textContent = 'waiting to start';
} else if (data.status === 'COMPLETED') {
progressEta.textContent = '—';
} else if (data.status === 'FAILED' || data.status === 'CANCELLED') {
progressEta.textContent = '—';
} else {
progressEta.textContent = '—';
}
}
}
/* --- Update status badge --- */
function updateStatusBadge(status) {
if (!statusBadge) return;
@@ -617,7 +722,8 @@ function initStatusPage(jobId, initialStatus) {
'</div>';
if (r.output_path) {
var filename = r.output_path.split('/').pop();
card.innerHTML += '<a href="/download/' + jobId + '/' + escapeHtml(filename) + '" class="btn btn-primary result-download">Download</a>';
card.innerHTML += '<a href="/download/' + jobId + '/' + escapeHtml(filename) + '" class="btn btn-primary result-download" data-download-bar>Download</a>' +
'<div class="download-progress" data-download-progress hidden><div class="download-progress-fill"></div><span class="download-progress-text">0%</span></div>';
}
resultsGrid.appendChild(card);
});
+80
View File
@@ -615,6 +615,86 @@ main {
transition: width 0.4s ease;
}
.progress-meta {
display: flex;
align-items: baseline;
gap: var(--space-3);
}
.progress-phase {
font-size: var(--text-sm);
font-weight: var(--font-medium);
color: var(--color-neutral-600);
max-width: 16rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.progress-eta {
font-family: var(--font-mono);
font-size: var(--text-xs);
color: var(--color-neutral-500);
}
/* Striped animation only while the section reports busy (aria-busy="true"). */
.progress-section[aria-busy="true"] .progress-fill {
background-image: repeating-linear-gradient(
45deg,
rgba(255, 255, 255, 0.25) 0,
rgba(255, 255, 255, 0.25) 8px,
transparent 8px,
transparent 16px
);
background-size: 22.627px 22.627px;
animation: progress-stripes 1s linear infinite;
}
@keyframes progress-stripes {
from { background-position: 0 0; }
to { background-position: 22.627px 0; }
}
@media (prefers-reduced-motion: reduce) {
.progress-section[aria-busy="true"] .progress-fill {
animation: none;
}
}
/* --- Download progress --- */
.download-progress {
position: relative;
width: 100%;
height: 6px;
margin-top: var(--space-2);
margin-bottom: var(--space-3);
background: var(--color-neutral-200);
border-radius: var(--radius-sm);
overflow: visible;
}
.download-progress[hidden] {
display: none;
}
.download-progress-fill {
height: 100%;
width: 0;
background: var(--color-primary-500);
border-radius: var(--radius-sm);
transition: width 0.2s ease;
}
.download-progress-text {
position: absolute;
top: calc(100% + 2px);
right: 0;
font-family: var(--font-mono);
font-size: var(--text-xs);
color: var(--color-neutral-500);
white-space: nowrap;
}
.current-model {
margin-top: var(--space-3);
font-size: var(--text-sm);
+10 -2
View File
@@ -20,7 +20,11 @@
<div class="progress-section card" id="progress-section" aria-live="polite" aria-busy="false">
<div class="progress-header">
<span class="progress-label">Processing Progress</span>
<span class="progress-pct" id="progress-pct">{{ "%.0f"|format(job.progress * 100) }}%</span>
<span class="progress-meta">
<span class="progress-phase" id="progress-phase">Processing</span>
<span class="progress-eta" id="progress-eta">—</span>
<span class="progress-pct" id="progress-pct">{{ "%.0f"|format(job.progress * 100) }}%</span>
</span>
</div>
<div class="progress-track" role="progressbar" aria-valuenow="{{ "%.0f"|format(job.progress * 100) }}" aria-valuemin="0" aria-valuemax="100" aria-label="Processing progress">
<div class="progress-fill" id="progress-fill" style="width: {{ "%.0f"|format(job.progress * 100) }}%"></div>
@@ -124,7 +128,11 @@
<span class="meta-item"><strong>Duration:</strong> {{ "%.1f"|format(r.duration_seconds) }}s</span>
</div>
{% if r.output_path %}
<a href="/download/{{ job.job_id }}/{{ r.output_path | basename }}" class="btn btn-primary result-download" aria-label="Download result for {{ r.model_name }}">Download</a>
<a href="/download/{{ job.job_id }}/{{ r.output_path | basename }}" class="btn btn-primary result-download" aria-label="Download result for {{ r.model_name }}" data-download-bar>Download</a>
<div class="download-progress" data-download-progress hidden>
<div class="download-progress-fill"></div>
<span class="download-progress-text">0%</span>
</div>
{% endif %}
</div>
{% endfor %}
+47
View File
@@ -182,3 +182,50 @@ def test_job_defaults_live_box_counts_zero():
job = Job(job_id="test", video_path="/tmp/x.mp4", model_configs=[])
assert job.live_box_loading == 0
assert job.live_box_unloading == 0
# ── Download progress (Task: progress bars) ──────────────────────────────
def _completed_job_with_output(content=b"video-bytes"):
import os
import time
from app import job_queue
from src.job import JobStatus
job = job_queue.add_job(video_path="/tmp/test.mp4", model_configs=[])
time.sleep(0.3)
with job_queue._lock:
job.status = JobStatus.COMPLETED
path = os.path.join(job.output_dir, "out.mp4")
with open(path, "wb") as fh:
fh.write(content)
return job, path
def test_download_route_sets_content_length(client):
"""GET /download/<id>/<file> sets Content-Length equal to file size."""
import os
from app import _compress_for_download
job, path = _completed_job_with_output()
expected = os.path.getsize(path)
# Small file: helper returns None, route serves the original.
assert _compress_for_download(path) is None
resp = client.get(f"/download/{job.job_id}/out.mp4")
assert resp.status_code == 200
assert resp.headers["Content-Length"] == str(expected)
assert int(resp.headers["Content-Length"]) == expected
def test_status_page_has_download_progress_markup(client):
"""Rendered status page carries the download progress bar markup."""
job = _job_with_box_results()
resp = client.get(f"/status/{job.job_id}")
assert resp.status_code == 200
html = resp.get_data(as_text=True)
assert "data-download-progress" in html
assert "data-download-bar" in html
assert "download-progress-fill" in html
+22
View File
@@ -47,6 +47,18 @@ def test_empty_file_returns_defaults(tmp_path):
assert load_config(str(p)) == DEFAULTS
def test_partial_yaml_only_box_conf_merges(tmp_path):
"""Only detection.box_conf overrides; sack_conf stays at default 0.4."""
p = tmp_path / "config.yaml"
p.write_text("detection:\n box_conf: 0.25\n", encoding="utf-8")
cfg = load_config(str(p))
assert cfg["detection"]["box_conf"] == 0.25
assert cfg["detection"]["sack_conf"] == 0.4
assert cfg["min_bbox_area"] == DEFAULTS["min_bbox_area"]
assert _section_keys(cfg) == _section_keys(DEFAULTS)
def test_repo_config_yaml_exists_and_parses():
"""Real repo config.yaml exists, parses, types sane."""
real = os.path.join(REPO_ROOT, "config.yaml")
@@ -54,7 +66,17 @@ def test_repo_config_yaml_exists_and_parses():
cfg = load_config(real)
assert isinstance(cfg["detection"]["sack_conf"], float)
assert isinstance(cfg["detection"]["box_conf"], float)
assert isinstance(cfg["detection"]["truck_conf"], float)
# Platform-aligned detection tuning (matches karung_counter_semarang)
assert cfg["detection"]["box_conf"] == 0.35
assert cfg["detection"]["truck_conf"] == 0.45
assert cfg["iou"]["suppress_sack_box"] == 0.4
assert cfg["min_bbox_area"]["sack"] == 1500
assert cfg["min_bbox_area"]["box"] == 1500
assert cfg["min_bbox_area"]["truck"] == 5000
for key in ("detect_interval", "sup_det_interval", "truck_det_interval", "preview_every_n"):
assert isinstance(cfg["pipeline"][key], int), key
assert cfg["pipeline"][key] > 0, key
+42
View File
@@ -329,6 +329,48 @@ def test_run_merged_pipeline_propagates_box_counts(tmp_path, monkeypatch):
assert result.box_net_count == 3
# ── Per-class conf gating (platform-aligned detection tuning) ─────────────
def test_apply_class_confs_per_class_thresholds():
"""box keeps >=0.35, sack keeps >=0.40, truck untouched."""
from src.pipeline import _apply_class_confs
dets = [
Detection(bbox=(0, 0, 10, 10), confidence=0.36, class_id=1, class_name="box"),
Detection(bbox=(0, 0, 10, 10), confidence=0.34, class_id=1, class_name="box"),
Detection(bbox=(0, 0, 10, 10), confidence=0.39, class_id=0, class_name="sack"),
Detection(bbox=(0, 0, 10, 10), confidence=0.40, class_id=0, class_name="sack"),
Detection(bbox=(0, 0, 10, 10), confidence=0.10, class_id=2, class_name="truck"),
]
out = _apply_class_confs(dets, sack_conf=0.4, box_conf=0.35)
assert [(d.class_name, d.confidence) for d in out] == [
("box", 0.36),
("sack", 0.40),
("truck", 0.10),
]
def test_apply_min_area_per_class_thresholds():
"""Areas below per-class min drop; unknown class kept."""
from src.pipeline import _apply_min_area
areas = {"sack": 1500, "box": 1500, "truck": 5000}
dets = [
Detection(bbox=(0, 0, 30, 30), confidence=0.9, class_id=0, class_name="sack"), # 900 drop
Detection(bbox=(0, 0, 50, 50), confidence=0.9, class_id=0, class_name="sack"), # 2500 keep
Detection(bbox=(0, 0, 100, 40), confidence=0.9, class_id=2, class_name="truck"), # 4000 drop
Detection(bbox=(0, 0, 100, 60), confidence=0.9, class_id=2, class_name="truck"), # 6000 keep
Detection(bbox=(0, 0, 10, 10), confidence=0.9, class_id=9, class_name="unknown"), # min 0 keep
]
out = _apply_min_area(dets, areas)
assert [(d.class_name, (d.bbox[2] - d.bbox[0]) * (d.bbox[3] - d.bbox[1])) for d in out] == [
("sack", 2500),
("truck", 6000),
("unknown", 100),
]
# ── Perf/output tuning params (signature contracts) ────────────────────