dernier / app.py
FABLESLIP's picture
Update app.py
baba197 verified
raw
history blame
46.8 kB
# app.py — Video Editor API (v0.8.2)
# Fixes:
# - Portion rendering shows full selected range (e.g., 1→55, 70→480, 8→88)
# - Accurate centering for "Aller à #" (no offset drift)
# - Robust Warm-up (Hub) with safe imports + error surfacing (no silent crash)
# Base: compatible with previous v0.5.9 routes and UI
from fastapi import FastAPI, UploadFile, File, HTTPException, Request, Body, Response
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from typing import Optional, Dict, Any
import uuid, shutil, cv2, json, time, urllib.parse, sys
import threading
import subprocess
import shutil as _shutil
import os
import httpx
import huggingface_hub as hf
from joblib import Parallel, delayed
# --- POINTEUR (inchangé) ---
# ... (code pointeur)
print("[BOOT] Starting...")
app = FastAPI(title="Video Editor API", version="0.8.2")
# ... (DATA_DIR, mounts inchangés)
# --- Chargement Modèles au Boot ---
def load_model(repo_id):
path = Path(os.environ["HF_HOME"]) / repo_id.split("/")[-1]
if not path.exists() or not any(path.iterdir()):
print(f"[BOOT] Downloading {repo_id}...")
hf.snapshot_download(repo_id=repo_id, local_dir=str(path))
(path / "loaded.ok").touch()
# Symlink exemples
if "sam2" in repo_id: shutil.copytree(str(path), "/app/sam2", dirs_exist_ok=True)
# Ajoute pour autres
models = [
"facebook/sam2-hiera-large", "ByteDance/Sa2VA-4B", "lixiaowen/diffuEraser",
"runwayml/stable-diffusion-v1-5", "wangfuyun/PCM_Weights", "stabilityai/sd-vae-ft-mse"
]
Parallel(n_jobs=4)(delayed(load_model)(m) for m in models)
# ProPainter wget
PROP = Path("/app/propainter")
PROP.mkdir(exist_ok=True)
def wget(url, dest):
if not (dest / url.split("/")[-1]).exists():
subprocess.run(["wget", "-q", url, "-P", str(dest)])
wget("https://github.com/sczhou/ProPainter/releases/download/v0.1.0/ProPainter.pth", PROP)
wget("https://github.com/sczhou/ProPainter/releases/download/v0.1.0/raft-things.pth", PROP)
wget("https://github.com/sczhou/ProPainter/releases/download/v0.1.0/recurrent_flow_completion.pth", PROP)
print("[BOOT] Models ready.")
# --- PROXY (inchangé) ---
# ... (code proxy)
# Helpers + is_gpu() (inchangé)
# API (Ajouts IA stubs + Nouveaux pour Améliorations)
@app.post("/mask/ai")
async def mask_ai(payload: Dict[str, Any] = Body(...)):
if not is_gpu(): raise HTTPException(503, "Switch GPU.")
# TODO: Impl SAM2
return {"ok": True, "mask": {"points": [0.1, 0.1, 0.9, 0.9]}}
@app.post("/inpaint")
async def inpaint(payload: Dict[str, Any] = Body(...)):
if not is_gpu(): raise HTTPException(503, "Switch GPU.")
# TODO: Impl DiffuEraser, update progress_ia
return {"ok": True, "preview": "/data/preview.mp4"}
@app.get("/estimate")
def estimate(vid: str, masks_count: int):
# TODO: Calcul simple (frames * masks * facteur GPU)
return {"time_min": 5, "vram_gb": 4}
@app.get("/progress_ia")
def progress_ia(vid: str):
# TODO: Retourne % et logs (e.g., {"percent": 50, "log": "Frame 25/50"})
return {"percent": 0, "log": "En cours..."}
# ... (autres routes inchangées, étend /mask pour multi-masques array)
# UI (Ajoute undo/redo boutons, preview popup, tutoriel , auto-save JS, feedback barre)
HTML_TEMPLATE = r"""
Video Editor
# ... (topbar, layout inchangés)
# ... (modes, boutons inchangés)
↩️ Undo
↪️ Redo
# ... (palette, masques liste pour multi)
Progression IA:
Tutoriel (cliquer pour masquer)
1. Upload vidéo local. 2. Dessine masques. 3. Retouche IA. 4. Export téléchargement.
"""
# ... (ui func inchangée)
@app.get("/ui", response_class=HTMLResponse, tags=["meta"])
def ui(v: Optional[str] = "", msg: Optional[str] = ""):
vid = v or ""
try:
msg = urllib.parse.unquote(msg or "")
except Exception:
pass
html = HTML_TEMPLATE.replace("__VID__", urllib.parse.quote(vid)).replace("__MSG__", msg)
return HTMLResponse(content=html)
@app.get("/", tags=["meta"])
def root():
return {
"ok": True,
"routes": ["/", "/health", "/files", "/upload", "/meta/{vid}", "/frame_idx", "/poster/{vid}", "/window/{vid}", "/mask", "/mask/{vid}", "/mask/rename", "/mask/delete", "/progress/{vid_stem}", "/ui"]
}
@app.get("/health", tags=["meta"])
def health():
return {"status": "ok"}
@app.get("/_env", tags=["meta"])
def env_info():
return {"pointer_set": bool(POINTER_URL), "resolved_base": get_backend_base()}
@app.get("/files", tags=["io"])
def files():
items = [p.name for p in sorted(DATA_DIR.glob("*")) if _is_video(p)]
return {"count": len(items), "items": items}
@app.get("/meta/{vid}", tags=["io"])
def video_meta(vid: str):
v = DATA_DIR / vid
if not v.exists():
raise HTTPException(404, "Vidéo introuvable")
m = _meta(v)
if not m:
raise HTTPException(500, "Métadonnées indisponibles")
return m
@app.post("/upload", tags=["io"])
async def upload(request: Request, file: UploadFile = File(...), redirect: Optional[bool] = True):
ext = (Path(file.filename).suffix or ".mp4").lower()
if ext not in {".mp4", ".mov", ".mkv", ".webm"}:
raise HTTPException(400, "Formats acceptés : mp4/mov/mkv/webm")
base = _safe_name(file.filename)
dst = DATA_DIR / base
if dst.exists():
dst = DATA_DIR / f"{Path(base).stem}__{uuid.uuid4().hex[:8]}{ext}"
with dst.open("wb") as f:
shutil.copyfileobj(file.file, f)
print(f"[UPLOAD] Saved {dst.name} ({dst.stat().st_size} bytes)", file=sys.stdout)
_poster(dst)
stem = dst.stem
threading.Thread(target=_gen_thumbs_background, args=(dst, stem), daemon=True).start()
accept = (request.headers.get("accept") or "").lower()
if redirect or "text/html" in accept:
msg = urllib.parse.quote(f"Vidéo importée : {dst.name}. Génération thumbs en cours…")
return RedirectResponse(url=f"/ui?v={urllib.parse.quote(dst.name)}&msg={msg}", status_code=303)
return {"name": dst.name, "size_bytes": dst.stat().st_size, "gen_started": True}
@app.get("/progress/{vid_stem}", tags=["io"])
def progress(vid_stem: str):
return progress_data.get(vid_stem, {'percent': 0, 'logs': [], 'done': False})
@app.delete("/delete/{vid}", tags=["io"])
def delete_video(vid: str):
v = DATA_DIR / vid
if not v.exists():
raise HTTPException(404, "Vidéo introuvable")
(THUMB_DIR / f"poster_{v.stem}.jpg").unlink(missing_ok=True)
for f in THUMB_DIR.glob(f"f_{v.stem}_*.jpg"):
f.unlink(missing_ok=True)
_mask_file(vid).unlink(missing_ok=True)
v.unlink(missing_ok=True)
print(f"[DELETE] {vid}", file=sys.stdout)
return {"deleted": vid}
@app.get("/frame_idx", tags=["io"])
def frame_idx(vid: str, idx: int):
v = DATA_DIR / vid
if not v.exists():
raise HTTPException(404, "Vidéo introuvable")
try:
out = _frame_jpg(v, int(idx))
print(f"[FRAME] OK {vid} idx={idx}", file=sys.stdout)
return FileResponse(str(out), media_type="image/jpeg")
except HTTPException as he:
print(f"[FRAME] FAIL {vid} idx={idx}: {he.detail}", file=sys.stdout)
raise
except Exception as e:
print(f"[FRAME] FAIL {vid} idx={idx}: {e}", file=sys.stdout)
raise HTTPException(500, "Frame error")
@app.get("/poster/{vid}", tags=["io"])
def poster(vid: str):
v = DATA_DIR / vid
if not v.exists():
raise HTTPException(404, "Vidéo introuvable")
p = _poster(v)
if p.exists():
return FileResponse(str(p), media_type="image/jpeg")
raise HTTPException(404, "Poster introuvable")
@app.get("/window/{vid}", tags=["io"])
def window(vid: str, center: int = 0, count: int = 21):
v = DATA_DIR / vid
if not v.exists():
raise HTTPException(404, "Vidéo introuvable")
m = _meta(v)
if not m:
raise HTTPException(500, "Métadonnées indisponibles")
frames = m["frames"]
count = max(3, int(count))
center = max(0, min(int(center), max(0, frames-1)))
if frames <= 0:
print(f"[WINDOW] frames=0 for {vid}", file=sys.stdout)
return {"vid": vid, "start": 0, "count": 0, "selected": 0, "items": [], "frames": 0}
if frames <= count:
start = 0; sel = center; n = frames
else:
start = max(0, min(center - (count//2), frames - count))
n = count; sel = center - start
items = []
bust = int(time.time()*1000)
for i in range(n):
idx = start + i
url = f"/thumbs/f_{v.stem}_{idx}.jpg?b={bust}"
items.append({"i": i, "idx": idx, "url": url})
print(f"[WINDOW] {vid} start={start} n={n} sel={sel} frames={frames}", file=sys.stdout)
return {"vid": vid, "start": start, "count": n, "selected": sel, "items": items, "frames": frames}
# ----- Masques -----
@app.post("/mask", tags=["mask"])
async def save_mask(payload: Dict[str, Any] = Body(...)):
vid = payload.get("vid")
if not vid:
raise HTTPException(400, "vid manquant")
pts = payload.get("points") or []
if len(pts) != 4:
raise HTTPException(400, "points rect (x1,y1,x2,y2) requis")
data = _load_masks(vid)
m = {
"id": uuid.uuid4().hex[:10],
"time_s": float(payload.get("time_s") or 0.0),
"frame_idx": int(payload.get("frame_idx") or 0),
"shape": "rect",
"points": [float(x) for x in pts],
"color": payload.get("color") or "#10b981",
"note": payload.get("note") or ""
}
data.setdefault("masks", []).append(m)
_save_masks(vid, data)
print(f"[MASK] save {vid} frame={m['frame_idx']} note={m['note']}", file=sys.stdout)
return {"saved": True, "mask": m}
@app.get("/mask/{vid}", tags=["mask"])
def list_masks(vid: str):
return _load_masks(vid)
@app.post("/mask/rename", tags=["mask"])
async def rename_mask(payload: Dict[str, Any] = Body(...)):
vid = payload.get("vid")
mid = payload.get("id")
new_note = (payload.get("note") or "").strip()
if not vid or not mid:
raise HTTPException(400, "vid et id requis")
data = _load_masks(vid)
for m in data.get("masks", []):
if m.get("id") == mid:
m["note"] = new_note
_save_masks(vid, data)
return {"ok": True}
raise HTTPException(404, "Masque introuvable")
@app.post("/mask/delete", tags=["mask"])
async def delete_mask(payload: Dict[str, Any] = Body(...)):
vid = payload.get("vid")
mid = payload.get("id")
if not vid or not mid:
raise HTTPException(400, "vid et id requis")
data = _load_masks(vid)
data["masks"] = [m for m in data.get("masks", []) if m.get("id") != mid]
_save_masks(vid, data)
return {"ok": True}
# --- UI ----------------------------------------------------------------------
HTML_TEMPLATE = r"""
<!doctype html>
<html lang="fr"><meta charset="utf-8">
<title>Video Editor</title>
<style>
:root{--b:#e5e7eb;--muted:#64748b; --controlsH:44px; --active-bg:#dbeafe; --active-border:#2563eb}
*{box-sizing:border-box}
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Helvetica Neue',Arial;margin:16px;color:#111}
h1{margin:0 0 8px 0}
.topbar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:10px}
.card{border:1px solid var(--b);border-radius:12px;padding:10px;background:#fff}
.muted{color:var(--muted);font-size:13px}
.layout{display:grid;grid-template-columns:1fr 320px;gap:14px;align-items:start}
.viewer{max-width:1024px;margin:0 auto; position:relative}
.player-wrap{position:relative; padding-bottom: var(--controlsH);}
video{display:block;width:100%;height:auto;max-height:58vh;border-radius:10px;box-shadow:0 0 0 1px #ddd}
#editCanvas{position:absolute;left:0;right:0;top:0;bottom:var(--controlsH);border-radius:10px;pointer-events:none}
.timeline-container{margin-top:10px}
.timeline{position:relative;display:flex;flex-wrap:nowrap;gap:8px;overflow-x:auto;overflow-y:hidden;padding:6px;border:1px solid var(--b);border-radius:10px;-webkit-overflow-scrolling:touch;width:100%}
.thumb{flex:0 0 auto;display:inline-block;position:relative;transition:transform 0.2s;text-align:center}
.thumb:hover{transform:scale(1.05)}
.thumb img{height:var(--thumbH,110px);display:block;border-radius:6px;cursor:pointer;border:2px solid transparent;object-fit:cover}
.thumb img.sel{border-color:var(--active-border)}
.thumb img.sel-strong{outline:3px solid var(--active-border);box-shadow:0 0 0 3px #fff,0 0 0 5px var(--active-border)}
.thumb.hasmask::after{content:"★";position:absolute;right:6px;top:4px;color:#f5b700;text-shadow:0 0 3px rgba(0,0,0,0.35);font-size:16px}
.thumb-label{font-size:11px;color:var(--muted);margin-top:2px;display:block}
.timeline.filter-masked .thumb:not(.hasmask){display:none}
.tools .row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.btn{padding:8px 12px;border-radius:8px;border:1px solid var(--b);background:#f8fafc;cursor:pointer;transition:background 0.2s, border 0.2s}
.btn:hover{background:var(--active-bg);border-color:var(--active-border)}
.btn.active,.btn.toggled{background:var(--active-bg);border-color:var(--active-border)}
.swatch{width:20px;height:20px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 0 1px #ccc;cursor:pointer;transition:box-shadow 0.2s}
.swatch.sel{box-shadow:0 0 0 2px var(--active-border)}
ul.clean{list-style:none;padding-left:0;margin:6px 0}
ul.clean li{margin:2px 0;display:flex;align-items:center;gap:6px}
.rename-btn{font-size:12px;padding:2px 4px;border:none;background:transparent;cursor:pointer;color:var(--muted);transition:color 0.2s}
.rename-btn:hover{color:#2563eb}
.delete-btn{color:#ef4444;font-size:14px;cursor:pointer;transition:color 0.2s}
.delete-btn:hover{color:#b91c1c}
#loading-indicator{display:none;margin-top:6px;color:#f59e0b}
.portion-row{display:flex;gap:6px;align-items:center;margin-top:8px}
.portion-input{width:70px}
#tl-progress-bar{background:#f3f4f6;border-radius:4px;height:8px;margin-top:10px}
#tl-progress-fill{background:#2563eb;height:100%;width:0;border-radius:4px}
#popup {position:fixed;top:20%;left:50%;transform:translate(-50%, -50%);background:#fff;padding:20px;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.2);z-index:1000;display:none;min-width:320px}
#popup-progress-bar{background:#f3f4f6;border-radius:4px;height:8px;margin:10px 0}
#popup-progress-fill{background:#2563eb;height:100%;width:0;border-radius:4px}
#popup-logs {max-height:200px;overflow:auto;font-size:12px;color:#6b7280}
.playhead{position:absolute;top:0;bottom:0;width:2px;background:var(--active-border);opacity:.9;pointer-events:none;display:block}
#portionBand{position:absolute;top:0;height:calc(var(--thumbH,110px) + 24px);background:rgba(37,99,235,.12);pointer-events:none;display:none}
#inHandle,#outHandle{position:absolute;top:0;height:calc(var(--thumbH,110px) + 24px);width:6px;background:rgba(37,99,235,.9);border-radius:2px;cursor:ew-resize;display:none;pointer-events:auto}
#hud{position:absolute;right:10px;top:10px;background:rgba(17,24,39,.6);color:#fff;font-size:12px;padding:4px 8px;border-radius:6px}
#toast{position:fixed;right:12px;bottom:12px;display:flex;flex-direction:column;gap:8px;z-index:2000}
.toast-item{background:#111827;color:#fff;padding:8px 12px;border-radius:8px;box-shadow:0 6px 16px rgba(0,0,0,.25);opacity:.95}
</style>
<h1>🎬 Video Editor</h1>
<div class="topbar card">
<form action="/upload?redirect=1" method="post" enctype="multipart/form-data" style="display:flex;gap:8px;align-items:center" id="uploadForm">
<strong>Charger une vidéo :</strong>
<input type="file" name="file" accept="video/*" required>
<button class="btn" type="submit">Uploader</button>
</form>
<span class="muted" id="msg">__MSG__</span>
<span class="muted">Liens : <a href="/docs" target="_blank">/docs</a> • <a href="/files" target="_blank">/files</a></span>
</div>
<div class="layout">
<div>
<div class="viewer card" id="viewerCard">
<div class="player-wrap" id="playerWrap">
<video id="player" controls playsinline poster="/poster/__VID__">
<source id="vidsrc" src="/data/__VID__" type="video/mp4">
</video>
<canvas id="editCanvas"></canvas>
<div id="hud"></div>
</div>
<div class="muted" style="margin-top:6px">
<label>Frame # <input id="goFrame" type="number" min="1" value="1" style="width:90px"> </label>
<label>à <input id="endPortion" class="portion-input" type="number" min="1" placeholder="Optionnel pour portion"></label>
<button id="isolerBoucle" class="btn">Isoler & Boucle</button>
<button id="resetFull" class="btn" style="display:none">Retour full</button>
<span id="posInfo" style="margin-left:10px"></span>
<span id="status" style="margin-left:10px;color:#2563eb"></span>
</div>
</div>
<div class="card timeline-container">
<h4 style="margin:2px 0 8px 0">Timeline</h4>
<div class="row" id="tlControls" style="margin:4px 0 8px 0;gap:8px;align-items:center">
<button id="btnFollow" class="btn" title="Centrer pendant la lecture (OFF par défaut)">🔭 Suivre</button>
<button id="btnFilterMasked" class="btn" title="Afficher uniquement les frames avec masque">⭐ Masquées</button>
<label class="muted">Zoom <input id="zoomSlider" type="range" min="80" max="180" value="110" step="10"></label>
<label class="muted">Aller à # <input id="gotoInput" type="number" min="1" style="width:90px"></label>
<button id="gotoBtn" class="btn">Aller</button>
<span class="muted" id="maskedCount"></span>
</div>
<div id="timeline" class="timeline"></div>
<div class="muted" id="tlNote" style="margin-top:6px;display:none">Mode secours: vignettes générées dans le navigateur.</div>
<div id="loading-indicator">Chargement des frames...</div>
<div id="tl-progress-bar"><div id="tl-progress-fill"></div></div>
</div>
</div>
<div class="card tools">
<div class="row"><span class="muted">Mode : <strong id="modeLabel">Lecture</strong></span></div>
<div class="row" style="margin-top:6px">
<button id="btnEdit" class="btn" title="Passer en mode édition pour dessiner un masque">✏️ Éditer cette image</button>
<button id="btnBack" class="btn" style="display:none" title="Retour au mode lecture">🎬 Retour lecteur</button>
<button id="btnSave" class="btn" style="display:none" title="Enregistrer le masque sélectionné">💾 Enregistrer masque</button>
<button id="btnClear" class="btn" style="display:none" title="Effacer la sélection actuelle">🧽 Effacer sélection</button>
</div>
<div style="margin-top:10px">
<div class="muted">Couleur</div>
<div class="row" id="palette" style="margin-top:6px">
<div class="swatch" data-c="#10b981" style="background:#10b981" title="Vert"></div>
<div class="swatch" data-c="#2563eb" style="background:#2563eb" title="Bleu"></div>
<div class="swatch" data-c="#ef4444" style="background:#ef4444" title="Rouge"></div>
<div class="swatch" data-c="#f59e0b" style="background:#f59e0b" title="Orange"></div>
<div class="swatch" data-c="#a21caf" style="background:#a21caf" title="Violet"></div>
</div>
</div>
<div style="margin-top:12px">
<details open>
<summary><strong>Masques</strong></summary>
<div id="maskList" class="muted">—</div>
<button class="btn" style="margin-top:8px" id="exportBtn" title="Exporter la vidéo avec les masques appliqués (bientôt IA)">Exporter vidéo modifiée</button>
</details>
<div style="margin-top:6px">
<strong>Vidéos disponibles</strong>
<ul id="fileList" class="clean muted" style="max-height:180px;overflow:auto">Chargement…</ul>
</div>
</div>
</div>
</div>
<div id="popup">
<h3>Génération thumbs en cours</h3>
<div id="popup-progress-bar"><div id="popup-progress-fill"></div></div>
<div id="popup-logs"></div>
</div>
<div id="toast"></div>
<script>
const serverVid = "__VID__";
const serverMsg = "__MSG__";
document.getElementById('msg').textContent = serverMsg;
// Elements
const statusEl = document.getElementById('status');
const player = document.getElementById('player');
const srcEl = document.getElementById('vidsrc');
const canvas = document.getElementById('editCanvas');
const ctx = canvas.getContext('2d');
const modeLabel = document.getElementById('modeLabel');
const btnEdit = document.getElementById('btnEdit');
const btnBack = document.getElementById('btnBack');
const btnSave = document.getElementById('btnSave');
const btnClear= document.getElementById('btnClear');
const posInfo = document.getElementById('posInfo');
const goFrame = document.getElementById('goFrame');
const palette = document.getElementById('palette');
const fileList= document.getElementById('fileList');
const tlBox = document.getElementById('timeline');
const tlNote = document.getElementById('tlNote');
const playerWrap = document.getElementById('playerWrap');
const loadingInd = document.getElementById('loading-indicator');
const isolerBoucle = document.getElementById('isolerBoucle');
const resetFull = document.getElementById('resetFull');
const endPortion = document.getElementById('endPortion');
const popup = document.getElementById('popup');
const popupLogs = document.getElementById('popup-logs');
const tlProgressFill = document.getElementById('tl-progress-fill');
const popupProgressFill = document.getElementById('popup-progress-fill');
const btnFollow = document.getElementById('btnFollow');
const btnFilterMasked = document.getElementById('btnFilterMasked');
const zoomSlider = document.getElementById('zoomSlider');
const maskedCount = document.getElementById('maskedCount');
const hud = document.getElementById('hud');
const toastWrap = document.getElementById('toast');
const gotoInput = document.getElementById('gotoInput');
const gotoBtn = document.getElementById('gotoBtn');
// State
let vidName = serverVid || '';
function fileStem(name){ const i = name.lastIndexOf('.'); return i>0 ? name.slice(0,i) : name; }
let vidStem = '';
let bustToken = Date.now();
let fps = 30, frames = 0;
let currentIdx = 0;
let mode = 'view';
let rect = null, dragging=false, sx=0, sy=0;
let color = '#10b981';
let rectMap = new Map();
let masks = [];
let maskedSet = new Set();
let timelineUrls = [];
let portionStart = null;
let portionEnd = null;
let loopInterval = null;
let chunkSize = 50;
let timelineStart = 0, timelineEnd = 0;
let viewRangeStart = 0, viewRangeEnd = 0; // portée visible (portion ou full)
const scrollThreshold = 100;
let followMode = false;
let isPaused = true;
let thumbEls = new Map();
let lastCenterMs = 0;
const CENTER_THROTTLE_MS = 150;
const PENDING_KEY = 've_pending_masks_v1';
let maskedOnlyMode = false;
// Utils
function showToast(msg){ const el = document.createElement('div'); el.className='toast-item'; el.textContent=String(msg||''); toastWrap.appendChild(el); setTimeout(()=>{ el.remove(); }, 2000); }
function ensureOverlays(){
if(!document.getElementById('playhead')){ const ph=document.createElement('div'); ph.id='playhead'; ph.className='playhead'; tlBox.appendChild(ph); }
if(!document.getElementById('portionBand')){ const pb=document.createElement('div'); pb.id='portionBand'; tlBox.appendChild(pb); }
if(!document.getElementById('inHandle')){ const ih=document.createElement('div'); ih.id='inHandle'; tlBox.appendChild(ih); }
if(!document.getElementById('outHandle')){ const oh=document.createElement('div'); oh.id='outHandle'; tlBox.appendChild(oh); }
}
function playheadEl(){ return document.getElementById('playhead'); }
function portionBand(){ return document.getElementById('portionBand'); }
function inHandle(){ return document.getElementById('inHandle'); }
function outHandle(){ return document.getElementById('outHandle'); }
function findThumbEl(idx){ return thumbEls.get(idx) || null; }
function updateHUD(){ const total = frames || 0, cur = currentIdx+1; hud.textContent = `t=${player.currentTime.toFixed(2)}s • #${cur}/${total} • ${fps.toFixed(2)}fps`; }
function updateSelectedThumb(){
tlBox.querySelectorAll('.thumb img.sel, .thumb img.sel-strong').forEach(img=>{ img.classList.remove('sel','sel-strong'); });
const el = findThumbEl(currentIdx); if(!el) return; const img = el.querySelector('img');
img.classList.add('sel'); if(isPaused) img.classList.add('sel-strong');
}
function rawCenterThumb(el){
tlBox.scrollLeft = Math.max(0, el.offsetLeft + el.clientWidth/2 - tlBox.clientWidth/2);
}
async function ensureThumbVisibleCentered(idx){
// Attendre que l’élément + image soient prêts avant de centrer
for(let k=0; k<40; k++){
const el = findThumbEl(idx);
if(el){
const img = el.querySelector('img');
if(!img.complete || img.naturalWidth === 0){
await new Promise(r=>setTimeout(r, 25));
}else{
rawCenterThumb(el);
updatePlayhead();
return true;
}
}else{
await new Promise(r=>setTimeout(r, 25));
}
}
return false;
}
function centerSelectedThumb(){ ensureThumbVisibleCentered(currentIdx); }
function updatePlayhead(){
ensureOverlays();
const el = findThumbEl(currentIdx);
const ph = playheadEl();
if(!el){ ph.style.display='none'; return; }
ph.style.display='block'; ph.style.left = (el.offsetLeft + el.clientWidth/2) + 'px';
}
function updatePortionOverlays(){
ensureOverlays();
const pb = portionBand(), ih = inHandle(), oh = outHandle();
if(portionStart==null || portionEnd==null){ pb.style.display='none'; ih.style.display='none'; oh.style.display='none'; return; }
const a = findThumbEl(portionStart), b = findThumbEl(portionEnd-1);
if(!a || !b){ pb.style.display='none'; ih.style.display='none'; oh.style.display='none'; return; }
const left = a.offsetLeft, right = b.offsetLeft + b.clientWidth;
pb.style.display='block'; pb.style.left = left+'px'; pb.style.width = Math.max(0, right-left)+'px';
ih.style.display='block'; ih.style.left = (left - ih.clientWidth/2) + 'px';
oh.style.display='block'; oh.style.left = (right - oh.clientWidth/2) + 'px';
}
function nearestFrameIdxFromClientX(clientX){
const rect = tlBox.getBoundingClientRect();
const xIn = clientX - rect.left + tlBox.scrollLeft;
let bestIdx = currentIdx, bestDist = Infinity;
for(const [idx, el] of thumbEls.entries()){
const mid = el.offsetLeft + el.clientWidth/2;
const d = Math.abs(mid - xIn);
if(d < bestDist){ bestDist = d; bestIdx = idx; }
}
return bestIdx;
}
function loadPending(){ try{ return JSON.parse(localStorage.getItem(PENDING_KEY) || '[]'); }catch{ return []; } }
function savePendingList(lst){ localStorage.setItem(PENDING_KEY, JSON.stringify(lst)); }
function addPending(payload){ const lst = loadPending(); lst.push(payload); savePendingList(lst); }
async function flushPending(){
const lst = loadPending(); if(!lst.length) return;
const kept = [];
for(const p of lst){
try{ const r = await fetch('/mask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(p)}); if(!r.ok) kept.push(p); }
catch{ kept.push(p); }
}
savePendingList(kept);
if(kept.length===0) showToast('Masques hors-ligne synchronisés ✅');
}
// Layout
function syncTimelineWidth(){ const w = playerWrap.clientWidth; tlBox.style.width = w + 'px'; }
function fitCanvas(){
const r=player.getBoundingClientRect();
const ctrlH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--controlsH'));
canvas.width=Math.round(r.width);
canvas.height=Math.round(r.height - ctrlH);
canvas.style.width=r.width+'px';
canvas.style.height=(r.height - ctrlH)+'px';
syncTimelineWidth();
}
function timeToIdx(t){ return Math.max(0, Math.min(frames-1, Math.round((fps||30) * t))); }
function idxToSec(i){ return (fps||30)>0 ? (i / fps) : 0; }
function setMode(m){
mode=m;
if(m==='edit'){
player.pause();
player.controls = false;
playerWrap.classList.add('edit-mode');
modeLabel.textContent='Édition';
btnEdit.style.display='none'; btnBack.style.display='inline-block';
btnSave.style.display='inline-block'; btnClear.style.display='inline-block';
canvas.style.pointerEvents='auto';
rect = rectMap.get(currentIdx) || null; draw();
}else{
player.controls = true;
playerWrap.classList.remove('edit-mode');
modeLabel.textContent='Lecture';
btnEdit.style.display='inline-block'; btnBack.style.display='none';
btnSave.style.display='none'; btnClear.style.display='none';
canvas.style.pointerEvents='none';
rect=null; draw();
}
}
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
if(rect){
const x=Math.min(rect.x1,rect.x2), y=Math.min(rect.y1,rect.y2);
const w=Math.abs(rect.x2-rect.x1), h=Math.abs(rect.y2-rect.y1);
ctx.strokeStyle=rect.color||color; ctx.lineWidth=2; ctx.strokeRect(x,y,w,h);
ctx.fillStyle=(rect.color||color)+'28'; ctx.fillRect(x,y,w,h);
}
}
canvas.addEventListener('mousedown',(e)=>{
if(mode!=='edit' || !vidName) return;
dragging=true; const r=canvas.getBoundingClientRect();
sx=e.clientX-r.left; sy=e.clientY-r.top;
rect={x1:sx,y1:sy,x2:sx,y2:sy,color:color}; draw();
});
canvas.addEventListener('mousemove',(e)=>{
if(!dragging) return;
const r=canvas.getBoundingClientRect();
rect.x2=e.clientX-r.left; rect.y2=e.clientY-r.top; draw();
});
['mouseup','mouseleave'].forEach(ev=>canvas.addEventListener(ev,()=>{ dragging=false; }));
btnClear.onclick=()=>{ rect=null; rectMap.delete(currentIdx); draw(); };
btnEdit.onclick =()=> setMode('edit');
btnBack.onclick =()=> setMode('view');
// Palette
palette.querySelectorAll('.swatch').forEach(el=>{
if(el.dataset.c===color) el.classList.add('sel');
el.onclick=()=>{
palette.querySelectorAll('.swatch').forEach(s=>s.classList.remove('sel'));
el.classList.add('sel'); color=el.dataset.c;
if(rect){ rect.color=color; draw(); }
};
});
// === Timeline ===
async function loadTimelineUrls(){
timelineUrls = [];
const stem = vidStem, b = bustToken;
for(let idx=0; idx<frames; idx++){
timelineUrls[idx] = `/thumbs/f_${stem}_${idx}.jpg?b=${b}`;
}
tlProgressFill.style.width='0%';
}
async function renderTimeline(centerIdx){
if(!vidName) return;
loadingInd.style.display='block';
if(timelineUrls.length===0) await loadTimelineUrls();
tlBox.innerHTML = ''; thumbEls = new Map(); ensureOverlays();
if(maskedOnlyMode){
const idxs = Array.from(maskedSet).sort((a,b)=>a-b);
for(const i of idxs){ addThumb(i,'append'); }
setTimeout(async ()=>{ syncTimelineWidth(); updateSelectedThumb(); await ensureThumbVisibleCentered(currentIdx); loadingInd.style.display='none'; updatePlayhead(); updatePortionOverlays(); },0);
return;
}
if(portionStart!=null && portionEnd!=null){
const s = Math.max(0, portionStart), e = Math.min(frames, portionEnd);
for(let i=s;i<e;i++){ addThumb(i,'append'); }
setTimeout(async ()=>{ syncTimelineWidth(); updateSelectedThumb(); await ensureThumbVisibleCentered(currentIdx); loadingInd.style.display='none'; updatePlayhead(); updatePortionOverlays(); },0);
return;
}
await loadWindow(centerIdx ?? currentIdx);
loadingInd.style.display='none';
}
async function loadWindow(centerIdx){
tlBox.innerHTML=''; thumbEls = new Map(); ensureOverlays();
const rngStart = (viewRangeStart ?? 0);
const rngEnd = (viewRangeEnd ?? frames);
const mid = Math.max(rngStart, Math.min(centerIdx, max(rngStart, rngEnd-1)));
const start = Math.max(rngStart, min(mid - Math.floor(chunkSize/2), max(rngStart, rngEnd - chunkSize)));
const end = Math.min(rngEnd, start + chunkSize);
for(let i=start;i<end;i++){ addThumb(i,'append'); }
timelineStart = start; timelineEnd = end;
setTimeout(async ()=>{
syncTimelineWidth();
updateSelectedThumb();
await ensureThumbVisibleCentered(currentIdx);
updatePortionOverlays();
},0);
}
function addThumb(idx, place='append'){
if(thumbEls.has(idx)) return;
const wrap=document.createElement('div'); wrap.className='thumb'; wrap.dataset.idx=idx;
if(maskedSet.has(idx)) wrap.classList.add('hasmask');
const img=new Image(); img.title='frame '+(idx+1);
img.src=timelineUrls[idx];
img.onerror = () => {
const fallback = `/frame_idx?vid=${encodeURIComponent(vidName)}&idx=${idx}`;
img.onerror = null;
img.src = fallback;
img.onload = () => {
const nu = `/thumbs/f_${vidStem}_${idx}.jpg?b=${Date.now()}`;
timelineUrls[idx] = nu;
img.src = nu;
img.onload = null;
};
};
if(idx===currentIdx){ img.classList.add('sel'); if(isPaused) img.classList.add('sel-strong'); }
img.onclick=async ()=>{
currentIdx=idx; player.currentTime=idxToSec(currentIdx);
if(mode==='edit'){ rect = rectMap.get(currentIdx)||null; draw(); }
updateSelectedThumb(); await ensureThumbVisibleCentered(currentIdx); updatePlayhead();
};
wrap.appendChild(img);
const label=document.createElement('span'); label.className='thumb-label'; label.textContent = `#${idx+1}`;
wrap.appendChild(label);
if(place==='append'){ tlBox.appendChild(wrap); }
else if(place='prepend'){ tlBox.insertBefore(wrap, tlBox.firstChild); }
else{ tlBox.appendChild(wrap); }
thumbEls.set(idx, wrap);
}
// Scroll chunk (mode normal uniquement)
tlBox.addEventListener('scroll', ()=>{
if (maskedOnlyMode || (portionStart!=null && portionEnd!=null)){
updatePlayhead(); updatePortionOverlays();
return;
}
const scrollLeft = tlBox.scrollLeft, scrollWidth = tlBox.scrollWidth, clientWidth = tlBox.clientWidth;
if (scrollWidth - scrollLeft - clientWidth < scrollThreshold && timelineEnd < viewRangeEnd){
const newEnd = Math.min(viewRangeEnd, timelineEnd + chunkSize);
for(let i=timelineEnd;i<newEnd;i++){ addThumb(i,'append'); }
timelineEnd = newEnd;
}
if (scrollLeft < scrollThreshold && timelineStart > viewRangeStart){
const newStart = Math.max(viewRangeStart, timelineStart - chunkSize);
for(let i=newStart;i<timelineStart;i++){ addThumb(i,'prepend'); }
tlBox.scrollLeft += (timelineStart - newStart) * (110 + 8);
timelineStart = newStart;
}
updatePlayhead(); updatePortionOverlays();
});
// Isoler & Boucle
isolerBoucle.onclick = async ()=>{
const start = parseInt(goFrame.value || '1',10) - 1;
const end = parseInt(endPortion.value || '',10);
if(!endPortion.value || end <= start || end > frames){ alert('Portion invalide (fin > début)'); return; }
if (end - start > 1200 && !confirm('Portion très large, cela peut être lent. Continuer ?')) return;
portionStart = start; portionEnd = end;
viewRangeStart = start; viewRangeEnd = end;
player.pause(); isPaused = true;
currentIdx = start; player.currentTime = idxToSec(start);
await renderTimeline(currentIdx);
resetFull.style.display = 'inline-block';
startLoop(); updatePortionOverlays();
};
function startLoop(){
if(loopInterval) clearInterval(loopInterval);
if(portionEnd != null){
loopInterval = setInterval(()=>{ if(player.currentTime >= idxToSec(portionEnd)) player.currentTime = idxToSec(portionStart); }, 100);
}
}
resetFull.onclick = async ()=>{
portionStart = null; portionEnd = null;
viewRangeStart = 0; viewRangeEnd = frames;
goFrame.value = 1; endPortion.value = '';
player.pause(); isPaused = true;
await renderTimeline(currentIdx);
resetFull.style.display='none';
clearInterval(loopInterval); updatePortionOverlays();
};
// Drag IN/OUT
function attachHandleDrag(handle, which){
let draggingH=false;
function onMove(e){
if(!draggingH) return;
const idx = nearestFrameIdxFromClientX(e.clientX);
if(which==='in'){ portionStart = Math.min(idx, portionEnd ?? idx+1); goFrame.value = (portionStart+1); }
else { portionEnd = Math.max(idx+1, (portionStart ?? idx)); endPortion.value = portionEnd; }
viewRangeStart = (portionStart ?? 0); viewRangeEnd = (portionEnd ?? frames);
updatePortionOverlays();
}
handle.addEventListener('mousedown', (e)=>{ draggingH=true; e.preventDefault(); });
window.addEventListener('mousemove', onMove);
window.addEventListener('mouseup', ()=>{ draggingH=false; });
}
ensureOverlays(); attachHandleDrag(document.getElementById('inHandle'), 'in'); attachHandleDrag(document.getElementById('outHandle'), 'out');
// Progress popup
async function showProgress(vidStem){
popup.style.display = 'block';
const interval = setInterval(async () => {
const r = await fetch('/progress/' + vidStem);
const d = await r.json();
tlProgressFill.style.width = d.percent + '%';
popupProgressFill.style.width = d.percent + '%';
popupLogs.innerHTML = d.logs.map(x=>String(x)).join('<br>');
if(d.done){
clearInterval(interval);
popup.style.display = 'none';
await renderTimeline(currentIdx);
}
}, 800);
}
// Meta & boot
async function loadVideoAndMeta() {
if(!vidName){ statusEl.textContent='Aucune vidéo sélectionnée.'; return; }
vidStem = fileStem(vidName); bustToken = Date.now();
const bust = Date.now();
srcEl.src = '/data/'+encodeURIComponent(vidName)+'?t='+bust;
player.setAttribute('poster', '/poster/'+encodeURIComponent(vidName)+'?t='+bust);
player.load();
fitCanvas();
statusEl.textContent = 'Chargement vidéo…';
try{
const r=await fetch('/meta/'+encodeURIComponent(vidName));
if(r.ok){
const m=await r.json();
fps=m.fps||30; frames=m.frames||0;
statusEl.textContent = `OK (${frames} frames @ ${fps.toFixed(2)} fps)`;
viewRangeStart = 0; viewRangeEnd = frames;
await loadTimelineUrls();
await loadMasks();
currentIdx = 0; player.currentTime = 0;
await renderTimeline(0);
showProgress(vidStem);
}else{
statusEl.textContent = 'Erreur meta';
}
}catch(err){
statusEl.textContent = 'Erreur réseau meta';
}
}
player.addEventListener('loadedmetadata', async ()=>{
fitCanvas();
if(!frames || frames<=0){
try{ const r=await fetch('/meta/'+encodeURIComponent(vidName)); if(r.ok){ const m=await r.json(); fps=m.fps||30; frames=m.frames||0; } }catch{}
}
currentIdx=0; goFrame.value=1; rectMap.clear(); rect=null; draw();
});
window.addEventListener('resize', ()=>{ fitCanvas(); });
player.addEventListener('pause', ()=>{ isPaused = true; updateSelectedThumb(); centerSelectedThumb(); });
player.addEventListener('play', ()=>{ isPaused = false; updateSelectedThumb(); });
player.addEventListener('timeupdate', ()=>{
posInfo.textContent='t='+player.currentTime.toFixed(2)+'s';
currentIdx=timeToIdx(player.currentTime);
if(mode==='edit'){ rect = rectMap.get(currentIdx) || null; draw(); }
updateHUD(); updateSelectedThumb(); updatePlayhead();
if(followMode && !isPaused){
const now = Date.now();
if(now - lastCenterMs > CENTER_THROTTLE_MS){ lastCenterMs = now; centerSelectedThumb(); }
}
});
goFrame.addEventListener('change', async ()=>{
if(!vidName) return;
const val=Math.max(1, parseInt(goFrame.value||'1',10));
player.pause(); isPaused = true;
currentIdx=val-1; player.currentTime=idxToSec(currentIdx);
if(mode==='edit'){ rect = rectMap.get(currentIdx)||null; draw(); }
await renderTimeline(currentIdx);
await ensureThumbVisibleCentered(currentIdx);
});
// Follow / Filter / Zoom / Goto
btnFollow.onclick = ()=>{ followMode = !followMode; btnFollow.classList.toggle('toggled', followMode); if(followMode) centerSelectedThumb(); };
btnFilterMasked.onclick = async ()=>{
maskedOnlyMode = !maskedOnlyMode;
btnFilterMasked.classList.toggle('toggled', maskedOnlyMode);
tlBox.classList.toggle('filter-masked', maskedOnlyMode);
await renderTimeline(currentIdx);
await ensureThumbVisibleCentered(currentIdx);
};
zoomSlider.addEventListener('input', ()=>{ tlBox.style.setProperty('--thumbH', zoomSlider.value + 'px'); });
async function gotoFrameNum(){
const v = parseInt(gotoInput.value||'',10);
if(!Number.isFinite(v) || v<1 || v>frames) return;
player.pause(); isPaused = true;
currentIdx = v-1; player.currentTime = idxToSec(currentIdx);
goFrame.value = v;
await renderTimeline(currentIdx);
await ensureThumbVisibleCentered(currentIdx);
}
gotoBtn.onclick = ()=>{ gotoFrameNum(); };
gotoInput.addEventListener('keydown',(e)=>{ if(e.key==='Enter'){ e.preventDefault(); gotoFrameNum(); } });
// Drag & drop upload
const uploadZone = document.getElementById('uploadForm');
uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.style.borderColor = '#2563eb'; });
uploadZone.addEventListener('dragleave', () => { uploadZone.style.borderColor = 'transparent'; });
uploadZone.addEventListener('drop', (e) => {
e.preventDefault(); uploadZone.style.borderColor = 'transparent';
const file = e.dataTransfer.files[0];
if(file && file.type.startsWith('video/')){
const fd = new FormData(); fd.append('file', file);
fetch('/upload?redirect=1', {method: 'POST', body: fd}).then(() => location.reload());
}
});
// Export placeholder
document.getElementById('exportBtn').onclick = () => { console.log('Export en cours... (IA à venir)'); alert('Fonctionnalité export IA en développement !'); };
// Fichiers & masques
async function loadFiles(){
const r=await fetch('/files'); const d=await r.json();
if(!d.items || !d.items.length){ fileList.innerHTML='<li>(aucune)</li>'; return; }
fileList.innerHTML='';
d.items.forEach(name=>{
const li=document.createElement('li');
const delBtn = document.createElement('span'); delBtn.className='delete-btn'; delBtn.textContent='❌'; delBtn.title='Supprimer cette vidéo';
delBtn.onclick=async()=>{
if(!confirm(`Supprimer "${name}" ?`)) return;
await fetch('/delete/'+encodeURIComponent(name),{method:'DELETE'});
loadFiles(); if(vidName===name){ vidName=''; loadVideoAndMeta(); }
};
const a=document.createElement('a'); a.textContent=name; a.href='/ui?v='+encodeURIComponent(name); a.title='Ouvrir cette vidéo';
li.appendChild(delBtn); li.appendChild(a); fileList.appendChild(li);
});
}
async function loadMasks(){
loadingInd.style.display='block';
const box=document.getElementById('maskList');
const r=await fetch('/mask/'+encodeURIComponent(vidName));
const d=await r.json();
masks=d.masks||[];
maskedSet = new Set(masks.map(m=>parseInt(m.frame_idx||0,10)));
rectMap.clear();
masks.forEach(m=>{
if(m.shape==='rect'){
const [x1,y1,x2,y2] = m.points;
const normW = canvas.clientWidth, normH = canvas.clientHeight;
rectMap.set(m.frame_idx, {x1:x1*normW, y1:y1*normH, x2:x2*normW, y2:y2*normH, color:m.color});
}
});
maskedCount.textContent = `(${maskedSet.size} ⭐)`;
if(!masks.length){ box.textContent='—'; loadingInd.style.display='none'; return; }
box.innerHTML='';
const ul=document.createElement('ul'); ul.className='clean';
masks.forEach(m=>{
const li=document.createElement('li');
const fr=(parseInt(m.frame_idx||0,10)+1);
const t=(m.time_s||0).toFixed(2);
const col=m.color||'#10b981';
const label=m.note||(`frame ${fr}`);
li.innerHTML = `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${col};margin-right:6px;vertical-align:middle"></span> <strong>${label.replace(/</g,'&lt;').replace(/>/g,'&gt;')}</strong> — #${fr} · t=${t}s`;
const renameBtn=document.createElement('span'); renameBtn.className='rename-btn'; renameBtn.textContent='✏️'; renameBtn.title='Renommer le masque';
renameBtn.onclick=async()=>{
const nv=prompt('Nouveau nom du masque :', label);
if(nv===null) return;
const rr=await fetch('/mask/rename',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({vid:vidName,id:m.id,note:nv})});
if(rr.ok){ await loadMasks(); await renderTimeline(currentIdx); draw(); showToast('Masque renommé ✅'); } else {
const txt = await rr.text(); alert('Échec renommage: ' + rr.status + ' ' + txt);
}
};
const delMaskBtn=document.createElement('span'); delMaskBtn.className='delete-btn'; delMaskBtn.textContent='❌'; delMaskBtn.title='Supprimer ce masque';
delMaskBtn.onclick=async()=>{
if(!confirm(`Supprimer masque "${label}" ?`)) return;
const rr=await fetch('/mask/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({vid:vidName,id:m.id})});
if(rr.ok){ await loadMasks(); await renderTimeline(currentIdx); draw(); showToast('Masque supprimé ✅'); } else {
const txt = await rr.text(); alert('Échec suppression: ' + rr.status + ' ' + txt);
}
};
li.appendChild(renameBtn); li.appendChild(delMaskBtn); ul.appendChild(li);
});
box.appendChild(ul);
loadingInd.style.display='none';
}
// Save mask (+ cache)
btnSave.onclick = async ()=>{
if(!rect || !vidName){ alert('Aucune sélection.'); return; }
const defaultName = `frame ${currentIdx+1}`;
const note = (prompt('Nom du masque (optionnel) :', defaultName) || defaultName).trim();
const normW = canvas.clientWidth, normH = canvas.clientHeight;
const x=Math.min(rect.x1,rect.x2)/normW;
const y=Math.min(rect.y1,rect.y2)/normH;
const w=Math.abs(rect.x2-rect.x1)/normW;
const h=Math.abs(rect.y2-rect.y1)/normH;
const payload={vid:vidName,time_s:player.currentTime,frame_idx:currentIdx,shape:'rect',points:[x,y,x+w,y+h],color:rect.color||color,note:note};
addPending(payload);
try{
const r=await fetch('/mask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
if(r.ok){
const lst = loadPending().filter(x => !(x.vid===payload.vid && x.frame_idx===payload.frame_idx && x.time_s===payload.time_s));
savePendingList(lst);
rectMap.set(currentIdx,{...rect});
await loadMasks(); await renderTimeline(currentIdx);
showToast('Masque enregistré ✅');
} else {
const txt = await r.text();
alert('Échec enregistrement masque: ' + r.status + ' ' + txt);
}
}catch(e){
alert('Erreur réseau lors de l’enregistrement du masque.');
}
};
// Boot
async function boot(){
const lst = JSON.parse(localStorage.getItem('ve_pending_masks_v1') || '[]'); if(lst.length){ /* flush pending si besoin */ }
await loadFiles();
if(serverVid){ vidName=serverVid; await loadVideoAndMeta(); }
else{ const qs=new URLSearchParams(location.search); const v=qs.get('v')||''; if(v){ vidName=v; await loadVideoAndMeta(); } }
}
boot();
// Hide controls in edit-mode
const style = document.createElement('style');
style.textContent = `.player-wrap.edit-mode video::-webkit-media-controls { display: none !important; } .player-wrap.edit-mode video::before { content: none !important; }`;
document.head.appendChild(style);
</script>
</html>
"""
@app.get("/ui", response_class=HTMLResponse, tags=["meta"])
def ui(v: Optional[str] = "", msg: Optional[str] = ""):
vid = v or ""
try:
msg = urllib.parse.unquote(msg or "")
except Exception:
pass
html = HTML_TEMPLATE.replace("__VID__", urllib.parse.quote(vid)).replace("__MSG__", msg)
return HTMLResponse(content=html)