Spaces:
Sleeping
Sleeping
from flask import Flask, request, send_file, jsonify | |
import os | |
import subprocess | |
app = Flask(__name__) | |
def download_video(): | |
try: | |
# URLの取得 | |
video_url = request.args.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') | |
# yt-dlpコマンドの設定 | |
cookies_file = 'cookies.txt' # エクスポートしたクッキーを指定 | |
cmd = [ | |
'yt-dlp', | |
'--cookies', cookies_file, | |
'--output', output_file, # 出力ファイルのパスを指定 | |
'-f', 'bestvideo+bestaudio/best', # 最適なビデオ+オーディオフォーマットを選択 | |
video_url | |
] | |
# yt-dlpコマンドを実行 | |
result = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
# 出力とエラーメッセージをログに表示 | |
print(result.stdout.decode()) # コマンド実行結果を表示 | |
print(result.stderr.decode()) # エラーメッセージを表示 | |
# ダウンロードされたファイルのパスを取得 | |
# 出力ファイル名の形式をチェック | |
file_path = os.path.join(output_path, 'nRh5QyKIs8o.mp4') # 固定ファイル名でなく、動的に取得する方法が良い | |
if not os.path.exists(file_path): | |
return jsonify({"error": "File not found"}), 404 | |
# ファイルをクライアントに送信 | |
return send_file(file_path, as_attachment=True) | |
except Exception as e: | |
return jsonify({"error": str(e)}), 500 | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port=7860, debug=True) | |