File size: 2,619 Bytes
1071e3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf5a840
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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")