Adityadn's picture
Update app.py
4f55526 verified
raw
history blame
2.57 kB
import gradio as gr
import os
import json
from acrcloud.recognizer import ACRCloudRecognizer
# Retrieve ACRCloud credentials from environment variables
acr_access_key = os.environ.get('ACR_ACCESS_KEY')
acr_access_secret = os.environ.get('ACR_ACCESS_SECRET')
acr_host = 'identify-ap-southeast-1.acrcloud.com' # Default host, can be adjusted
# ACRCloud recognizer configuration
config = {
'host': acr_host,
'access_key': acr_access_key,
'access_secret': acr_access_secret,
'timeout': 10 # seconds
}
# Initialize ACRCloud recognizer
acr = ACRCloudRecognizer(config)
def identify_audio(file):
# Gradio provides a file object, and file.name contains the path
file_path = file.name # Gradio file object already provides a file path
# Get the duration of the audio file in milliseconds
duration_ms = int(acr.get_duration_ms_by_file(file_path))
results = []
# Process audio in 10-second chunks
for i in range(0, duration_ms // 1000, 10):
res = acr.recognize_by_file(file_path, i, 10)
results.append(f"Time {i}s: {res.strip()}")
# Full recognition result
full_result = acr.recognize_by_file(file_path, 0)
# Parse full_result from string to JSON
full_result_parsed = json.loads(full_result)
# Extract desired details from parsed result
if 'metadata' in full_result_parsed and 'music' in full_result_parsed['metadata']:
music_data = full_result_parsed['metadata']['music'][0]
title = music_data.get('title', 'Unknown Title')
artists = ', '.join([artist['name'] for artist in music_data.get('artists', [])])
album = music_data.get('album', {}).get('name', 'Unknown Album')
release_date = music_data.get('release_date', 'Unknown Release Date')
full_result_text = f"Title: {title}\nArtists: {artists}\nAlbum: {album}\nRelease Date: {release_date}"
else:
full_result_text = "No music metadata found in the result."
# Recognize using file buffer
with open(file_path, 'rb') as f:
buf = f.read()
buffer_result = acr.recognize_by_filebuffer(buf, 0)
return {
"Partial Results": results,
"Full Result": full_result_text,
"Buffer Result": buffer_result
}
# Create Gradio interface
iface = gr.Interface(
fn=identify_audio,
inputs=gr.File(label="Upload Audio File"),
outputs=gr.JSON(label="Audio Metadata"),
title="Audio Search by File",
description="Upload an audio file to identify it using ACRCloud."
)
# Launch the Gradio interface
iface.launch()