Download process/process_raw2wav.py from OpenTSLab/MachineHearing: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/datasets/OpenTSLab/MachineHearing/resolve/main/process/process_raw2wav.py
- Command line
-
hf download hf://datasets/OpenTSLab/MachineHearing/process/process_raw2wav.py
-
curl -L -o process_raw2wav.py https://huggingface.co/datasets/OpenTSLab/MachineHearing/resolve/main/process/process_raw2wav.py
2.45 kB
| # -*- coding: utf-8 -*- | |
| import json | |
| import wave | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path(__file__).resolve().parent.parent | |
| CONVERT_TASKS = {"GWOSC", "LEAVES", "Iquique", "Llaima", "RadSeg", "RadioML"} | |
| def main(): | |
| total = converted = 0 | |
| with (ROOT / "meta_data.jsonl").open("r", encoding="utf-8") as fin, \ | |
| (ROOT / "wav_data.jsonl").open("w", encoding="utf-8") as fout: | |
| for line in fin: | |
| if not line.strip(): | |
| continue | |
| data = json.loads(line) | |
| if data["task_name"] in CONVERT_TASKS: | |
| data_type = data["data_type"] | |
| assert data_type in ("csv", "npy") | |
| src_rel = Path(data["input_ts"]["path"]) | |
| src_path = ROOT / src_rel | |
| assert src_rel.parent.name == "raw_input" and src_path.is_file() | |
| if data_type == "csv": | |
| signal = pd.read_csv(src_path, header=None).values | |
| else: | |
| signal = np.load(src_path) | |
| signal = signal.flatten().astype(np.float64) | |
| assert signal.size > 0 | |
| abs_max = np.max(np.abs(signal)) | |
| if abs_max > 0: | |
| signal = signal / abs_max | |
| signal = (signal * 32767).astype(np.int16) | |
| wav_rel = src_rel.parent.parent / "wav_input" / (src_rel.stem + ".wav") | |
| wav_path = ROOT / wav_rel | |
| wav_path.parent.mkdir(parents=True, exist_ok=True) | |
| with wave.open(str(wav_path), "wb") as wf: | |
| wf.setnchannels(1) | |
| wf.setsampwidth(2) | |
| wf.setframerate(16000) | |
| wf.writeframes(signal.tobytes()) | |
| data["data_type"] = "wav" | |
| data["input_ts"]["path"] = wav_rel.as_posix() | |
| data["input_ts"]["length"] = int(signal.size) | |
| data["input_ts"]["num_channel"] = 1 | |
| data["input_ts"]["fs"] = 16000 | |
| if data["task_name"] in ("Iquique", "RadSeg", "RadioML"): | |
| data["input_ts"]["channel_detail"] = [] | |
| converted += 1 | |
| fout.write(json.dumps(data, ensure_ascii=False) + "\n") | |
| total += 1 | |
| assert total == 6128 and converted == 3428 | |
| print(f"Done: {converted} WAV files, {total} JSONL records") | |
| if __name__ == "__main__": | |
| main() | |