Spaces:
Running
Running
import gradio as gr | |
from transformers import pipeline | |
import torch | |
import os | |
# --- Performance Improvement --- | |
# 1. Determine the number of available CPU cores. | |
num_cpu_cores = os.cpu_count() | |
# 2. Configure PyTorch to use all available CPU cores for its operations. | |
# This is crucial for speeding up model inference on a CPU. | |
if num_cpu_cores is not None: | |
torch.set_num_threads(num_cpu_cores) | |
print(f"β PyTorch is configured to use {num_cpu_cores} CPU cores.") | |
else: | |
print("Could not determine the number of CPU cores. Using default settings.") | |
# Initialize the audio classification pipeline | |
# We specify device=-1 to explicitly enforce running on the CPU. | |
pipe = pipeline( | |
"audio-classification", | |
model="MIT/ast-finetuned-audioset-10-10-0.4593", | |
device=-1 # -1 for CPU, 0 for the first GPU, etc. | |
) | |
# Define the function to classify an audio file | |
def classify_audio(audio): | |
""" | |
Takes an audio file path, classifies it using the pipeline, | |
and returns a dictionary of top labels and their scores. | |
""" | |
if audio is None: | |
return "Please upload an audio file first." | |
# The pipeline handles the loading, preprocessing, and inference. | |
result = pipe(audio) | |
# The output is formatted for the Gradio Label component. | |
return {label['label']: label['score'] for label in result} | |
# Set up the Gradio interface | |
app = gr.Interface( | |
fn=classify_audio, # Function to classify audio | |
inputs=gr.Audio(type="filepath", label="Upload Audio"), # Input for uploading an audio file | |
outputs=gr.Label(num_top_classes=3, label="Top 3 Predictions"), # Output with top 3 classification results | |
title="Audio Classification", # App title | |
description="Upload an audio file to classify it. This app is optimized to run on all available CPU cores.", | |
examples=[ | |
# You can add example audio files here if you have them locally | |
# ["path/to/your/example_audio_1.wav"], | |
# ["path/to/your/example_audio_2.mp3"], | |
] | |
) | |
# Launch the app | |
if __name__ == "__main__": | |
app.launch() |