from flask import Flask, request, send_file, jsonify import os import youtube_dl app = Flask(__name__) @app.route('/download', methods=['POST']) def download_video(): try: # リクエストからURLを取得 video_url = request.json.get('url') if not video_url: return jsonify({"error": "URL is required"}), 400 # 保存するファイル名とパスを設定 output_path = "downloads" os.makedirs(output_path, exist_ok=True) output_file = os.path.join(output_path, '%(title)s.%(ext)s') # youtube-dlのオプション設定 ydl_opts = { 'format': 'bestvideo+bestaudio/best', # 最高画質を指定 'outtmpl': output_file, # 保存先テンプレート 'merge_output_format': 'mp4', # 出力フォーマット } # 動画のダウンロード with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(video_url, download=True) downloaded_file = ydl.prepare_filename(info) mp4_file = downloaded_file.rsplit('.', 1)[0] + '.mp4' # ファイルをクライアントに送信 return send_file(mp4_file, as_attachment=True) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=7860)