File size: 8,650 Bytes
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
VocalSense - AI Voice Detection System
Main entry point for CLI and application.
"""
import sys
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))


def main():
    """Main entry point."""
    import argparse
    
    parser = argparse.ArgumentParser(
        description="VocalSense - AI Voice Detection System",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Start the API server
  python main.py serve --port 8000
  
  # Analyze a single audio file
  python main.py analyze --file audio.wav --language English
  
  # Extract features from audio
  python main.py features --file audio.wav
  
  # Train the model on your dataset
  python main.py train --epochs 50 --model random_forest
        """
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Available commands")
    
    # Serve command
    serve_parser = subparsers.add_parser("serve", help="Start the API server")
    serve_parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
    serve_parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
    serve_parser.add_argument("--reload", action="store_true", help="Enable auto-reload")
    
    # Analyze command
    analyze_parser = subparsers.add_parser("analyze", help="Analyze an audio file")
    analyze_parser.add_argument("--file", "-f", required=True, help="Path to audio file")
    analyze_parser.add_argument(
        "--language", "-l",
        default="English",
        choices=["Hindi", "Tamil", "Telugu", "Malayalam", "English"],
        help="Language of the audio"
    )
    
    # Batch command - analyze multiple files
    batch_parser = subparsers.add_parser("batch", help="Analyze all audio files in a folder")
    batch_parser.add_argument("--folder", "-d", required=True, help="Path to folder with audio files")
    batch_parser.add_argument(
        "--language", "-l",
        default="English",
        choices=["Hindi", "Tamil", "Telugu", "Malayalam", "English"],
        help="Language of the audio"
    )
    
    # Features command
    features_parser = subparsers.add_parser("features", help="Extract features from audio")
    features_parser.add_argument("--file", "-f", required=True, help="Path to audio file")
    features_parser.add_argument("--output", "-o", help="Output JSON file")
    
    # Train command
    train_parser = subparsers.add_parser("train", help="Train the AI voice detection model")
    train_parser.add_argument("--epochs", "-e", type=int, default=50, help="Number of epochs")
    train_parser.add_argument(
        "--model", "-m",
        default="random_forest",
        choices=["random_forest", "svm"],
        help="Model type to train"
    )
    
    args = parser.parse_args()
    
    if args.command == "serve":
        run_server(args.host, args.port, args.reload)
    elif args.command == "analyze":
        analyze_file(args.file, args.language)
    elif args.command == "batch":
        batch_analyze(args.folder, args.language)
    elif args.command == "features":
        extract_features_cli(args.file, args.output)
    elif args.command == "train":
        run_training(args.model, args.epochs)
    else:
        parser.print_help()


def run_server(host: str, port: int, reload: bool):
    """Start the FastAPI server."""
    import uvicorn
    print(f"Starting VocalSense API server on {host}:{port}...")
    uvicorn.run(
        "api.app:app",
        host=host,
        port=port,
        reload=reload
    )


def analyze_file(file_path: str, language: str):
    """Analyze a single audio file."""
    import json
    from api.detector import get_detector
    
    path = Path(file_path)
    if not path.exists():
        print(f"Error: File not found: {file_path}")
        sys.exit(1)
    
    print(f"Analyzing: {path.name}")
    print(f"Language: {language}")
    print("-" * 40)
    
    detector = get_detector()
    result = detector.analyze_file(file_path, language)
    
    print(f"Status: {result['status']}")
    print(f"Classification: {result['classification']}")
    print(f"Confidence: {result['confidenceScore']:.2%}")
    print(f"Explanation: {result['explanation']}")
    
    # Show detailed scores if available
    if 'details' in result:
        details = result['details']
        print("-" * 40)
        print("Detailed Analysis:")
        if details.get('model_score') is not None:
            print(f"  Model Score: {details['model_score']:.2%}")
        if details.get('heuristic_score') is not None:
            print(f"  Heuristic Score: {details['heuristic_score']:.2%}")
        print(f"  Final Score: {details['final_score']:.2%}")
        print(f"  Method: {result.get('method', 'unknown')}")


def batch_analyze(folder_path: str, language: str):
    """Analyze all audio files in a folder."""
    from api.detector import get_detector
    
    folder = Path(folder_path)
    if not folder.exists():
        print(f"Error: Folder not found: {folder_path}")
        sys.exit(1)
    
    # Find all audio files
    extensions = ['.wav', '.mp3', '.m4a', '.ogg', '.flac']
    audio_files = []
    for ext in extensions:
        audio_files.extend(folder.glob(f"*{ext}"))
    
    if not audio_files:
        print(f"No audio files found in: {folder_path}")
        sys.exit(1)
    
    print(f"Found {len(audio_files)} audio files")
    print(f"Language: {language}")
    print("=" * 60)
    
    detector = get_detector()
    
    ai_count = 0
    human_count = 0
    results = []
    
    for audio_file in audio_files:
        try:
            result = detector.analyze_file(str(audio_file), language)
            classification = result['classification']
            confidence = result['confidenceScore']
            
            if classification == "AI_GENERATED":
                ai_count += 1
                status = "[AI]"
            else:
                human_count += 1
                status = "[HUMAN]"
            
            print(f"{status} ({confidence:.0%}) - {audio_file.name}")
            results.append(result)
            
        except Exception as e:
            print(f"[ERROR] {audio_file.name}: {e}")
    
    # Summary
    print("=" * 60)
    print("SUMMARY:")
    print(f"  Total files: {len(audio_files)}")
    print(f"  AI detected: {ai_count}")
    print(f"  Human detected: {human_count}")


def extract_features_cli(file_path: str, output_path: str = None):
    """Extract and display features from audio."""
    import json
    from utils.audio import load_audio, preprocess_audio
    from features.spectral import extract_spectral_features
    from features.mfcc import extract_mfcc_features
    from features.prosody import extract_prosodic_features
    from config import SAMPLE_RATE
    
    path = Path(file_path)
    if not path.exists():
        print(f"Error: File not found: {file_path}")
        sys.exit(1)
    
    print(f"Extracting features from: {path.name}")
    print("-" * 40)
    
    # Load and preprocess
    audio, sr = load_audio(file_path, sr=SAMPLE_RATE)
    audio = preprocess_audio(audio, sr)
    
    # Extract features
    features = {
        "spectral": extract_spectral_features(audio, sr),
        "mfcc": {k: v for k, v in extract_mfcc_features(audio, sr).items() 
                 if "mfcc_0" in k or "mfcc_1" in k or "energy" in k},
        "prosody": extract_prosodic_features(audio, sr)
    }
    
    if output_path:
        with open(output_path, "w") as f:
            json.dump(features, f, indent=2)
        print(f"Features saved to: {output_path}")
    else:
        print("\nSpectral Features:")
        for k, v in features["spectral"].items():
            print(f"  {k}: {v:.4f}")
        
        print("\nProsodic Features:")
        for k, v in features["prosody"].items():
            print(f"  {k}: {v:.4f}")


def run_training(model_type: str, epochs: int):
    """Train the AI voice detection model."""
    from training.trainer import train_full_pipeline
    
    print("Starting VocalSense Training...")
    print(f"Model: {model_type}")
    print(f"Epochs: {epochs}")
    
    try:
        model, metrics = train_full_pipeline(
            model_type=model_type,
            epochs=epochs
        )
    except FileNotFoundError as e:
        print(f"\nError: {e}")
        print("\nMake sure you have audio files in:")
        print("  - data/real/  (human voice samples)")
        print("  - data/fake/  (AI/TTS voice samples)")
        sys.exit(1)
    except ValueError as e:
        print(f"\nError: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()