Apply ruff lint and rename cryptic identifiers to readable names

This commit is contained in:
Stefano Zini
2026-11-05 09:09:20 +01:00
parent 19de4654ff
commit ead33657c7
24 changed files with 4459 additions and 1856 deletions
+114 -49
View File
@@ -6,93 +6,158 @@
Usage: uv run meet.py [--screen] [--name meet_...]
Any Teams (desktop or web) works: loopback captures whatever plays on default speakers.
"""
import argparse, subprocess, sys, time, wave, threading
import argparse
import subprocess
import time
import wave
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
parser = argparse.ArgumentParser()
parser.add_argument(
"--screen", action="store_true", help="also record screen to mp4 (ffmpeg gdigrab)"
)
parser.add_argument("--name", default=time.strftime("meet_%Y-%m-%dT%H-%M-%S"))
parser.add_argument("--seconds", type=float, help="auto-stop after N seconds")
args = parser.parse_args()
out = Path(__file__).parent / "out" / args.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
SAMPLE_RATE = 16000
# Downmix to mono, then resample to SAMPLE_RATE by linear interpolation (simple, fine for speech).
def to16k(samples, channels, sample_rate):
samples = samples.reshape(-1, channels).mean(axis=1)
count = int(len(samples) * SAMPLE_RATE / sample_rate)
return np.interp(
np.linspace(0, len(samples) - 1, count), np.arange(len(samples)), samples
).astype(np.float32)
# 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()
audio_interface = 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": []}
loopback_device = audio_interface.get_default_wasapi_loopback()
mic_device = audio_interface.get_device_info_by_index(
audio_interface.get_host_api_info_by_type(pa.paWASAPI)["defaultInputDevice"]
)
buffers = {"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"])
for key, device in (("sys", loopback_device), ("mic", mic_device)):
channels, sample_rate = int(device["maxInputChannels"]), int(device["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)
def callback(data, frame_count, time_info, status_flags, key=key):
buffers[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
stream = audio_interface.open(
format=pa.paInt16,
channels=channels,
rate=sample_rate,
input=True,
input_device_index=device["index"],
frames_per_buffer=1024,
stream_callback=callback,
)
streams.append((key, channels, sample_rate, stream))
print(f"loopback: {loopback_device['name']}\nmic: {mic_device['name']}")
ffmpeg_process = 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)
if args.screen:
ffmpeg_process = 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
start_time = time.time()
while not args.seconds or time.time() - start_time < args.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()
if ffmpeg_process:
ffmpeg_process.stdin.write(b"q")
ffmpeg_process.stdin.flush()
ffmpeg_process.wait()
# Stop PortAudio.
p.terminate()
audio_interface.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))
mixed_sources = []
for key, channels, sample_rate, _stream in streams:
raw = np.frombuffer(b"".join(buffers[key]), dtype=np.int16).astype(np.float32) / 32768
if len(raw):
mixed_sources.append(
to16k(raw[: len(raw) // channels * channels], channels, sample_rate)
)
# 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)
max_length = max(len(source) for source in mixed_sources)
mixed = sum(np.pad(source, (0, max_length - len(source))) for source in mixed_sources)
# Clip to avoid overflow when summing.
y = np.clip(y, -1, 1)
mixed = np.clip(mixed, -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())
with wave.open(str(path), "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(SAMPLE_RATE)
wav_file.writeframes((mixed * 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")
db.upsert_recording(
args.name, source="meet", started_at=start_timestamp, 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")}
env = {
key: value
for key, value in os.environ.items()
if key 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)
subprocess.run(
["uv", "run", "--script", "flow.py", args.name], cwd=Path(__file__).parent, env=env
)
# Start timestamp stored in the DB row.
T0 = time.strftime("%Y-%m-%d %H:%M:%S")
start_timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
# Record, then hand off to the pipeline.
finish(record())