Add explanatory comments across codebase

This commit is contained in:
Stefano Zini
2026-11-04 14:23:18 +01:00
parent b8aa5548a2
commit 82b72b6c28
34 changed files with 934 additions and 0 deletions
+22
View File
@@ -11,66 +11,88 @@ from pathlib import Path
import numpy as np
import pyaudiowpatch as pa
# CLI: --screen adds video, --name sets the folder under out/, --seconds auto-stops.
ap = argparse.ArgumentParser()
ap.add_argument("--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)")
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")
a = ap.parse_args()
out = Path(__file__).parent / "out" / a.name; out.mkdir(parents=True, exist_ok=True) # out/<name>/source.mp4 + source.wav
# Output rate: matches what transcription expects (16 kHz mono).
SR = 16000
# Downmix to mono, then resample to SR by linear interpolation (simple, fine for speech).
def to16k(x, ch, sr):
x = x.reshape(-1, ch).mean(axis=1)
n = int(len(x) * SR / sr)
return np.interp(np.linspace(0, len(x) - 1, n), np.arange(len(x)), x).astype(np.float32)
# Capture system audio (WASAPI loopback = what plays on the speakers) and the default mic.
def record():
p = pa.PyAudio()
# Loopback device and default mic device.
lb = p.get_default_wasapi_loopback()
mic = p.get_device_info_by_index(p.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"])
bufs = {"sys": [], "mic": []}
streams = []
# One stream per source, at the device's own channel count and rate; converted to 16 kHz mono in the mix step.
for key, d in (("sys", lb), ("mic", mic)):
ch, sr = int(d["maxInputChannels"]), int(d["defaultSampleRate"])
# Callback appends raw PCM chunks; paContinue keeps the stream running.
def cb(data, f, t, s, key=key): bufs[key].append(data); return (None, pa.paContinue)
# int16 PCM, 1024-frame buffers.
st = p.open(format=pa.paInt16, channels=ch, rate=sr, input=True,
input_device_index=d["index"], frames_per_buffer=1024, stream_callback=cb)
streams.append((key, ch, sr, st))
print(f"loopback: {lb['name']}\nmic: {mic['name']}")
ff = None
# Optional screen capture: ffmpeg gdigrab at 15 fps, H.264 mp4.
if a.screen:
ff = subprocess.Popen(["ffmpeg", "-y", "-f", "gdigrab", "-framerate", "15", "-i", "desktop",
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
str(out / "source.mp4")], stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("Recording... Ctrl+C to stop")
# Wait until Ctrl+C or the --seconds limit.
try:
t0 = time.time()
while not a.seconds or time.time() - t0 < a.seconds: time.sleep(0.5)
except KeyboardInterrupt: pass
# Send 'q' so ffmpeg finalises the mp4 cleanly.
if ff: ff.stdin.write(b"q"); ff.stdin.flush(); ff.wait()
# Stop PortAudio.
p.terminate()
# Mix: decode each stream and convert to 16 kHz mono float in [-1, 1].
mix = []
for key, ch, sr, st in streams:
raw = np.frombuffer(b"".join(bufs[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw): mix.append(to16k(raw[: len(raw) // ch * ch], ch, sr))
# Pad shorter streams with silence and sum them.
n = max(len(m) for m in mix)
y = sum(np.pad(m, (0, n - len(m))) for m in mix)
# Clip to avoid overflow when summing.
y = np.clip(y, -1, 1)
path = out / "source.wav"
# Write a 16-bit mono WAV.
with wave.open(str(path), "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR)
w.writeframes((y * 32767).astype(np.int16).tobytes())
return path
# Save the DB row, then run the transcription/report pipeline (flow.py) as a child uv process.
def finish(path):
import os
import db
now = time.strftime("%Y-%m-%d %H:%M:%S")
# Queued DB row with the start and end time.
db.upsert_recording(a.name, source="meet", started_at=T0, ended_at=now, status="queued")
# Drop inherited PYTHONHOME vars so the child uv/python picks its own interpreter.
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
# Point the child at the local Prefect server; bypass the proxy for localhost.
env.update(PREFECT_API_URL="http://127.0.0.1:4200/api", NO_PROXY="127.0.0.1,localhost")
subprocess.run(["uv", "run", "--script", "flow.py", a.name], cwd=Path(__file__).parent, env=env)
# Start timestamp stored in the DB row.
T0 = time.strftime("%Y-%m-%d %H:%M:%S")
# Record, then hand off to the pipeline.
finish(record())