# /// script # requires-python = ">=3.10,<3.13" # dependencies = ["prefect>=3", "faster-whisper", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"] # /// """Meeting pipeline. uv run --script flow.py [--from STEP] [--speakers N] [--device cuda|npu] [--bench-npu]""" import os os.environ.setdefault("PREFECT_API_URL", "http://127.0.0.1:4200/api") os.environ["NO_PROXY"] = "127.0.0.1,localhost" 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_LOG_PRINTS", "true") # module print()s show in Prefect UI import argparse, sys from pathlib import Path from prefect import flow, task from prefect.runtime import flow_run from prefect.task_runners import ThreadPoolTaskRunner import audio, db, diarize, docs, llama, memory, report, shots, speakers, transcribe HERE = Path(__file__).parent STEPS = ["audio", "transcribe", "diarize", "speakers", "shots", "docs", "report", "memory", "render"] 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) @task(name="audio") def t_audio(name): step_status(name, "audio"); audio.run(name) @task(name="transcribe") def t_transcribe(name, model, device, status=True): if status: step_status(name, "transcribing") transcribe.run(name, model=model, device=device) @task(name="diarize") def t_diarize(name, n): step_status(name, "diarizing"); diarize.run(name, speakers=n) @task(name="speakers") def t_speakers(name): step_status(name, "identifying"); speakers.run(name) @task(name="shots", retries=1, retry_delay_seconds=10) def t_shots(name, status=True): if status: step_status(name, "shots") shots.run(name) @task(name="docs", retries=1, retry_delay_seconds=10) def t_docs(name): step_status(name, "docs"); docs.run(name) @task(name="report", retries=1, retry_delay_seconds=10) def t_report(name): step_status(name, "report"); report.run(name) @task(name="memory") def t_memory(name): step_status(name, "memory"); memory.run(name) 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 def ensure(self, vision=True): if self.p and self.vision != vision: self.close() self.vision = vision log = db.out_dir(self.name) / ("llama.log" if vision else "llama_text.log") try: p = llama.start(vision=vision, log=log) except Exception: 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 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 def default_device(): try: d = (db.OUT / "transcribe_device.txt").read_text().strip() return d if d in ("cuda", "npu") else "cuda" except OSError: return "cuda" @flow(name="meeting", log_prints=True, task_runner=ThreadPoolTaskRunner(max_workers=3)) def meeting(name: str, start_from: str = "audio", speakers: int = 5, model: str = "large-v3-turbo", device: str | None = None): device = device or default_device() go = lambda s: STEPS.index(s) >= STEPS.index(start_from) L = Llama(name) try: db.upsert_recording(name, flow_run_id=str(flow_run.id)) db.progress_start(name, start_from) if start_from == "render": memory.run(name, link=False) else: if go("audio"): t_audio(name) spk_chain = lambda: [t_diarize(name, speakers), t_speakers(name)] if go("diarize") else ([t_speakers(name)] if go("speakers") else None) if device == "npu" and go("transcribe") and go("shots"): db.set_status(name, "transcribing") L.ensure() f_t = t_transcribe.submit(name, model, "npu", False) f_s = t_shots.submit(name, False) try: f_t.result() except Exception as e: if "NPU failed" not in repr(e): raise f_s.result(); L.close() print("NPU failed, transcribed on cuda") t_transcribe(name, model, "cuda") spk_chain(); L.ensure(); f_s = None else: spk_chain() if f_s is not None: f_s.result() else: if go("transcribe"): t_transcribe(name, model, device) spk_chain() if go("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) t_memory(name) db.step(name, "done") except Exception as e: db.set_status(name, "error", repr(e)[:500]) raise finally: L.close() def bench(name): d = db.out_dir(name) 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") dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu" (db.OUT / "transcribe_device.txt").write_text(dev) print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}") if __name__ == "__main__": if sys.argv[1:] == ["--prefect-server"]: # server.py: run Prefect from this cached env (an ephemeral --with env needs PyPI) import subprocess sys.exit(subprocess.call([sys.executable, "-m", "prefect", "server", "start", "--host", "127.0.0.1", "--port", "4200"])) sys.stdout.reconfigure(encoding="utf-8") ap = argparse.ArgumentParser() ap.add_argument("name"); ap.add_argument("--from", dest="start", default="audio", choices=STEPS) ap.add_argument("--speakers", type=int, default=5); ap.add_argument("--device", choices=["cuda", "npu"]) ap.add_argument("--bench-npu", action="store_true") a = ap.parse_args() if a.bench_npu: bench(a.name) else: meeting(a.name, a.start, a.speakers, device=a.device)