951 lines
33 KiB
Python
951 lines
33 KiB
Python
# app.py
|
|
"""Flask web UI for feedmill_recounter — port 9050."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import math
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
|
|
from dotenv import load_dotenv
|
|
from flask import (
|
|
Flask, render_template, request, redirect,
|
|
url_for, send_file, jsonify,
|
|
)
|
|
import time as _time
|
|
from flask import Response
|
|
from werkzeug.utils import secure_filename
|
|
|
|
from pathlib import Path
|
|
|
|
from shapely.geometry import Polygon
|
|
|
|
from src.compress import compress_in_place
|
|
from src.job import JobQueue
|
|
from src.model_registry import scan_models, scan_model_groups, ModelConfig
|
|
from src.model_conversion import (
|
|
conversion_manager,
|
|
MODEL_UPLOAD_EXTENSIONS,
|
|
conversion_status_dict,
|
|
)
|
|
from src.preview import (
|
|
extract_thumbnail, extract_sample_frames, probe_video,
|
|
resize_video_to_max_height, extract_frame_jpeg,
|
|
)
|
|
from src.pipeline import ANALYSIS_SIZE
|
|
from src.truck_roi import TruckROI
|
|
from src.validation import ValidationError
|
|
from src.zone_config import (
|
|
load_zone_config, list_zone_presets, build_static_roi, get_active_zone,
|
|
DEFAULT_ZONES, ZONE_BOUNDS_H, ZONE_BOUNDS_W,
|
|
resolve_zone, save_zone_preset, sync_fcp_zones,
|
|
)
|
|
|
|
load_dotenv()
|
|
|
|
app = Flask(__name__, template_folder="templates", static_folder="static")
|
|
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "change-me")
|
|
app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024 * 1024 # 2GB
|
|
|
|
MODELS_DIR = os.getenv("MODELS_DIR", "./models")
|
|
UPLOAD_DIR = os.getenv("UPLOAD_DIR", "./uploads")
|
|
OUTPUT_DIR = os.path.abspath(os.getenv("OUTPUT_DIR", "./output"))
|
|
|
|
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
|
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
|
|
|
job_queue = JobQueue(output_dir=OUTPUT_DIR)
|
|
|
|
VIDEO_EXTENSIONS = ('.mp4', '.avi', '.mkv', '.mov', '.webm')
|
|
ZONES_PATH = os.getenv("ZONES_PATH", "./zones.json")
|
|
|
|
|
|
def _parse_model_configs(form):
|
|
"""Parse model selection from request form.
|
|
|
|
Returns:
|
|
(model_configs, class_filters) tuple.
|
|
"""
|
|
selected_stems = form.getlist("model_stems")
|
|
selected_models = form.getlist("models")
|
|
model_configs = []
|
|
class_filters = {}
|
|
|
|
if selected_stems:
|
|
groups = scan_model_groups(MODELS_DIR)
|
|
groups_by_stem = {g.stem: g for g in groups}
|
|
|
|
for stem in selected_stems:
|
|
if stem not in groups_by_stem:
|
|
continue
|
|
group = groups_by_stem[stem]
|
|
fmt = form.get(f"format_{stem}", group.default_format)
|
|
if fmt not in group.format_paths:
|
|
continue
|
|
model_configs.append(ModelConfig(
|
|
filename=os.path.basename(group.format_paths[fmt]),
|
|
path=group.format_paths[fmt],
|
|
stem=stem,
|
|
known_classes=list(group.known_classes),
|
|
))
|
|
filter_val = form.get(f"filter_{stem}", "")
|
|
if not filter_val or filter_val in ("default",):
|
|
pass
|
|
elif filter_val == "all":
|
|
class_filters[stem] = None
|
|
else:
|
|
class_filters[stem] = filter_val.split(",")
|
|
elif selected_models:
|
|
models = scan_models(MODELS_DIR)
|
|
by_name = {m.filename: m for m in models}
|
|
|
|
for name in selected_models:
|
|
if name in by_name:
|
|
model_configs.append(by_name[name])
|
|
filter_val = form.get(f"filter_{name}", "")
|
|
if not filter_val or filter_val in ("default",):
|
|
pass
|
|
elif filter_val == "all":
|
|
class_filters[name] = None
|
|
else:
|
|
class_filters[name] = filter_val.split(",")
|
|
|
|
return model_configs, class_filters
|
|
|
|
|
|
@app.template_filter("basename")
|
|
def basename_filter(path):
|
|
"""Extract filename from path for templates."""
|
|
return os.path.basename(path)
|
|
|
|
|
|
@app.route("/")
|
|
def index():
|
|
model_groups = scan_model_groups(MODELS_DIR)
|
|
return render_template("index.html", model_groups=model_groups, models_dir=MODELS_DIR)
|
|
|
|
|
|
@app.route("/upload", methods=["POST"])
|
|
def upload():
|
|
if conversion_manager.is_running():
|
|
return "Model conversion in progress", 409
|
|
video = request.files.get("video")
|
|
if not video or not video.filename:
|
|
return "No video uploaded", 400
|
|
|
|
safe_name = secure_filename(video.filename)
|
|
if not safe_name or not safe_name.lower().endswith(VIDEO_EXTENSIONS):
|
|
return "Invalid video file type", 400
|
|
|
|
model_configs, class_filters = _parse_model_configs(request.form)
|
|
|
|
if not model_configs:
|
|
return "No models selected", 400
|
|
|
|
job = _save_and_queue(
|
|
video, model_configs, class_filters,
|
|
request.form.get("output_height", ""),
|
|
request.form.get("zone_mode", "fixed"),
|
|
request.form.get("zone_preset", ""),
|
|
)
|
|
return redirect(url_for("status", job_id=job.job_id))
|
|
|
|
|
|
def _static_roi(zone: dict) -> TruckROI:
|
|
"""Build the fixed zone ROI in FCP's 1280x720 analysis frame.
|
|
|
|
Zone presets are stored in 1920x1080 (zones.json reference_resolution is
|
|
[1920, 1080]) and scaled to 1280x720 at runtime.
|
|
"""
|
|
return build_static_roi(zone, *ANALYSIS_SIZE)
|
|
|
|
|
|
def _resolve_zone(
|
|
zone_mode: str, zone_preset: str
|
|
) -> tuple[str, TruckROI | None, str, Polygon | None, Polygon | None]:
|
|
"""Resolve the counting zone of a job (auto-syncing FCP zones when newer)."""
|
|
return resolve_zone(
|
|
zone_mode,
|
|
zone_preset,
|
|
ZONES_PATH,
|
|
ANALYSIS_SIZE,
|
|
zone_reader=get_active_zone,
|
|
)
|
|
|
|
|
|
def _save_and_queue(video, model_configs, class_filters,
|
|
output_height, zone_mode, zone_preset):
|
|
"""Save upload (collision-safe), transcode to 720p, resolve fixed zone,
|
|
enqueue job. Shared by /upload and /api/analyze."""
|
|
safe_name = secure_filename(video.filename)
|
|
# Client name without extension — used for the annotated output name.
|
|
source_stem = os.path.splitext(safe_name)[0]
|
|
video_path = os.path.join(UPLOAD_DIR, safe_name)
|
|
base, ext = os.path.splitext(video_path)
|
|
n = 1
|
|
while os.path.exists(video_path):
|
|
video_path = f"{base}_{n}{ext}"
|
|
n += 1
|
|
video.save(video_path)
|
|
|
|
# Transcode to 720p max height to save storage and speed up processing
|
|
video_path = resize_video_to_max_height(video_path, max_height=720)
|
|
|
|
zone_mode, fixed_zone, zone_preset, counting_polygon, truck_polygon = _resolve_zone(
|
|
zone_mode, zone_preset
|
|
)
|
|
|
|
return job_queue.add_job(
|
|
video_path=video_path,
|
|
source_stem=source_stem,
|
|
model_configs=model_configs,
|
|
class_filters=class_filters,
|
|
zone_mode=zone_mode,
|
|
fixed_zone=fixed_zone,
|
|
counting_polygon=counting_polygon,
|
|
truck_polygon=truck_polygon,
|
|
zone_preset=zone_preset,
|
|
output_max_height=(int(output_height) if output_height else None),
|
|
)
|
|
|
|
|
|
def _resolve_fcp_mode(mode: str):
|
|
"""Map an FCP model-mode letter to (ModelConfigs, class_filters).
|
|
|
|
Reads config.yaml fcp.mode_models: {letter: {stem: [engine classes]}}
|
|
mirroring FCP models.modes engines[].classes. Returns
|
|
(model_configs, class_filters, error); error is None on success,
|
|
(None, None, msg) when the letter is unknown or a stem is missing.
|
|
"""
|
|
from src.config import load_config
|
|
|
|
mode = (mode or "").strip().upper()
|
|
try:
|
|
mapping = (load_config().get("fcp") or {}).get("mode_models") or {}
|
|
except ValidationError as exc:
|
|
# A broken config.yaml must answer JSON, not a 500 HTML page.
|
|
return None, None, f"invalid config.yaml: {exc}"
|
|
stem_classes = mapping.get(mode)
|
|
if not stem_classes:
|
|
return None, None, (
|
|
f"unknown fcp_mode: {mode!r} (valid: {', '.join(sorted(mapping))})"
|
|
)
|
|
groups = {g.stem: g for g in scan_model_groups(MODELS_DIR)}
|
|
configs = []
|
|
class_filters: dict = {}
|
|
for stem, classes in stem_classes.items():
|
|
group = groups.get(stem)
|
|
if group is None:
|
|
return None, None, (
|
|
f"fcp_mode {mode!r} maps to stem {stem!r} not found under {MODELS_DIR}"
|
|
)
|
|
configs.append(ModelConfig(
|
|
filename=os.path.basename(group.format_paths[group.default_format]),
|
|
path=group.format_paths[group.default_format],
|
|
stem=stem,
|
|
known_classes=list(group.known_classes),
|
|
))
|
|
if isinstance(classes, list) and classes:
|
|
class_filters[stem] = [str(c) for c in classes]
|
|
return configs, class_filters, None
|
|
|
|
|
|
# Serializes API submits: busy-check → save/transcode → enqueue is one
|
|
# atomic section so overlapping POSTs can't both pass the busy guard and
|
|
# double-book the GPU. Ponytail: per-process lock, fine with gunicorn-less
|
|
# single-threaded app.run; add a cross-process lock only if multi-worker.
|
|
_ANALYZE_LOCK = threading.Lock()
|
|
|
|
|
|
@app.route("/api/analyze", methods=["POST"])
|
|
def api_analyze():
|
|
"""Machine-facing analyze: multipart video + fcp_mode (or model_stems).
|
|
|
|
Optional auth: X-API-Key header required iff env RECOUNTER_API_KEY set.
|
|
202 on accept, 400 validation, 401 bad key, 409 when another job is
|
|
pending/running (one GPU — serializes external callers).
|
|
"""
|
|
key = os.getenv("RECOUNTER_API_KEY")
|
|
if key and request.headers.get("X-API-Key") != key:
|
|
return jsonify({"error": "unauthorized"}), 401
|
|
|
|
video = request.files.get("video")
|
|
if not video or not video.filename:
|
|
return jsonify({"error": "No video uploaded"}), 400
|
|
safe_name = secure_filename(video.filename)
|
|
if not safe_name or not safe_name.lower().endswith(VIDEO_EXTENSIONS):
|
|
return jsonify({"error": "Invalid video file type"}), 400
|
|
|
|
fcp_mode = request.form.get("fcp_mode", "")
|
|
|
|
with _ANALYZE_LOCK:
|
|
active = [
|
|
{"job_id": j.job_id, "status": j.status.name}
|
|
for j in job_queue.list_jobs()
|
|
if j.status.name in ("PENDING", "RUNNING")
|
|
]
|
|
if active:
|
|
return jsonify({"error": "busy", "active": active}), 409
|
|
if conversion_manager.is_running():
|
|
return jsonify({"error": "busy", "reason": "conversion running"}), 409
|
|
|
|
if fcp_mode:
|
|
model_configs, class_filters, err = _resolve_fcp_mode(fcp_mode)
|
|
if err:
|
|
return jsonify({"error": err}), 400
|
|
else:
|
|
model_configs, class_filters = _parse_model_configs(request.form)
|
|
if not model_configs:
|
|
return jsonify({
|
|
"error": "No models selected (send fcp_mode or model_stems)",
|
|
}), 400
|
|
|
|
job = _save_and_queue(
|
|
video, model_configs, class_filters,
|
|
request.form.get("output_height", ""),
|
|
request.form.get("zone_mode", "fixed"),
|
|
request.form.get("zone_preset", ""),
|
|
)
|
|
return jsonify({"job_id": job.job_id,
|
|
"status_url": f"/api/jobs/{job.job_id}"}), 202
|
|
|
|
|
|
@app.route("/upload/reuse", methods=["POST"])
|
|
def upload_reuse():
|
|
"""Re-analyze an existing uploaded video."""
|
|
video_path = request.form.get("video_path", "")
|
|
if not video_path or not os.path.isfile(video_path):
|
|
return "Video not found", 400
|
|
|
|
model_configs, class_filters = _parse_model_configs(request.form)
|
|
|
|
# For upload reuse, only transcode if video is taller than 720p
|
|
meta = probe_video(video_path)
|
|
if meta["height"] > 720:
|
|
video_path = resize_video_to_max_height(video_path, max_height=720)
|
|
if not model_configs:
|
|
return "No models selected", 400
|
|
|
|
output_height = request.form.get("output_height", "")
|
|
zone_mode = request.form.get("zone_mode", "fixed")
|
|
zone_mode, fixed_zone, zone_preset, counting_polygon, truck_polygon = _resolve_zone(
|
|
zone_mode, request.form.get("zone_preset", "")
|
|
)
|
|
|
|
job = job_queue.add_job(
|
|
video_path=video_path,
|
|
model_configs=model_configs,
|
|
class_filters=class_filters,
|
|
zone_mode=zone_mode,
|
|
fixed_zone=fixed_zone,
|
|
counting_polygon=counting_polygon,
|
|
truck_polygon=truck_polygon,
|
|
zone_preset=zone_preset,
|
|
output_max_height=(int(output_height) if output_height else None),
|
|
)
|
|
return redirect(url_for("status", job_id=job.job_id))
|
|
|
|
|
|
@app.route("/status/<job_id>")
|
|
def status(job_id):
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return "Job not found", 404
|
|
return render_template("status.html", job=job)
|
|
|
|
|
|
@app.route("/jobs")
|
|
def jobs_list():
|
|
jobs = job_queue.list_jobs()
|
|
return render_template("jobs.html", jobs=jobs)
|
|
|
|
|
|
@app.route("/download/<job_id>/<filename>")
|
|
def download(job_id, filename):
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return "Job not found", 404
|
|
if job.status.name in ("PENDING", "RUNNING"):
|
|
return "Job still processing", 409
|
|
safe_filename = secure_filename(filename)
|
|
output_dir_abs = os.path.abspath(job.output_dir)
|
|
file_path = os.path.abspath(os.path.join(job.output_dir, safe_filename))
|
|
if os.path.commonpath([output_dir_abs, file_path]) != output_dir_abs:
|
|
return "File not found", 404
|
|
# Videos only: never a temp file of an encode in flight, never a stray file.
|
|
if not safe_filename.lower().endswith(VIDEO_EXTENSIONS):
|
|
return "File not found", 404
|
|
if not os.path.isfile(file_path):
|
|
return "File not found", 404
|
|
send_path = compress_in_place(file_path) or file_path
|
|
# send_file sets Content-Length (and the 206/Content-Range of a ranged
|
|
# request) itself - overriding it here would describe a body we do not send.
|
|
return send_file(send_path, as_attachment=True, download_name=os.path.basename(send_path))
|
|
|
|
|
|
@app.route("/calibrate")
|
|
def calibrate_page():
|
|
"""Interactive zone calibration page."""
|
|
return render_template("calibrate.html")
|
|
|
|
|
|
@app.route("/api/frame")
|
|
def api_frame():
|
|
"""One JPEG frame of an uploaded video, resized to the analysis size."""
|
|
safe = secure_filename(request.args.get("video", ""))
|
|
if not safe or not safe.lower().endswith(VIDEO_EXTENSIONS):
|
|
return jsonify({"error": "invalid filename"}), 400
|
|
try:
|
|
t = float(request.args.get("t", "0"))
|
|
except ValueError:
|
|
return jsonify({"error": "invalid t"}), 400
|
|
if not math.isfinite(t) or t < 0:
|
|
return jsonify({"error": "invalid t"}), 400
|
|
path = os.path.join(UPLOAD_DIR, safe)
|
|
if not os.path.isfile(path):
|
|
return jsonify({"error": "not found"}), 404
|
|
try:
|
|
jpeg = extract_frame_jpeg(path, t, ANALYSIS_SIZE)
|
|
except ValueError:
|
|
return jsonify({"error": "invalid t"}), 400
|
|
except (FileNotFoundError, RuntimeError, OSError) as exc:
|
|
return jsonify({"error": str(exc)}), 500
|
|
return Response(jpeg, mimetype="image/jpeg")
|
|
|
|
|
|
@app.route("/api/videos")
|
|
def api_videos():
|
|
"""List previously uploaded videos."""
|
|
videos = []
|
|
for f in sorted(Path(UPLOAD_DIR).iterdir(), key=lambda x: x.stat().st_mtime, reverse=True):
|
|
if f.is_file() and f.suffix.lower() in VIDEO_EXTENSIONS:
|
|
videos.append({
|
|
"filename": f.name,
|
|
"size": f.stat().st_size,
|
|
"mtime": f.stat().st_mtime,
|
|
"path": str(f),
|
|
})
|
|
return jsonify(videos)
|
|
|
|
|
|
@app.route("/api/videos/<filename>", methods=["DELETE"])
|
|
def api_delete_video(filename):
|
|
"""Delete an uploaded video."""
|
|
safe = secure_filename(filename)
|
|
if not safe or not safe.lower().endswith(VIDEO_EXTENSIONS):
|
|
return jsonify({"error": "invalid filename"}), 400
|
|
file_path = os.path.join(UPLOAD_DIR, safe)
|
|
if not os.path.isfile(file_path):
|
|
return jsonify({"error": "not found"}), 404
|
|
os.remove(file_path)
|
|
return jsonify({"status": "deleted"})
|
|
|
|
|
|
@app.route("/api/models")
|
|
def api_models():
|
|
groups = scan_model_groups(MODELS_DIR)
|
|
return jsonify([
|
|
{
|
|
"stem": g.stem,
|
|
"formats": g.formats,
|
|
"format_paths": g.format_paths,
|
|
"known_classes": g.known_classes,
|
|
"default_format": g.default_format,
|
|
}
|
|
for g in groups
|
|
])
|
|
|
|
|
|
def _active_analysis_jobs():
|
|
return [j for j in job_queue.list_jobs() if j.status.name in ("PENDING", "RUNNING")]
|
|
|
|
|
|
def _find_model_group(stem: str):
|
|
for g in scan_model_groups(MODELS_DIR):
|
|
if g.stem == stem:
|
|
return g
|
|
return None
|
|
|
|
|
|
def _upload_model_file():
|
|
"""Core handler for model uploads."""
|
|
file = (
|
|
request.files.get("model")
|
|
or request.files.get("file")
|
|
or request.files.get("upload")
|
|
or request.files.get("model_file")
|
|
)
|
|
if file is None or not file.filename:
|
|
return jsonify({"error": "no model file provided"}), 400
|
|
|
|
safe = secure_filename(file.filename)
|
|
if not safe:
|
|
return jsonify({"error": "invalid filename"}), 400
|
|
if Path(safe).suffix.lower() not in MODEL_UPLOAD_EXTENSIONS:
|
|
return jsonify({"error": "invalid model file type"}), 400
|
|
|
|
models_dir = Path(MODELS_DIR)
|
|
models_dir.mkdir(parents=True, exist_ok=True)
|
|
dest = models_dir / safe
|
|
overwrite = str(request.form.get("overwrite", "")).lower() in ("1", "true", "yes") or request.args.get("overwrite") in ("1", "true", "yes")
|
|
if dest.exists() and not overwrite:
|
|
return jsonify({"error": "file already exists"}), 409
|
|
|
|
file.save(str(dest))
|
|
|
|
stem = Path(safe).stem
|
|
group = _find_model_group(stem)
|
|
formats = list(group.formats) if group else [Path(safe).suffix.lower()]
|
|
has_engine = (models_dir / f"{stem}.engine").is_file()
|
|
convertible = (models_dir / f"{stem}.pt").is_file() or (models_dir / f"{stem}.onnx").is_file()
|
|
return jsonify(
|
|
{
|
|
"status": "uploaded",
|
|
"filename": safe,
|
|
"name": safe,
|
|
"stem": stem,
|
|
"path": str(dest),
|
|
"formats": formats,
|
|
"has_engine": has_engine,
|
|
"conversion_available": (not has_engine) and convertible,
|
|
}
|
|
), 201
|
|
|
|
|
|
def _start_conversion(stem=None):
|
|
"""Core handler for starting a conversion. Stem may come from URL or body."""
|
|
if stem is None and request.view_args:
|
|
stem = request.view_args.get("stem")
|
|
if not stem:
|
|
data = request.get_json(silent=True) or {}
|
|
stem = (
|
|
data.get("stem")
|
|
or data.get("model_stem")
|
|
or data.get("model")
|
|
or request.form.get("stem")
|
|
or request.form.get("model_stem")
|
|
or request.form.get("model")
|
|
)
|
|
if not stem:
|
|
return jsonify({"error": "stem is required"}), 400
|
|
stem = str(stem).strip()
|
|
# Reject anything that looks like a path; only bare stems allowed.
|
|
if "/" in stem or "\\" in stem or stem in (".", ".."):
|
|
return jsonify({"error": "invalid stem"}), 400
|
|
|
|
group = _find_model_group(stem)
|
|
if group is None:
|
|
return jsonify({"error": "model not found"}), 404
|
|
|
|
models_dir = Path(MODELS_DIR)
|
|
if ".engine" in (group.formats or []):
|
|
return jsonify({"status": "already_exists", "stem": stem}), 200
|
|
|
|
source = None
|
|
for ext in (".pt", ".onnx"):
|
|
candidate = models_dir / f"{stem}{ext}"
|
|
if candidate.is_file():
|
|
source = candidate
|
|
break
|
|
if source is None:
|
|
return jsonify({"error": "no convertible source (.pt/.onnx)"}), 400
|
|
|
|
if _active_analysis_jobs():
|
|
return jsonify({"error": "busy", "active": len(_active_analysis_jobs())}), 409
|
|
if conversion_manager.is_running():
|
|
return jsonify({"error": "conversion already running"}), 409
|
|
|
|
try:
|
|
job = conversion_manager.start(models_dir, stem, source)
|
|
except (RuntimeError, FileNotFoundError, OSError) as exc:
|
|
return jsonify({"error": str(exc)}), 409
|
|
if job is None:
|
|
return jsonify({"status": "already_exists", "stem": stem}), 200
|
|
return jsonify(
|
|
{
|
|
"job_id": job.job_id,
|
|
"status": job.status,
|
|
"stage": job.stage,
|
|
"stem": stem,
|
|
}
|
|
), 202
|
|
|
|
|
|
def _conversion_status(job_id: str):
|
|
job = conversion_manager.get(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
return jsonify(conversion_status_dict(job)), 200
|
|
|
|
|
|
def _list_conversions():
|
|
jobs = conversion_manager.list()
|
|
return jsonify({"conversions": [conversion_status_dict(j) for j in jobs]})
|
|
|
|
|
|
def _cancel_conversion(job_id: str):
|
|
ok = conversion_manager.cancel(job_id)
|
|
if not ok:
|
|
job = conversion_manager.get(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
return jsonify({"error": "cannot cancel conversion in state " + job.status}), 400
|
|
return jsonify({"status": "cancelled", "job_id": job_id})
|
|
|
|
|
|
# --- Model upload / conversion routes (with aliases for client compatibility) ---
|
|
_UPLOAD_RULES = [
|
|
"/api/models/upload",
|
|
"/api/model/upload",
|
|
"/api/upload/model",
|
|
"/models/upload",
|
|
"/upload/model",
|
|
]
|
|
for _rule in _UPLOAD_RULES:
|
|
app.add_url_rule(_rule, endpoint=f"upload_model_{_rule}", view_func=_upload_model_file, methods=["POST"])
|
|
|
|
_CONVERT_START_RULES = [
|
|
"/api/models/<stem>/convert",
|
|
"/api/model/<stem>/convert",
|
|
"/api/models/convert",
|
|
"/api/model/convert",
|
|
"/api/convert/model",
|
|
]
|
|
for _rule in _CONVERT_START_RULES:
|
|
app.add_url_rule(_rule, endpoint=f"start_conversion_{_rule}", view_func=_start_conversion, methods=["POST"])
|
|
|
|
_STATUS_RULES = [
|
|
"/api/models/conversions/<job_id>",
|
|
"/api/model/conversions/<job_id>",
|
|
"/api/conversions/<job_id>",
|
|
"/api/conversion/<job_id>",
|
|
"/api/models/conversion/<job_id>",
|
|
]
|
|
for _rule in _STATUS_RULES:
|
|
app.add_url_rule(_rule, endpoint=f"conversion_status_{_rule}", view_func=_conversion_status, methods=["GET"])
|
|
|
|
_LIST_RULES = ["/api/models/conversions", "/api/conversions", "/api/model/conversions"]
|
|
for _rule in _LIST_RULES:
|
|
app.add_url_rule(_rule, endpoint=f"list_conversions_{_rule}", view_func=_list_conversions, methods=["GET"])
|
|
|
|
_CANCEL_RULES = [
|
|
"/api/models/conversions/<job_id>/cancel",
|
|
"/api/model/conversions/<job_id>/cancel",
|
|
"/api/conversions/<job_id>/cancel",
|
|
"/api/conversion/<job_id>/cancel",
|
|
]
|
|
for _rule in _CANCEL_RULES:
|
|
app.add_url_rule(_rule, endpoint=f"cancel_conversion_{_rule}", view_func=_cancel_conversion, methods=["POST"])
|
|
|
|
|
|
@app.route("/api/zones")
|
|
def api_zones():
|
|
"""Return zone presets from zones.json."""
|
|
if not os.path.isfile(ZONES_PATH):
|
|
return jsonify([])
|
|
sync_fcp_zones(ZONES_PATH)
|
|
try:
|
|
presets = list_zone_presets(ZONES_PATH)
|
|
return jsonify(presets)
|
|
except Exception:
|
|
return jsonify([])
|
|
|
|
|
|
def _is_local_request() -> bool:
|
|
"""True when the request came from this machine.
|
|
|
|
The recounter serves one port, so FCP's office/operator port split
|
|
(counter_dashboard.py:2275) does not exist here. Remote operators use
|
|
an SSH tunnel, which makes the request arrive from loopback.
|
|
"""
|
|
# ::ffff:127.0.0.1 is the IPv4-mapped form of the loopback address; it
|
|
# shows up when the server listens on :: (IPv6) and the client is IPv4.
|
|
return request.remote_addr in ("127.0.0.1", "::1", "::ffff:127.0.0.1")
|
|
|
|
|
|
def _read_zones_config():
|
|
"""Return (config, error_response) for the zones file.
|
|
|
|
error_response is a Flask response tuple when the file is missing or
|
|
unusable, else None. Never raises: a corrupt zones.json must answer
|
|
with a status code, never a traceback.
|
|
"""
|
|
if not os.path.isfile(ZONES_PATH):
|
|
return None, (jsonify({"error": "zones.json not found"}), 404)
|
|
sync_fcp_zones(ZONES_PATH)
|
|
try:
|
|
config = load_zone_config(ZONES_PATH)
|
|
except OSError as exc:
|
|
return None, (jsonify({"error": f"cannot read zones.json: {exc}"}), 500)
|
|
except ValueError as exc: # malformed JSON
|
|
return None, (jsonify({"error": f"zones.json is not valid JSON: {exc}"}), 500)
|
|
if not isinstance(config, dict):
|
|
return None, (jsonify({"error": "zones.json must contain a JSON object"}), 500)
|
|
return config, None
|
|
|
|
|
|
@app.route("/api/zones/<preset_name>", methods=["GET"])
|
|
def api_zone_detail(preset_name: str):
|
|
"""Return one zone preset plus the coordinate space it is authored in."""
|
|
config, error = _read_zones_config()
|
|
if error is not None:
|
|
return error
|
|
presets = config.get("presets")
|
|
preset = presets.get(preset_name) if isinstance(presets, dict) else None
|
|
if preset is None:
|
|
return jsonify({"error": "unknown preset"}), 404
|
|
return jsonify({
|
|
"preset": preset,
|
|
"source_width": ZONE_BOUNDS_W,
|
|
"source_height": ZONE_BOUNDS_H,
|
|
})
|
|
|
|
|
|
@app.route("/api/zones/<preset_name>", methods=["POST"])
|
|
def api_zone_save(preset_name: str):
|
|
"""Save one zone preset. Localhost only."""
|
|
if not _is_local_request():
|
|
return jsonify({"error": "local access only"}), 403
|
|
_, error = _read_zones_config()
|
|
if error is not None:
|
|
return error
|
|
raw = request.get_data(cache=True)
|
|
if raw:
|
|
try:
|
|
payload = json.loads(raw)
|
|
except (ValueError, UnicodeDecodeError):
|
|
return jsonify({"error": "request body is not valid JSON"}), 400
|
|
else:
|
|
payload = {}
|
|
preset = payload.get("preset", payload) if isinstance(payload, dict) else payload
|
|
if not isinstance(preset, dict):
|
|
return jsonify({"error": "preset must be an object"}), 400
|
|
try:
|
|
save_zone_preset(ZONES_PATH, preset_name, preset)
|
|
except FileNotFoundError:
|
|
return jsonify({"error": "zones.json not found"}), 404
|
|
except ValueError as exc:
|
|
return jsonify({"error": str(exc)}), 400
|
|
except OSError as exc:
|
|
return jsonify({"error": str(exc)}), 500
|
|
return jsonify({"status": "saved"})
|
|
|
|
|
|
@app.route("/api/zones/<preset_name>/reset", methods=["POST"])
|
|
def api_zone_reset(preset_name: str):
|
|
"""Restore a preset to the shipped default. Localhost only."""
|
|
if not _is_local_request():
|
|
return jsonify({"error": "local access only"}), 403
|
|
_, error = _read_zones_config()
|
|
if error is not None:
|
|
return error
|
|
default = DEFAULT_ZONES.get(preset_name)
|
|
if default is None:
|
|
return jsonify({"error": "unknown preset"}), 404
|
|
try:
|
|
save_zone_preset(ZONES_PATH, preset_name, default, replace=True)
|
|
except FileNotFoundError:
|
|
return jsonify({"error": "zones.json not found"}), 404
|
|
except ValueError as exc:
|
|
return jsonify({"error": str(exc)}), 400
|
|
except OSError as exc:
|
|
return jsonify({"error": str(exc)}), 500
|
|
return jsonify({"status": "reset", "preset": default})
|
|
|
|
|
|
@app.route("/api/jobs")
|
|
def api_jobs():
|
|
return jsonify([{
|
|
"job_id": j.job_id,
|
|
"status": j.status.name,
|
|
"progress": j.progress,
|
|
"video_path": os.path.basename(j.video_path),
|
|
"results": [
|
|
{
|
|
"model": r.model_name,
|
|
"loading": r.loading_count,
|
|
"unloading": r.unloading_count,
|
|
"net": r.net_count,
|
|
"truncated": r.truncated,
|
|
"frames_expected": r.frames_expected,
|
|
}
|
|
for r in j.results
|
|
],
|
|
} for j in job_queue.list_jobs()])
|
|
|
|
|
|
@app.route("/api/jobs/<job_id>/cancel", methods=["POST"])
|
|
def api_cancel_job(job_id):
|
|
"""Cancel a running or pending job."""
|
|
success = job_queue.cancel_job(job_id)
|
|
if success:
|
|
return jsonify({"status": "cancelled"})
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
return jsonify({"error": "cannot cancel job in state " + job.status.name}), 400
|
|
|
|
|
|
@app.route("/api/jobs/active")
|
|
def api_active_jobs():
|
|
"""Return count of running/pending jobs."""
|
|
active = [j for j in job_queue.list_jobs() if j.status.name in ('RUNNING', 'PENDING')]
|
|
return jsonify({
|
|
"count": len(active),
|
|
"jobs": [{"job_id": j.job_id, "status": j.status.name, "video": os.path.basename(j.video_path)} for j in active],
|
|
})
|
|
|
|
|
|
@app.route("/api/jobs/<job_id>", methods=["DELETE"])
|
|
def api_delete_job(job_id):
|
|
"""Delete a completed/failed/cancelled job."""
|
|
success = job_queue.delete_job(job_id)
|
|
if success:
|
|
return jsonify({"status": "deleted"})
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
return jsonify({"error": "cannot delete job in state " + job.status.name}), 400
|
|
|
|
|
|
@app.route("/api/jobs/<job_id>/preview", methods=["PUT"])
|
|
def api_toggle_preview(job_id):
|
|
"""Toggle live preview on/off for a running job."""
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
data = request.get_json(silent=True) or {}
|
|
enabled = data.get("enabled", True)
|
|
with job_queue._lock:
|
|
job.preview_enabled = enabled
|
|
return jsonify({"status": "ok", "preview_enabled": enabled})
|
|
|
|
|
|
@app.route("/api/jobs/<job_id>")
|
|
def api_job_detail(job_id):
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
return jsonify({
|
|
"job_id": job.job_id,
|
|
"status": job.status.name,
|
|
"progress": job.progress,
|
|
"current_model": job.current_model,
|
|
"results": [
|
|
{
|
|
"model_name": r.model_name,
|
|
"loading_count": r.loading_count,
|
|
"unloading_count": r.unloading_count,
|
|
"net_count": r.net_count,
|
|
"box_loading_count": r.box_loading_count,
|
|
"box_unloading_count": r.box_unloading_count,
|
|
"box_net_count": r.box_net_count,
|
|
"batch_count": r.batch_count,
|
|
"frame_count": r.frame_count,
|
|
"duration_seconds": r.duration_seconds,
|
|
"output_path": os.path.basename(r.output_path) if r.output_path else None,
|
|
"truncated": r.truncated,
|
|
"frames_expected": r.frames_expected,
|
|
}
|
|
for r in job.results
|
|
],
|
|
"error": job.error,
|
|
"live_fps": job.live_fps,
|
|
"live_loading": job.live_loading,
|
|
"live_unloading": job.live_unloading,
|
|
"live_box_loading": job.live_box_loading,
|
|
"live_box_unloading": job.live_box_unloading,
|
|
"live_frame": job.live_frame,
|
|
})
|
|
|
|
|
|
@app.route("/preview/thumb/<job_id>")
|
|
def preview_thumb(job_id):
|
|
"""Serve a thumbnail JPEG for a job's video (cached in job output_dir)."""
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return "Job not found", 404
|
|
thumb_path = os.path.join(job.output_dir, "thumbnail.jpg")
|
|
if not os.path.isfile(thumb_path):
|
|
try:
|
|
extract_thumbnail(job.video_path, thumb_path)
|
|
except (FileNotFoundError, RuntimeError):
|
|
return "Could not generate thumbnail", 404
|
|
return send_file(thumb_path, mimetype="image/jpeg")
|
|
|
|
|
|
@app.route("/api/jobs/<job_id>/samples")
|
|
def api_job_samples(job_id):
|
|
"""Return JSON array of sample frame paths (extract if not cached)."""
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
samples_dir = os.path.join(job.output_dir, "samples")
|
|
cache_file = os.path.join(samples_dir, ".cached")
|
|
if not os.path.isfile(cache_file):
|
|
try:
|
|
paths = extract_sample_frames(job.video_path, samples_dir)
|
|
with open(cache_file, "w") as f:
|
|
f.write("\n".join(paths))
|
|
except (FileNotFoundError, RuntimeError):
|
|
return jsonify({"error": "could not generate samples"}), 404
|
|
else:
|
|
with open(cache_file) as f:
|
|
paths = [line.strip() for line in f if line.strip()]
|
|
rel_paths = [os.path.relpath(p, job.output_dir) for p in paths]
|
|
return jsonify(rel_paths)
|
|
|
|
|
|
@app.route("/api/preview/<job_id>")
|
|
def api_preview(job_id):
|
|
job = job_queue.get_job(job_id)
|
|
if job is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
preview_path = job.preview_path
|
|
if not preview_path:
|
|
return jsonify({"error": "no preview path"}), 404
|
|
|
|
def generate():
|
|
consecutive_fails = 0
|
|
MAX_FAILS = 30
|
|
last_mtime = -1.0
|
|
while True:
|
|
try:
|
|
st = os.stat(preview_path)
|
|
if st.st_mtime != last_mtime:
|
|
last_mtime = st.st_mtime
|
|
with open(preview_path, "rb") as f:
|
|
jpeg = f.read()
|
|
yield (b"--frame\r\n"
|
|
b"Content-Type: image/jpeg\r\n\r\n" + jpeg + b"\r\n")
|
|
consecutive_fails = 0
|
|
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 main():
|
|
host = os.getenv("WEB_HOST", "0.0.0.0")
|
|
port = int(os.getenv("WEB_PORT", "9050"))
|
|
debug = os.getenv("FLASK_DEBUG", "false").lower() == "true"
|
|
|
|
print(f"Feedmill Recounter web UI: http://{host}:{port}")
|
|
app.run(host=host, port=port, debug=debug)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|