Apply ruff lint and rename cryptic identifiers to readable names
This commit is contained in:
+200
-79
@@ -4,8 +4,10 @@
|
||||
# ///
|
||||
# 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.
|
||||
@@ -16,186 +18,305 @@ 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
|
||||
# stdlib only: CLI args, JSON, paths, exit codes.
|
||||
import argparse, json, sys
|
||||
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
|
||||
# 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"]
|
||||
# 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, s):
|
||||
def step_status(name, stage):
|
||||
# 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)
|
||||
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 t_audio(name): step_status(name, "audio"); audio.run(name)
|
||||
def audio_task(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")
|
||||
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 t_diarize(name, n): step_status(name, "diarizing"); diarize.run(name, speakers=n)
|
||||
def diarize_task(name, speaker_count):
|
||||
step_status(name, "diarizing")
|
||||
diarize.run(name, speakers=speaker_count)
|
||||
|
||||
|
||||
@task(name="speakers")
|
||||
def t_speakers(name): step_status(name, "identifying"); speakers.run(name)
|
||||
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 t_shots(name, status=True):
|
||||
if status: step_status(name, "shots")
|
||||
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 t_docs(name): step_status(name, "docs"); docs.run(name)
|
||||
def docs_task(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)
|
||||
def report_task(name):
|
||||
step_status(name, "report")
|
||||
report.run(name)
|
||||
|
||||
|
||||
@task(name="memory")
|
||||
def t_memory(name): step_status(name, "memory"); memory.run(name)
|
||||
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.p, self.vision = name, None, None
|
||||
|
||||
def __init__(self, name):
|
||||
self.name, self.process, self.vision = name, None, None
|
||||
|
||||
def ensure(self, vision=True):
|
||||
if self.p and self.vision != vision: self.close()
|
||||
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:
|
||||
p = llama.start(vision=vision, log=log)
|
||||
except Exception:
|
||||
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'")
|
||||
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.p = self.p or p
|
||||
self.process = self.process or process
|
||||
|
||||
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
|
||||
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:
|
||||
d = (db.GLOBAL / "transcribe_device.txt").read_text().strip()
|
||||
return d if d in ("cuda", "npu") else "cuda"
|
||||
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):
|
||||
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)
|
||||
|
||||
# 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.
|
||||
L = Llama(name)
|
||||
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.
|
||||
sj = db.out_dir(name) / "shots.json"
|
||||
try: done = json.loads(sj.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError): done = []
|
||||
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 done:
|
||||
for f in ("shots.json", "glossary.json"): (db.out_dir(name) / f).write_text("[]")
|
||||
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 go("shots"): print("shots skipped")
|
||||
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":
|
||||
L.ensure(vision=False)
|
||||
llama_server.ensure(vision=False)
|
||||
report.retitle(name)
|
||||
memory.run(name, link=False)
|
||||
elif start_from == "render":
|
||||
memory.run(name, link=False)
|
||||
else:
|
||||
if go("audio"): t_audio(name)
|
||||
if should_run("audio"):
|
||||
audio_task(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)
|
||||
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 go("transcribe") and go("shots") and not skip_shots:
|
||||
if (
|
||||
device == "npu"
|
||||
and should_run("transcribe")
|
||||
and should_run("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)
|
||||
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:
|
||||
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()
|
||||
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")
|
||||
t_transcribe(name, model, "cuda")
|
||||
transcribe_task(name, model, "cuda")
|
||||
# Shots already finished above; clear the handle.
|
||||
spk_chain(); L.ensure(); f_s = None
|
||||
speaker_chain()
|
||||
llama_server.ensure()
|
||||
shots_future = None
|
||||
else:
|
||||
spk_chain()
|
||||
speaker_chain()
|
||||
# Shots still running in parallel; wait for them before text stages.
|
||||
if f_s is not None: f_s.result()
|
||||
if shots_future is not None:
|
||||
shots_future.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)
|
||||
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.
|
||||
t_memory(name)
|
||||
memory_task(name)
|
||||
db.step(name, "done")
|
||||
except Exception as e:
|
||||
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(e)[:500])
|
||||
db.set_status(name, "error", repr(error)[:500])
|
||||
raise
|
||||
finally:
|
||||
L.close()
|
||||
llama_server.close()
|
||||
|
||||
|
||||
# Benchmark both transcribers on the same audio and store the choice for default_device().
|
||||
def bench(name):
|
||||
d = db.out_dir(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=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")
|
||||
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).
|
||||
dev = "cuda" if npu_s is None or npu_s > 3 * cuda_s else "npu"
|
||||
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(dev)
|
||||
print(f"npu_s={npu_s} cuda_s={cuda_s} device={dev}")
|
||||
(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)
|
||||
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.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=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()
|
||||
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 a.bench_npu: bench(a.name)
|
||||
else: meeting(a.name, a.start, a.speakers, device=a.device)
|
||||
if args.bench_npu:
|
||||
bench(args.name)
|
||||
else:
|
||||
meeting(args.name, args.start, args.speakers, device=args.device)
|
||||
|
||||
Reference in New Issue
Block a user