yt-dl2 / app.py
soiz1's picture
Update app.py
cf5a840 verified
from flask import Flask, request, send_file, render_template_string, abort
import yt_dlp
import os
import tempfile
app = Flask(__name__)
# デモページのHTML(シンプルなフォーム)
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') # 例: mp4
quality = request.args.get('quality', 'best') # 例: 720p, best
if not url:
return abort(400, 'URLパラメーターが必要です')
# 一時フォルダに保存
temp_dir = tempfile.mkdtemp()
# 保存テンプレート
output_template = os.path.join(temp_dir, '%(title)s.%(ext)s')
# yt-dlpオプション設定
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,
}
# 画質指定が "best" の場合は単純に best を指定する
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")