Spaces:
Running
Running
import subprocess | |
import gradio as gr | |
import os | |
def get_audio_metadata(file_path): | |
try: | |
# Run ffmpeg to extract metadata | |
result = subprocess.run( | |
[ | |
"ffmpeg", | |
"-i", | |
file_path, | |
"-hide_banner", | |
], | |
stderr=subprocess.PIPE, | |
text=True | |
) | |
# Parse output for metadata | |
output = result.stderr | |
metadata = { | |
"Codec": None, | |
"Container": None, | |
"Channels": None, | |
"Sample Rate": None, | |
"Bitrate": None, | |
} | |
# Extract codec | |
if "Audio:" in output: | |
audio_line = [line for line in output.splitlines() if "Audio:" in line] | |
if audio_line: | |
audio_info = audio_line[0].split() | |
metadata["Codec"] = audio_info[audio_info.index("Audio:") + 1] | |
# Extract container format | |
if "Input #0," in output: | |
container_line = [line for line in output.splitlines() if "Input #0," in line] | |
if container_line: | |
container_info = container_line[0].split() | |
metadata["Container"] = container_info[2].strip(',') | |
# Extract channels, sample rate, and bitrate | |
for line in output.splitlines(): | |
if "Audio:" in line: | |
audio_info = line.split() | |
for item in audio_info: | |
if "Hz" in item: | |
metadata["Sample Rate"] = item | |
if "kb/s" in item: | |
metadata["Bitrate"] = item | |
if "stereo" in item or "mono" in item: | |
metadata["Channels"] = item | |
return metadata | |
except Exception as e: | |
return {"Error": str(e)} | |
def process_audio(file): | |
# Save the uploaded file temporarily | |
temp_file = "temp_audio_file" | |
with open(temp_file, "wb") as f: | |
f.write(file.read()) | |
# Get metadata | |
metadata = get_audio_metadata(temp_file) | |
# Remove the temporary file | |
os.remove(temp_file) | |
return metadata | |
# Gradio interface | |
def create_interface(): | |
inputs = gr.Audio(label="Upload an audio file", type="file") | |
outputs = gr.JSON(label="Audio Metadata") | |
interface = gr.Interface( | |
fn=process_audio, | |
inputs=inputs, | |
outputs=outputs, | |
title="Audio Metadata Extractor", | |
description="Upload an audio file to extract its codec, container, channels, sample rate, and bitrate using ffmpeg." | |
) | |
return interface | |
if __name__ == "__main__": | |
create_interface().launch() | |