Download fix_section_timings.py from baniguru/speech_data_recordings: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/baniguru/speech_data_recordings/resolve/main/fix_section_timings.py
- Command line
-
hf download hf://datasets/baniguru/speech_data_recordings/fix_section_timings.py
-
curl -L -o fix_section_timings.py https://huggingface.co/datasets/baniguru/speech_data_recordings/resolve/main/fix_section_timings.py
12.9 kB
| #!/usr/bin/env python3 | |
| """Adjust section timings in JSON files in each immediate child folder. | |
| Python 3.9+; dependencies: numpy, scipy, and the ffmpeg executable. | |
| python3 -m pip install numpy scipy | |
| python3 fix_section_timings.py /path/to/parent --dry-run | |
| python3 fix_section_timings.py /path/to/parent | |
| The parent contains child folders such as ang1, ang2, ... with an MP3 and a | |
| JSON object containing audio_file and sections. There is no folder-count limit. | |
| Only start_time/end_time change. Sections are not merged, and text, IDs, other | |
| metadata, folder names, filenames, and audio bytes remain unchanged. | |
| JSON files are overwritten in place. No backup or sidecar files are created | |
| or read. Each run uses the timestamps currently in the JSON files. | |
| Processing is sequential, CPU-only, one audio file at a time. No ASR model, | |
| database, network access, or GPU is needed. Existing timestamps must already | |
| approximately locate the right speech; this is waveform refinement, not | |
| transcription or forced alignment. Settings below reproduce ang1-5_fixed.zip | |
| (the revision with the example onset at 24.040 seconds). | |
| The RMS heuristic rejects weak noise, but cannot perfectly distinguish speech | |
| from loud noise or music. A file without a reliable onset is left unchanged. | |
| """ | |
| import argparse | |
| import copy | |
| import json | |
| import math | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import stat | |
| import subprocess | |
| import sys | |
| import tempfile | |
| try: | |
| import numpy as np | |
| from scipy.ndimage import binary_closing | |
| except ImportError as exc: | |
| raise SystemExit("Install dependencies: python3 -m pip install numpy scipy") from exc | |
| # These defaults are the settings verified against the supplied fixed ZIP. | |
| SAMPLE_RATE = 16000 | |
| FRAME_SAMPLES = 160 # 10 ms RMS window | |
| HOP_SAMPLES = 16 # 1 ms envelope spacing | |
| STRONG_DB = -30.0 | |
| EDGE_DB = -35.0 | |
| FALLBACK_END_DB = -32.0 | |
| class TimingError(Exception): | |
| """A file cannot be refined safely using its current structure/timings.""" | |
| def runs(mask): | |
| delta = np.diff(np.r_[False, mask, False].astype(int)) | |
| return list(zip(np.flatnonzero(delta == 1), np.flatnonzero(delta == -1))) | |
| def activity(db, lo, hi, threshold=STRONG_DB, ms=25): | |
| a = max(0, round(lo * 1000)) | |
| b = min(len(db), round(hi * 1000)) | |
| if b <= a: | |
| return [] | |
| mask = binary_closing(db[a:b] > threshold, | |
| structure=np.ones(11), border_value=0) | |
| return [((a + s) / 1000, (a + e) / 1000 + .01) | |
| for s, e in runs(mask) if e - s >= ms] | |
| def decode_audio(path, ffmpeg): | |
| result = subprocess.run( | |
| [ffmpeg, "-nostdin", "-v", "error", "-i", str(path), | |
| "-ac", "1", "-ar", str(SAMPLE_RATE), "-f", "f32le", "-"], | |
| stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) | |
| if result.returncode: | |
| raise TimingError("ffmpeg failed: " + result.stderr.decode("utf-8", "replace").strip()) | |
| if len(result.stdout) % 4: | |
| raise TimingError("ffmpeg returned incomplete float32 audio") | |
| samples = np.frombuffer(result.stdout, dtype="<f4") | |
| if len(samples) < FRAME_SAMPLES or not np.isfinite(samples).all(): | |
| raise TimingError("decoded audio is too short or contains invalid samples") | |
| return samples | |
| def envelope(samples): | |
| # Same float64 cumulative-sum calculation as the fixed-ZIP workflow. | |
| energy = np.r_[0, np.cumsum(samples.astype(np.float64) ** 2)] | |
| starts = np.arange(0, len(samples) - FRAME_SAMPLES + 1, HOP_SAMPLES) | |
| mean_square = (energy[starts + FRAME_SAMPLES] - energy[starts]) / FRAME_SAMPLES | |
| return 10 * np.log10(np.maximum(mean_square, 1e-18)) | |
| def validate(data, label): | |
| if not isinstance(data, dict) or not isinstance(data.get("sections"), list): | |
| raise TimingError(label + ": expected an object containing a sections array") | |
| if not data["sections"]: | |
| raise TimingError(label + ": sections array is empty") | |
| previous_start = -1.0 | |
| for i, section in enumerate(data["sections"], 1): | |
| if not isinstance(section, dict): | |
| raise TimingError(f"{label}: section {i} is not an object") | |
| for key in ("start_time", "end_time"): | |
| value = section.get(key) | |
| if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): | |
| raise TimingError(f"{label}: section {i} has invalid {key}") | |
| start, end = section["start_time"], section["end_time"] | |
| if not 0 <= start < end or start < previous_start: | |
| raise TimingError(f"{label}: section {i} has invalid or unordered times") | |
| previous_start = start | |
| def refine_timings(data, db, duration): | |
| validate(data, "input") | |
| sections = data["sections"] | |
| if sections[-1]["end_time"] > duration + .1: | |
| raise TimingError("timestamps exceed the audio duration; expected seconds, not milliseconds") | |
| starts = [] | |
| for i, section in enumerate(sections): | |
| lo = max(0, section["start_time"] - .18, | |
| sections[i - 1]["end_time"] + .1 if i else 0) | |
| hi = min(section["end_time"], section["start_time"] + .5) | |
| cores = activity(db, lo, hi, threshold=STRONG_DB, ms=25) | |
| if not cores: | |
| raise TimingError(f"section {i + 1}: no sustained speech onset near its timestamp") | |
| onset = cores[0][0] | |
| # Preserve a short opening syllable before the sustained syllable. | |
| short = activity(db, lo, onset + .05, threshold=STRONG_DB, ms=8) | |
| for a, b in reversed(short): | |
| if a >= onset: | |
| continue | |
| if onset - b <= .18: | |
| onset = a | |
| else: | |
| break | |
| # Recover the initial consonant using hysteresis; add no fixed padding. | |
| lower = activity(db, max(lo, onset - .035), min(hi, onset + .05), | |
| threshold=EDGE_DB, ms=8) | |
| connected = [(a, b) for a, b in lower | |
| if a <= onset + .005 and b >= onset - .01] | |
| if connected: | |
| onset = min(a for a, b in connected) | |
| starts.append(round(float(onset), 2)) | |
| output = copy.deepcopy(data) | |
| for i, section in enumerate(sections): | |
| new = output["sections"][i] | |
| new["start_time"] = starts[i] | |
| limit = min(duration, starts[i + 1] - .015) if i + 1 < len(sections) else duration | |
| a = round(section["end_time"] * 1000) | |
| b = min(len(db), round(limit * 1000)) | |
| if b <= a: | |
| raise TimingError(f"section {i + 1}: no usable end-search interval before the next onset") | |
| mask = binary_closing(db[a:b] < EDGE_DB, | |
| structure=np.ones(11), border_value=0) | |
| quiet = [(a + u) / 1000 for u, v in runs(mask) if v - u >= 50] | |
| if quiet: | |
| end = quiet[0] | |
| else: | |
| mask = binary_closing(db[a:b] < FALLBACK_END_DB, | |
| structure=np.ones(16), border_value=0) | |
| quiet = [(a + u) / 1000 for u, v in runs(mask) if v - u >= 40] | |
| if quiet: | |
| end = quiet[0] | |
| else: | |
| lo = max(a, round((limit - .18) * 1000)) | |
| if lo >= b: | |
| raise TimingError(f"section {i + 1}: no usable energy minimum") | |
| end = (lo + int(np.argmin(db[lo:b]))) / 1000 | |
| new["end_time"] = round(float(min(end, limit)), 2) | |
| if new["end_time"] > limit: | |
| new["end_time"] = round(float(limit - .005), 2) | |
| if not 0 <= new["start_time"] < new["end_time"] <= duration + .001: | |
| raise TimingError(f"section {i + 1}: calculated boundary is invalid") | |
| for i, (left, right) in enumerate(zip(output["sections"], output["sections"][1:]), 1): | |
| if left["end_time"] > right["start_time"]: | |
| raise TimingError(f"sections {i}/{i + 1}: calculated boundaries overlap") | |
| return output | |
| def read_json(path): | |
| try: | |
| raw = path.read_bytes() | |
| return raw, json.loads(raw.decode("utf-8-sig")) | |
| except (UnicodeError, json.JSONDecodeError) as exc: | |
| raise TimingError(f"{path.name}: invalid UTF-8 JSON: {exc}") from exc | |
| def choose_audio(folder, data): | |
| candidates = sorted(p for p in folder.iterdir() | |
| if p.is_file() and not p.is_symlink() | |
| and not p.name.startswith(".") and p.suffix.lower() == ".mp3") | |
| reference = data.get("audio_file") | |
| if isinstance(reference, str): | |
| # Accept an existing basename reference without following paths outside | |
| # this child folder. Also supports metadata containing a Windows path. | |
| name = reference.replace("\\", "/").rsplit("/", 1)[-1] | |
| matches = [p for p in candidates if p.name == name] | |
| if len(matches) == 1: | |
| return matches[0] | |
| if len(candidates) == 1: | |
| return candidates[0] | |
| raise TimingError("need one MP3, or an audio_file field matching one of the MP3 filenames") | |
| def atomic_replace(path, content): | |
| mode = stat.S_IMODE(path.stat().st_mode) | |
| fd, temp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=str(path.parent)) | |
| try: | |
| with os.fdopen(fd, "wb") as stream: | |
| stream.write(content) | |
| stream.flush() | |
| os.fsync(stream.fileno()) | |
| os.chmod(temp_name, mode) | |
| os.replace(temp_name, path) | |
| finally: | |
| if os.path.exists(temp_name): | |
| os.unlink(temp_name) | |
| def process_json(path, current_raw, current, ffmpeg, dry_run): | |
| validate(current, path.name) | |
| audio = choose_audio(path.parent, current) | |
| samples = decode_audio(audio, ffmpeg) | |
| duration = len(samples) / SAMPLE_RATE | |
| db = envelope(samples) | |
| del samples | |
| output = refine_timings(current, db, duration) | |
| changed = sum(a["start_time"] != b["start_time"] or a["end_time"] != b["end_time"] | |
| for a, b in zip(current["sections"], output["sections"])) | |
| if output == current: | |
| return len(output["sections"]), 0 | |
| if not dry_run: | |
| content = (json.dumps(output, ensure_ascii=False, indent=2) + "\n").encode("utf-8") | |
| # Detect a concurrent edit before replacing a user's file. | |
| if path.read_bytes() != current_raw: | |
| raise TimingError("JSON changed during processing; left it untouched") | |
| atomic_replace(path, content) | |
| return len(output["sections"]), changed | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("parent", type=Path, help="parent containing the immediate audio/JSON child folders") | |
| parser.add_argument("--dry-run", action="store_true", help="calculate/report changes without writing files") | |
| parser.add_argument("--ffmpeg", default="ffmpeg", help="ffmpeg executable name or full path") | |
| args = parser.parse_args(argv) | |
| parent = args.parent.expanduser().resolve() | |
| if not parent.is_dir(): | |
| parser.error("parent is not an existing directory") | |
| ffmpeg = shutil.which(args.ffmpeg) | |
| if not ffmpeg: | |
| parser.error("ffmpeg was not found; install it or provide --ffmpeg /path/to/ffmpeg") | |
| folders = sorted(p for p in parent.iterdir() | |
| if p.is_dir() and not p.is_symlink() and not p.name.startswith(".")) | |
| total_files = total_sections = total_changed = errors = skipped = 0 | |
| for index, folder in enumerate(folders, 1): | |
| json_files = sorted(p for p in folder.iterdir() | |
| if p.is_file() and not p.is_symlink() and not p.name.startswith(".") | |
| and p.suffix.lower() == ".json") | |
| found = False | |
| for path in json_files: | |
| try: | |
| raw, data = read_json(path) | |
| if not isinstance(data, dict) or "sections" not in data: | |
| continue | |
| found = True | |
| print(f"[{index}/{len(folders)}] {folder.name}/{path.name}: processing...", flush=True) | |
| count, changed = process_json(path, raw, data, ffmpeg, args.dry_run) | |
| total_files += 1 | |
| total_sections += count | |
| total_changed += changed | |
| action = "would update" if args.dry_run else "updated" | |
| print(f" {count} sections; {action} {changed}; remaining folders: {len(folders) - index}", flush=True) | |
| except (OSError, TimingError) as exc: | |
| errors += 1 | |
| print(f" ERROR {folder.name}/{path.name}: {exc}", file=sys.stderr, flush=True) | |
| if not found: | |
| skipped += 1 | |
| print(f"[{index}/{len(folders)}] {folder.name}: skipped (no section JSON)", flush=True) | |
| print(f"Done: {total_files} JSON files, {total_sections} sections, {total_changed} changed; " | |
| f"{skipped} folders skipped, {errors} errors.") | |
| return 1 if errors else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |