77 lines
3.4 KiB
Python
77 lines
3.4 KiB
Python
# /// 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, subprocess, sys, time, wave, threading
|
|
from pathlib import Path
|
|
import numpy as np
|
|
import pyaudiowpatch as pa
|
|
|
|
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
|
|
SR = 16000
|
|
|
|
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)
|
|
|
|
def record():
|
|
p = pa.PyAudio()
|
|
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 = []
|
|
for key, d in (("sys", lb), ("mic", mic)):
|
|
ch, sr = int(d["maxInputChannels"]), int(d["defaultSampleRate"])
|
|
def cb(data, f, t, s, key=key): bufs[key].append(data); return (None, pa.paContinue)
|
|
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
|
|
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")
|
|
try:
|
|
t0 = time.time()
|
|
while not a.seconds or time.time() - t0 < a.seconds: time.sleep(0.5)
|
|
except KeyboardInterrupt: pass
|
|
if ff: ff.stdin.write(b"q"); ff.stdin.flush(); ff.wait()
|
|
p.terminate()
|
|
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))
|
|
n = max(len(m) for m in mix)
|
|
y = sum(np.pad(m, (0, n - len(m))) for m in mix)
|
|
y = np.clip(y, -1, 1)
|
|
path = out / "source.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
|
|
|
|
def finish(path):
|
|
import os
|
|
import db
|
|
now = time.strftime("%Y-%m-%d %H:%M:%S")
|
|
db.upsert_recording(a.name, source="meet", started_at=T0, ended_at=now, status="queued")
|
|
env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")}
|
|
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)
|
|
|
|
T0 = time.strftime("%Y-%m-%d %H:%M:%S")
|
|
finish(record())
|