soiz commited on
Commit
4bcc346
Β·
verified Β·
1 Parent(s): e142bba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py CHANGED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, send_file, jsonify
2
+ from pytube import YouTube
3
+ import os
4
+
5
+ app = Flask(__name__)
6
+
7
+ @app.route('/watch', methods=['GET'])
8
+ def download_video():
9
+ # URLパラパータを取得
10
+ video_id = request.args.get('id')
11
+ file_type = request.args.get('file', 'mp4') # γƒ‡γƒ•γ‚©γƒ«γƒˆγ― mp4
12
+ quality = request.args.get('quality', '720p') # γƒ‡γƒ•γ‚©γƒ«γƒˆγ― 720p
13
+
14
+ if not video_id:
15
+ return jsonify({'error': 'Missing video ID'}), 400
16
+
17
+ try:
18
+ # YouTube URLγ‚’δ½œζˆ
19
+ youtube_url = f'https://www.youtube.com/watch?v={video_id}'
20
+ yt = YouTube(youtube_url)
21
+
22
+ # γƒ•γ‚‘γ‚€γƒ«δΏε­˜η”¨γƒ‡γ‚£γƒ¬γ‚―γƒˆγƒͺ
23
+ download_dir = "downloads"
24
+ if not os.path.exists(download_dir):
25
+ os.makedirs(download_dir)
26
+
27
+ # 動画をダウンロード (MP4)
28
+ if file_type == 'mp4':
29
+ stream = yt.streams.filter(res=quality, file_extension='mp4').first()
30
+ if not stream:
31
+ return jsonify({'error': f'Video with quality {quality} not found'}), 404
32
+
33
+ file_path = stream.download(output_path=download_dir)
34
+
35
+ # γ‚ͺーディγ‚ͺをダウンロード (MP3)
36
+ elif file_type == 'mp3':
37
+ stream = yt.streams.filter(only_audio=True).first()
38
+ if not stream:
39
+ return jsonify({'error': 'Audio stream not found'}), 404
40
+
41
+ temp_file_path = stream.download(output_path=download_dir)
42
+ file_path = os.path.splitext(temp_file_path)[0] + '.mp3'
43
+
44
+ # MP3に倉換
45
+ os.rename(temp_file_path, file_path)
46
+
47
+ else:
48
+ return jsonify({'error': 'Invalid file type. Use "mp4" or "mp3"'}), 400
49
+
50
+ # γƒ•γ‚‘γ‚€γƒ«γ‚’γ‚―γƒ©γ‚€γ‚’γƒ³γƒˆγ«ι€δΏ‘
51
+ return send_file(file_path, as_attachment=True)
52
+
53
+ except Exception as e:
54
+ return jsonify({'error': str(e)}), 500
55
+
56
+ finally:
57
+ # γ‚―γƒͺーンをップ: δ½Ώη”¨εΎŒγ«γƒ•γ‚‘γ‚€γƒ«γ‚’ε‰Šι™€
58
+ if os.path.exists(file_path):
59
+ os.remove(file_path)
60
+
61
+
62
+ if __name__ == '__main__':
63
+ app.run(debug=True)