| from flask import Flask, request, send_file, render_template_string, abort |
| import yt_dlp |
| import os |
| import tempfile |
|
|
| app = Flask(__name__) |
|
|
| |
| DEMO_HTML = """ |
| <!DOCTYPE html> |
| <html> |
| <head><title>yt-dlp Flask Demo</title></head> |
| <body> |
| <h1>YouTube動画ダウンロードデモ</h1> |
| <form action="/download" method="get"> |
| URL: <input type="text" name="url" size="60" required><br><br> |
| フォーマット (例: mp4, webm): <input type="text" name="format" placeholder="mp4"><br><br> |
| 画質 (例: 720p, 1080p, best): <input type="text" name="quality" placeholder="best"><br><br> |
| <button type="submit">ダウンロード</button> |
| </form> |
| </body> |
| </html> |
| """ |
|
|
| @app.route('/') |
| def index(): |
| return render_template_string(DEMO_HTML) |
|
|
| @app.route('/download') |
| def download_video(): |
| url = request.args.get('url') |
| format_ext = request.args.get('format') |
| quality = request.args.get('quality', 'best') |
|
|
| if not url: |
| return abort(400, 'URLパラメーターが必要です') |
|
|
| |
| temp_dir = tempfile.mkdtemp() |
| |
| output_template = os.path.join(temp_dir, '%(title)s.%(ext)s') |
|
|
| |
| ydl_opts = { |
| 'outtmpl': output_template, |
| 'format': 'bestvideo[ext={}][height<={}] + bestaudio/best'.format(format_ext if format_ext else '', quality if quality != 'best' else '9999'), |
| 'merge_output_format': format_ext if format_ext else 'mp4', |
| 'noplaylist': True, |
| 'quiet': True, |
| 'no_warnings': True, |
| } |
|
|
| |
| if quality == 'best': |
| if format_ext: |
| ydl_opts['format'] = f'bestvideo[ext={format_ext}]+bestaudio/best' |
| else: |
| ydl_opts['format'] = 'bestvideo+bestaudio/best' |
|
|
| |
| try: |
| with yt_dlp.YoutubeDL(ydl_opts) as ydl: |
| info = ydl.extract_info(url) |
| |
| filename = ydl.prepare_filename(info) |
| if not os.path.exists(filename): |
| return abort(500, '動画ファイルが見つかりませんでした') |
| except Exception as e: |
| return abort(500, f'動画ダウンロード中にエラーが発生しました: {str(e)}') |
|
|
| |
| return send_file(filename, as_attachment=True) |
|
|
| if __name__ == '__main__': |
| app.run(debug=True, port=7860, host="0.0.0.0") |
|
|