Probe duration via demux fallback (webm N/A); run one flow at a time, queue the rest
This commit is contained in:
@@ -57,7 +57,7 @@ Base URL `http://127.0.0.1:18765`.
|
|||||||
| POST | `/chunk` | `name`, body = webm chunk (append) |
|
| POST | `/chunk` | `name`, body = webm chunk (append) |
|
||||||
| POST | `/events` | `name`, body = JSON array of Teams call events |
|
| POST | `/events` | `name`, body = JSON array of Teams call events |
|
||||||
| POST | `/stop` | `name` → finalize recording, start pipeline |
|
| POST | `/stop` | `name` → finalize recording, start pipeline |
|
||||||
| POST | `/run` | `name`, `from`, `speakers` → rerun pipeline |
|
| POST | `/run` | `name`, `from`, `speakers` → accoda la pipeline (una alla volta; 409 se già in coda/esecuzione) |
|
||||||
| POST | `/run_all` | `from` → rerun every recording one at a time, oldest first (API only) |
|
| POST | `/run_all` | `from` → rerun every recording one at a time, oldest first (API only) |
|
||||||
| POST | `/speaker_map` | `name`, body = `{"Speaker 1": "Mario Rossi"}` → re-render |
|
| POST | `/speaker_map` | `name`, body = `{"Speaker 1": "Mario Rossi"}` → re-render |
|
||||||
|
|
||||||
|
|||||||
+1
-3
@@ -11,7 +11,5 @@ def run(name):
|
|||||||
"-af", "highpass=f=80,loudnorm=I=-18:TP=-2:LRA=11", "-c:a", "libopus", "-b:a", "24k", str(dst)],
|
"-af", "highpass=f=80,loudnorm=I=-18:TP=-2:LRA=11", "-c:a", "libopus", "-b:a", "24k", str(dst)],
|
||||||
capture_output=True, text=True)
|
capture_output=True, text=True)
|
||||||
if r.returncode: raise RuntimeError(r.stderr[-500:])
|
if r.returncode: raise RuntimeError(r.stderr[-500:])
|
||||||
d = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(dst)],
|
db.upsert_recording(name, duration_s=db.duration(dst))
|
||||||
capture_output=True, text=True, check=True).stdout.strip()
|
|
||||||
db.upsert_recording(name, duration_s=float(d))
|
|
||||||
return dst
|
return dst
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
|
"""SQLite index of meetings (out/meetings.db) + shared helpers."""
|
||||||
import json, re, sqlite3, time
|
import json, re, sqlite3, subprocess, time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
HERE = Path(__file__).parent
|
HERE = Path(__file__).parent
|
||||||
@@ -177,6 +177,20 @@ def media(name):
|
|||||||
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(".webm", ".mp4", ".mkv", ".mov")
|
return first(".webm", ".wav", ".mp4", ".mkv", ".mov", ".m4a", ".mp3"), first(".webm", ".mp4", ".mkv", ".mov")
|
||||||
|
|
||||||
|
|
||||||
|
def duration(path) -> float:
|
||||||
|
"""Seconds. MediaRecorder webm has no container duration (N/A): fall back to a copy-demux pass (~1 s/h)."""
|
||||||
|
p = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
try: return float(p.stdout.strip())
|
||||||
|
except ValueError: pass
|
||||||
|
r = subprocess.run(["ffmpeg", "-v", "error", "-stats", "-i", str(path), "-map", "0", "-c", "copy", "-f", "null", "-"],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
m = re.findall(r"time=(\d+):(\d\d):(\d\d(?:\.\d+)?)", r.stderr)
|
||||||
|
if not m: raise ValueError(((p.stderr or r.stderr).strip() or "nessuna durata")[-300:])
|
||||||
|
h, mi, s = m[-1]
|
||||||
|
return int(h) * 3600 + int(mi) * 60 + float(s)
|
||||||
|
|
||||||
|
|
||||||
def add_events(name, rows):
|
def add_events(name, rows):
|
||||||
connect().executemany("INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
|
connect().executemany("INSERT INTO call_events(name,t,kind,who_key,who,text) VALUES(?,?,?,?,?,?)",
|
||||||
[(name, *r) for r in rows])
|
[(name, *r) for r in rows])
|
||||||
|
|||||||
+33
-28
@@ -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}}"
|
PRINT_CSS = "@media print{body{max-width:none;padding:0}img,tr{break-inside:avoid}h2,h3{break-after:avoid}}"
|
||||||
LOCK = threading.Lock()
|
LOCK = threading.Lock()
|
||||||
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"]
|
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"]
|
||||||
QUEUE = [] # names waiting for the batch re-run, oldest first
|
QUEUE = [] # (name, start_from, speakers) waiting for the single runner, oldest first
|
||||||
BATCH = None # batch thread
|
BATCH = None # runner thread, None when idle
|
||||||
|
QLOCK = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
def make_pdf(name):
|
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):
|
def launch(name, start_from, speakers=5):
|
||||||
"""Spawn flow.py. Returns False if a job for this name is still running."""
|
"""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)
|
j = JOBS.get(name)
|
||||||
if j and j.poll() is None: return False
|
if (j and j.poll() is None) or any(q[0] == name for q in QUEUE): return False
|
||||||
d = db.out_dir(name)
|
QUEUE.append((name, start_from, speakers))
|
||||||
JOBS[name] = subprocess.Popen(["uv", "run", "--script", "flow.py", name, "--from", start_from, "--speakers", str(speakers)],
|
db.set_status(name, "queued")
|
||||||
cwd=HERE, env=ENV, stdout=open(d / "flow.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
|
if BATCH is None:
|
||||||
|
BATCH = threading.Thread(target=pump, daemon=True); BATCH.start()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def batch(start_from):
|
def pump():
|
||||||
"""Re-run every queued recording one at a time (one GPU), oldest first so memory links point backwards."""
|
"""Drain QUEUE serially, oldest first so memory links point backwards."""
|
||||||
while QUEUE:
|
global BATCH
|
||||||
n = QUEUE.pop(0)
|
while True:
|
||||||
j = JOBS.get(n)
|
with QLOCK:
|
||||||
if j: j.wait()
|
if not QUEUE: BATCH = None; return
|
||||||
launch(n, start_from); JOBS[n].wait()
|
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):
|
def run_all(start_from):
|
||||||
global BATCH
|
if BATCH is not None: return False
|
||||||
if BATCH and BATCH.is_alive(): return False
|
for r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name"):
|
||||||
QUEUE[:] = [r[0] for r in db.connect().execute("SELECT name FROM recordings WHERE status!='recording' ORDER BY name")]
|
launch(r[0], start_from)
|
||||||
for n in QUEUE: db.set_status(n, "queued")
|
|
||||||
BATCH = threading.Thread(target=batch, args=(start_from,), daemon=True); BATCH.start()
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -125,7 +131,7 @@ def title(n):
|
|||||||
return TITLES[n][1]
|
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):
|
def flow_pids(name=None):
|
||||||
@@ -143,7 +149,7 @@ def prefect_state(run_id, typ, msg):
|
|||||||
|
|
||||||
def cancel(name, reason="cancelled from web UI"):
|
def cancel(name, reason="cancelled from web UI"):
|
||||||
"""Kill the flow's process tree (uv -> python -> llama-server) and close its Prefect run."""
|
"""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)
|
j = JOBS.get(name)
|
||||||
pids = {j.pid} if j and j.poll() is None else set()
|
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)
|
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)
|
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
|
w = db.media(n)[0]; d["mb"] = round(w.stat().st_size / 1e6, 1) if w else 0
|
||||||
rs.append(d)
|
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()]}
|
"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":
|
elif u.path == "/delete":
|
||||||
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return self._send(b"not found", 404)
|
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return self._send(b"not found", 404)
|
||||||
j = JOBS.get(name)
|
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()
|
db.delete_recording(name); JOBS.pop(name, None); self._send()
|
||||||
elif u.path == "/cancel":
|
elif u.path == "/cancel":
|
||||||
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
|
self._send(b"") if cancel(name) else self._send("nessun processo attivo: run chiusa".encode(), 200)
|
||||||
elif u.path == "/run":
|
elif u.path == "/run":
|
||||||
ok = launch(name, q.get("from", "audio"), int(q.get("speakers") or 5))
|
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":
|
elif u.path == "/run_all":
|
||||||
f = q.get("from", "audio")
|
f = q.get("from", "audio")
|
||||||
if f not in STEPS: return self._send(b"bad step", 400)
|
if f not in STEPS: return self._send(b"bad step", 400)
|
||||||
@@ -513,7 +519,7 @@ class H(BaseHTTPRequestHandler):
|
|||||||
try: m = json.loads(data)
|
try: m = json.loads(data)
|
||||||
except ValueError: return self._send(b"bad json", 400)
|
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")
|
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("salvato, render dopo il job in corso".encode(), 202)
|
||||||
else: self._send(b"not found", 404)
|
else: self._send(b"not found", 404)
|
||||||
def upload(self, q):
|
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)
|
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)
|
if left: tmp.unlink(missing_ok=True); return self._send("upload interrotto".encode(), 400)
|
||||||
tmp.replace(dst)
|
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 = db.duration(dst)
|
||||||
try: dur = float(r.stdout.strip())
|
except ValueError as e: dst.unlink(); return self._send(f"file non leggibile: {e}".encode(), 400)
|
||||||
except ValueError: dst.unlink(); return self._send("file non leggibile da ffprobe (né audio né video)".encode(), 400)
|
|
||||||
(db.out_dir(name) / "upload.json").write_text(json.dumps({"filename": fn}, ensure_ascii=False), encoding="utf-8")
|
(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)
|
db.upsert_recording(name, source="upload", started_at=now(), status="queued", bytes=n, duration_s=dur)
|
||||||
launch(name, "audio")
|
launch(name, "audio")
|
||||||
|
|||||||
Reference in New Issue
Block a user