Spaces:
Runtime error
Runtime error
import gradio as gr | |
import librosa | |
import numpy as np | |
import torch | |
import logging | |
from transformers import AutoModelForAudioClassification | |
logging.basicConfig(level=logging.INFO) | |
model_path = "./" | |
model = AutoModelForAudioClassification.from_pretrained(model_path) | |
def preprocess_audio(audio_file_path, sr=16000): | |
waveform, _ = librosa.load(audio_file_path, sr=sr) | |
waveform = librosa.effects.trim(waveform)[0] # Trim silence | |
return waveform | |
def extract_features(waveform, sr=16000, n_mels=128, n_fft=2048, hop_length=512): | |
S = librosa.feature.melspectrogram(y=waveform, sr=sr, n_mels=n_mels, n_fft=n_fft, hop_length=hop_length) | |
S_DB = librosa.power_to_db(S, ref=np.max) | |
return torch.tensor(S_DB).float().unsqueeze(0) # Add batch dimension | |
def predict_voice(audio_file_path): | |
try: | |
waveform = preprocess_audio(audio_file_path) | |
features = extract_features(waveform) | |
with torch.no_grad(): | |
outputs = model(features) | |
logits = outputs.logits | |
predicted_index = logits.argmax() | |
label = model.config.id2label[predicted_index.item()] | |
confidence = torch.softmax(logits, dim=1).max().item() * 100 | |
result = f"The voice is classified as '{label}' with a confidence of {confidence:.2f}%." | |
logging.info("Prediction successful.") | |
except Exception as e: | |
result = f"Error during processing: {e}" | |
logging.error(result) | |
return result | |
iface = gr.Interface( | |
fn=predict_voice, | |
inputs=gr.Audio(label="Upload Audio File", type="file"), | |
outputs=gr.Text(label="Prediction"), | |
title="Voice Authenticity Detection", | |
description="Detects whether a voice is real or AI-generated. Upload an audio file to see the results." | |
) | |
iface.launch() | |