Kabatubare's picture
Update app.py
1364a7f verified
raw
history blame
1.81 kB
import gradio as gr
from transformers import AutoFeatureExtractor, AutoModelForAudioClassification
import torch
import librosa
import numpy as np
local_model_path = "./"
extractor = AutoFeatureExtractor.from_pretrained(local_model_path)
model = AutoModelForAudioClassification.from_pretrained(local_model_path)
def preprocess_audio(audio_file_path, target_sample_rate=16000):
# Load the audio file, ensuring mono conversion
waveform, _ = librosa.load(audio_file_path, sr=target_sample_rate, mono=True)
# Normalizing waveform to be between -1 and 1
waveform = librosa.util.normalize(waveform)
return waveform, target_sample_rate
def predict_voice(audio_file_path):
try:
waveform, sample_rate = preprocess_audio(audio_file_path)
# Ensure waveform is a float32 array
waveform = waveform.astype(np.float32)
inputs = extractor(waveform, return_tensors="pt", sampling_rate=sample_rate)
with torch.no_grad():
outputs = model(**inputs)
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}%."
except Exception as e:
# Improved error handling for debugging
result = f"Error during processing: {e}"
return result
iface = gr.Interface(
fn=predict_voice,
inputs=gr.Audio(label="Upload Audio File", type="filepath"),
outputs=gr.Textbox(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()