Probe duration via demux fallback (webm N/A); run one flow at a time, queue the rest
This commit is contained in:
+34
-29
@@ -29,8 +29,9 @@ EDGE = Path(os.path.expandvars(r"%ProgramFiles(x86)%\Microsoft\Edge\Application\
|
||||
PRINT_CSS = "@media print{body{max-width:none;padding:0}img,tr{break-inside:avoid}h2,h3{break-after:avoid}}"
|
||||
LOCK = threading.Lock()
|
||||
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"]
|
||||
QUEUE = [] # names waiting for the batch re-run, oldest first
|
||||
BATCH = None # batch thread
|
||||
QUEUE = [] # (name, start_from, speakers) waiting for the single runner, oldest first
|
||||
BATCH = None # runner thread, None when idle
|
||||
QLOCK = threading.Lock()
|
||||
|
||||
|
||||
def make_pdf(name):
|
||||
@@ -63,30 +64,35 @@ def now(): return time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def launch(name, start_from, speakers=5):
|
||||
"""Spawn flow.py. Returns False if a job for this name is still running."""
|
||||
j = JOBS.get(name)
|
||||
if j and j.poll() is None: return False
|
||||
d = db.out_dir(name)
|
||||
JOBS[name] = subprocess.Popen(["uv", "run", "--script", "flow.py", name, "--from", start_from, "--speakers", str(speakers)],
|
||||
cwd=HERE, env=ENV, stdout=open(d / "flow.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
|
||||
"""Queue a flow run. One flow at a time (one GPU): the rest wait. False if `name` is already running or queued."""
|
||||
global BATCH
|
||||
with QLOCK:
|
||||
j = JOBS.get(name)
|
||||
if (j and j.poll() is None) or any(q[0] == name for q in QUEUE): return False
|
||||
QUEUE.append((name, start_from, speakers))
|
||||
db.set_status(name, "queued")
|
||||
if BATCH is None:
|
||||
BATCH = threading.Thread(target=pump, daemon=True); BATCH.start()
|
||||
return True
|
||||
|
||||
|
||||
def batch(start_from):
|
||||
"""Re-run every queued recording one at a time (one GPU), oldest first so memory links point backwards."""
|
||||
while QUEUE:
|
||||
n = QUEUE.pop(0)
|
||||
j = JOBS.get(n)
|
||||
if j: j.wait()
|
||||
launch(n, start_from); JOBS[n].wait()
|
||||
def pump():
|
||||
"""Drain QUEUE serially, oldest first so memory links point backwards."""
|
||||
global BATCH
|
||||
while True:
|
||||
with QLOCK:
|
||||
if not QUEUE: BATCH = None; return
|
||||
name, start_from, speakers = QUEUE.pop(0)
|
||||
d = db.out_dir(name)
|
||||
JOBS[name] = subprocess.Popen(["uv", "run", "--script", "flow.py", name, "--from", start_from, "--speakers", str(speakers)],
|
||||
cwd=HERE, env=ENV, stdout=open(d / "flow.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
|
||||
JOBS[name].wait()
|
||||
|
||||
|
||||
def run_all(start_from):
|
||||
global BATCH
|
||||
if BATCH and BATCH.is_alive(): return False
|
||||
QUEUE[:] = [r[0] for r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name")]
|
||||
for n in QUEUE: db.set_status(n, "queued")
|
||||
BATCH = threading.Thread(target=batch, args=(start_from,), daemon=True); BATCH.start()
|
||||
if BATCH is not None: return False
|
||||
for r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name"):
|
||||
launch(r[0], start_from)
|
||||
return True
|
||||
|
||||
|
||||
@@ -125,7 +131,7 @@ def title(n):
|
||||
return TITLES[n][1]
|
||||
|
||||
|
||||
def busy(): return bool(BATCH and BATCH.is_alive()) or any(p.poll() is None for p in JOBS.values())
|
||||
def busy(): return bool(QUEUE) or any(p.poll() is None for p in JOBS.values())
|
||||
|
||||
|
||||
def flow_pids(name=None):
|
||||
@@ -143,7 +149,7 @@ def prefect_state(run_id, typ, msg):
|
||||
|
||||
def cancel(name, reason="cancelled from web UI"):
|
||||
"""Kill the flow's process tree (uv -> python -> llama-server) and close its Prefect run."""
|
||||
if name in QUEUE: QUEUE.remove(name)
|
||||
with QLOCK: QUEUE[:] = [q for q in QUEUE if q[0] != name]
|
||||
j = JOBS.get(name)
|
||||
pids = {j.pid} if j and j.poll() is None else set()
|
||||
for pid in pids | set(flow_pids(name)): subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True)
|
||||
@@ -247,7 +253,7 @@ def status():
|
||||
if d["running"] and not d["prog"]: d["boot"] = last_log(n)
|
||||
w = db.media(n)[0]; d["mb"] = round(w.stat().st_size / 1e6, 1) if w else 0
|
||||
rs.append(d)
|
||||
return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE) + bool(BATCH and BATCH.is_alive()),
|
||||
return {"now": t, "recs": rs, "busy": busy(), "queue": len(QUEUE),
|
||||
"llm": [llama.current(True), llama.current(False)], "llms": [[k, llama.MODELS[k][0]] for k in llama.available()]}
|
||||
|
||||
|
||||
@@ -493,13 +499,13 @@ class H(BaseHTTPRequestHandler):
|
||||
elif u.path == "/delete":
|
||||
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return self._send(b"not found", 404)
|
||||
j = JOBS.get(name)
|
||||
if (j and j.poll() is None) or name in R or name in QUEUE: return self._send("in elaborazione o in registrazione: ferma prima".encode(), 409)
|
||||
if (j and j.poll() is None) or name in R or any(x[0] == name for x in QUEUE): return self._send("in elaborazione o in registrazione: ferma prima".encode(), 409)
|
||||
db.delete_recording(name); JOBS.pop(name, None); self._send()
|
||||
elif u.path == "/cancel":
|
||||
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
|
||||
elif u.path == "/run":
|
||||
ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 5))
|
||||
self._send(b"" if ok else "già in esecuzione".encode(), 200 if ok else 409)
|
||||
self._send(b"" if ok else "già in coda o in esecuzione".encode(), 200 if ok else 409)
|
||||
elif u.path == "/run_all":
|
||||
f = q.get("from", "audio")
|
||||
if f not in STEPS: return self._send(b"bad step", 400)
|
||||
@@ -513,7 +519,7 @@ class H(BaseHTTPRequestHandler):
|
||||
try: m = json.loads(data)
|
||||
except ValueError: return self._send(b"bad json", 400)
|
||||
for label, person in m.items(): db.set_speaker_map(name, label, str(person).strip(), "manual")
|
||||
if launch(name, "render"): self._send(b"salvato, render avviato")
|
||||
if launch(name, "render"): self._send("salvato, render in coda".encode())
|
||||
else: self._send("salvato, render dopo il job in corso".encode(), 202)
|
||||
else: self._send(b"not found", 404)
|
||||
def upload(self, q):
|
||||
@@ -526,9 +532,8 @@ class H(BaseHTTPRequestHandler):
|
||||
while left and (b := self.rfile.read(min(1 << 20, left))): f.write(b); left -= len(b)
|
||||
if left: tmp.unlink(missing_ok=True); return self._send("upload interrotto".encode(), 400)
|
||||
tmp.replace(dst)
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(dst)], capture_output=True, text=True)
|
||||
try: dur = float(r.stdout.strip())
|
||||
except ValueError: dst.unlink(); return self._send("file non leggibile da ffprobe (né audio né video)".encode(), 400)
|
||||
try: dur = db.duration(dst)
|
||||
except ValueError as e: dst.unlink(); return self._send(f"file non leggibile: {e}".encode(), 400)
|
||||
(db.out_dir(name) / "upload.json").write_text(json.dumps({"filename": fn}, ensure_ascii=False), encoding="utf-8")
|
||||
db.upsert_recording(name, source="upload", started_at=now(), status="queued", bytes=n, duration_s=dur)
|
||||
launch(name, "audio")
|
||||
|
||||
Reference in New Issue
Block a user