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()