# /// script # requires-python = ">=3.10,<3.13" # dependencies = ["pyaudiowpatch", "numpy"] # /// """Record Teams (system loopback) + your mic, Ctrl+C to stop, then run the flow (flow.py). Usage: uv run meet.py [--screen] [--name meet_...] Any Teams (desktop or web) works: loopback captures whatever plays on default speakers. """ 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. 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//source.mp4 + source.wav # Output rate: matches what transcription expects (16 kHz mono). 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) # Capture system audio (WASAPI loopback = what plays on the speakers) and the default mic. def record(): audio_interface = pa.PyAudio() # Loopback device and default mic device. 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, 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 callback(data, frame_count, time_info, status_flags, key=key): buffers[key].append(data) return (None, pa.paContinue) # int16 PCM, 1024-frame buffers. 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 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: 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 ffmpeg_process: ffmpeg_process.stdin.write(b"q") ffmpeg_process.stdin.flush() ffmpeg_process.wait() # Stop PortAudio. audio_interface.terminate() # Mix: decode each stream and convert to 16 kHz mono float in [-1, 1]. 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. 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. mixed = np.clip(mixed, -1, 1) path = out / "source.wav" # Write a 16-bit mono WAV. 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( 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 = { 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", args.name], cwd=Path(__file__).parent, env=env ) # Start timestamp stored in the DB row. start_timestamp = time.strftime("%Y-%m-%d %H:%M:%S") # Record, then hand off to the pipeline. finish(record())