AudioSpan / prepare /prepare_anchor.py
holvan's picture
Add files using upload-large-folder tool
57c7939 verified
Raw
History Blame Contribute Delete
14.3 kB
#!/usr/bin/env python3
"""Rebuild anchor (edited) audio from native audio + replay manifest.
Reproduces, for each record in ``anchor_manifest.jsonl``, the edit that
produced the anchor recording from its native source:
addition overlay sound events at SNR-calibrated volume
deletion hard silence or blurred masking of regions
modification region-scoped volume or speed change
Only ``ffmpeg``/``ffprobe`` are required. Replay is exact except for
blur_mask, whose rendering params were randomized in the original pipeline
and are replaced with fixed defaults (the masked regions stay exact, which
is what the questions depend on).
Usage:
python prepare_anchor.py [--manifest metadata/media/anchor/anchor_manifest.jsonl]
[--root .] [--only OPERATION] [--overwrite] [--dry-run]
"""
import argparse
import json
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
def ffprobe_format(path: Path) -> tuple[int, int]:
"""Return (sample_rate, channels) of the first audio stream."""
proc = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "a:0",
"-show_entries", "stream=sample_rate,channels",
"-of", "csv=p=0", str(path)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
rate, ch = proc.stdout.decode().strip().split(",")
return int(rate), int(ch)
def read_jsonl(path: Path) -> list[dict]:
with open(path, encoding="utf-8") as fh:
return [json.loads(line) for line in fh if line.strip()]
def run(cmd: list[str], dry_run: bool = False) -> None:
if dry_run:
print(" [dry-run] " + " ".join(cmd[:8]) + " ...")
return
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.returncode != 0:
err = proc.stderr.decode("utf-8", errors="replace").strip()
raise RuntimeError(f"command failed (rc={proc.returncode}): {' '.join(cmd[:6])}...\n{err[-800:]}")
def ffprobe_duration(path: Path) -> float:
proc = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", str(path)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
return float(proc.stdout.decode().strip())
def analyze_rms_db(path: Path, start: float | None = None, dur: float | None = None) -> float:
"""Return RMS loudness (dB) of a file or a region of it."""
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "info"]
if start is not None:
cmd += ["-ss", f"{start}"]
if dur is not None:
cmd += ["-t", f"{dur}"]
cmd += ["-i", str(path), "-af", "volumedetect", "-f", "null", "-"]
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
text = proc.stderr.decode("utf-8", errors="replace")
m = re.search(r"mean_volume: ([-\d.]+) dB", text)
return float(m.group(1)) if m else -30.0
def out_codec_args(rate: int | None = None, channels: int | None = None) -> list[str]:
args = ["-c:a", "flac"]
if rate is not None:
args += ["-ar", str(rate)]
if channels is not None:
args += ["-ac", str(channels)]
return args
def resolve_event(manifest_path: str, events_dir: Path) -> Path:
"""Map a manifest event path to the local audio/events/ file."""
return events_dir / Path(manifest_path).name
def replay_addition(rec: dict, native: Path, out: Path, events_dir: Path, dry_run: bool,
fmt: tuple[int, int] | None = None) -> None:
positions = rec["params"]["positions"]
inputs = ["-i", str(native)]
filter_parts = []
mix_inputs = ["[0:a]"]
for idx, pos in enumerate(positions, start=1):
event_path = resolve_event(pos["event_audio_path"], events_dir)
if not event_path.is_file() and not dry_run:
raise FileNotFoundError(f"event audio missing: {event_path}")
inputs += ["-i", str(event_path)]
offset_ms = int(float(pos["position_sec"]) * 1000)
volume_db = pos.get("volume_db")
if volume_db is None:
snr = float(pos["snr_db"])
region_dur = float(pos.get("duration_sec") or 3.0)
bg_rms = analyze_rms_db(native, float(pos["position_sec"]), region_dur) if not dry_run else -25.0
ev_rms = analyze_rms_db(event_path) if not dry_run else -25.0
volume_db = round((bg_rms + snr) - ev_rms, 1)
volume_db = max(-30.0, min(30.0, volume_db))
label = f"evt{idx}"
filter_parts.append(f"[{idx}:a]adelay={offset_ms}|{offset_ms},volume={volume_db}dB[{label}]")
mix_inputs.append(f"[{label}]")
weights = " ".join(["1"] * len(mix_inputs))
filter_parts.append(
f"{''.join(mix_inputs)}amix=inputs={len(mix_inputs)}:duration=first"
f":dropout_transition=0:normalize=0:weights={weights}[mixed]"
)
rate, channels = fmt if fmt else (None, None)
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *inputs,
"-filter_complex", ";".join(filter_parts), "-map", "[mixed]",
*out_codec_args(rate, channels), str(out)]
run(cmd, dry_run)
def replay_deletion(rec: dict, native: Path, out: Path, dry_run: bool) -> None:
mask_type = rec["params"].get("mask_type", "hard_mask")
regions = rec["params"]["regions"]
if mask_type == "hard_mask":
filters = [f"volume=enable='between(t,{s},{e})':volume=0" for s, e in regions]
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", str(native),
"-af", ",".join(filters), *out_codec_args(), str(out)]
run(cmd, dry_run)
return
if mask_type == "blur_mask":
_replay_blur_mask(native, out, regions, dry_run)
return
raise ValueError(f"unsupported mask_type: {mask_type}")
def _replay_blur_mask(native: Path, out: Path, regions: list, dry_run: bool) -> None:
"""Deterministic blur mask (original used randomized params; regions are exact)."""
lowpass_freq = 300
blur_attenuation_db = -6.0
noise_level_db = -8.0
fade_sec = 0.5
noise_color = "pink"
dynamic_noise = True
fluct_db = 3.0
fluct_rate = 0.8
blur_gain = 10 ** (blur_attenuation_db / 20)
noise_gain = 10 ** (noise_level_db / 20)
if dynamic_noise:
lo = noise_gain * (10 ** (-fluct_db / 20))
hi = noise_gain * (10 ** (+fluct_db / 20))
rng = hi - lo
r1 = 2 * math.pi * fluct_rate
r2 = 2 * math.pi * (fluct_rate * 2.3)
noise_expr = f"{lo:.8f}+({rng:.8f})*(0.5+0.3*sin({r1}*t)+0.2*sin({r2}*t))"
else:
noise_expr = f"{noise_gain:.6f}"
valid = [(float(s), float(e)) for s, e in regions if float(e) > float(s)]
total_duration = ffprobe_duration(native) if not dry_run else 300.0
orig_parts, blur_parts = [], []
for s, e in valid:
seg_dur = e - s
eff_fade = min(fade_sec, seg_dur / 2.5)
fie, fos = s + eff_fade, e - eff_fade
orig_parts.append(
f"if(between(t,{s},{fie}),(({fie}-t)/{eff_fade:.4f}),"
f"if(between(t,{fie},{fos}),0,"
f"if(between(t,{fos},{e}),((t-{fos})/{eff_fade:.4f}),1)))"
)
blur_parts.append(
f"if(between(t,{s},{fie}),((t-{s})/{eff_fade:.4f}),"
f"if(between(t,{fie},{fos}),1,"
f"if(between(t,{fos},{e}),(({e}-t)/{eff_fade:.4f}),0)))"
)
if len(valid) == 1:
orig_env, blur_env = orig_parts[0], blur_parts[0]
else:
orig_env, blur_env = "1", "0"
for i in range(len(valid) - 1, -1, -1):
s, e = valid[i]
orig_env = f"if(between(t,{s},{e}),{orig_parts[i]},{orig_env})"
blur_env = f"if(between(t,{s},{e}),{blur_parts[i]},{blur_env})"
filter_complex = (
f"[0:a]asplit=2[orig][to_blur];"
f"[to_blur]lowpass=f={lowpass_freq},volume={blur_gain:.6f}[blurred];"
f"[1:a]volume='{noise_expr}':eval=frame[noise_scaled];"
f"[blurred][noise_scaled]amix=inputs=2:duration=first:weights=3 1[blur_noise];"
f"[orig]volume='{orig_env}':eval=frame[orig_env];"
f"[blur_noise]volume='{blur_env}':eval=frame[blur_env];"
f"[orig_env][blur_env]amix=inputs=2:duration=first:normalize=0[out]"
)
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-i", str(native),
"-f", "lavfi", "-i",
f"anoisesrc=color={noise_color}:duration={total_duration:.2f}:sample_rate=16000",
"-filter_complex", filter_complex, "-map", "[out]",
*out_codec_args(), str(out)]
run(cmd, dry_run)
def _atempo_chain(factor: float) -> str:
parts = []
remaining = factor
while remaining > 2.0:
parts.append("atempo=2.0")
remaining /= 2.0
while remaining < 0.5:
parts.append("atempo=0.5")
remaining /= 0.5
parts.append(f"atempo={remaining:.4f}")
return ",".join(parts)
def replay_modification(rec: dict, native: Path, out: Path, dry_run: bool) -> None:
kind = rec["params"]["kind"]
regions = rec["params"]["regions"]
if kind == "volume":
filters = []
for region in regions:
s, e = region["region_sec"]
gain = 10 ** (float(region["delta_db"]) / 20)
filters.append(f"volume=enable='between(t,{s},{e})':volume={gain}")
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", str(native),
"-af", ",".join(filters), *out_codec_args(), str(out)]
run(cmd, dry_run)
return
if kind == "speed":
_replay_speed(native, out, regions, dry_run)
return
raise ValueError(f"unsupported modification kind: {kind}")
def _replay_speed(native: Path, out: Path, regions: list, dry_run: bool) -> None:
"""Apply region-scoped atempo and re-concatenate. Regions use original timeline."""
total = ffprobe_duration(native) if not dry_run else 600.0
segs = sorted(regions, key=lambda r: r["region_sec"][0])
# Build a clip plan: (kind, start, end, factor)
plan = []
cursor = 0.0
for region in segs:
s, e = region["region_sec"]
factor = float(region["speed_factor"])
if s > cursor + 0.05:
plan.append(("copy", cursor, s, None))
plan.append(("atempo", s, e, factor))
cursor = e
if cursor < total - 0.05:
plan.append(("copy", cursor, total, None))
if dry_run:
print(f" [dry-run] speed modification: {len(plan)} clips")
return
tmpdir = tempfile.mkdtemp(prefix="anchor_speed_")
try:
clip_paths = []
for i, (kind, s, e, factor) in enumerate(plan):
seg_path = os.path.join(tmpdir, f"seg_{i:03d}.flac")
extract = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-ss", f"{s}", "-to", f"{e}", "-i", str(native),
*out_codec_args(), seg_path]
run(extract)
if kind == "atempo":
tempo_path = os.path.join(tmpdir, f"seg_{i:03d}_tempo.flac")
run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-i", seg_path, "-af", _atempo_chain(factor),
*out_codec_args(), tempo_path])
clip_paths.append(tempo_path)
else:
clip_paths.append(seg_path)
concat_list = os.path.join(tmpdir, "concat.txt")
with open(concat_list, "w", encoding="utf-8") as fh:
for p in clip_paths:
fh.write(f"file '{p}'\n")
run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-f", "concat", "-safe", "0", "-i", concat_list,
*out_codec_args(), str(out)])
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
def process_record(rec: dict, root: Path, overwrite: bool, dry_run: bool) -> str:
media_id = rec["media_id"]
operation = rec["operation"]
native = root / "audio" / "native" / Path(rec["native_audio_path"]).name
out = root / "audio" / "anchor" / Path(rec["target_audio_path"]).name
events_dir = root / "audio" / "events"
if out.is_file() and not overwrite and not dry_run:
return "skip"
if not native.is_file() and not dry_run:
return "missing-native"
out.parent.mkdir(parents=True, exist_ok=True)
if operation == "addition":
fmt = None if dry_run else ffprobe_format(native)
replay_addition(rec, native, out, events_dir, dry_run, fmt)
elif operation == "deletion":
replay_deletion(rec, native, out, dry_run)
elif operation == "modification":
replay_modification(rec, native, out, dry_run)
else:
return f"unknown-operation:{operation}"
return "ok"
def main():
parser = argparse.ArgumentParser(description="Rebuild anchor audio from manifest")
parser.add_argument("--manifest", default="metadata/media/anchor/anchor_manifest.jsonl")
parser.add_argument("--root", default=".", help="release root (contains audio/ + prepare/)")
parser.add_argument("--only", choices=["addition", "deletion", "modification"],
help="process only this operation")
parser.add_argument("--overwrite", action="store_true")
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--limit", type=int, default=0, help="process at most N records (debug)")
args = parser.parse_args()
root = Path(args.root).resolve()
manifest_path = root / args.manifest
if not manifest_path.is_file():
print(f"ERROR: manifest not found: {manifest_path}", file=sys.stderr)
sys.exit(1)
records = read_jsonl(manifest_path)
if args.only:
records = [r for r in records if r["operation"] == args.only]
if args.limit:
records = records[:args.limit]
print(f"Processing {len(records)} anchor records (root={root})")
counts = {}
for rec in records:
status = process_record(rec, root, args.overwrite, args.dry_run)
counts[status] = counts.get(status, 0) + 1
if status not in ("ok", "skip"):
print(f" [{status}] {rec['media_id']} ({rec['operation']})")
print("Summary:", counts)
if __name__ == "__main__":
main()