Datasets:

License:
File size: 3,982 Bytes
380b711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from pathlib import Path
from multiprocessing import Pool, cpu_count
import shutil
from tqdm import tqdm
from pydub import AudioSegment
from pydub.exceptions import PydubException

# --- Configuration ---
# Source directory containing MP3 files.
SOURCE_ROOT = Path("data/MTG/audio-low")
# Destination directory for FLAC files.
DEST_ROOT = Path("data/MTG/audio")
# Number of processes to use. Defaults to the number of CPU cores.
PROCESS_COUNT = cpu_count()

def check_ffmpeg():
    """Checks if ffmpeg is installed, as pydub requires it for mp3/flac support."""
    if not shutil.which("ffmpeg"):
        print("Error: ffmpeg is not installed or not in your system's PATH.")
        print("pydub requires ffmpeg for mp3 and flac processing.")
        print("Please install ffmpeg to run this script.")
        print(" - on Ubuntu/Debian: sudo apt install ffmpeg")
        print(" - on macOS (Homebrew): brew install ffmpeg")
        return False
    return True

def process_file(task):
    """
    Converts a single mp3 file to flac using pydub.
    This function is designed to be called by a multiprocessing Pool.
    
    Args:
        task (tuple): A tuple containing (mp3_path, flac_path).

    Returns:
        str: A status message ('skipped', 'converted', 'failed').
    """
    mp3_path, flac_path = task

    try:
        # Skip if the destination file already exists.
        if flac_path.exists():
            return "skipped"

        # Ensure the destination directory exists.
        flac_path.parent.mkdir(parents=True, exist_ok=True)

        # Load the mp3 file using pydub
        audio = AudioSegment.from_file(str(mp3_path), format="mp3")
        
        # Export the audio to flac format
        audio.export(str(flac_path), format="flac")
        
        return "converted"
        
    except PydubException as e:
        # Handle exceptions specifically from pydub
        print(f"\n--- PYDUB Error for {mp3_path.name}: {e} ---")
        return "failed"
    except Exception as e:
        # Handle other unexpected errors (e.g., file permissions)
        print(f"\n--- An unexpected error occurred for {mp3_path.name}: {e} ---")
        return "failed"


def main():
    """Main function to discover files and run the conversion process."""
    if not check_ffmpeg():
        return
        
    if not SOURCE_ROOT.is_dir():
        print(f"Error: Source directory not found at '{SOURCE_ROOT}'")
        return

    print(f"Source directory: {SOURCE_ROOT}")
    print(f"Destination directory: {DEST_ROOT}")
    print(f"Using {PROCESS_COUNT} processes for conversion.")
    
    # Discover all .mp3 files recursively in the source directory.
    print("Finding all mp3 files...")
    mp3_files = list(SOURCE_ROOT.rglob("*.mp3"))

    if not mp3_files:
        print("No .mp3 files found in the source directory.")
        return
        
    print(f"Found {len(mp3_files)} mp3 files to process.")

    # Create a list of tasks (input_path, output_path) for the process pool.
    tasks = []
    for mp3_path in mp3_files:
        relative_path = mp3_path.relative_to(SOURCE_ROOT)
        flac_path = (DEST_ROOT / relative_path).with_suffix(".flac")
        tasks.append((mp3_path, flac_path))

    # Use a multiprocessing Pool to process files in parallel.
    print("Starting conversion with pydub...")
    with Pool(processes=PROCESS_COUNT) as pool:
        results = list(tqdm(pool.imap_unordered(process_file, tasks), total=len(tasks)))

    # Print summary
    converted_count = results.count("converted")
    skipped_count = results.count("skipped")
    failed_count = results.count("failed")
    
    print("\n--- Conversion Summary ---")
    print(f"Total files: {len(tasks)}")
    print(f"Successfully converted: {converted_count}")
    print(f"Skipped (already exist): {skipped_count}")
    print(f"Failed: {failed_count}")
    print("--------------------------")
    print("All tasks complete.")


if __name__ == "__main__":
    main()