File size: 11,590 Bytes
273477a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""
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()