|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Copyright 2025 BoHao Su |
| 4 | +# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) |
| 5 | + |
| 6 | +import argparse |
| 7 | +import os |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +import soundfile as sf |
| 12 | +from tqdm import tqdm |
| 13 | +from versa.scorer_shared import audio_loader_setup, load_audio, wav_normalize |
| 14 | + |
| 15 | + |
| 16 | +def get_parser() -> argparse.Namespace: |
| 17 | + """Get argument parser.""" |
| 18 | + parser = argparse.ArgumentParser(description="Chunk audios into fixed durations.") |
| 19 | + parser.add_argument( |
| 20 | + "--pred", |
| 21 | + type=str, |
| 22 | + required=True, |
| 23 | + help="Wav.scp for generated waveforms, or a dir depending on --io.", |
| 24 | + ) |
| 25 | + parser.add_argument( |
| 26 | + "--io", |
| 27 | + type=str, |
| 28 | + default="kaldi", |
| 29 | + choices=["kaldi", "soundfile", "dir"], |
| 30 | + help="IO interface to use.", |
| 31 | + ) |
| 32 | + parser.add_argument( |
| 33 | + "--chunk_duration", |
| 34 | + type=float, |
| 35 | + default=3.0, |
| 36 | + help="Duration (sec) of each chunk window.", |
| 37 | + ) |
| 38 | + parser.add_argument( |
| 39 | + "--hop_duration", |
| 40 | + type=float, |
| 41 | + default=None, |
| 42 | + help="Hop size (sec) between chunk starts. " |
| 43 | + "If None, equals --chunk_duration (non-overlap).", |
| 44 | + ) |
| 45 | + parser.add_argument( |
| 46 | + "--output_dir", |
| 47 | + type=str, |
| 48 | + required=True, |
| 49 | + help="Directory to write chunked wav files.", |
| 50 | + ) |
| 51 | + parser.add_argument( |
| 52 | + "--min_last_chunk", |
| 53 | + type=float, |
| 54 | + default=0.0, |
| 55 | + help="Minimum duration (sec) required to keep the final (short) chunk. " |
| 56 | + "Set >0 to drop very short tails.", |
| 57 | + ) |
| 58 | + return parser |
| 59 | + |
| 60 | + |
| 61 | +def main(): |
| 62 | + args = get_parser().parse_args() |
| 63 | + |
| 64 | + output_dir = Path(args.output_dir) |
| 65 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 66 | + |
| 67 | + if args.chunk_duration <= 0: |
| 68 | + raise ValueError("--chunk_duration must be > 0") |
| 69 | + |
| 70 | + hop_duration = ( |
| 71 | + args.hop_duration if args.hop_duration is not None else args.chunk_duration |
| 72 | + ) |
| 73 | + if hop_duration <= 0: |
| 74 | + raise ValueError("--hop_duration must be > 0") |
| 75 | + |
| 76 | + if args.min_last_chunk < 0: |
| 77 | + raise ValueError("--min_last_chunk must be >= 0") |
| 78 | + |
| 79 | + gen_files = audio_loader_setup(args.pred, args.io) |
| 80 | + if len(gen_files) == 0: |
| 81 | + raise FileNotFoundError( |
| 82 | + "Not found any generated audio files from --pred with --io." |
| 83 | + ) |
| 84 | + |
| 85 | + total_chunks = 0 |
| 86 | + for key in tqdm(list(gen_files.keys()), desc="Chunking"): |
| 87 | + src_path = gen_files[key] |
| 88 | + try: |
| 89 | + sr, wav = load_audio(src_path, args.io) |
| 90 | + wav = wav_normalize(wav) |
| 91 | + if wav.ndim > 1: |
| 92 | + # Convert to mono if multichannel |
| 93 | + wav = np.mean(wav, axis=-1) |
| 94 | + except Exception as e: |
| 95 | + print(f"[WARN] Failed to load {key} from {src_path}: {e}") |
| 96 | + continue |
| 97 | + |
| 98 | + chunk_len = int(round(args.chunk_duration * sr)) |
| 99 | + hop_len = int(round(hop_duration * sr)) |
| 100 | + min_last_len = int(round(args.min_last_chunk * sr)) |
| 101 | + |
| 102 | + if chunk_len <= 0 or hop_len <= 0: |
| 103 | + print(f"[WARN] Non-positive chunk/hop for key={key}; skipping.") |
| 104 | + continue |
| 105 | + |
| 106 | + n_samples = len(wav) |
| 107 | + if n_samples == 0: |
| 108 | + print(f"[WARN] Empty audio for key={key}; skipping.") |
| 109 | + continue |
| 110 | + |
| 111 | + # Iterate chunk start positions |
| 112 | + chunk_idx = 0 |
| 113 | + start = 0 |
| 114 | + while start < n_samples: |
| 115 | + end = start + chunk_len |
| 116 | + if end > n_samples: |
| 117 | + # last (short) chunk |
| 118 | + if (n_samples - start) < min_last_len: |
| 119 | + break # drop the tail if too short |
| 120 | + end = n_samples |
| 121 | + |
| 122 | + chunk = wav[start:end] |
| 123 | + if len(chunk) == 0: |
| 124 | + break |
| 125 | + |
| 126 | + # Include time range in filename for traceability |
| 127 | + t0 = start / sr |
| 128 | + t1 = end / sr |
| 129 | + out_name = f"{key}_chunk{chunk_idx:04d}_{t0:.3f}-{t1:.3f}.wav" |
| 130 | + out_path = output_dir / out_name |
| 131 | + |
| 132 | + try: |
| 133 | + sf.write(str(out_path), chunk, sr, subtype="PCM_16") |
| 134 | + total_chunks += 1 |
| 135 | + except Exception as e: |
| 136 | + print(f"[WARN] Failed to write {out_path}: {e}") |
| 137 | + |
| 138 | + chunk_idx += 1 |
| 139 | + start += hop_len |
| 140 | + |
| 141 | + print(f"Done. Wrote {total_chunks} chunks to: {output_dir.resolve()}") |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + main() |
0 commit comments