File size: 1,411 Bytes
81bcd2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)