File size: 7,554 Bytes
adabee1 | 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 | """Derived CoRal dataset with short edges, cut at the aligned speech boundaries.
CoRal clips start with 0.3-1.2 s (median 0.83 s) of room noise, breaths and lip noise
before the first word. Two effects:
* the voice model learns it: every sentence starts with ~0.75 s of quiet hiss;
* the alignment QC rejects ~2,900 train clips as "unexplained_voiced_speech_in_pause",
84% of them only because of voiced noise in these edges.
Each clip is cut to --lead seconds before its first aligned phone and --tail seconds after
its last one, using the adapted Danish CTC head's durations (system "adapted",
checks/full-head-{validation,test}/clips.jsonl). The aligner is calibrated on onsets, so
unvoiced first phones (/s/, /f/, /h/) are kept, unlike an energy or VAD trim. 10 ms
raised-cosine fades avoid clicks at the cut. Clips without an alignment are copied
unchanged. Everything downstream (features, CTC head, QC, annotations) is rerun on the
result, so a bad cut is rejected by the same QC as any other clip.
Guard: an edge is left untrimmed when the --guard-window seconds just outside the cut hold
a 50 ms frame within --guard-db of the clip's speech level (90th percentile frame), since
that may be a late-aligned word rather than noise. Trimming never removes possible speech.
Usage (kit image):
python scripts/trim_edges.py --data data/coral_da \
--evaluation checks/full-head-validation checks/full-head-test \
--config config.da.json --output data/coral_da_trim
"""
import argparse
import hashlib
import json
import sys
from collections import Counter
from pathlib import Path
import numpy as np
import soundfile as sf
sys.path.insert(0, '/opt/kit')
from prepare_coral import waveform_sha256 # noqa: E402
SPLITS = ('train', 'validation', 'test')
FADE_SECONDS = 0.010
FRAME = 1200 # 50 ms at 24 kHz, for the guard
def frame_levels(wave):
frames = wave[:len(wave) // FRAME * FRAME].astype(np.float64).reshape(-1, FRAME)
return 20 * np.log10(np.sqrt((frames ** 2).mean(1)) + 1e-9)
def alignments(folders):
out = {}
for folder in folders:
for line in (folder / 'clips.jsonl').read_text(encoding='utf-8').splitlines():
row = json.loads(line)
if row['system'] == 'adapted' and not row.get('negative_control') and row.get('durations'):
out[row['id']] = row['durations']
return out
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--data', type=Path, required=True)
p.add_argument('--evaluation', type=Path, nargs='+', required=True)
p.add_argument('--config', type=Path, required=True)
p.add_argument('--output', type=Path, required=True)
p.add_argument('--lead', type=float, default=0.15)
p.add_argument('--tail', type=float, default=0.20)
p.add_argument('--guard-db', type=float, default=10.0)
p.add_argument('--guard-window', type=float, default=0.4)
args = p.parse_args()
if args.output.exists() and any(args.output.iterdir()):
raise SystemExit(f'{args.output} must be new or empty')
hop = json.loads(args.config.read_text())['hop']
aligned = alignments(args.evaluation)
meta = json.loads((args.data / 'preparation.json').read_text())
sr = meta['sample_rate']
lead, tail, fade = round(args.lead * sr), round(args.tail * sr), round(FADE_SECONDS * sr)
window = round(args.guard_window * sr) // FRAME
ramp = 0.5 - 0.5 * np.cos(np.linspace(0, np.pi, fade, dtype=np.float64))
(args.output / 'audio').mkdir(parents=True, exist_ok=True)
stats, removed, durations = Counter(), {'lead': [], 'tail': []}, Counter()
for split in SPLITS:
rows = [json.loads(l) for l in (args.data / f'{split}.jsonl').read_text(encoding='utf-8').splitlines() if l.strip()]
with (args.output / f'{split}.jsonl').open('w', encoding='utf-8') as manifest:
for row in rows:
wave, rate = sf.read(args.data / row['audio'], dtype='float32')
assert rate == sr and wave.ndim == 1
n, d = len(wave), aligned.get(row['id'])
start, end = 0, n
if d is not None:
first, last_end = d[0] * hop, (sum(d) - d[-1]) * hop
start = max(0, first - lead)
end = min(n, max(last_end + tail, start + 32 * hop))
levels = frame_levels(wave)
loud = levels > np.percentile(levels, 90) - args.guard_db
if start and loud[max(0, start // FRAME - window):start // FRAME].any():
start = 0
stats['lead_guarded'] += 1
if end < n and loud[-(-end // FRAME):-(-end // FRAME) + window].any():
end = n
stats['tail_guarded'] += 1
stats['aligned'] += 1
else:
stats['unaligned_copied'] += 1
cut = wave[start:end].astype(np.float64)
if start > 0:
cut[:fade] *= ramp
if end < n:
cut[-fade:] *= ramp[::-1]
cut = cut.astype(np.float32)
removed['lead'].append(start / sr)
removed['tail'].append((n - end) / sr)
path = args.output / row['audio']
sf.write(path, cut, sr, subtype='FLOAT', format='WAV')
row.update(audio_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
waveform_sha256=waveform_sha256(cut, sr), duration_seconds=round(len(cut) / sr, 3),
edge_trim={'untrimmed_audio_sha256': row['audio_sha256'], 'start_sample': start,
'end_sample': end, 'aligned': d is not None,
'guard': {'db': args.guard_db, 'window_seconds': args.guard_window}})
durations[split] += len(cut) / sr
manifest.write(json.dumps(row, ensure_ascii=False) + '\n')
summary = {'clips': dict(stats),
'removed_seconds': {k: {'median': float(np.median(v)), 'p90': float(np.percentile(v, 90)),
'total_hours': float(np.sum(v) / 3600)} for k, v in removed.items()}}
meta.update(
created_utc=None, derived_from={'data': str(args.data), 'preparation_sha256':
hashlib.sha256((args.data / 'preparation.json').read_bytes()).hexdigest(),
'alignment': [str(f) for f in args.evaluation]},
transforms=meta['transforms'] + [f'edge trim at aligned speech: {args.lead} s before the first phone, '
f'{args.tail} s after the last (adapted CTC head), 10 ms fades; edge kept when '
f'{args.guard_window} s outside the cut holds a frame within '
f'{args.guard_db} dB of speech level'],
not_performed=[x for x in meta['not_performed'] if x not in ('silence trimming', 'audio cropping')],
duration_seconds={k: round(v, 3) for k, v in durations.items()}, edge_trim=summary)
from datetime import datetime, timezone
meta['created_utc'] = datetime.now(timezone.utc).isoformat()
(args.output / 'preparation.json').write_text(json.dumps(meta, indent=2, ensure_ascii=False))
print(json.dumps(summary, indent=2))
if __name__ == '__main__':
main()
|