practice / app.py
jc180's picture
c
0fed8b2
raw
history blame
1.79 kB
import gradio as gr
import torch
import torchaudio
from transformers import AutoFeatureExtractor, ASTForAudioClassification
model_name = "MIT/ast-finetuned-audioset-10-10-0.4593"
model = ASTForAudioClassification.from_pretrained(model_name)
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
device = torch.device("cpu")
model.to(device)
def classify_sound(file_path):
wv, sr = torchaudio.load(file_path)
original_shape = wv.shape
# Convert to mono
if wv.shape[0] > 1:
wv = wv.mean(dim=0, keepdim=True)
inputs = feature_extractor(
wv.squeeze().numpy(), sampling_rate=16000, return_tensors="pt"
)
with torch.no_grad():
logits = model(**inputs).logits
probs = torch.softmax(logits, dim=-1)[0]
top5 = torch.topk(probs, k=5)
top5_labels = [
(model.config.id2label[idx.item()], round(prob.item(), 4))
for idx, prob in zip(top5.indices, top5.values)
]
full_probs = {
model.config.id2label[i]: round(prob.item(), 4)
for i, prob in enumerate(probs)
}
return {
"Top 5 Predictions": dict(top5_labels),
"Sampling Rate": sr,
"Waveform Shape": str(original_shape),
"All Probabilities": full_probs
}
demo = gr.Interface(
fn=classify_sound,
inputs=gr.Audio(sources="upload", type="filepath"),
outputs=[
gr.Label(label = "Top 5 Pred", num_top_classes=5),
gr.Textbox(label="Sample Rate"),
gr.Textbox(label="Waveform Shape"),
gr.JSON(label="All Class Probabilities")
],
title="Audio Classification with AST",
description="Upload an audio clip (speech, music, ambient sound, etc.). Model: MIT AST fine-tuned on AudioSet (10 classes).",
live=False,
)
demo.launch()