import streamlit as st import requests import os # Hugging Face API setup API_URL = "https://api-inference.huggingface.co/models/MIT/ast-finetuned-audioset-10-10-0.4593" HF_TOKEN = os.getenv("HF_TOKEN") headers = {"Authorization": f"Bearer {HF_TOKEN}"} # Function to send the audio file to the Hugging Face API and get the classification result def classify_audio(audio_file_path): with open(audio_file_path, "rb") as audio_file: response = requests.post( "https://api-inference.huggingface.co/models/MIT/ast-finetuned-audioset-10-10-0.4593", headers=headers, files={"file": audio_file} ) # Check the response status and return JSON if successful, or an error message if response.status_code == 200: return response.json() else: return {"error": f"Failed to classify audio. Status code: {response.status_code}"} # Streamlit interface st.title("Audio Classifier") # Define the folder where your audio files are located audio_folder = "audio_files" # List the audio files in the folder try: audio_files = os.listdir(audio_folder) audio_file_options = [f for f in audio_files if f.endswith(('.mp3', '.wav'))] except Exception as e: st.error(f"Error accessing the audio files: {e}") st.stop() # Dropdown to select an audio file selected_file = st.selectbox("Select an audio file:", audio_file_options) # Button to classify the selected audio file if st.button("Classify"): # Get the full path of the selected audio file audio_file_path = os.path.join(audio_folder, selected_file) # Show the audio player st.audio(audio_file_path) # Get and display the classification results results = classify_audio(audio_file_path) # Check for errors if "error" in results: st.error(results["error"]) else: st.write("Results:") # Loop through each result in the list of results for result in results: # Check if result is a dictionary with 'label' and 'score' keys if isinstance(result, dict) and 'label' in result and 'score' in result: st.write(f"Label: {result['label']}, Confidence: {result['score']:.2f}") else: st.error(f"Unexpected result format: {result}") # Get and display the classification results results = classify_audio(audio_file_path) st.write("Results:") for result in results: st.write(f"Label: {result['label']}, Confidence: {result['score']:.2f}")