File size: 10,166 Bytes
8562e9b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | #!/usr/bin/env python3
"""Shared deterministic helpers for HFD third-party audio construction."""
from __future__ import annotations
import hashlib
import json
import math
import os
import re
import subprocess
import wave
from pathlib import Path
from typing import Any, Iterable, Sequence
import numpy as np
SAMPLE_RATE = 16_000
WINDOW_SAMPLES = 9_600
STRIDE_SAMPLES = 6_400
OVERLAP_SAMPLES = WINDOW_SAMPLES - STRIDE_SAMPLES
PCM16_SCALE = np.float32(32768.0)
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def canonical_json_bytes(payload: Any) -> bytes:
return json.dumps(
payload,
ensure_ascii=False,
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
def canonical_json_sha256(payload: Any) -> str:
return hashlib.sha256(canonical_json_bytes(payload)).hexdigest()
def stable_u64(*parts: object) -> int:
payload = "\0".join(str(part) for part in parts).encode("utf-8")
return int.from_bytes(hashlib.sha256(payload).digest()[:8], "big")
def write_json_atomic(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
temporary.write_text(
json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
os.replace(temporary, path)
def write_jsonl_atomic(path: Path, rows: Iterable[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
with temporary.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(
json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n"
)
os.replace(temporary, path)
def read_jsonl(path: Path) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
with path.open("r", encoding="utf-8") as handle:
for line_number, line in enumerate(handle, 1):
if not line.strip():
continue
payload = json.loads(line)
if not isinstance(payload, dict):
raise ValueError(f"Expected JSON object at {path}:{line_number}")
rows.append(payload)
return rows
def decode_audio_float(path: Path, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
process = subprocess.run(
[
"ffmpeg",
"-v",
"error",
"-i",
str(path),
"-ac",
"1",
"-ar",
str(sample_rate),
"-f",
"f32le",
"pipe:1",
],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
audio = np.frombuffer(process.stdout, dtype="<f4").copy()
if audio.size <= 0 or not np.isfinite(audio).all():
raise RuntimeError(f"Decoded invalid audio: {path}")
return np.ascontiguousarray(audio, dtype=np.float32)
def read_pcm16_wav(path: Path, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
with wave.open(str(path), "rb") as handle:
contract = (
handle.getnchannels(),
handle.getsampwidth(),
handle.getframerate(),
handle.getcomptype(),
)
expected = (1, 2, sample_rate, "NONE")
if contract != expected:
raise ValueError(
f"Expected mono PCM16 {sample_rate} Hz WAV at {path}, "
f"got {contract}"
)
raw = handle.readframes(handle.getnframes())
return np.frombuffer(raw, dtype="<i2").astype(np.float32) / PCM16_SCALE
def quantize_pcm16(audio: np.ndarray) -> np.ndarray:
value = np.asarray(audio, dtype=np.float32).reshape(-1)
if not np.isfinite(value).all():
raise ValueError("Audio contains NaN or Inf")
return (
np.rint(value * PCM16_SCALE)
.clip(-32768, 32767)
.astype("<i2")
)
def write_pcm16_wav_atomic(
path: Path,
audio: np.ndarray,
sample_rate: int = SAMPLE_RATE,
) -> None:
pcm = quantize_pcm16(audio)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
with wave.open(str(temporary), "wb") as handle:
handle.setnchannels(1)
handle.setsampwidth(2)
handle.setframerate(sample_rate)
handle.writeframes(pcm.tobytes())
os.replace(temporary, path)
def active_rms(audio: np.ndarray) -> float:
value = np.asarray(audio, dtype=np.float32).reshape(-1)
if value.size == 0:
return 0.0
peak = float(np.max(np.abs(value), initial=0.0))
threshold = max(1e-5, peak * 0.02)
active = value[np.abs(value) >= threshold]
if active.size == 0:
active = value
return float(np.sqrt(np.mean(np.square(active), dtype=np.float64)))
def audio_stats(audio: np.ndarray) -> dict[str, float | int]:
value = np.asarray(audio, dtype=np.float32).reshape(-1)
if value.size == 0 or not np.isfinite(value).all():
raise ValueError("Cannot summarize empty or non-finite audio")
return {
"sample_count": int(value.size),
"duration_seconds": float(value.size / SAMPLE_RATE),
"peak": float(np.max(np.abs(value))),
"rms": float(np.sqrt(np.mean(np.square(value), dtype=np.float64))),
"active_rms": active_rms(value),
}
def gain_for_db(reference_rms: float, interference_rms: float, db: float) -> float:
if reference_rms <= 0.0 or interference_rms <= 0.0:
raise ValueError(
f"RMS values must be positive: reference={reference_rms} "
f"interference={interference_rms}"
)
return float(reference_rms / (interference_rms * math.pow(10.0, db / 20.0)))
def measured_db(reference_rms: float, interference_rms: float) -> float:
if reference_rms <= 0.0 or interference_rms <= 0.0:
raise ValueError("Cannot measure a dB ratio with zero RMS")
return float(20.0 * math.log10(reference_rms / interference_rms))
def signal_to_residual_db_on_active_signal(
signal: np.ndarray,
mixture: np.ndarray,
) -> float:
target = np.asarray(signal, dtype=np.float32).reshape(-1)
combined = np.asarray(mixture, dtype=np.float32).reshape(-1)
if target.shape != combined.shape or target.size == 0:
raise ValueError(
f"Signal and mixture must have the same non-empty shape: "
f"{target.shape} != {combined.shape}"
)
if not np.isfinite(target).all() or not np.isfinite(combined).all():
raise ValueError("Signal or mixture contains NaN or Inf")
peak = float(np.max(np.abs(target), initial=0.0))
threshold = max(1e-5, peak * 0.02)
mask = np.abs(target) >= threshold
if not np.any(mask):
raise ValueError("Signal has no active samples")
target_rms = float(
np.sqrt(np.mean(np.square(target[mask]), dtype=np.float64))
)
residual = combined[mask] - target[mask]
residual_rms = float(
np.sqrt(np.mean(np.square(residual), dtype=np.float64))
)
if residual_rms <= 1e-12:
return float("inf")
return measured_db(target_rms, residual_rms)
def reconstruct_overlapping_windows(
windows: Sequence[np.ndarray],
*,
atol: float = 1.0 / 32768.0,
) -> np.ndarray:
if not windows:
raise ValueError("At least one audio window is required")
normalized = [np.asarray(window, dtype=np.float32).reshape(-1) for window in windows]
if any(window.shape != (WINDOW_SAMPLES,) for window in normalized):
raise ValueError("All HFD windows must contain exactly 9,600 samples")
for previous, current in zip(normalized, normalized[1:]):
if not np.allclose(
previous[-OVERLAP_SAMPLES:],
current[:OVERLAP_SAMPLES],
rtol=0.0,
atol=atol,
):
raise ValueError("Adjacent HFD windows disagree in their overlap")
pieces = [normalized[0]]
pieces.extend(window[OVERLAP_SAMPLES:] for window in normalized[1:])
return np.ascontiguousarray(np.concatenate(pieces), dtype=np.float32)
def expected_window_count(sample_count: int) -> int:
count = int(sample_count)
if count < WINDOW_SAMPLES:
return 0
remainder = count - WINDOW_SAMPLES
if remainder % STRIDE_SAMPLES != 0:
raise ValueError(
f"Waveform length is off the HFD grid: samples={sample_count}"
)
return remainder // STRIDE_SAMPLES + 1
def normalize_transcript(text: str) -> str:
return " ".join(re.findall(r"[a-z]+(?:'[a-z]+)?", text.lower()))
COMMAND_WORDS = frozenset(
{
"backward",
"bend",
"bow",
"clap",
"close",
"come",
"continue",
"crawl",
"dance",
"down",
"forward",
"freeze",
"go",
"hold",
"jump",
"kick",
"kneel",
"lean",
"left",
"lift",
"look",
"lower",
"move",
"nod",
"open",
"pause",
"point",
"punch",
"raise",
"reach",
"right",
"rotate",
"run",
"salute",
"shake",
"sit",
"spin",
"squat",
"stand",
"step",
"stop",
"stretch",
"swing",
"turn",
"up",
"wait",
"walk",
"wave",
}
)
def semantic_filter_reason(
transcript: str,
exact_command_phrases: set[str] | None = None,
) -> str | None:
normalized = normalize_transcript(transcript)
words = normalized.split()
if len(words) < 4:
return "too_few_words"
matches = sorted(COMMAND_WORDS.intersection(words))
if matches:
return "command_words:" + ",".join(matches)
for phrase in sorted(exact_command_phrases or set()):
if len(phrase.split()) >= 2 and phrase in normalized:
return f"target_phrase:{phrase}"
return None
|