Spaces:
Sleeping
Sleeping
Download src/main.py from Shahzroux/audio-mastering-engine: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/Shahzroux/audio-mastering-engine/resolve/main/src/main.py
- Command line
-
hf download hf://spaces/Shahzroux/audio-mastering-engine/src/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Shahzroux/audio-mastering-engine/resolve/main/src/main.py
11.6 kB
| """ | |
| Main Mastering Engine Application | |
| Command-line interface for AI-powered mastering | |
| """ | |
| import sys | |
| import os | |
| from pathlib import Path | |
| from typing import Optional | |
| # Add src to path | |
| sys.path.insert(0, str(Path(__file__).parent.parent)) | |
| from analysis.audio_analyzer import AudioAnalyzer | |
| from ai.genre_classifier import SimpleGenreDetector | |
| from ai.preset_system import PresetLibrary | |
| from dsp.processor import MasteringProcessor | |
| class MasteringEngine: | |
| """ | |
| Main mastering engine class that coordinates all components | |
| """ | |
| def __init__(self): | |
| print("π΅ Initializing Mastering Engine...") | |
| self.analyzer = AudioAnalyzer() | |
| self.genre_detector = SimpleGenreDetector() | |
| self.preset_library = PresetLibrary() | |
| self.processor = MasteringProcessor() | |
| print("β Engine ready!\n") | |
| def analyze_audio(self, audio_path: str): | |
| """Analyze audio file""" | |
| features = self.analyzer.analyze(audio_path) | |
| self.analyzer.print_analysis(features) | |
| return features | |
| def suggest_presets(self, audio_path: str, num_suggestions: int = 3): | |
| """ | |
| Analyze audio and suggest best presets | |
| """ | |
| print("π Analyzing audio and suggesting presets...\n") | |
| # Analyze | |
| features = self.analyzer.analyze(audio_path) | |
| # Detect genre | |
| genre_probs = self.genre_detector.detect_genre(features) | |
| top_genre = max(genre_probs, key=genre_probs.get) | |
| print(f"πΈ Detected Genre: {top_genre.upper()}") | |
| print(f" Confidence: {genre_probs[top_genre]*100:.1f}%\n") | |
| # Get presets for this genre | |
| genre_presets = self.preset_library.get_presets_by_category(top_genre) | |
| if not genre_presets: | |
| print(f"β οΈ No presets found for genre '{top_genre}'") | |
| print(" Using general presets instead.\n") | |
| genre_presets = list(self.preset_library.presets.values())[:3] | |
| # Limit to num_suggestions | |
| suggested = genre_presets[:num_suggestions] | |
| print(f"π‘ Suggested Presets ({len(suggested)}):") | |
| for i, preset in enumerate(suggested, 1): | |
| print(f"\n {i}. {preset.name}") | |
| print(f" {preset.description}") | |
| print(f" Target: {preset.target_lufs} LUFS") | |
| print() | |
| return suggested | |
| def master_audio(self, | |
| input_path: str, | |
| output_path: Optional[str] = None, | |
| preset_name: Optional[str] = None, | |
| auto_preset: bool = False): | |
| """ | |
| Master audio file | |
| Args: | |
| input_path: Input audio file | |
| output_path: Output file path (auto-generated if None) | |
| preset_name: Name of preset to use | |
| auto_preset: Automatically select best preset | |
| """ | |
| # Validate input | |
| if not os.path.exists(input_path): | |
| print(f"β Error: File not found: {input_path}") | |
| return | |
| # Generate output path if not provided | |
| if output_path is None: | |
| input_file = Path(input_path) | |
| output_path = str(input_file.parent / f"{input_file.stem}_mastered{input_file.suffix}") | |
| # Get preset | |
| if auto_preset: | |
| print("π€ Auto-selecting best preset...") | |
| suggested = self.suggest_presets(input_path, num_suggestions=1) | |
| preset = suggested[0] | |
| elif preset_name: | |
| preset = self.preset_library.get_preset(preset_name) | |
| if not preset: | |
| print(f"β Error: Preset '{preset_name}' not found") | |
| print(f"\nAvailable presets:") | |
| for name in self.preset_library.list_all_presets(): | |
| print(f" β’ {name}") | |
| return | |
| else: | |
| print("β Error: Please specify preset_name or use auto_preset=True") | |
| return | |
| # Process | |
| print(f"\nποΈ Mastering with: {preset.name}") | |
| results = self.processor.process_file(input_path, output_path, preset) | |
| # Print summary | |
| print("\n" + "="*60) | |
| print("β MASTERING COMPLETE!") | |
| print("="*60) | |
| print(f"π₯ Input: {input_path}") | |
| print(f"π€ Output: {output_path}") | |
| print(f"\nπ Results:") | |
| print(f" Input: {results['input_lufs']:.1f} LUFS, Peak: {results['input_peak_db']:.1f} dBFS") | |
| print(f" Output: {results['output_lufs']:.1f} LUFS, Peak: {results['output_peak_db']:.1f} dBFS") | |
| print(f" Change: {results['lufs_change']:+.1f} LU") | |
| print("="*60 + "\n") | |
| return results | |
| def batch_master(self, | |
| input_folder: str, | |
| output_folder: str, | |
| preset_name: str = None, | |
| auto_preset: bool = True): | |
| """ | |
| Master multiple files in a folder | |
| """ | |
| input_path = Path(input_folder) | |
| output_path = Path(output_folder) | |
| # Create output folder | |
| output_path.mkdir(parents=True, exist_ok=True) | |
| # Find audio files | |
| audio_extensions = ['.wav', '.mp3', '.flac', '.aiff', '.m4a'] | |
| audio_files = [] | |
| for ext in audio_extensions: | |
| audio_files.extend(input_path.glob(f'*{ext}')) | |
| if not audio_files: | |
| print(f"β No audio files found in {input_folder}") | |
| return | |
| print(f"π Found {len(audio_files)} audio files") | |
| print(f"π€ Output folder: {output_folder}\n") | |
| # Process each file | |
| results = [] | |
| for i, audio_file in enumerate(audio_files, 1): | |
| print(f"\n{'='*60}") | |
| print(f"Processing {i}/{len(audio_files)}: {audio_file.name}") | |
| print(f"{'='*60}") | |
| output_file = output_path / f"{audio_file.stem}_mastered{audio_file.suffix}" | |
| result = self.master_audio( | |
| str(audio_file), | |
| str(output_file), | |
| preset_name=preset_name, | |
| auto_preset=auto_preset | |
| ) | |
| if result: | |
| results.append({ | |
| 'file': audio_file.name, | |
| **result | |
| }) | |
| # Summary | |
| print("\n" + "="*60) | |
| print("π BATCH MASTERING COMPLETE!") | |
| print("="*60) | |
| print(f"Processed: {len(results)} files") | |
| print(f"Output: {output_folder}") | |
| print("="*60 + "\n") | |
| return results | |
| def list_presets(self, category: Optional[str] = None): | |
| """List available presets""" | |
| print("\nπ AVAILABLE PRESETS") | |
| print("="*60) | |
| if category: | |
| presets = self.preset_library.get_presets_by_category(category) | |
| print(f"Category: {category.upper()}") | |
| else: | |
| presets = self.preset_library.presets.values() | |
| print("All Categories") | |
| # Group by category | |
| by_category = {} | |
| for preset in presets: | |
| if preset.category not in by_category: | |
| by_category[preset.category] = [] | |
| by_category[preset.category].append(preset) | |
| # Print grouped | |
| for cat, cat_presets in sorted(by_category.items()): | |
| print(f"\nπΈ {cat.upper()}:") | |
| for preset in cat_presets: | |
| preset_key = preset.name.lower().replace(' ', '_') | |
| print(f" β’ {preset_key:25s} - {preset.description}") | |
| print("\n" + "="*60 + "\n") | |
| def show_preset(self, preset_name: str): | |
| """Show detailed preset information""" | |
| self.preset_library.print_preset_info(preset_name) | |
| def main(): | |
| """ | |
| Main CLI function | |
| """ | |
| import argparse | |
| parser = argparse.ArgumentParser( | |
| description='AI-Powered Audio Mastering Engine', | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=""" | |
| Examples: | |
| # Analyze audio | |
| python main.py analyze input.wav | |
| # Master with auto preset selection | |
| python main.py master input.wav --auto | |
| # Master with specific preset | |
| python main.py master input.wav --preset edm_club_master | |
| # Master with custom output path | |
| python main.py master input.wav -o output.wav --preset hiphop_808_punch | |
| # Batch process folder | |
| python main.py batch input_folder/ output_folder/ --auto | |
| # List presets | |
| python main.py list-presets | |
| # Show preset details | |
| python main.py show-preset edm_club_master | |
| """ | |
| ) | |
| subparsers = parser.add_subparsers(dest='command', help='Command to run') | |
| # Analyze command | |
| analyze_parser = subparsers.add_parser('analyze', help='Analyze audio file') | |
| analyze_parser.add_argument('input', help='Input audio file') | |
| # Master command | |
| master_parser = subparsers.add_parser('master', help='Master audio file') | |
| master_parser.add_argument('input', help='Input audio file') | |
| master_parser.add_argument('-o', '--output', help='Output file path') | |
| master_parser.add_argument('-p', '--preset', help='Preset name to use') | |
| master_parser.add_argument('--auto', action='store_true', | |
| help='Auto-select best preset') | |
| # Batch command | |
| batch_parser = subparsers.add_parser('batch', help='Batch process folder') | |
| batch_parser.add_argument('input_folder', help='Input folder') | |
| batch_parser.add_argument('output_folder', help='Output folder') | |
| batch_parser.add_argument('-p', '--preset', help='Preset name to use') | |
| batch_parser.add_argument('--auto', action='store_true', | |
| help='Auto-select preset for each file') | |
| # List presets | |
| list_parser = subparsers.add_parser('list-presets', help='List available presets') | |
| list_parser.add_argument('-c', '--category', help='Filter by category') | |
| # Show preset | |
| show_parser = subparsers.add_parser('show-preset', help='Show preset details') | |
| show_parser.add_argument('preset_name', help='Preset name') | |
| # Suggest presets | |
| suggest_parser = subparsers.add_parser('suggest', help='Suggest presets for audio') | |
| suggest_parser.add_argument('input', help='Input audio file') | |
| suggest_parser.add_argument('-n', '--num', type=int, default=3, | |
| help='Number of suggestions') | |
| args = parser.parse_args() | |
| if not args.command: | |
| parser.print_help() | |
| return | |
| # Initialize engine | |
| engine = MasteringEngine() | |
| # Execute command | |
| if args.command == 'analyze': | |
| engine.analyze_audio(args.input) | |
| elif args.command == 'master': | |
| engine.master_audio( | |
| args.input, | |
| output_path=args.output, | |
| preset_name=args.preset, | |
| auto_preset=args.auto | |
| ) | |
| elif args.command == 'batch': | |
| engine.batch_master( | |
| args.input_folder, | |
| args.output_folder, | |
| preset_name=args.preset, | |
| auto_preset=args.auto | |
| ) | |
| elif args.command == 'list-presets': | |
| engine.list_presets(category=args.category) | |
| elif args.command == 'show-preset': | |
| engine.show_preset(args.preset_name) | |
| elif args.command == 'suggest': | |
| engine.suggest_presets(args.input, num_suggestions=args.num) | |
| if __name__ == "__main__": | |
| main() | |