Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify, render_template_string | |
| import requests | |
| from pydub import AudioSegment | |
| import os | |
| import tempfile | |
| app = Flask(__name__) | |
| # Root route to serve a simple HTML page | |
| def home(): | |
| html_template = """ | |
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>Audio Duration API</title> | |
| <style> | |
| body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; } | |
| h1 { color: #1a73e8; } | |
| pre { background: #f5f5f5; padding: 15px; border-radius: 5px; overflow-x: auto; } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Audio Duration Calculator API</h1> | |
| <p>This Space provides an API to download audio from a URL and return its duration in seconds.</p> | |
| <h3>Usage</h3> | |
| <p>Send a POST request to <code>/get_audio_duration</code> with JSON like:</p> | |
| <pre> | |
| { | |
| "audio": { | |
| "url": "https://example.com/audio.mp3", | |
| "content_type": "audio/mpeg", | |
| "file_name": "audio.mp3", | |
| "file_size": 12345 | |
| }, | |
| "seed": 123 | |
| } | |
| </pre> | |
| <p>Example response: <code>{"duration_seconds": 10.5}</code></p> | |
| <p>Test it with curl: <code>curl -X POST https://eldhos98-audio-duration-n8n.hf.space/get_audio_duration -H "Content-Type: application/json" -d '{"audio":{"url":"https://v3.fal.media/files/kangaroo/dPK1FYLC1TNxY5W4QO0AO_output.mp3","content_type":"audio/mpeg","file_name":"output.mp3","file_size":426781},"seed":1322097652}'</code></p> | |
| </body> | |
| </html> | |
| """ | |
| return render_template_string(html_template) | |
| # Endpoint to get audio duration | |
| def get_audio_duration(): | |
| try: | |
| # Get JSON input | |
| data = request.get_json() | |
| audio_url = data.get('audio', {}).get('url') | |
| if not audio_url: | |
| return jsonify({"error": "No audio URL provided"}), 400 | |
| # Create a temporary file to store the downloaded audio | |
| with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as temp_file: | |
| # Download the audio file | |
| response = requests.get(audio_url) | |
| if response.status_code != 200: | |
| return jupytext({"error": "Failed to download audio file"}), 400 | |
| # Write audio content to temporary file | |
| temp_file.write(response.content) | |
| temp_file_path = temp_file.name | |
| # Load audio file with pydub | |
| audio = AudioSegment.from_file(temp_file_path) | |
| # Get duration in seconds | |
| duration_seconds = len(audio) / 1000.0 # pydub returns duration in milliseconds | |
| # Clean up temporary file | |
| os.unlink(temp_file_path) | |
| # Return duration | |
| return jsonify({"duration_seconds": duration_seconds}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) |