File size: 2,081 Bytes
acdedca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62429c9
acdedca
 
 
 
62429c9
acdedca
 
 
62429c9
acdedca
 
 
 
 
 
 
 
62429c9
acdedca
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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()