Datasets:

Modalities:
Audio
Image
License:
GTZAN / convert2jsonl_rhythm.py
a43992899's picture
Upload folder using huggingface_hub
3b38eca verified
import os
import json
import wave
import jams # pip install jams
def load_txt(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return [line.strip() for line in lines]
def write_jsonl(data, output_file):
with open(output_file, 'w') as file:
for item in data:
json.dump(item, file)
file.write('\n')
def get_audio_info(audio_path):
"""
Extract duration (seconds), sample_rate (Hz), num_samples (int), bit_depth (bits), and channels (int) from a WAV file.
"""
with wave.open(audio_path, 'rb') as wf:
sample_rate = wf.getframerate()
num_samples = wf.getnframes()
duration = num_samples / float(sample_rate)
sample_width = wf.getsampwidth() # in bytes
bit_depth = sample_width * 8 # convert to bits
channels = wf.getnchannels() # number of audio channels
return duration, sample_rate, num_samples, bit_depth, channels
def get_label_from_jams(path):
jam_obj = jams.load(path)
full_data = {
"beat": [],
"downbeat": [],
"tempo": None,
"meter": None
}
for ann in jam_obj.search(namespace="beat"):
anno_type = ann['sandbox']['annotation_type']
for i in ann['data']:
# onset time in seconds of the beats
if anno_type == 'beat':
full_data['beat'].append(i.time)
elif anno_type == 'downbeat':
full_data['downbeat'].append(i.time)
else:
print(f"Unknown annotation type: {anno_type}") # 8-th notes are removed
for ann in jam_obj.search(namespace="tag_open"):
if "meter" in ann['sandbox']:
full_data['meter'] = ann['sandbox']['meter']
full_data['tempo'] = float(ann['sandbox']['tempo mean'])
return full_data
def convert_gtzan_rhythm_to_jsonl(output_dir):
# Paths to filtered file lists
train_txt = os.path.join(output_dir, "train_filtered.txt")
val_txt = os.path.join(output_dir, "valid_filtered.txt")
test_txt = os.path.join(output_dir, "test_filtered.txt")
train_list = load_txt(train_txt)
val_list = load_txt(val_txt)
test_list = load_txt(test_txt)
train_jsonl, val_jsonl, test_jsonl = [], [], []
prefix = os.path.join(output_dir, "genres")
# Process each split and append metadata
for split_list, out_list in [(train_list, train_jsonl), (val_list, val_jsonl), (test_list, test_jsonl)]:
for rel_path in split_list:
path = os.path.join(prefix, rel_path)
wav_filename = os.path.basename(path)
jams_path = os.path.join(output_dir, 'GTZAN-Rhythm_v2_ismir2015_lbd/jams/', wav_filename.replace('.wav', '.wav.jams'))
label = get_label_from_jams(jams_path)
try:
duration, sr, num_samples, bit_depth, channels = get_audio_info(path)
except Exception as e:
print(f"Error reading {path}: {e}")
continue
out_list.append({
"audio_path": path,
"label": label,
"duration": duration,
"sample_rate": sr,
"num_samples": num_samples,
"bit_depth": bit_depth,
"channels": channels
})
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
write_jsonl(train_jsonl, os.path.join(output_dir, "GTZANBeatTracking.train.jsonl"))
write_jsonl(val_jsonl, os.path.join(output_dir, "GTZANBeatTracking.val.jsonl"))
write_jsonl(test_jsonl, os.path.join(output_dir, "GTZANBeatTracking.test.jsonl"))
print(f"train: {len(train_jsonl)}, val: {len(val_jsonl)}, test: {len(test_jsonl)}")
print("Conversion completed.")
if __name__ == "__main__":
convert_gtzan_rhythm_to_jsonl("data/GTZAN")