RakhatM commited on
Commit
5b8fdc4
·
verified ·
1 Parent(s): f9cfa73

Add KazMix-3 manifests + generation scripts

Browse files
.gitattributes CHANGED
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ test_clean_kazakh3mix_lufsfix_posneg.json filter=lfs diff=lfs merge=lfs -text
62
+ train_clean_100_kazakh3mix_lufsfix_posneg.json filter=lfs diff=lfs merge=lfs -text
63
+ val_kazakh3mix_lufsfix_posneg.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ language: [kk]
4
+ task_categories: [automatic-speech-recognition]
5
+ tags: [target-speaker-asr, speech-separation, kazakh, overlapping-speech]
6
+ pretty_name: KazMix-3
7
+ ---
8
+
9
+ # KazMix-3
10
+
11
+ Kazakh three-speaker overlapping-speech dataset for **target-speaker ASR (TS-ASR)**, released with the [Persona-ASR](https://github.com/IS2AI/Persona_ASR) project.
12
+
13
+ This repository provides the **mixture manifests** and the **generation scripts**, not the audio. Mixtures are derived from the **Kazakh Speech Dataset (KSD, [OpenSLR 140](https://www.openslr.org/140/))**; download KSD and run the scripts to reproduce the audio locally.
14
+
15
+ ## Contents
16
+ - `train_clean_100_kazakh3mix_lufsfix_posneg.json`, `val_kazakh3mix_lufsfix_posneg.json`, `test_clean_kazakh3mix_lufsfix_posneg.json` — target-speaker manifests with positive (target-present) and negative (target-absent) trials.
17
+ - `scripts/` — LUFS-uniform 3-speaker mixture generation and manifest building.
18
+
19
+ ## Manifest fields
20
+ Each entry includes `mixture_audio`, `enrollment_audio`, `transcript`, `speaker_id`, `target_index`, `sample_type` (positive/negative), `label`, and mixing metadata.
21
+
22
+ ## Regenerating the audio
23
+ 1. Download KSD from https://www.openslr.org/140/.
24
+ 2. Run `scripts/rerender_kazakh3mix_lufs_uniform.py` (see the Persona-ASR repo for full setup), pointing it at your local KSD path.
25
+
26
+ ## Citation
27
+ Please cite Persona-ASR and KSD (OpenSLR 140).
scripts/build_official_librimix3_persona_manifest.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build target-speaker manifests from official Libri3Mix clean/max audio.
3
+
4
+ Each positive row points at a Libri3Mix mixture and one present source. Each
5
+ negative row uses the same mixture but an enrollment utterance from a speaker
6
+ that is absent from the mixture. Negatives are sampled at a fixed ratio of the
7
+ positive count per split.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ import random
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+ import soundfile as sf
20
+
21
+
22
+ SPLITS = {
23
+ "train_clean_100": ("libri3mix_train-clean-100.csv", "train-100"),
24
+ "val": ("libri3mix_dev-clean.csv", "dev"),
25
+ "test_clean": ("libri3mix_test-clean.csv", "test"),
26
+ }
27
+
28
+
29
+ def utt_id_from_rel(path: str) -> str:
30
+ return Path(path).stem
31
+
32
+
33
+ def speaker_id_from_rel(path: str) -> str:
34
+ return Path(path).parts[-3]
35
+
36
+
37
+ def load_transcripts(librispeech_dir: Path) -> dict[str, str]:
38
+ transcripts: dict[str, str] = {}
39
+ for trans_path in librispeech_dir.rglob("*.trans.txt"):
40
+ with trans_path.open("r", encoding="utf-8") as f:
41
+ for line in f:
42
+ line = line.strip()
43
+ if not line:
44
+ continue
45
+ utt, text = line.split(" ", 1)
46
+ transcripts[utt] = text
47
+ return transcripts
48
+
49
+
50
+ def duration_sec(path: Path) -> float:
51
+ info = sf.info(str(path))
52
+ return float(info.frames) / float(info.samplerate)
53
+
54
+
55
+ def existing_source_paths(row: pd.Series, librispeech_dir: Path) -> list[Path]:
56
+ return [librispeech_dir / str(row[f"source_{i}_path"]) for i in range(1, 4)]
57
+
58
+
59
+ def make_positive(
60
+ *,
61
+ row: pd.Series,
62
+ split_dir: Path,
63
+ librispeech_dir: Path,
64
+ transcripts: dict[str, str],
65
+ source_idx: int,
66
+ root: Path,
67
+ ) -> dict:
68
+ mix_id = str(row["mixture_ID"])
69
+ source_rel = str(row[f"source_{source_idx}_path"])
70
+ source_path = librispeech_dir / source_rel
71
+ utt_id = utt_id_from_rel(source_rel)
72
+ speaker_id = speaker_id_from_rel(source_rel)
73
+ mix_path = split_dir / "mix_clean" / f"{mix_id}.wav"
74
+ target_path = split_dir / f"s{source_idx}" / f"{mix_id}.wav"
75
+ return {
76
+ "id": f"{mix_id}_target_{source_idx - 1}_pos",
77
+ "mixture_id": mix_id,
78
+ "mixture_audio": str(mix_path.resolve()),
79
+ "enrollment_audio": str(source_path.resolve()),
80
+ "enrollment_clean_source_path": str(source_path.resolve()),
81
+ "transcript": transcripts.get(utt_id, ""),
82
+ "speaker_id": speaker_id,
83
+ "target_speaker_id": speaker_id,
84
+ "target_index": source_idx - 1,
85
+ "duration": duration_sec(mix_path),
86
+ "sample_type": "positive",
87
+ "class": "positive",
88
+ "label": 1,
89
+ "is_target_present": True,
90
+ "clean_source_rel": source_rel,
91
+ "clean_source_path": str(source_path.resolve()),
92
+ "target_in_mix_path": str(target_path.resolve()),
93
+ "mixture_variant": "official_librimix3_wav16k_max_mix_clean",
94
+ "dataset_root": str(root.resolve()),
95
+ }
96
+
97
+
98
+ def make_negative(
99
+ *,
100
+ row: pd.Series,
101
+ split_dir: Path,
102
+ absent_source: Path,
103
+ transcripts: dict[str, str],
104
+ neg_idx: int,
105
+ root: Path,
106
+ ) -> dict:
107
+ mix_id = str(row["mixture_ID"])
108
+ source_rel = str(absent_source.relative_to(root / "LibriSpeech"))
109
+ utt_id = absent_source.stem
110
+ speaker_id = speaker_id_from_rel(source_rel)
111
+ mix_path = split_dir / "mix_clean" / f"{mix_id}.wav"
112
+ return {
113
+ "id": f"{mix_id}_neg_{neg_idx}",
114
+ "mixture_id": mix_id,
115
+ "mixture_audio": str(mix_path.resolve()),
116
+ "enrollment_audio": str(absent_source.resolve()),
117
+ "enrollment_clean_source_path": str(absent_source.resolve()),
118
+ "transcript": "",
119
+ "speaker_id": speaker_id,
120
+ "target_speaker_id": speaker_id,
121
+ "target_index": None,
122
+ "duration": duration_sec(mix_path),
123
+ "sample_type": "negative",
124
+ "class": "negative",
125
+ "label": 0,
126
+ "is_target_present": False,
127
+ "clean_source_rel": source_rel,
128
+ "clean_source_path": str(absent_source.resolve()),
129
+ "target_in_mix_path": None,
130
+ "negative_reference_transcript": transcripts.get(utt_id, ""),
131
+ "mixture_variant": "official_librimix3_wav16k_max_mix_clean",
132
+ "dataset_root": str(root.resolve()),
133
+ }
134
+
135
+
136
+ def validate_rendered_split(split_dir: Path, expected_mixes: int) -> None:
137
+ required_dirs = ["mix_clean", "s1", "s2", "s3"]
138
+ counts = {d: len(list((split_dir / d).glob("*.wav"))) for d in required_dirs}
139
+ missing = {k: v for k, v in counts.items() if v != expected_mixes}
140
+ if missing:
141
+ raise RuntimeError(f"Incomplete rendered split {split_dir}: counts={counts}, expected={expected_mixes}")
142
+
143
+
144
+ def build_split(
145
+ *,
146
+ name: str,
147
+ csv_path: Path,
148
+ split_dir: Path,
149
+ librispeech_dir: Path,
150
+ transcripts: dict[str, str],
151
+ out_dir: Path,
152
+ root: Path,
153
+ negative_ratio: float,
154
+ seed: int,
155
+ ) -> dict:
156
+ df = pd.read_csv(csv_path)
157
+ validate_rendered_split(split_dir, len(df))
158
+ split_enrollments: list[Path] = []
159
+ for _, row in df.iterrows():
160
+ split_enrollments.extend(existing_source_paths(row, librispeech_dir))
161
+ positives: list[dict] = []
162
+ present_by_mix: list[set[str]] = []
163
+ for _, row in df.iterrows():
164
+ present = {speaker_id_from_rel(str(row[f"source_{i}_path"])) for i in range(1, 4)}
165
+ present_by_mix.append(present)
166
+ for source_idx in range(1, 4):
167
+ rec = make_positive(
168
+ row=row,
169
+ split_dir=split_dir,
170
+ librispeech_dir=librispeech_dir,
171
+ transcripts=transcripts,
172
+ source_idx=source_idx,
173
+ root=root,
174
+ )
175
+ if not rec["transcript"]:
176
+ raise RuntimeError(f"Missing transcript for {rec['clean_source_path']}")
177
+ positives.append(rec)
178
+
179
+ rng = random.Random(seed)
180
+ target_negatives = math.floor(len(positives) * negative_ratio)
181
+ negatives: list[dict] = []
182
+ rows = list(df.iterrows())
183
+ attempts = 0
184
+ while len(negatives) < target_negatives:
185
+ row_idx, row = rows[len(negatives) % len(rows)]
186
+ present = present_by_mix[row_idx]
187
+ candidate = rng.choice(split_enrollments)
188
+ attempts += 1
189
+ if speaker_id_from_rel(str(candidate.relative_to(librispeech_dir))) in present:
190
+ if attempts > target_negatives * 100:
191
+ raise RuntimeError("Could not sample enough absent-speaker negatives")
192
+ continue
193
+ negatives.append(
194
+ make_negative(
195
+ row=row,
196
+ split_dir=split_dir,
197
+ absent_source=candidate,
198
+ transcripts=transcripts,
199
+ neg_idx=len(negatives),
200
+ root=root,
201
+ )
202
+ )
203
+
204
+ records = positives + negatives
205
+ rng.shuffle(records)
206
+ out_path = out_dir / f"{name}_official_libri3mix_clean_max_16k_posneg.json"
207
+ out_path.write_text(json.dumps(records, indent=2), encoding="utf-8")
208
+ return {
209
+ "manifest": str(out_path),
210
+ "total": len(records),
211
+ "positive": len(positives),
212
+ "negative": len(negatives),
213
+ "negative_ratio": len(negatives) / max(1, len(positives)),
214
+ }
215
+
216
+
217
+ def main() -> None:
218
+ ap = argparse.ArgumentParser()
219
+ ap.add_argument("--root", type=Path, default=Path("/workspace/LibriMix/storage_dir"))
220
+ ap.add_argument("--metadata-dir", type=Path, default=Path("/workspace/LibriMix/metadata/Libri3Mix"))
221
+ ap.add_argument("--out-dir", type=Path, default=Path("/workspace/new/data/LibriMix/persona_asr/official_libri3mix_clean_max_16k"))
222
+ ap.add_argument("--negative-ratio", type=float, default=0.5)
223
+ ap.add_argument("--seed", type=int, default=1337)
224
+ args = ap.parse_args()
225
+
226
+ root = args.root
227
+ librispeech_dir = root / "LibriSpeech"
228
+ librimix_dir = root / "Libri3Mix" / "wav16k" / "max"
229
+ args.out_dir.mkdir(parents=True, exist_ok=True)
230
+
231
+ transcripts = load_transcripts(librispeech_dir)
232
+ summary = {}
233
+ for idx, (name, (csv_name, split_name)) in enumerate(SPLITS.items()):
234
+ summary[name] = build_split(
235
+ name=name,
236
+ csv_path=args.metadata_dir / csv_name,
237
+ split_dir=librimix_dir / split_name,
238
+ librispeech_dir=librispeech_dir,
239
+ transcripts=transcripts,
240
+ out_dir=args.out_dir,
241
+ root=root,
242
+ negative_ratio=args.negative_ratio,
243
+ seed=args.seed + idx,
244
+ )
245
+
246
+ summary_path = args.out_dir / "summary.json"
247
+ summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")
248
+ print(json.dumps(summary, indent=2))
249
+
250
+
251
+ if __name__ == "__main__":
252
+ main()
scripts/fix_kazakh3mix_enrollment_leakage.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Replace leaked enrollments in Kazakh3Mix manifests.
3
+
4
+ A "leaked positive" is one where `enrollment_audio` is identical to one of the
5
+ clean source clips that appear in the mixture (`source_clean_paths`). For each
6
+ such row, pick a different utterance from the SAME target speaker (in the same
7
+ split's source directory) that does not appear in `source_clean_paths`.
8
+
9
+ Only the enrollment fields are touched. Speakers, splits, mixture audio, target
10
+ indices, and labels are unchanged.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import random
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+
21
+ SPLIT_DIR = {"train": "train-100", "val": "dev", "test": "test"}
22
+ CLEAN_ROOT = Path("/workspace/LibriMix/storage_dir/KazakhSpeech3Mix/wav16k")
23
+
24
+
25
+ def index_speaker_utterances(split_dir_name: str) -> dict[str, list[str]]:
26
+ """speaker_id -> sorted list of clean utterance paths in that split."""
27
+ root = CLEAN_ROOT / split_dir_name
28
+ index: dict[str, list[str]] = defaultdict(list)
29
+ if not root.exists():
30
+ return index
31
+ for spk_dir in root.iterdir():
32
+ if not spk_dir.is_dir():
33
+ continue
34
+ for wav in spk_dir.iterdir():
35
+ if wav.suffix.lower() == ".wav":
36
+ index[spk_dir.name].append(str(wav))
37
+ for k in index:
38
+ index[k].sort()
39
+ return index
40
+
41
+
42
+ def fix_manifest(in_path: Path, out_path: Path, split_dir_name: str, seed: int) -> dict:
43
+ rows = json.loads(in_path.read_text())
44
+ speaker_index = index_speaker_utterances(split_dir_name)
45
+ rng = random.Random(seed)
46
+
47
+ n_pos = sum(1 for r in rows if r.get("is_target_present"))
48
+ n_leaked = 0
49
+ n_fixed = 0
50
+ n_unfixable = 0
51
+
52
+ for r in rows:
53
+ if not r.get("is_target_present"):
54
+ continue
55
+ enr = r.get("enrollment_audio")
56
+ sources = list(r.get("source_clean_paths") or [])
57
+ if enr not in sources:
58
+ continue
59
+ n_leaked += 1
60
+
61
+ spk = str(r.get("target_speaker_id") or r.get("speaker_id"))
62
+ forbidden = set(sources)
63
+ # Also forbid the original (leaked) enrollment so we definitely replace it.
64
+ forbidden.add(enr)
65
+ candidates = [u for u in speaker_index.get(spk, []) if u not in forbidden]
66
+ if not candidates:
67
+ # Fallback: any utterance from this speaker that differs from current enrollment.
68
+ candidates = [u for u in speaker_index.get(spk, []) if u != enr]
69
+ if not candidates:
70
+ n_unfixable += 1
71
+ continue
72
+ new_enr = rng.choice(candidates)
73
+ r["enrollment_audio"] = new_enr
74
+ r["enrollment_clean_source_path"] = new_enr
75
+ # also propagate to top-level fields used in some downstream code
76
+ if r.get("clean_source_path") == enr:
77
+ r["clean_source_path"] = new_enr
78
+ n_fixed += 1
79
+
80
+ out_path.parent.mkdir(parents=True, exist_ok=True)
81
+ out_path.write_text(json.dumps(rows, ensure_ascii=False, indent=2))
82
+ return {
83
+ "in": str(in_path), "out": str(out_path),
84
+ "positives": n_pos, "leaked": n_leaked,
85
+ "fixed": n_fixed, "unfixable": n_unfixable,
86
+ }
87
+
88
+
89
+ def main() -> None:
90
+ ap = argparse.ArgumentParser()
91
+ ap.add_argument("--in-dir", type=Path,
92
+ default=Path("data/LibriMix/persona_asr/kazakh3mix_clean_max_16k_lufsfix"))
93
+ ap.add_argument("--out-dir", type=Path,
94
+ default=Path("data/LibriMix/persona_asr/kazakh3mix_clean_max_16k_lufsfix"),
95
+ help="Default: overwrite in_dir in place.")
96
+ ap.add_argument("--seed", type=int, default=20260617)
97
+ args = ap.parse_args()
98
+
99
+ summary = []
100
+ plans = [
101
+ ("train", "train_clean_100_kazakh3mix_lufsfix_posneg.json"),
102
+ ("val", "val_kazakh3mix_lufsfix_posneg.json"),
103
+ ("test", "test_clean_kazakh3mix_lufsfix_posneg.json"),
104
+ ]
105
+ for split, fname in plans:
106
+ in_p = args.in_dir / fname
107
+ out_p = args.out_dir / fname
108
+ s = fix_manifest(in_p, out_p, SPLIT_DIR[split], args.seed + hash(split) % 10_000)
109
+ s["split"] = split
110
+ summary.append(s)
111
+ print(f" {split:>5}: positives={s['positives']:>6} leaked={s['leaked']:>4} "
112
+ f"fixed={s['fixed']:>4} unfixable={s['unfixable']:>3}")
113
+ print(json.dumps(summary, indent=2))
114
+
115
+
116
+ if __name__ == "__main__":
117
+ main()
scripts/rerender_kazakh3mix_lufs_uniform.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Re-render Kazakh3Mix mixtures using LibriMix's true LUFS-uniform convention.
3
+
4
+ The existing Kazakh3Mix renders use an SNR-driven scheme: all sources normalized
5
+ to -25 LUFS, then the target rescaled to be loudness-louder than the interferers.
6
+ That makes the Kazakh target +3.6 dB louder relative to the combined interferers
7
+ than the official LibriMix renders (where each source LUFS is drawn from
8
+ Uniform[-33, -25] independently and the resulting target/(sum interferers) is
9
+ naturally ~-3.5 dB).
10
+
11
+ This script:
12
+ - reads the EXISTING posneg manifests (preserves speaker assignments, splits,
13
+ pos/neg labels, enrollment/target pairings — none of those are broken),
14
+ - for each mixture, re-loads the 3 clean source files referenced by
15
+ `source_clean_paths`,
16
+ - draws each source's loudness independently from Uniform[-33, -25] LUFS,
17
+ - normalizes each via pyloudnorm, sums, prevents clipping (scale down only),
18
+ - writes new mix_clean / s1 / s2 / s3 wavs into a parallel output directory,
19
+ - writes a new manifest with `mixture_audio` / `target_in_mix_path` / `s*_path`
20
+ rewritten and the *observed* per-source SNR re-measured.
21
+
22
+ Run:
23
+ python scripts/rerender_kazakh3mix_lufs_uniform.py \
24
+ --in-manifest data/LibriMix/persona_asr/kazakh3mix_clean_max_16k/train_clean_100_kazakh3mix_clean_max_16k_posneg.json \
25
+ --out-audio-root /workspace/LibriMix/storage_dir/Kazakh3Mix_lufsfix/wav16k/max/train-100 \
26
+ --out-manifest data/LibriMix/persona_asr/kazakh3mix_clean_max_16k_lufsfix/train_clean_100_kazakh3mix_lufsfix_posneg.json \
27
+ --workers 16
28
+
29
+ Tiny smoke-test mode: pass `--limit 100` to render only the first 100 mixtures.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import json
35
+ import os
36
+ import random
37
+ import warnings
38
+ from concurrent.futures import ProcessPoolExecutor, as_completed
39
+ from pathlib import Path
40
+
41
+ import numpy as np
42
+ import soundfile as sf
43
+ from tqdm.auto import tqdm
44
+
45
+ warnings.filterwarnings("ignore")
46
+ import pyloudnorm as pyln # noqa: E402
47
+
48
+ SR = 16_000
49
+ LUFS_MIN = -33.0
50
+ LUFS_MAX = -25.0
51
+ SILENCE_LUFS = -70.0
52
+ MAX_AMP = 0.9
53
+ EPS = 1e-12
54
+
55
+
56
+ def lufs_of(audio: np.ndarray) -> float:
57
+ if len(audio) < int(0.4 * SR):
58
+ return SILENCE_LUFS
59
+ meter = pyln.Meter(SR)
60
+ try:
61
+ L = float(meter.integrated_loudness(audio.astype(np.float64)))
62
+ return L if np.isfinite(L) else SILENCE_LUFS
63
+ except Exception:
64
+ return SILENCE_LUFS
65
+
66
+
67
+ def normalize_to_lufs(audio: np.ndarray, target_lufs: float) -> np.ndarray:
68
+ cur = lufs_of(audio)
69
+ if cur <= SILENCE_LUFS + 1.0:
70
+ return audio.astype(np.float32)
71
+ gain = 10.0 ** ((target_lufs - cur) / 20.0)
72
+ return (audio.astype(np.float32) * gain)
73
+
74
+
75
+ def measure_snr_db(target: np.ndarray, interf_sum: np.ndarray) -> float:
76
+ n = max(len(target), len(interf_sum))
77
+ t = np.zeros(n, dtype=np.float64); t[: len(target)] = target
78
+ i = np.zeros(n, dtype=np.float64); i[: len(interf_sum)] = interf_sum
79
+ pt = float((t * t).mean() + EPS)
80
+ pi = float((i * i).mean() + EPS)
81
+ return 10.0 * np.log10(pt / pi)
82
+
83
+
84
+ def render_one(args: tuple) -> dict | None:
85
+ """Render one mixture. Returns updated manifest row or None on failure."""
86
+ row, out_audio_root, seed = args
87
+ try:
88
+ target_index = row.get("target_index")
89
+ is_pos = bool(row.get("is_target_present") or (row.get("label") == 1))
90
+ source_paths = row.get("source_clean_paths") or []
91
+ if not source_paths or len(source_paths) != 3:
92
+ return None
93
+ # Load sources
94
+ sources = []
95
+ for p in source_paths:
96
+ wav, sr = sf.read(p, dtype="float32")
97
+ if wav.ndim == 2:
98
+ wav = wav.mean(axis=1)
99
+ if sr != SR:
100
+ return None
101
+ sources.append(wav.astype(np.float32))
102
+
103
+ # LUFS-uniform sampling
104
+ rng = random.Random(seed)
105
+ lufs_targets = [rng.uniform(LUFS_MIN, LUFS_MAX) for _ in range(3)]
106
+ scaled = [normalize_to_lufs(w, l) for w, l in zip(sources, lufs_targets)]
107
+
108
+ # Pad to max length, sum (max mode)
109
+ n = max(len(s) for s in scaled)
110
+ padded = [np.concatenate([s, np.zeros(n - len(s), dtype=np.float32)]) for s in scaled]
111
+ mix = np.sum(padded, axis=0).astype(np.float64)
112
+
113
+ # Clipping prevention (only scale DOWN — LibriMix recipe)
114
+ peak = float(np.max(np.abs(mix))) if mix.size else 0.0
115
+ clip_scale = 1.0
116
+ if peak > MAX_AMP:
117
+ clip_scale = MAX_AMP / peak
118
+ mix = mix * clip_scale
119
+ padded = [(p * clip_scale).astype(np.float32) for p in padded]
120
+
121
+ mix = mix.astype(np.float32)
122
+
123
+ # Observed SNR (target vs sum of two interferers)
124
+ snr_db = None
125
+ if is_pos and target_index is not None and 0 <= int(target_index) < 3:
126
+ ti = int(target_index)
127
+ others = [padded[i] for i in range(3) if i != ti]
128
+ snr_db = round(float(measure_snr_db(padded[ti], np.sum(others, axis=0))), 3)
129
+
130
+ # Write files
131
+ mix_id = row.get("mixture_id")
132
+ out_audio_root = Path(out_audio_root)
133
+ (out_audio_root / "mix_clean").mkdir(parents=True, exist_ok=True)
134
+ for si in ("s1", "s2", "s3"):
135
+ (out_audio_root / si).mkdir(parents=True, exist_ok=True)
136
+ mix_path = out_audio_root / "mix_clean" / f"{mix_id}.wav"
137
+ sf.write(str(mix_path), mix, SR, subtype="PCM_16")
138
+ s_paths = []
139
+ for i, p in enumerate(padded, start=1):
140
+ sp = out_audio_root / f"s{i}" / f"{mix_id}.wav"
141
+ sf.write(str(sp), p.astype(np.float32), SR, subtype="PCM_16")
142
+ s_paths.append(str(sp))
143
+
144
+ # Build updated row
145
+ out_row = dict(row)
146
+ out_row["mixture_audio"] = str(mix_path)
147
+ out_row["s1_path"] = s_paths[0]
148
+ out_row["s2_path"] = s_paths[1]
149
+ out_row["s3_path"] = s_paths[2]
150
+ out_row["target_in_mix_path"] = s_paths[int(target_index)] if (is_pos and target_index is not None) else None
151
+ out_row["snr_db"] = snr_db
152
+ out_row["requested_snr_db"] = None # no longer requested; observed only
153
+ out_row["source_snr_scale"] = None
154
+ out_row["controlled_source_index"] = None
155
+ out_row["lufs_per_source"] = [round(l, 3) for l in lufs_targets]
156
+ out_row["clip_scale"] = round(clip_scale, 6)
157
+ out_row["mixture_variant"] = "kazakh3mix_wav16k_max_mix_clean_lufsfix"
158
+ return out_row
159
+ except Exception as e:
160
+ return {"_error": f"{type(e).__name__}: {e}", "id": row.get("id")}
161
+
162
+
163
+ def main() -> None:
164
+ ap = argparse.ArgumentParser()
165
+ ap.add_argument("--in-manifest", type=Path, required=True)
166
+ ap.add_argument("--out-audio-root", type=Path, required=True,
167
+ help="e.g. /workspace/LibriMix/storage_dir/Kazakh3Mix_lufsfix/wav16k/max/train-100")
168
+ ap.add_argument("--out-manifest", type=Path, required=True)
169
+ ap.add_argument("--workers", type=int, default=16)
170
+ ap.add_argument("--limit", type=int, default=0,
171
+ help="Render only first N rows (smoke test). 0 = all.")
172
+ ap.add_argument("--seed", type=int, default=42)
173
+ args = ap.parse_args()
174
+
175
+ rows = json.loads(args.in_manifest.read_text())
176
+ if args.limit and args.limit > 0:
177
+ rows = rows[: args.limit]
178
+ print(f"[rerender] in={args.in_manifest.name} rows={len(rows)} → out_audio={args.out_audio_root} workers={args.workers}")
179
+
180
+ args.out_audio_root.mkdir(parents=True, exist_ok=True)
181
+ args.out_manifest.parent.mkdir(parents=True, exist_ok=True)
182
+
183
+ rng = random.Random(args.seed)
184
+ jobs = [(row, str(args.out_audio_root), rng.randint(0, 10**9)) for row in rows]
185
+ new_rows: list[dict] = []
186
+ errors = 0
187
+ with ProcessPoolExecutor(max_workers=args.workers) as pool:
188
+ futures = [pool.submit(render_one, j) for j in jobs]
189
+ for fut in tqdm(as_completed(futures), total=len(futures), desc=args.in_manifest.stem):
190
+ r = fut.result()
191
+ if r is None:
192
+ errors += 1
193
+ continue
194
+ if "_error" in r:
195
+ errors += 1
196
+ continue
197
+ new_rows.append(r)
198
+
199
+ new_rows.sort(key=lambda r: r.get("id", ""))
200
+ args.out_manifest.write_text(json.dumps(new_rows, ensure_ascii=False, indent=2))
201
+ print(f"[rerender] wrote {args.out_manifest} ({len(new_rows)} rows; {errors} errors)")
202
+
203
+ # Quick stats
204
+ pos = [r for r in new_rows if r.get("is_target_present")]
205
+ snrs = [r.get("snr_db") for r in pos if r.get("snr_db") is not None]
206
+ if snrs:
207
+ a = np.array(snrs)
208
+ print(f"[rerender] observed target/(sum interferers) SNR (positives): "
209
+ f"mean={a.mean():+.2f} std={a.std():.2f} p10={np.percentile(a, 10):+.2f} p90={np.percentile(a, 90):+.2f}")
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
test_clean_kazakh3mix_lufsfix_posneg.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:586fcecbd265331c01a53161044a6762678f4fcbb01bb1032704a818106a5f38
3
+ size 29947999
train_clean_100_kazakh3mix_lufsfix_posneg.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a592d42d462c7110cafa60020b17a04f270b36c829e582b5ca29396ab2d6d90
3
+ size 144716595
val_kazakh3mix_lufsfix_posneg.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33387b3deaf4cee6e04bfc457758197977a12f7c62686751811660c6e7121862
3
+ size 29749563
Free AI Image Generator No sign-up. Instant results. Open Now