yt / app.py
soiz's picture
Update app.py
11511b8 verified
from flask import Flask, request, send_file, jsonify
from pytube import YouTube
import os
app = Flask(__name__)
@app.route('/download', methods=['GET'])
def download_video():
# URLパラメータを取得
video_id = request.args.get('id')
file_type = request.args.get('file', 'mp4') # デフォルトは mp4
quality = request.args.get('quality', '720p') # デフォルトは 720p
if not video_id:
return jsonify({'error': 'Missing video ID'}), 400
file_path = None # file_path を事前に初期化
try:
# YouTube URLを作成
youtube_url = f'https://www.youtube.com/watch?v={video_id}'
# OAuthを有効化してYouTubeオブジェクトを作成
try:
yt = YouTube(youtube_url, use_oauth=False)
except Exception as e:
if "device" in str(e).lower():
return jsonify({'error': 'OAuth authentication required. Please follow the instructions in the log to complete authentication.'}), 401
return jsonify({'error': str(e)}), 500
# ファイル保存用ディレクトリ
download_dir = "downloads"
if not os.path.exists(download_dir):
os.makedirs(download_dir)
# 動画をダウンロード (MP4)
if file_type == 'mp4':
stream = yt.streams.filter(res=quality, file_extension='mp4').first()
if not stream:
return jsonify({'error': f'Video with quality {quality} not found'}), 404
file_path = stream.download(output_path=download_dir)
# オーディオをダウンロード (MP3)
elif file_type == 'mp3':
stream = yt.streams.filter(only_audio=True).first()
if not stream:
return jsonify({'error': 'Audio stream not found'}), 404
temp_file_path = stream.download(output_path=download_dir)
file_path = os.path.splitext(temp_file_path)[0] + '.mp3'
# MP3に変換
os.rename(temp_file_path, file_path)
else:
return jsonify({'error': 'Invalid file type. Use "mp4" or "mp3"'}), 400
# ファイルをクライアントに送信
return send_file(file_path, as_attachment=True)
except Exception as e:
# エラー内容をログに記録またはレスポンスに含める
return jsonify({'error': str(e)}), 500
finally:
# クリーンアップ: 使用後にファイルを削除
if file_path and os.path.exists(file_path):
os.remove(file_path)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)