File size: 2,193 Bytes
4bcc346 08b9d9a 4bcc346 08b9d9a 4bcc346 08b9d9a |
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 |
from flask import Flask, request, send_file, jsonify
from pytube import YouTube
import os
app = Flask(__name__)
@app.route('/watch', 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}'
yt = YouTube(youtube_url)
# γγ‘γ€γ«δΏεη¨γγ£γ¬γ―γγͺ
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(debug=True, host='0.0.0.0')
|