Add explanatory comments across codebase
This commit is contained in:
+36
@@ -4,28 +4,38 @@
|
||||
# ///
|
||||
# ponytail: ctranslate2 4.8 links cublas64_12 (matches the nvidia-*-cu12 wheels); bump all three together when it moves to CUDA 13
|
||||
"""Meeting pipeline. uv run --script flow.py <name> [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]"""
|
||||
# Prefect pipeline entry point. Env vars below (lines 8-16) must be set before prefect is imported (line 21).
|
||||
import os
|
||||
# Talk to the local Prefect server started by server.py; setdefault keeps a user override.
|
||||
os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api")
|
||||
# Bypass the corporate proxy for localhost, or Prefect API calls get routed out.
|
||||
os.environ["NO_PROXY"] = "127.0.0.1,localhost"
|
||||
# Turn off Prefect's usage analytics.
|
||||
os.environ["PREFECT_SERVER_ANALYTICS_ENABLED"] = "false"
|
||||
# Prefect log level follows LOG_LEVEL (default INFO).
|
||||
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
|
||||
# stdlib only: CLI args, JSON, paths, exit codes.
|
||||
import argparse, json, sys
|
||||
from pathlib import Path
|
||||
from prefect import flow, task
|
||||
from prefect.runtime import flow_run
|
||||
from prefect.task_runners import ThreadPoolTaskRunner
|
||||
# Pipeline stage modules living next to this file.
|
||||
import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
# Stage order. --from picks a start point; go() compares indices into this list.
|
||||
STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render", "title"]
|
||||
|
||||
|
||||
# Record the current stage for the GUI. LLM stages include the loaded model name so timing stats stay per model.
|
||||
def step_status(name, s):
|
||||
# key per model for the LLM steps: their speed (and so the ETA) depends on it
|
||||
db.step(name, s, f"{s}@{llama.current(s == 'shots')}" if s in ("shots", "report") else s)
|
||||
|
||||
|
||||
# One Prefect task per stage: set status, then call the stage's run().
|
||||
@task(name="audio")
|
||||
def t_audio(name): step_status(name, "audio"); audio.run(name)
|
||||
|
||||
@@ -40,6 +50,7 @@ def t_diarize(name, n): step_status(name, "diarizing"); diarize.run(name, speake
|
||||
@task(name="speakers")
|
||||
def t_speakers(name): step_status(name, "identifying"); speakers.run(name)
|
||||
|
||||
# shots/docs/report call LLM servers that can fail transiently: retry once after 10 s.
|
||||
@task(name="shots", retries=1, retry_delay_seconds=10)
|
||||
def t_shots(name, status=True):
|
||||
if status: step_status(name, "shots")
|
||||
@@ -55,6 +66,7 @@ def t_report(name): step_status(name, "report"); report.run(name)
|
||||
def t_memory(name): step_status(name, "memory"); memory.run(name)
|
||||
|
||||
|
||||
# Owns one llama-server process per run; switching profile (vision <-> text) restarts it.
|
||||
class Llama:
|
||||
"""Start llama-server in vision (shots) or text (report) profile; switching restarts it. Terminate in close() only if we started it."""
|
||||
def __init__(self, name): self.name, self.p, self.vision = name, None, None
|
||||
@@ -65,15 +77,18 @@ class Llama:
|
||||
try:
|
||||
p = llama.start(vision=vision, log=log)
|
||||
except Exception:
|
||||
# llama.log with 'out of memory' means another CUDA app holds VRAM; tell the user the fix.
|
||||
if log.exists() and "out of memory" in log.read_text(errors="replace"):
|
||||
raise RuntimeError("GPU busy: free VRAM (close other CUDA apps) and retry from 'shots'")
|
||||
raise
|
||||
# Keep the process we started earlier; llama.start() returns None when a server is already running.
|
||||
self.p = self.p or p
|
||||
def close(self):
|
||||
if self.p and self.p.poll() is None: self.p.terminate(); self.p.wait() # wait: port must be free before a profile switch
|
||||
self.p = None
|
||||
|
||||
|
||||
# Device: GUI/bench file wins, else cuda. Unknown values fall back to cuda.
|
||||
def default_device():
|
||||
try:
|
||||
d = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
|
||||
@@ -82,24 +97,31 @@ def default_device():
|
||||
return "cuda"
|
||||
|
||||
|
||||
# Up to 3 threads; ordering comes from explicit .result() waits, not from the runner.
|
||||
@flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3))
|
||||
def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str = "large-v3-turbo", device: str | None = None):
|
||||
device = device or default_device()
|
||||
# True if stage s is at or after the requested start (--from).
|
||||
go = lambda s: STEPS.index(s) >= STEPS.index(start_from)
|
||||
# Owns the llama-server process; always closed in the finally block.
|
||||
L = Llama(name)
|
||||
try:
|
||||
# Link the DB row to this Prefect run so the GUI can find it.
|
||||
db.upsert_recording(name, flow_run_id=str(flow_run.id))
|
||||
db.progress_start(name, start_from)
|
||||
# shots run every time unless the GUI toggle "Salta schermate" is on
|
||||
# Resume: reuse shots already extracted by an earlier run.
|
||||
sj = db.out_dir(name) / "shots.json"
|
||||
try: done = json.loads(sj.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError): done = []
|
||||
no_shots = (db.GLOBAL / "skip_shots.txt").exists() # GUI toggle "Salta schermate"
|
||||
skip_shots = no_shots
|
||||
# Toggle on with no prior shots: write empty placeholders so downstream steps find their files.
|
||||
if no_shots and not done:
|
||||
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]")
|
||||
db.replace_shots(name, [])
|
||||
if skip_shots and go("shots"): print("shots skipped")
|
||||
# Title/render restart: re-run only text-only post-processing, no vision model needed.
|
||||
if start_from == "title":
|
||||
L.ensure(vision=False)
|
||||
report.retitle(name)
|
||||
@@ -108,45 +130,58 @@ def meeting(name: str, start_from: str = "audio", speakers: int = 0, model: str
|
||||
memory.run(name, link=False)
|
||||
else:
|
||||
if go("audio"): t_audio(name)
|
||||
# Speaker labelling: diarize, then name mapping.
|
||||
spk_chain = lambda: [t_diarize(name, speakers), t_speakers(name)] if go("diarize") else ([t_speakers(name)] if go("speakers") else None)
|
||||
# NPU path: transcribe on the NPU while shots run on the GPU VLM at the same time.
|
||||
if device == "npu" and go("transcribe") and go("shots") and not skip_shots:
|
||||
db.set_status(name, "transcribing")
|
||||
L.ensure()
|
||||
f_t = t_transcribe.submit(name, model, "npu", False)
|
||||
f_s = t_shots.submit(name, False)
|
||||
# Wait for NPU transcription; shots keep running meanwhile.
|
||||
try:
|
||||
f_t.result()
|
||||
except Exception as e:
|
||||
# Only the NPU failure is handled here; anything else is a real error.
|
||||
if "NPU failed" not in repr(e): raise
|
||||
f_s.result(); L.close()
|
||||
print("NPU failed, transcribed on cuda")
|
||||
t_transcribe(name, model, "cuda")
|
||||
# Shots already finished above; clear the handle.
|
||||
spk_chain(); L.ensure(); f_s = None
|
||||
else:
|
||||
spk_chain()
|
||||
# Shots still running in parallel; wait for them before text stages.
|
||||
if f_s is not None: f_s.result()
|
||||
else:
|
||||
# Sequential path (CUDA, or NPU without shots).
|
||||
if go("transcribe"): t_transcribe(name, model, device)
|
||||
spk_chain()
|
||||
if go("shots") and not skip_shots: L.ensure(); t_shots(name)
|
||||
L.ensure(vision=False) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile
|
||||
if go("docs"): t_docs(name)
|
||||
if go("report"): t_report(name)
|
||||
# Memory update: always runs as the final stage.
|
||||
t_memory(name)
|
||||
db.step(name, "done")
|
||||
except Exception as e:
|
||||
# Record the failure for the GUI, then re-raise so Prefect marks the run failed.
|
||||
db.set_status(name, "error", repr(e)[:500])
|
||||
raise
|
||||
finally:
|
||||
L.close()
|
||||
|
||||
|
||||
# Benchmark both transcribers on the same audio and store the choice for default_device().
|
||||
def bench(name):
|
||||
d = db.out_dir(name)
|
||||
# A failed NPU run is recorded as None so the comparison below picks CUDA.
|
||||
try: npu_s = transcribe.run(name, device="npu", out_path=d / "bench_npu.txt")
|
||||
except Exception as e: print("npu error:", e); npu_s = None
|
||||
cuda_s = transcribe.run(name, device="cuda", out_path=d / "bench_cuda.txt")
|
||||
# NPU is picked unless it failed or is more than 3x slower than CUDA (deliberate tolerance, not fastest-wins).
|
||||
dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
|
||||
# Persist for later runs (read by default_device).
|
||||
(db.GLOBAL / "transcribe_device.txt").write_text(dev)
|
||||
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}")
|
||||
|
||||
@@ -161,5 +196,6 @@ if __name__ == "__main__":
|
||||
ap.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster"); ap.add_argument("--device", choices=["cuda", "npu"])
|
||||
ap.add_argument("--bench-npu", action="store_true")
|
||||
a = ap.parse_args()
|
||||
# --bench-npu is a one-off benchmark; it does not run the pipeline.
|
||||
if a.bench_npu: bench(a.name)
|
||||
else: meeting(a.name, a.start, a.speakers, device=a.device)
|
||||
|
||||
Reference in New Issue
Block a user