CRICKET / code /audio.py
d9993r's picture
Add files using upload-large-folder tool
14c58d8 verified
Raw History Blame Contribute Delete
6.26 kB
"""Audio: bat-on-ball sound onsets (section 7.3) and speech transcription (section 7.5).
Bat contact makes a short broadband 'crack'. We take the clip's audio, compute
spectral flux in the 2-8 kHz band every 5 ms, and pick the sharpest onset in the
window where contact is plausible. At 25-30 fps video, audio (5 ms steps) can
time contact more finely than frames can.
Speech (coach voice or commentary) is transcribed with faster-whisper if it is
installed (pip install faster-whisper). Segments keep word timestamps so they can
be attached to deliveries by time. Treated as model output (source_type model_asr)
and kept apart from typed coach notes."""
import json
import shutil
import subprocess
from pathlib import Path
import numpy as np
SR = 16000
def has_audio(path):
if not shutil.which("ffprobe"):
return False
out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "a", "-show_entries", "stream=index",
"-of", "csv=p=0", str(path)], capture_output=True, text=True).stdout
return bool(out.strip())
def load_audio(path, start_s=0.0, dur_s=None):
"""Mono float32 PCM at 16 kHz via ffmpeg, or None if there is no audio."""
if not shutil.which("ffmpeg") or not has_audio(path):
return None
cmd = ["ffmpeg", "-v", "error", "-ss", f"{start_s:.3f}", "-i", str(path)]
if dur_s:
cmd += ["-t", f"{dur_s:.3f}"]
cmd += ["-vn", "-ac", "1", "-ar", str(SR), "-f", "f32le", "-"]
raw = subprocess.run(cmd, capture_output=True).stdout
a = np.frombuffer(raw, dtype=np.float32)
return a if a.size > SR // 10 else None
def onset_strength(a, hop=80, win=512, band=(2000, 8000)):
"""Spectral flux in a high band, normalised by its median. One value per 5 ms."""
if a is None or a.size < win * 2:
return None, None
n = 1 + (a.size - win) // hop
idx = np.arange(win)[None, :] + hop * np.arange(n)[:, None]
frames = a[idx] * np.hanning(win)[None, :]
spec = np.abs(np.fft.rfft(frames, axis=1))
f = np.fft.rfftfreq(win, 1 / SR)
sel = (f >= band[0]) & (f <= band[1])
s = np.log1p(spec[:, sel] * 100)
flux = np.maximum(np.diff(s, axis=0), 0).sum(axis=1)
flux = np.concatenate([[0], flux])
med = np.median(flux) + 1e-6
times = (np.arange(n) * hop + win / 2) / SR
return times, flux / med
def contact_from_sound(a, lo_s, hi_s, min_ratio=6.0):
"""Sharpest onset in [lo_s, hi_s] (seconds from the start of `a`)."""
times, f = onset_strength(a)
if times is None:
return None
m = (times >= lo_s) & (times <= hi_s)
if not m.any():
return None
i = np.flatnonzero(m)[int(np.argmax(f[m]))]
if f[i] < min_ratio:
return None
return {"t": float(times[i]), "strength": round(float(f[i]), 1),
"confidence": round(float(min(0.6, f[i] / (3 * min_ratio))), 3)}
def _transcribe_faster_whisper(path, acfg):
from faster_whisper import WhisperModel
model = WhisperModel(acfg.get("whisper_model", "small"), device="cpu", compute_type="int8")
segs, info = model.transcribe(str(path), language=acfg.get("language"), word_timestamps=True, vad_filter=True)
out = []
for s in segs:
out.append({"start": round(s.start, 3), "end": round(s.end, 3), "text": s.text.strip(), "speaker": None,
"words": [{"w": w.word.strip(), "s": round(w.start, 3), "e": round(w.end, 3),
"score": round(float(w.probability), 3), "speaker": None} for w in (s.words or [])]})
return {"status": "ok", "engine": "faster_whisper", "model": f"faster-whisper:{acfg.get('whisper_model', 'small')}",
"language": info.language, "word_timestamps": True,
"notes": [],
"segments": out, "speakers": {}}
def transcribe(path, acfg=None, out_json=None, model_size=None, language=None):
"""Speech to text with word timestamps (faster-whisper, CPU)."""
if isinstance(acfg, str) or acfg is None: # backwards compatible signature
acfg = {"whisper_model": acfg or model_size or "small", "language": language}
if not has_audio(path):
out = {"status": "skipped", "reason": "no audio track"}
else:
try:
out = _transcribe_faster_whisper(path, acfg)
except ImportError:
out = {"status": "skipped", "reason": "pip install faster-whisper to transcribe speech"}
if out_json:
Path(out_json).parent.mkdir(parents=True, exist_ok=True)
json.dump(out, open(out_json, "w"), ensure_ascii=False)
return out
def segments_in_window(transcript, start_s, end_s, roles=None):
"""Transcript segments overlapping a delivery window, re-timed to clip time."""
out = []
for s in (transcript or {}).get("segments", []):
if s["end"] < start_s or s["start"] > end_s:
continue
out.append({"t_clip_start": round(max(0.0, s["start"] - start_s), 3),
"t_clip_end": round(min(end_s, s["end"]) - start_s, 3), "text": s["text"],
"words": [{"w": w["w"], "t": round(w["s"] - start_s, 3), "e": round(w["e"] - start_s, 3)}
for w in s.get("words", []) if start_s <= w["s"] <= end_s]})
return out
def av_offset(path_a, path_b, max_lag_s=10.0, dur_s=60.0):
"""Time offset between two recordings of the same session from their audio
(e.g. two phones and a clap). Positive = B started later than A."""
a, b = load_audio(path_a, 0, dur_s), load_audio(path_b, 0, dur_s)
if a is None or b is None:
return None
ta, fa = onset_strength(a)
tb, fb = onset_strength(b)
n = 1 << int(np.ceil(np.log2(len(fa) + len(fb))))
xc = np.fft.irfft(np.fft.rfft(fa - fa.mean(), n) * np.conj(np.fft.rfft(fb - fb.mean(), n)), n)
step = ta[1] - ta[0]
maxlag = int(max_lag_s / step)
lags = np.concatenate([np.arange(0, maxlag), np.arange(-maxlag, 0)])
vals = np.concatenate([xc[:maxlag], xc[-maxlag:]])
k = int(np.argmax(vals))
peak, second = vals[k], np.sort(vals)[-int(0.2 / step) - 1] if len(vals) > 50 else 0
return {"offset_s": round(-float(lags[k]) * step, 3), "confidence": round(float(min(1.0, (peak - second) / (abs(peak) + 1e-9) * 5)), 3)}