manifest_tools.py
4.71 KB
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
143
144
"""External dataset manifest conversion templates."""
from __future__ import annotations
import argparse
import csv
import json
import random
from pathlib import Path
from typing import List, Dict
import soundfile as sf
def write_catalog(records: List[Dict], output_path: Path):
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w") as f:
json.dump(records, f, indent=2, ensure_ascii=False)
def csv_to_catalog(csv_path: Path, output_path: Path, path_field: str = "audio_path", id_field: str = "song_id"):
records = []
with open(csv_path, newline="") as f:
reader = csv.DictReader(f)
for row in reader:
records.append(
{
"song_id": row[id_field],
"audio_path": row[path_field],
"duration": float(row.get("duration", 0.0) or 0.0),
"type": "reference",
"source_dataset": row.get("source_dataset", "external"),
}
)
write_catalog(records, output_path)
return len(records)
def build_train_eval_from_audio_dir(
audio_dir: Path,
output_dir: Path,
source_dataset: str,
exts: tuple[str, ...] = (".wav", ".mp3", ".flac", ".ogg"),
eval_ratio: float = 0.2,
query_duration: float = 8.0,
seed: int = 42,
):
rng = random.Random(seed)
files = [p for p in sorted(audio_dir.rglob("*")) if p.suffix.lower() in exts]
output_dir.mkdir(parents=True, exist_ok=True)
manifests_dir = output_dir / "manifests"
manifests_dir.mkdir(parents=True, exist_ok=True)
refs = []
train = []
test = []
for idx, path in enumerate(files):
rel = path.relative_to(output_dir.parent if output_dir.parent in path.parents else audio_dir.parent)
song_id = f"{source_dataset}_{idx:05d}"
try:
info = sf.info(str(path))
duration = float(info.duration)
except Exception:
duration = 0.0
ref = {
"song_id": song_id,
"audio_path": str(rel),
"duration": duration,
"type": "reference",
"source_dataset": source_dataset,
}
refs.append(ref)
if duration >= query_duration:
max_offset = max(0.0, duration - query_duration)
offset = rng.uniform(0.0, max_offset) if max_offset > 0 else 0.0
query = {
"song_id": song_id,
"audio_path": str(rel),
"duration": query_duration,
"type": "clean",
"offset": round(offset, 3),
"segment_type": "external_query",
"source_dataset": source_dataset,
}
if rng.random() < eval_ratio:
test.append(query)
else:
train.append(query)
if len(files) >= 2 and not train and test:
train.append(test.pop())
if len(files) >= 2 and not test and train:
test.append(train.pop())
write_catalog(refs, manifests_dir / "catalog.json")
write_catalog(train + refs, manifests_dir / "train.json")
write_catalog(test + refs, manifests_dir / "test.json")
write_catalog([], manifests_dir / "val.json")
return {
"catalog": len(refs),
"train_queries": len(train),
"test_queries": len(test),
"output_dir": str(manifests_dir),
}
def main():
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("csv-to-catalog")
p.add_argument("csv_path")
p.add_argument("output_path")
p.add_argument("--path-field", default="audio_path")
p.add_argument("--id-field", default="song_id")
p = sub.add_parser("audio-dir-to-splits")
p.add_argument("audio_dir")
p.add_argument("output_dir")
p.add_argument("--source-dataset", required=True)
p.add_argument("--eval-ratio", type=float, default=0.2)
p.add_argument("--query-duration", type=float, default=8.0)
p.add_argument("--seed", type=int, default=42)
args = parser.parse_args()
if args.cmd == "csv-to-catalog":
count = csv_to_catalog(Path(args.csv_path), Path(args.output_path), args.path_field, args.id_field)
print(json.dumps({"status": "ok", "records": count}, ensure_ascii=False))
elif args.cmd == "audio-dir-to-splits":
summary = build_train_eval_from_audio_dir(
Path(args.audio_dir),
Path(args.output_dir),
source_dataset=args.source_dataset,
eval_ratio=args.eval_ratio,
query_duration=args.query_duration,
seed=args.seed,
)
print(json.dumps({"status": "ok", **summary}, ensure_ascii=False))
if __name__ == "__main__":
main()