One folder per meeting (out/<name>/source.*, transcript.txt, meta.json, logs/), out/_global; speaker transcript from DB; throwaway Edge profile; skip shots only when all images exist

This commit is contained in:
Stefano Zini
2026-11-03 16:02:05 +01:00
parent a479853372
commit f855768f1f
11 changed files with 85 additions and 76 deletions
+22 -5
View File
@@ -5,6 +5,8 @@ from pathlib import Path
HERE = Path(__file__).parent HERE = Path(__file__).parent
OUT = HERE / "out" OUT = HERE / "out"
DB = OUT / "meetings.db" DB = OUT / "meetings.db"
GLOBAL = OUT / "_global" # llm.txt, step_stats.json, transcribe_device.txt, prefect/embed/llama logs, edge profile
GLOBAL.mkdir(parents=True, exist_ok=True)
SCHEMA = """ SCHEMA = """
CREATE TABLE IF NOT EXISTS recordings( CREATE TABLE IF NOT EXISTS recordings(
@@ -95,11 +97,27 @@ def out_dir(name) -> Path:
return d return d
def logs(name) -> Path:
d = out_dir(name) / "logs"
d.mkdir(exist_ok=True)
return d
def meta(name) -> dict:
"""out/<name>/meta.json: {"title": manual title, "upload": original filename}; absent keys = not set."""
return _jload(OUT / name / "meta.json", {})
def set_meta(name, **kw):
m = {**meta(name), **kw}
_jsave(out_dir(name) / "meta.json", {k: v for k, v in m.items() if v})
# ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ---- # ---- progress + ETA (flow writes out/<name>/progress.json, server reads it) ----
ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses ORDER = ["audio", "transcribing", "diarizing", "identifying", "shots", "docs", "report", "memory"] # step statuses
FROM = {"audio": "audio", "transcribe": "transcribing", "diarize": "diarizing", "speakers": "identifying", FROM = {"audio": "audio", "transcribe": "transcribing", "diarize": "diarizing", "speakers": "identifying",
"shots": "shots", "docs": "docs", "report": "report", "memory": "memory", "render": "memory"} "shots": "shots", "docs": "docs", "report": "report", "memory": "memory", "render": "memory"}
STATS = OUT / "step_stats.json" STATS = GLOBAL / "step_stats.json"
# seconds of work per minute of audio, measured 2026-11-02 on RTX 500 Ada 4 GB + Core Ultra 7 155H (40-min call); # seconds of work per minute of audio, measured 2026-11-02 on RTX 500 Ada 4 GB + Core Ultra 7 155H (40-min call);
# replaced by a moving average of real runs as soon as one finishes (keys "<step>" or "<step>@<model>") # replaced by a moving average of real runs as soon as one finishes (keys "<step>" or "<step>@<model>")
SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@qwen4b": 23, "shots@qwen35b": 48, "shots": 30, SPM = {"audio": 1, "transcribing": 6, "diarizing": 9, "identifying": 1, "shots@qwen4b": 23, "shots@qwen35b": 48, "shots": 30,
@@ -122,13 +140,12 @@ def spm(key):
def delete_recording(name): def delete_recording(name):
"""Remove a meeting everywhere: DB rows in every table keyed by name, out/<name>/ and out/<name>.* files.""" """Remove a meeting everywhere: DB rows in every table keyed by name, and the folder out/<name>/."""
import shutil import shutil
c = connect() c = connect()
for t in ("recordings", "lines", "shots", "shot_text", "topics", "call_events", "speaker_map", "memory"): for t in ("recordings", "lines", "shots", "shot_text", "topics", "call_events", "speaker_map", "memory"):
c.execute(f"DELETE FROM {t} WHERE name=?", (name,)) c.execute(f"DELETE FROM {t} WHERE name=?", (name,))
shutil.rmtree(OUT / name, ignore_errors=True) shutil.rmtree(OUT / name, ignore_errors=True)
for p in OUT.glob(f"{name}.*"): p.unlink(missing_ok=True)
def progress(name): def progress(name):
@@ -169,11 +186,11 @@ def tick(name, done, total, note=""):
def media(name): def media(name):
"""(audio source, video source) in out/<name>/: source.<ext> (the CLI recorder may write source.wav + source.mp4); .wav/.m4a/.mp3 have no video."""
def first(*exts): def first(*exts):
for e in exts: for e in exts:
p = OUT / f"{name}{e}" p = OUT / name / f"source{e}"
if p.exists(): return p if p.exists(): return p
# audio source, video source; .mkv/.mov/.m4a/.mp3 come from GUI uploads (meet_*)
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")
+3 -5
View File
@@ -1,4 +1,4 @@
"""Label who speaks (sherpa-onnx, CPU): run(name) -> out/<name>.spk.txt, diar_segments.json, DB lines.""" """Label who speaks (sherpa-onnx, CPU): run(name) reads out/<name>/transcript.txt -> diar_segments.json + DB lines (speaker-labelled)."""
import json, re, subprocess, time import json, re, subprocess, time
from pathlib import Path from pathlib import Path
import numpy as np import numpy as np
@@ -41,7 +41,7 @@ def run(name, speakers=0, threshold=0.85):
print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({time.time() - t0:.0f} s)", flush=True) print(len(segs), "segments,", len({s[2] for s in segs}), f"speakers ({time.time() - t0:.0f} s)", flush=True)
lines = [] lines = []
for l in (db.OUT / f"{name}.txt").read_text(encoding="utf-8").splitlines(): for l in (db.out_dir(name) / "transcript.txt").read_text(encoding="utf-8").splitlines():
m = re.match(r"\[(\d+):(\d+)\] (.*)", l) m = re.match(r"\[(\d+):(\d+)\] (.*)", l)
if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3])) if m: lines.append((int(m[1]) * 60 + int(m[2]), m[3]))
out, order = [], {} out, order = [], {}
@@ -60,10 +60,8 @@ def run(name, speakers=0, threshold=0.85):
# labels by first appearance in the text; clusters never seen in text get the following numbers # labels by first appearance in the text; clusters never seen in text get the following numbers
for s in sorted(segs): for s in sorted(segs):
order.setdefault(s[2], len(order) + 1) order.setdefault(s[2], len(order) + 1)
(db.OUT / f"{name}.spk.txt").write_text("\n".join(
f"[{t//60:02d}:{t%60:02d}] " + (f"Speaker {order[sp]}: " if sp is not None else "") + text for t, sp, text in out), encoding="utf-8")
(db.out_dir(name) / "diar_segments.json").write_text(json.dumps( (db.out_dir(name) / "diar_segments.json").write_text(json.dumps(
[{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8") [{"start": s, "end": e, "label": f"Speaker {order[sp]}"} for s, e, sp in segs]), encoding="utf-8")
db.replace_lines(name, [(t, f"Speaker {order[sp]}" if sp is not None else None, text) for t, sp, text in out]) db.replace_lines(name, [(t, f"Speaker {order[sp]}" if sp is not None else None, text) for t, sp, text in out])
db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None})) db.upsert_recording(name, speakers=len({sp for _, sp, _ in out if sp is not None}))
print("saved", db.OUT / f"{name}.spk.txt") print("saved", len(out), "speaker-labelled lines")
+2 -1
View File
@@ -35,7 +35,8 @@ def _run(name):
gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else [] gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else []
from shots import CONTENT_KINDS from shots import CONTENT_KINDS
screens = list(dict.fromkeys(s["title"] for s in shots if s.get("lead") and s["kind"] in CONTENT_KINDS and s.get("title")))[:30] screens = list(dict.fromkeys(s["title"] for s in shots if s.get("lead") and s["kind"] in CONTENT_KINDS and s.get("title")))[:30]
txt = (db.OUT / f"{name}.txt").read_text(encoding="utf-8") if (db.OUT / f"{name}.txt").exists() else "" tx = db.out_dir(name) / "transcript.txt"
txt = tx.read_text(encoding="utf-8") if tx.exists() else ""
desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}" desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}"
queries = [title] if title else [] queries = [title] if title else []
+9 -6
View File
@@ -9,7 +9,7 @@ os.environ["NO_PROXY"] = "127.0.0.1,localhost"
os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false" os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false"
os.environ.setdefault("PREFECT_LOGGING_LEVEL", os.environ.get("LOG_LEVEL", "INFO").upper()) os.environ.setdefault("PREFECT_LOGGING_LEVEL", os.environ.get("LOG_LEVEL", "INFO").upper())
os.environ.setdefault("PREFECT_LOGGING_LOG_PRINTS", "true") # module print()s show in Prefect UI os.environ.setdefault("PREFECT_LOGGING_LOG_PRINTS", "true") # module print()s show in Prefect UI
import argparse, sys import argparse, json, sys
from pathlib import Path from pathlib import Path
from prefect import flow, task from prefect import flow, task
from prefect.runtime import flow_run from prefect.runtime import flow_run
@@ -60,7 +60,7 @@ class Llama:
def ensure(self, vision=True): def ensure(self, vision=True):
if self.p and self.vision != vision: self.close() if self.p and self.vision != vision: self.close()
self.vision = vision self.vision = vision
log = db.out_dir(self.name) / ("llama.log" if vision else "llama_text.log") log = db.logs(self.name) / ("llama.log" if vision else "llama_text.log")
try: try:
p = llama.start(vision=vision, log=log) p = llama.start(vision=vision, log=log)
except Exception: except Exception:
@@ -75,7 +75,7 @@ class Llama:
def default_device(): def default_device():
try: try:
d = (db.OUT / "transcribe_device.txt").read_text().strip() d = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
return d if d in ("cuda", "npu") else "cuda" return d if d in ("cuda", "npu") else "cuda"
except OSError: except OSError:
return "cuda" return "cuda"
@@ -90,8 +90,11 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str
db.upsert_recording(name, flow_run_id=str(flow_run.id)) db.upsert_recording(name, flow_run_id=str(flow_run.id))
db.progress_start(name, start_from) db.progress_start(name, start_from)
# shots (slow, one vision call per screen) depend only on the video: keep them when re-running an earlier step; an explicit "shots" run redoes them # shots (slow, one vision call per screen) depend only on the video: keep them when re-running an earlier step; an explicit "shots" run redoes them
sj = db.out_dir(name) / "shots.json" sj, sd = db.out_dir(name) / "shots.json", db.out_dir(name) / "shots"
skip_shots = start_from != "shots" and sj.exists() and sj.stat().st_size > 2 try: done = json.loads(sj.read_text(encoding="utf-8"))
except (OSError, ValueError): done = []
# complete = every referenced frame/crop is still on disk (a run cancelled mid-shots wipes them while shots.json is stale)
skip_shots = start_from != "shots" and bool(done) and all((sd / f).exists() for s in done for f in (s.get("file"), s.get("view")) if f)
if skip_shots and go("shots"): print("shots already done: skipped (run from 'shots' to redo)") if skip_shots and go("shots"): print("shots already done: skipped (run from 'shots' to redo)")
if start_from == "render": if start_from == "render":
memory.run(name, link=False) memory.run(name, link=False)
@@ -136,7 +139,7 @@ def bench(name):
except Exception as e: print("npu error:", e); npu_s = None except Exception as e: print("npu error:", e); npu_s = None
cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt") cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt")
dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu" dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
(db.OUT / "transcribe_device.txt").write_text(dev) (db.GLOBAL / "transcribe_device.txt").write_text(dev)
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}") print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}")
+1 -1
View File
@@ -4,7 +4,7 @@ from pathlib import Path
HERE = Path(__file__).parent HERE = Path(__file__).parent
SERVER = HERE / "bin" / "llama-server.exe" SERVER = HERE / "bin" / "llama-server.exe"
MD = HERE / "models" MD = HERE / "models"
CHOICE = HERE / "out" / "llm.txt" # GUI header: "<shots model> <report model>" CHOICE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <report model>"
# Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02. # Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02.
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop _Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster _IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
+3 -3
View File
@@ -16,7 +16,7 @@ ap.add_argument("--screen", action="store_true", help="also record screen to mp4
ap.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S")) ap.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
ap.add_argument("--seconds", type=float, help="auto-stop after N seconds") ap.add_argument("--seconds", type=float, help="auto-stop after N seconds")
a = ap.parse_args() a = ap.parse_args()
out = Path(__file__).parent / "out"; out.mkdir(exist_ok=True) out = Path(__file__).parent / "out" / a.name; out.mkdir(parents=True, exist_ok=True) # out/<name>/source.mp4 + source.wav
SR = 16000 SR = 16000
def to16k(x, ch, sr): def to16k(x, ch, sr):
@@ -41,7 +41,7 @@ def record():
if a.screen: if a.screen:
ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop", ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(out / f"{a.name}.mp4")], stdin=subprocess.PIPE, str(out / "source.mp4")], stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("Recording... Ctrl+C to stop") print("Recording... Ctrl+C to stop")
try: try:
@@ -57,7 +57,7 @@ def record():
n = max(len(m) for m in mix) n = max(len(m) for m in mix)
y = sum(np.pad(m, (0, n - len(m))) for m in mix) y = sum(np.pad(m, (0, n - len(m))) for m in mix)
y = np.clip(y, -1, 1) y = np.clip(y, -1, 1)
path = out / f"{a.name}.wav" path = out / "source.wav"
with wave.open(str(path), "wb") as w: with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR) w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
w.writeframes((y * 32767).astype(np.int16).tobytes()) w.writeframes((y * 32767).astype(np.int16).tobytes())
+2 -2
View File
@@ -108,7 +108,7 @@ def _link(name):
def run(name, link=True): def run(name, link=True):
"""Flow step: link to earlier meetings, index this one, render. Memory problems never fail the flow.""" """Flow step: link to earlier meetings, index this one, render. Memory problems never fail the flow."""
try: try:
with embedder(db.out_dir(name) / "embed.log"): with embedder(db.logs(name) / "embed.log"):
if link: if link:
try: _link(name) try: _link(name)
except Exception as e: print("memory link skipped:", repr(e)) except Exception as e: print("memory link skipped:", repr(e))
@@ -130,5 +130,5 @@ def ask(q):
if __name__ == "__main__": if __name__ == "__main__":
sys.stdout.reconfigure(encoding="utf-8") sys.stdout.reconfigure(encoding="utf-8")
if "--reindex" in sys.argv: if "--reindex" in sys.argv:
with embedder(db.OUT / "embed.log"): with embedder(db.GLOBAL / "embed.log"):
for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name) for p in sorted(db.OUT.glob("*/report.json")): index(p.parent.name)
+3 -10
View File
@@ -7,7 +7,6 @@ API = f"http://127.0.0.1:{llama.PORT}/v1/chat/completions"
JIRA_BROWSE = "https://italdesign.atlassian.net/browse" JIRA_BROWSE = "https://italdesign.atlassian.net/browse"
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open _open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open
TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b") TICKET = re.compile(r"\b[A-Z][A-Z0-9]{1,9}-\d{1,6}\b")
LINE = re.compile(r"^\[(\d+):(\d+)\] (?:(Speaker \d+): )?(.*)$")
SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. ' SYS_A = ('Dividi la trascrizione in argomenti discussi. Rispondi SOLO JSON: {"topics":[{"title":str,"start":"mm:ss","end":"mm:ss","summary":[str],"shown":[str],"decisions":[str],"actions":[{"who":str,"what":str,"when":str}],"open_questions":[str]}]}. '
'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. ' 'Le righe [SCHERMO] riportano cosa era visibile sullo schermo condiviso (tipo, titolo, testo letto): usale come fonte di fatti complementare al parlato. '
'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. ' 'In "shown" metti i fatti concreti visti a schermo e rilevanti per l\'argomento (valori, nomi di sistemi, ticket, errori, URL), ognuno iniziando con il timestamp "mm:ss" della riga [SCHERMO] da cui proviene. '
@@ -39,8 +38,7 @@ def _tick(note):
def _manual_title(name): def _manual_title(name):
p = db.out_dir(name) / "title.txt" return db.meta(name).get("title", "")
return p.read_text(encoding="utf-8").strip() if p.exists() else ""
THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room THINK = 1024 # reasoning budget per report call (server: --reasoning-budget); added to max_tokens so the answer keeps its room
@@ -74,13 +72,8 @@ def chat(system, user, max_tokens, retries=2, think=False):
def _transcript(name): def _transcript(name):
p = db.OUT / f"{name}.spk.txt" """[(sec, "Speaker N" | None, text)] from the lines table: diarize stores the speaker-labelled paragraphs there, names are applied at render time."""
if not p.exists(): p = db.OUT / f"{name}.txt" return [(int(t), sp, x) for t, sp, x in db.connect().execute("SELECT t, speaker, text FROM lines WHERE name=? ORDER BY rowid", (name,))]
rows = []
for l in p.read_text(encoding="utf-8").splitlines() if p.exists() else []:
m = LINE.match(l)
if m: rows.append((int(m[1]) * 60 + int(m[2]), m[3], m[4]))
return rows
def _load(name, f, default): def _load(name, f, default):
+37 -40
View File
@@ -7,6 +7,7 @@ Extension POSTs /chunk (10 s webm), /events (Teams call events), /stop. /stop la
GUI: http://127.0.0.1:18765/ GUI: http://127.0.0.1:18765/
""" """
import argparse, json, mimetypes, os, re, sqlite3, subprocess, time, urllib.request import argparse, json, mimetypes, os, re, sqlite3, subprocess, time, urllib.request
import tempfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from urllib.parse import urlparse, parse_qs from urllib.parse import urlparse, parse_qs
@@ -24,7 +25,6 @@ PREFECT = "http://127.0.0.1:4200"
ENV = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")} ENV = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
ENV.update(PREFECT_API_URL=PREFECT + "/api", NO_PROXY="127.0.0.1,localhost") ENV.update(PREFECT_API_URL=PREFECT + "/api", NO_PROXY="127.0.0.1,localhost")
NOPROXY = urllib.request.build_opener(urllib.request.ProxyHandler({})) NOPROXY = urllib.request.build_opener(urllib.request.ProxyHandler({}))
FILES = (("txt", ".txt"), ("spk.txt", ".spk.txt"))
EDGE = Path(os.path.expandvars(r"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe")) EDGE = Path(os.path.expandvars(r"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe"))
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()
@@ -42,7 +42,8 @@ def make_pdf(name):
tmp.write_text(html.read_text(encoding="utf-8").replace("<details", "<details open").replace("</style>", PRINT_CSS + "</style>", 1), encoding="utf-8") tmp.write_text(html.read_text(encoding="utf-8").replace("<details", "<details open").replace("</style>", PRINT_CSS + "</style>", 1), encoding="utf-8")
pdf.unlink(missing_ok=True) pdf.unlink(missing_ok=True)
try: try:
r = subprocess.run([str(EDGE), "--headless", "--disable-gpu", "--no-first-run", "--no-pdf-header-footer", f"--user-data-dir={d / '.edge-pdf'}", with tempfile.TemporaryDirectory(prefix="edge-pdf-", ignore_cleanup_errors=True) as prof: # throwaway profile: nothing left in the meeting folder, parallel calls can't collide
r = subprocess.run([str(EDGE), "--headless", "--disable-gpu", "--no-first-run", "--no-pdf-header-footer", f"--user-data-dir={prof}",
f"--print-to-pdf={pdf}", tmp.as_uri()], capture_output=True, timeout=180) f"--print-to-pdf={pdf}", tmp.as_uri()], capture_output=True, timeout=180)
finally: tmp.unlink(missing_ok=True) finally: tmp.unlink(missing_ok=True)
if not pdf.exists(): raise RuntimeError(r.stderr.decode(errors="replace")[-500:]) if not pdf.exists(): raise RuntimeError(r.stderr.decode(errors="replace")[-500:])
@@ -54,7 +55,7 @@ def ask_once(q):
with LOCK: with LOCK:
own = [] own = []
try: try:
own = [p for p in (llama.start_embed(log=out / "embed.log"), llama.start(vision=False, log=out / "llama.log")) if p is not None] own = [p for p in (llama.start_embed(log=db.GLOBAL / "embed.log"), llama.start(vision=False, log=db.GLOBAL / "llama.log")) if p is not None]
return memory.ask(q) return memory.ask(q)
finally: finally:
for p in own: p.terminate() for p in own: p.terminate()
@@ -83,9 +84,8 @@ def pump():
with QLOCK: with QLOCK:
if not QUEUE: BATCH = None; return if not QUEUE: BATCH = None; return
name, start_from, speakers = QUEUE.pop(0) 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)], 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) cwd=HERE, env=ENV, stdout=open(db.logs(name) / "flow.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
JOBS[name].wait() JOBS[name].wait()
@@ -105,17 +105,18 @@ def start_prefect():
if prefect_up(): return if prefect_up(): return
# flow.py's env already has Prefect: works offline (the old `uv run --with prefect` re-resolved from PyPI and died without DNS) # flow.py's env already has Prefect: works offline (the old `uv run --with prefect` re-resolved from PyPI and died without DNS)
subprocess.Popen(["uv", "run", "--script", "flow.py", "--prefect-server"], subprocess.Popen(["uv", "run", "--script", "flow.py", "--prefect-server"],
cwd=HERE, env=ENV, stdout=open(out / "prefect.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200) cwd=HERE, env=ENV, stdout=open(db.GLOBAL / "prefect.log", "ab"), stderr=subprocess.STDOUT, creationflags=0x08 | 0x200)
def backfill(): def backfill():
c = db.connect() c = db.connect()
have = {r[0] for r in c.execute("SELECT name FROM recordings")} have = {r[0] for r in c.execute("SELECT name FROM recordings")}
for p in sorted([*out.glob("teams_*.webm"), *[p for p in out.glob("meet_*.*") if p.suffix.lower() in UPLOAD_EXT]]): for p in sorted(out.glob("*/source.*")):
if p.stem in have or (p.suffix == ".webm" and time.time() - p.stat().st_mtime < 60): continue n = p.parent.name
db.upsert_recording(p.stem, source="ext" if p.stem.startswith("teams_") else "meet", if n in have or p.suffix.lower() not in UPLOAD_EXT or (p.suffix == ".webm" and time.time() - p.stat().st_mtime < 60): continue
status="done" if (out / p.stem / "report.html").exists() else "queued", bytes=p.stat().st_size) db.upsert_recording(n, source="ext" if n.startswith("teams_") else "meet",
have.add(p.stem) status="done" if (p.parent / "report.html").exists() else "queued", bytes=p.stat().st_size)
have.add(n)
TITLES = {} # name -> (report.json mtime, "title — date") TITLES = {} # name -> (report.json mtime, "title — date")
@@ -124,8 +125,7 @@ TITLES = {} # name -> (report.json mtime, "title — date")
def title(n): def title(n):
f = out / n / "report.json" f = out / n / "report.json"
if not f.exists(): if not f.exists():
m = out / n / "title.txt" return db.meta(n).get("title", "")
return m.read_text(encoding="utf-8").strip() if m.exists() else ""
m = f.stat().st_mtime m = f.stat().st_mtime
if TITLES.get(n, (0,))[0] != m: if TITLES.get(n, (0,))[0] != m:
try: j = json.loads(f.read_text(encoding="utf-8")); TITLES[n] = (m, f"{j.get('meeting_title') or ''} — {j.get('date') or ''}") try: j = json.loads(f.read_text(encoding="utf-8")); TITLES[n] = (m, f"{j.get('meeting_title') or ''} — {j.get('date') or ''}")
@@ -136,12 +136,10 @@ def title(n):
def busy(): return bool(QUEUE) 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 set_title(name, t): def set_title(name, t):
"""Manual meeting title (out/<name>/title.txt, wins over Teams/LLM titles); empty clears it. Patches report.json and re-renders.""" """Manual meeting title (out/<name>/meta.json, wins over Teams/LLM titles); empty clears it. Patches report.json and re-renders."""
t = " ".join(t.split())[:200] t = " ".join(t.split())[:200]
if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return False if not db.connect().execute("SELECT 1 FROM recordings WHERE name=?", (name,)).fetchone(): return False
f = out / name / "title.txt" db.set_meta(name, title=t)
if t: f.write_text(t, encoding="utf-8")
else: f.unlink(missing_ok=True)
rj = out / name / "report.json" rj = out / name / "report.json"
if rj.exists() and t: if rj.exists() and t:
j = json.loads(rj.read_text(encoding="utf-8")); j["meeting_title"] = t j = json.loads(rj.read_text(encoding="utf-8")); j["meeting_title"] = t
@@ -182,10 +180,10 @@ def drop_video(name):
j = JOBS.get(name) j = JOBS.get(name)
if not r or r["status"] != "done" or name in R or (j and j.poll() is None) or any(q[0] == name for q in QUEUE): return 0, "solo a report finito e senza run attivi" if not r or r["status"] != "done" or name in R or (j and j.poll() is None) or any(q[0] == name for q in QUEUE): return 0, "solo a report finito e senza run attivi"
if not (out / name / "audio.opus").exists(): return 0, "manca audio.opus: video non eliminato" if not (out / name / "audio.opus").exists(): return 0, "manca audio.opus: video non eliminato"
n = 0 fs = list((out / name).glob("source.*"))
for e in (".webm", ".mp4", ".mkv", ".mov"): if not fs: return 0, "nessun file sorgente"
p = out / f"{name}{e}" n = sum(f.stat().st_size for f in fs)
if p.exists(): n += p.stat().st_size; p.unlink() for f in fs: f.unlink()
return round(n / 1e6, 1), None return round(n / 1e6, 1), None
@@ -197,13 +195,13 @@ def merge(names):
if len(names) < 2 or None in rows: return None, "servono almeno 2 registrazioni esistenti" if len(names) < 2 or None in rows: return None, "servono almeno 2 registrazioni esistenti"
if any(r["status"] == "recording" or r["name"] in R or r["name"] in JOBS and JOBS[r["name"]].poll() is None for r in rows): return None, "ferma prima le registrazioni in corso" if any(r["status"] == "recording" or r["name"] in R or r["name"] in JOBS and JOBS[r["name"]].poll() is None for r in rows): return None, "ferma prima le registrazioni in corso"
rows.sort(key=lambda r: r["started_at"] or "") rows.sort(key=lambda r: r["started_at"] or "")
files = [out / f"{r['name']}.webm" for r in rows] files = [db.media(r["name"])[1] for r in rows]
if not all(f.exists() for f in files): return None, "solo registrazioni .webm" if not all(f and f.suffix == ".webm" for f in files): return None, "solo registrazioni .webm"
merged = rows[0]["name"] + "_merged" merged = rows[0]["name"] + "_merged"
if c.execute("SELECT 1 FROM recordings WHERE name=?", (merged,)).fetchone(): return None, "unione già esistente" if c.execute("SELECT 1 FROM recordings WHERE name=?", (merged,)).fetchone(): return None, "unione già esistente"
lst = out / f"{merged}.concat.txt" dst = db.out_dir(merged) / "source.webm"
lst.write_text("".join(f"file '{f.name}'\n" for f in files), encoding="utf-8") lst = dst.with_name("concat.txt")
dst = out / f"{merged}.webm" lst.write_text("".join(f"file '{f.as_posix()}'\n" for f in files), encoding="utf-8")
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(dst)], capture_output=True, text=True) r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(dst)], capture_output=True, text=True)
lst.unlink(missing_ok=True) lst.unlink(missing_ok=True)
if r.returncode: return None, r.stderr[-300:] if r.returncode: return None, r.stderr[-300:]
@@ -263,8 +261,8 @@ def slot():
def last_log(n): def last_log(n):
"""Last meaningful line of out/<n>/flow.log: what a started-but-not-yet-tracked run is doing (e.g. uv downloading deps).""" """Last meaningful line of out/<n>/logs/flow.log: what a started-but-not-yet-tracked run is doing (e.g. uv downloading deps)."""
f = out / n / "flow.log" f = out / n / "logs" / "flow.log"
try: try:
with open(f, "rb") as fh: fh.seek(max(0, f.stat().st_size - 4096)); tail = fh.read().decode("utf-8", "replace") with open(f, "rb") as fh: fh.seek(max(0, f.stat().st_size - 4096)); tail = fh.read().decode("utf-8", "replace")
except OSError: return "" except OSError: return ""
@@ -303,10 +301,9 @@ def status():
for r in db.connect().execute("SELECT * FROM recordings ORDER BY name DESC"): for r in db.connect().execute("SELECT * FROM recordings ORDER BY name DESC"):
n = r["name"]; d = dict(r) n = r["name"]; d = dict(r)
d["receiving_age_s"] = round(t - R[n]["last"]) if n in R else None d["receiving_age_s"] = round(t - R[n]["last"]) if n in R else None
d["files"] = [k for k, e in (*FILES, ("report.html", None)) if ((out / n / "report.html") if e is None else (out / f"{n}{e}")).exists()] d["files"] = ["report.html"] if (out / n / "report.html").exists() else []
j = JOBS.get(n); d["running"] = bool(j and j.poll() is None); d["title"] = title(n) j = JOBS.get(n); d["running"] = bool(j and j.poll() is None); d["title"] = title(n)
up = out / n / "upload.json" d["upload"] = db.meta(n).get("upload")
if up.exists(): d["upload"] = json.loads(up.read_text(encoding="utf-8")).get("filename")
d["prog"] = prog(n, d["duration_s"]) if d["running"] or d["status"] in db.ORDER else None d["prog"] = prog(n, d["duration_s"]) if d["running"] or d["status"] in db.ORDER else None
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
@@ -565,7 +562,7 @@ class H(BaseHTTPRequestHandler):
if u.path == "/upload": return self.upload(q) if u.path == "/upload": return self.upload(q)
data = self.rfile.read(int(self.headers.get("Content-Length", 0))) data = self.rfile.read(int(self.headers.get("Content-Length", 0)))
if u.path == "/chunk": if u.path == "/chunk":
with open(out / f"{name}.webm", "ab") as f: f.write(data) with open(db.out_dir(name) / "source.webm", "ab") as f: f.write(data)
if name not in R: db.upsert_recording(name, source="ext", started_at=now(), status="recording") if name not in R: db.upsert_recording(name, source="ext", started_at=now(), status="recording")
R.setdefault(name, {})["last"] = time.time() R.setdefault(name, {})["last"] = time.time()
db.connect().execute("UPDATE recordings SET chunks=chunks+1, bytes=bytes+?, updated_at=datetime('now') WHERE name=?", (len(data), name)) db.connect().execute("UPDATE recordings SET chunks=chunks+1, bytes=bytes+?, updated_at=datetime('now') WHERE name=?", (len(data), name))
@@ -645,16 +642,16 @@ class H(BaseHTTPRequestHandler):
except (KeyError, ValueError): return self._send(b"bad times", 400) except (KeyError, ValueError): return self._send(b"bad times", 400)
if not 0 <= s < e: return self._send("intervallo non valido".encode(), 400) if not 0 <= s < e: return self._send("intervallo non valido".encode(), 400)
new = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S"); ext = ".mp4" if v else ".m4a" new = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S"); ext = ".mp4" if v else ".m4a"
dst = out / f"{new}{ext}"; tmp = out / f"{new}{ext}.part" dst = db.out_dir(new) / f"source{ext}"; tmp = dst.with_name(f"source{ext}.part")
enc = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"] if v else ["-vn"] enc = ["-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"] if v else ["-vn"]
r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(s), "-t", str(e - s), "-i", str(src), *enc, r = subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", str(s), "-t", str(e - s), "-i", str(src), *enc,
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-f", "mp4", str(tmp)], capture_output=True, text=True) "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", "-f", "mp4", str(tmp)], capture_output=True, text=True)
if r.returncode or not tmp.exists() or not tmp.stat().st_size: if r.returncode or not tmp.exists() or not tmp.stat().st_size:
tmp.unlink(missing_ok=True); return self._send(f"ffmpeg: {r.stderr[-300:]}".encode(), 500) tmp.unlink(missing_ok=True); dst.parent.rmdir(); return self._send(f"ffmpeg: {r.stderr[-300:]}".encode(), 500)
tmp.replace(dst) tmp.replace(dst)
try: dur = db.duration(dst) try: dur = db.duration(dst)
except ValueError as x: dst.unlink(); return self._send(f"ritaglio non leggibile: {x}".encode(), 500) except ValueError as x: dst.unlink(); dst.parent.rmdir(); return self._send(f"ritaglio non leggibile: {x}".encode(), 500)
(db.out_dir(new) / "upload.json").write_text(json.dumps({"filename": f"{title(name) or name} [{int(s)}s-{int(e)}s]"}, ensure_ascii=False), encoding="utf-8") db.set_meta(new, upload=f"{title(name) or name} [{int(s)}s-{int(e)}s]")
db.upsert_recording(new, source="upload", started_at=now(), status="queued", bytes=dst.stat().st_size, duration_s=dur) db.upsert_recording(new, source="upload", started_at=now(), status="queued", bytes=dst.stat().st_size, duration_s=dur)
launch(new, "audio") launch(new, "audio")
self._json({"name": new, "duration_s": dur}) self._json({"name": new, "duration_s": dur})
@@ -663,14 +660,14 @@ class H(BaseHTTPRequestHandler):
if ext not in UPLOAD_EXT: return self._send(f"formato non supportato: {ext or '?'} (usa {', '.join(sorted(UPLOAD_EXT))})".encode(), 400) if ext not in UPLOAD_EXT: return self._send(f"formato non supportato: {ext or '?'} (usa {', '.join(sorted(UPLOAD_EXT))})".encode(), 400)
if not n: return self._send("file vuoto".encode(), 400) if not n: return self._send("file vuoto".encode(), 400)
name = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S") name = "meet_" + time.strftime("%Y-%m-%dT%H-%M-%S")
dst = out / f"{name}{ext}"; tmp = out / f"{name}{ext}.part"; left = n dst = db.out_dir(name) / f"source{ext}"; tmp = dst.with_name(f"source{ext}.part"); left = n
with open(tmp, "wb") as f: with open(tmp, "wb") as f:
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); dst.parent.rmdir(); return self._send("upload interrotto".encode(), 400)
tmp.replace(dst) tmp.replace(dst)
try: dur = db.duration(dst) try: dur = db.duration(dst)
except ValueError as e: dst.unlink(); return self._send(f"file non leggibile: {e}".encode(), 400) except ValueError as e: dst.unlink(); dst.parent.rmdir(); 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.set_meta(name, upload=fn)
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")
self._json({"name": name, "duration_s": dur}) self._json({"name": name, "duration_s": dur})
+1 -1
View File
@@ -145,7 +145,7 @@ def run(name, max_frames=60, scene=0.05):
kept = [kept[i] for i in keep] kept = [kept[i] for i in keep]
db.tick(name, 0, len(kept), "avvio del modello di visione") db.tick(name, 0, len(kept), "avvio del modello di visione")
srv = llama.start(log=d / "llama.log") # None if already running srv = llama.start(log=db.logs(name) / "llama.log") # None if already running
rows = [] rows = []
try: try:
for i, (t, p, _) in enumerate(kept): for i, (t, p, _) in enumerate(kept):
+1 -1
View File
@@ -91,7 +91,7 @@ def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path |
if out_path is not None: if out_path is not None:
out_path.write_text(txt, encoding="utf-8") out_path.write_text(txt, encoding="utf-8")
return secs return secs
(db.OUT / f"{name}.txt").write_text(txt, encoding="utf-8") (db.out_dir(name) / "transcript.txt").write_text(txt, encoding="utf-8")
db.replace_lines(name, [(t, None, x) for t, x in lines]) db.replace_lines(name, [(t, None, x) for t, x in lines])
db.upsert_recording(name, transcribe_device=used, transcribe_s=secs) db.upsert_recording(name, transcribe_device=used, transcribe_s=secs)
return secs return secs