# Import required libraries from flask import Flask, request, send_file import yt_dlp import os from flask_cors import CORS # Initialize Flask app and enable CORS app = Flask(__name__) CORS(app) # Route for serving index page @app.route('/') def index(): return send_file('index.html') # Route for handling video/audio downloads @app.route('/download', methods=['GET']) def download_video(): try: # Get URL and download type from request parameters video_url = request.args.get('url') download_type = request.args.get('type', 'video') # Default to video if not specified # Validate URL parameter if not video_url: return "Please provide a YouTube URL", 400 # Configure yt-dlp options based on download type if download_type == 'audio': try: # Options for audio download - MP3 format ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'outtmpl': '%(title)s.%(ext)s', } except Exception as e: print(f"Error: {str(e)}") return str(e), 500 else: # video # Options for video download - best quality ydl_opts = { 'format': 'best', 'outtmpl': '%(title)s.%(ext)s', } # Download the video/audio using yt-dlp with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(video_url, download=True) return "Download completed", 200 except Exception as e: # Handle any errors during download print(f"Error: {str(e)}") return str(e), 500 # Health check endpoint @app.route('/ping') def ping(): return 'pong' # Run the Flask app in debug mode if executed directly if __name__ == '__main__': app.run(debug=True, port=5000)