music2chords / convert2jsonl.py
taohu's picture
Upload folder using huggingface_hub
b3b13f7 verified
Raw History Blame Contribute Delete
7.77 kB
# data/Chords1217/convert2jsonl.py
"""
Use torchaudio to uniformly load audio files and extract metadata, converting
the contents of the audio/ and chordlab/ folders in the Chords1217 dataset into JSONL format.
Additionally, this version uses multiprocessing + a progress bar and
splits the final records into train/val/test (60/20/20) with seed=42.
Expected directory structure:
data/Chords1217/
├── audio/
│ ├── xxx.wav
│ ├── yyy.mp3
│ └── ...
└── chordlab/
├── xxx.lab
├── yyy.lab
└── ...
One .lab file may look like this:
0.0 0.21500000000000002 N
0.21500000000000002 1.6290000000000002 F#:min7
1.629 2.966 A:maj
2.966 4.287000000000001 E:sus4
4.287 5.709 B:sus4(b7)
5.7090000000000005 7.1370000000000005 F#:min7
"""
import os
import json
import random
from functools import partial
from multiprocessing import Pool, cpu_count
import torchaudio
from tqdm import tqdm
def write_jsonl(data, output_file):
"""
Write a list of dictionaries to a JSONL file (one JSON object per line).
"""
with open(output_file, 'w', encoding='utf-8') as f:
for item in data:
json.dump(item, f, ensure_ascii=False)
f.write('\n')
def get_audio_info(audio_path):
"""
Use torchaudio.info to retrieve audio metadata:
- duration: seconds (num_frames / sample_rate)
- sample_rate: Hz
- num_samples: total number of frames
- bit_depth: bits per sample (may be None for some formats)
- channels: number of channels
torchaudio supports multiple formats (wav, mp3, flac, ogg, etc.) provided
that the backend (sox/ffmpeg) is correctly installed.
"""
info = torchaudio.info(audio_path)
sample_rate = info.sample_rate
num_samples = info.num_frames
channels = info.num_channels
# bits_per_sample may be None for certain file types
bit_depth = info.bits_per_sample if hasattr(info, 'bits_per_sample') else None
duration = num_samples / sample_rate if sample_rate else 0.0
return duration, sample_rate, num_samples, bit_depth, channels
def parse_lab_file(lab_path):
"""
Parse a .lab file and return a list of chord segments:
[
{"start_time": float, "end_time": float, "chord_str": str},
...
]
Each line in the .lab file is expected to be:
start_time <tab> end_time <tab> chord_str
"""
chord_seq = []
with open(lab_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line:
continue
parts = line.split()
if len(parts) < 3:
# Skip lines that don't have at least 3 columns
continue
try:
start_time = float(parts[0])
end_time = float(parts[1])
chord_str = parts[2]
except ValueError:
# Skip lines with invalid floats
continue
chord_seq.append({
"start_time": start_time,
"end_time": end_time,
"chord_str": chord_str
})
return chord_seq
def process_single_file(fname, audio_dir, lab_dir):
"""
Given a filename (e.g. "xxx.wav"), parse its corresponding .lab file,
extract audio metadata, and return a record dict. If anything fails,
return None to indicate skipping.
"""
ext = os.path.splitext(fname)[1].lower()
if ext not in ['.wav', '.mp3', '.flac', '.ogg', '.aac', '.m4a']:
return None
audio_path = os.path.join(audio_dir, fname)
base_name = os.path.splitext(fname)[0]
lab_path = os.path.join(lab_dir, base_name + '.lab')
if not os.path.isfile(lab_path):
# No corresponding .lab file → skip
return None
# 1. Parse the .lab file to get chord sequence
chord_seq = parse_lab_file(lab_path)
if not chord_seq:
# If lab parsing yields nothing, still include an empty list
chord_seq = []
# 2. Get audio metadata using torchaudio
try:
duration, sample_rate, num_samples, bit_depth, channels = get_audio_info(audio_path)
except Exception:
# Failed to read audio file → skip
return None
# 3. Build the record dictionary
record = {
"audio_path": audio_path,
"label": chord_seq,
"duration": duration,
"sample_rate": sample_rate,
"num_samples": num_samples,
"bit_depth": bit_depth,
"channels": channels
}
return record
def convert_chords_to_jsonl(root_dir):
"""
Traverse the audio/ and chordlab/ subdirectories under root_dir and build JSONL output.
Uses multiprocessing + tqdm to speed up. After collecting all records, sorts them,
randomly splits into train/val/test (60/20/20) with seed=42, and writes three JSONL files.
"""
audio_dir = os.path.join(root_dir, "audio")
lab_dir = os.path.join(root_dir, "chordlab")
if not os.path.isdir(audio_dir):
print(f"Error: audio directory not found: {audio_dir}")
return
if not os.path.isdir(lab_dir):
print(f"Error: chordlab directory not found: {lab_dir}")
return
# List and sort all filenames in the audio directory
all_files = [
fname for fname in os.listdir(audio_dir)
if os.path.splitext(fname)[1].lower() in ['.wav', '.mp3', '.flac', '.ogg', '.aac', '.m4a']
]
all_files.sort() # sort alphabetically to have a deterministic order before splitting
# Prepare a partial function for multiprocessing
worker = partial(process_single_file, audio_dir=audio_dir, lab_dir=lab_dir)
# Use as many processes as CPU cores (minus 1 or so, but here we’ll just use all)
num_workers = max(1, cpu_count() - 1)
records = []
with Pool(processes=num_workers) as pool:
# imap_unordered to get results as they finish, and wrap with tqdm for progress bar
for result in tqdm(pool.imap_unordered(worker, all_files), total=len(all_files),
desc="Processing files", unit="file"):
if result is not None:
records.append(result)
if not records:
print("No valid records were processed. Exiting.")
return
# Sort records by audio_path (or any other field) to make the final order deterministic
records.sort(key=lambda x: x["audio_path"])
# Now split into train/val/test = 60%/20%/20% with seed=42
random.seed(42)
random.shuffle(records)
n = len(records)
n_train = int(0.6 * n)
n_val = int(0.2 * n)
# Ensure that all records are used; leftover go to test
n_test = n - n_train - n_val
train_records = records[:n_train]
val_records = records[n_train:n_train + n_val]
test_records = records[n_train + n_val:]
# Make sure output directory exists
os.makedirs(root_dir, exist_ok=True)
# Write out three separate JSONL files
write_jsonl(train_records, os.path.join(root_dir, "Chords1217.train.jsonl"))
write_jsonl(val_records, os.path.join(root_dir, "Chords1217.val.jsonl"))
write_jsonl(test_records, os.path.join(root_dir, "Chords1217.test.jsonl"))
print(f"Total files processed: {n}")
print(f" → Train: {len(train_records)} records")
print(f" → Validation: {len(val_records)} records")
print(f" → Test: {len(test_records)} records")
print(f"Outputs written to:\n"
f" {os.path.join(root_dir, 'Chords1217.train.jsonl')}\n"
f" {os.path.join(root_dir, 'Chords1217.val.jsonl')}\n"
f" {os.path.join(root_dir, 'Chords1217.test.jsonl')}")
if __name__ == "__main__":
convert_chords_to_jsonl("data/Chords1217")