vs / main.py
devmm03's picture
intial commit
0468ff5
Raw History Blame Contribute Delete
8.65 kB
"""
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()