from flask import Flask, request, jsonify, send_from_directory from flask_cors import CORS import os import uuid from moviepy.editor import VideoFileClip app = Flask(__name__) # Enable CORS for all domains CORS(app) # Directory to store uploaded files and converted audio files UPLOAD_FOLDER = 'uploads' AUDIO_FOLDER = 'audio' os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(AUDIO_FOLDER, exist_ok=True) # Allowed file extensions for video and audio ALLOWED_VIDEO_EXTENSIONS = {'mp4', 'mkv', 'avi', 'mov', 'webm'} ALLOWED_AUDIO_EXTENSIONS = {'mp3', 'wav', 'flac', 'aac'} def allowed_file(filename, file_type): ext = filename.rsplit('.', 1)[1].lower() if file_type == 'video': return '.' in filename and ext in ALLOWED_VIDEO_EXTENSIONS elif file_type == 'audio': return '.' in filename and ext in ALLOWED_AUDIO_EXTENSIONS return False @app.route('/api/v1/video-to-audio-convert', methods=['POST']) def convert_video_to_audio(): if 'file' not in request.files: return jsonify({ 'status': 'error', 'status_code': 400, 'message': 'No file part' }), 400 file = request.files['file'] target_format = request.form.get('format', 'mp3').lower() if file.filename == '': return jsonify({ 'status': 'error', 'status_code': 400, 'message': 'No selected file' }), 400 if not allowed_file(file.filename, 'video'): return jsonify({ 'status': 'error', 'status_code': 400, 'message': 'Unsupported video file type' }), 400 if target_format not in ALLOWED_AUDIO_EXTENSIONS: return jsonify({ 'status': 'error', 'status_code': 400, 'message': 'Unsupported audio format' }), 400 # Generate a unique filename to avoid collisions video_filename = str(uuid.uuid4()) + '.' + file.filename.rsplit('.', 1)[1].lower() video_path = os.path.join(UPLOAD_FOLDER, video_filename) file.save(video_path) # Define output audio file path audio_filename = video_filename.rsplit('.', 1)[0] + '.' + target_format audio_path = os.path.join(AUDIO_FOLDER, audio_filename) try: # Convert video to audio using MoviePy video_clip = VideoFileClip(video_path) audio_clip = video_clip.audio audio_clip.write_audiofile(audio_path, codec='aac' if target_format == 'aac' else None) audio_clip.close() video_clip.close() # After successful conversion, remove the video file os.remove(video_path) except Exception as e: return jsonify({ 'status': 'error', 'status_code': 500, 'message': f'Error during conversion: {str(e)}' }), 500 # Return server path of the converted audio file return jsonify({ 'status': 'success', 'status_code': 200, 'message': 'Conversion successful', 'audio_file': f'/download/{audio_filename}' # Server-relative path for download }), 200 @app.route('/download/', methods=['GET']) def download_audio(filename): return send_from_directory(AUDIO_FOLDER, filename) if __name__ == '__main__': app.run(debug=True)