323 lines
12 KiB
Python
323 lines
12 KiB
Python
# /// script
|
|
# requires-python = ">=3.10,<3.13"
|
|
# dependencies = ["prefect>=3", "faster-whisper", "ctranslate2==4.8.*", "av>=14,<17", "nvidia-cublas-cu12", "nvidia-cudnn-cu12==9.*", "sherpa-onnx", "numpy", "imagehash", "Pillow", "markdown", "openvino-genai", "huggingface_hub"]
|
|
# ///
|
|
# 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
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Pipeline stage modules living next to this file.
|
|
import audio
|
|
import db
|
|
import diarize
|
|
import docs
|
|
import llama
|
|
import memory
|
|
import report
|
|
import shots
|
|
import speakers
|
|
import transcribe
|
|
from prefect import flow, task
|
|
from prefect.runtime import flow_run
|
|
from prefect.task_runners import ThreadPoolTaskRunner
|
|
|
|
HERE = Path(__file__).parent
|
|
# Stage order. --from picks a start point; should_run() 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, stage):
|
|
# key per model for the LLM steps: their speed (and so the ETA) depends on it
|
|
db.step(
|
|
name,
|
|
stage,
|
|
f"{stage}@{llama.current(stage == 'shots')}" if stage in ("shots", "report") else stage,
|
|
)
|
|
|
|
|
|
# One Prefect task per stage: set status, then call the stage's run().
|
|
@task(name="audio")
|
|
def audio_task(name):
|
|
step_status(name, "audio")
|
|
audio.run(name)
|
|
|
|
|
|
@task(name="transcribe")
|
|
def transcribe_task(name, model, device, status=True):
|
|
if status:
|
|
step_status(name, "transcribing")
|
|
transcribe.run(name, model=model, device=device)
|
|
|
|
|
|
@task(name="diarize")
|
|
def diarize_task(name, speaker_count):
|
|
step_status(name, "diarizing")
|
|
diarize.run(name, speakers=speaker_count)
|
|
|
|
|
|
@task(name="speakers")
|
|
def speakers_task(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 shots_task(name, status=True):
|
|
if status:
|
|
step_status(name, "shots")
|
|
shots.run(name)
|
|
|
|
|
|
@task(name="docs", retries=1, retry_delay_seconds=10)
|
|
def docs_task(name):
|
|
step_status(name, "docs")
|
|
docs.run(name)
|
|
|
|
|
|
@task(name="report", retries=1, retry_delay_seconds=10)
|
|
def report_task(name):
|
|
step_status(name, "report")
|
|
report.run(name)
|
|
|
|
|
|
@task(name="memory")
|
|
def memory_task(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.process, self.vision = name, None, None
|
|
|
|
def ensure(self, vision=True):
|
|
if self.process and self.vision != vision:
|
|
self.close()
|
|
self.vision = vision
|
|
log = db.logs(self.name) / ("llama.log" if vision else "llama_text.log")
|
|
try:
|
|
process = llama.start(vision=vision, log=log)
|
|
except Exception as error:
|
|
# 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'"
|
|
) from error
|
|
raise
|
|
# Keep the process we started earlier; llama.start() returns None when a server is already running.
|
|
self.process = self.process or process
|
|
|
|
def close(self):
|
|
if self.process and self.process.poll() is None:
|
|
self.process.terminate()
|
|
self.process.wait() # wait: port must be free before a profile switch
|
|
self.process = None
|
|
|
|
|
|
# Device: GUI/bench file wins, else cuda. Unknown values fall back to cuda.
|
|
def default_device():
|
|
try:
|
|
device_name = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
|
|
return device_name if device_name in ("cuda", "npu") else "cuda"
|
|
except OSError:
|
|
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 is at or after the requested start (--from).
|
|
def should_run(stage):
|
|
return STEPS.index(stage) >= STEPS.index(start_from)
|
|
|
|
# Owns the llama-server process; always closed in the finally block.
|
|
llama_server = 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.
|
|
shots_json_path = db.out_dir(name) / "shots.json"
|
|
try:
|
|
previous_shots = json.loads(shots_json_path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
previous_shots = []
|
|
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 previous_shots:
|
|
for file_name in ("shots.json", "glossary.json"):
|
|
(db.out_dir(name) / file_name).write_text("[]")
|
|
db.replace_shots(name, [])
|
|
if skip_shots and should_run("shots"):
|
|
print("shots skipped")
|
|
# Title/render restart: re-run only text-only post-processing, no vision model needed.
|
|
if start_from == "title":
|
|
llama_server.ensure(vision=False)
|
|
report.retitle(name)
|
|
memory.run(name, link=False)
|
|
elif start_from == "render":
|
|
memory.run(name, link=False)
|
|
else:
|
|
if should_run("audio"):
|
|
audio_task(name)
|
|
|
|
# Speaker labelling: diarize, then name mapping.
|
|
def speaker_chain():
|
|
return (
|
|
[diarize_task(name, speakers), speakers_task(name)]
|
|
if should_run("diarize")
|
|
else ([speakers_task(name)] if should_run("speakers") else None)
|
|
)
|
|
|
|
# NPU path: transcribe on the NPU while shots run on the GPU VLM at the same time.
|
|
if (
|
|
device == "npu"
|
|
and should_run("transcribe")
|
|
and should_run("shots")
|
|
and not skip_shots
|
|
):
|
|
db.set_status(name, "transcribing")
|
|
llama_server.ensure()
|
|
transcribe_future = transcribe_task.submit(name, model, "npu", False)
|
|
shots_future = shots_task.submit(name, False)
|
|
# Wait for NPU transcription; shots keep running meanwhile.
|
|
try:
|
|
transcribe_future.result()
|
|
except Exception as error:
|
|
# Only the NPU failure is handled here; anything else is a real error.
|
|
if "NPU failed" not in repr(error):
|
|
raise
|
|
shots_future.result()
|
|
llama_server.close()
|
|
print("NPU failed, transcribed on cuda")
|
|
transcribe_task(name, model, "cuda")
|
|
# Shots already finished above; clear the handle.
|
|
speaker_chain()
|
|
llama_server.ensure()
|
|
shots_future = None
|
|
else:
|
|
speaker_chain()
|
|
# Shots still running in parallel; wait for them before text stages.
|
|
if shots_future is not None:
|
|
shots_future.result()
|
|
else:
|
|
# Sequential path (CUDA, or NPU without shots).
|
|
if should_run("transcribe"):
|
|
transcribe_task(name, model, device)
|
|
speaker_chain()
|
|
if should_run("shots") and not skip_shots:
|
|
llama_server.ensure()
|
|
shots_task(name)
|
|
llama_server.ensure(
|
|
vision=False
|
|
) # docs queries, report, memory are text-only: drop the vision encoder, use the text profile
|
|
if should_run("docs"):
|
|
docs_task(name)
|
|
if should_run("report"):
|
|
report_task(name)
|
|
# Memory update: always runs as the final stage.
|
|
memory_task(name)
|
|
db.step(name, "done")
|
|
except Exception as error:
|
|
# Record the failure for the GUI, then re-raise so Prefect marks the run failed.
|
|
db.set_status(name, "error", repr(error)[:500])
|
|
raise
|
|
finally:
|
|
llama_server.close()
|
|
|
|
|
|
# Benchmark both transcribers on the same audio and store the choice for default_device().
|
|
def bench(name):
|
|
out_dir = 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=out_dir / "bench_npu.txt")
|
|
except Exception as error:
|
|
print("npu error:", error)
|
|
npu_s = None
|
|
cuda_s = transcribe.run(name, device="cuda", out_path=out_dir / "bench_cuda.txt")
|
|
# NPU is picked unless it failed or is more than 3x slower than CUDA (deliberate tolerance, not fastest-wins).
|
|
chosen_device = "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(chosen_device)
|
|
print(f"npu_s={npu_s} cuda_s={cuda_s} device={chosen_device}")
|
|
|
|
|
|
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")
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("name")
|
|
parser.add_argument("--from", dest="start", default="audio", choices=STEPS)
|
|
parser.add_argument("--speakers", type=int, default=0, help="0 = auto from Teams roster")
|
|
parser.add_argument("--device", choices=["cuda", "npu"])
|
|
parser.add_argument("--bench-npu", action="store_true")
|
|
args = parser.parse_args()
|
|
# --bench-npu is a one-off benchmark; it does not run the pipeline.
|
|
if args.bench_npu:
|
|
bench(args.name)
|
|
else:
|
|
meeting(args.name, args.start, args.speakers, device=args.device)
|