File size: 3,404 Bytes
7d604c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import csv
import uuid
import wave
from pathlib import Path


def read_wav_info(wav_path: Path) -> tuple[int, float]:
    with wave.open(str(wav_path), "rb") as wav_file:
        sample_rate = wav_file.getframerate()
        frame_count = wav_file.getnframes()
    duration_seconds = frame_count / sample_rate if sample_rate else 0.0
    return sample_rate, duration_seconds


def collect_metadata(raw_dir: Path) -> list[dict[str, object]]:
    wav_files = sorted(raw_dir.glob("*.wav"))
    metadata = []
    for index, wav_path in enumerate(wav_files):
        sample_rate, duration_seconds = read_wav_info(wav_path)
        sequence = f"{index:08d}"
        metadata.append(
            {
                "source_path": wav_path,
                "sequence": sequence,
                "sample_rate": sample_rate,
                "duration_seconds": duration_seconds,
            }
        )
    return metadata


def rename_files(metadata: list[dict[str, object]]) -> None:
    rename_pairs = []
    finalized_pairs = []
    for item in metadata:
        source_path = item["source_path"]
        temp_name = f".__tmp__{uuid.uuid4().hex}.wav"
        temp_path = source_path.with_name(temp_name)
        source_path.rename(temp_path)
        rename_pairs.append((temp_path, source_path))
        item["source_path"] = temp_path

    try:
        for item in metadata:
            temp_path = item["source_path"]
            final_path = temp_path.with_name(f"{item['sequence']}.wav")
            temp_path.rename(final_path)
            finalized_pairs.append((final_path, temp_path))
            item["final_path"] = final_path
    except Exception:
        for final_path, temp_path in reversed(finalized_pairs):
            if final_path.exists():
                final_path.rename(temp_path)
        for temp_path, original_path in rename_pairs:
            if temp_path.exists():
                temp_path.rename(original_path)
        raise


def write_csv(csv_path: Path, metadata: list[dict[str, object]]) -> None:
    with csv_path.open("w", newline="", encoding="utf-8-sig") as csv_file:
        writer = csv.DictWriter(
            csv_file,
            fieldnames=["sequence", "sample_rate", "duration_seconds"],
        )
        writer.writeheader()
        for item in metadata:
            writer.writerow(
                {
                    "sequence": item["sequence"],
                    "sample_rate": item["sample_rate"],
                    "duration_seconds": f"{item['duration_seconds']:.6f}",
                }
            )


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Rename WAV files under raw/ to 8-digit integers and rebuild raw.csv."
    )
    parser.add_argument("--raw-dir", default="raw", help="Directory containing WAV files.")
    parser.add_argument("--csv-path", default="raw.csv", help="Output CSV path.")
    args = parser.parse_args()

    raw_dir = Path(args.raw_dir).resolve()
    csv_path = Path(args.csv_path).resolve()

    if not raw_dir.exists():
        raise FileNotFoundError(f"Raw directory not found: {raw_dir}")

    metadata = collect_metadata(raw_dir)
    rename_files(metadata)
    write_csv(csv_path, metadata)

    print(f"Processed {len(metadata)} wav files.")
    print(f"Renamed files in: {raw_dir}")
    print(f"Wrote metadata to: {csv_path}")


if __name__ == "__main__":
    main()