| from flask import Flask, request, jsonify |
| from pytubefix import YouTube |
| import re |
|
|
| app = Flask(__name__) |
|
|
| def download_video(url, resolution): |
| try: |
| yt = YouTube(url, use_po_token=True) |
| stream = yt.streams.filter(progressive=True, file_extension='mp4', resolution=resolution).first() |
| if stream: |
| stream.download() |
| return True, None |
| else: |
| return False, f"{resolution}のストリームが見つかりませんでした。利用可能: {[s.resolution for s in yt.streams.filter(progressive=True, file_extension='mp4')]}" |
| except Exception as e: |
| print(f"[Download Error] {e}") |
| return False, str(e) |
|
|
|
|
| def get_video_info(url): |
| try: |
| yt = YouTube(url, use_po_token=True) |
| video_info = { |
| "title": yt.title, |
| "author": yt.author, |
| "length": yt.length, |
| "views": yt.views, |
| "description": yt.description, |
| "publish_date": yt.publish_date.isoformat() if yt.publish_date else None |
| } |
| return video_info, None |
| except Exception as e: |
| print(f"[Video Info Error] {e}") |
| return None, str(e) |
|
|
|
|
| def is_valid_youtube_url(url): |
| pattern = r"^(https?://)?(www\.)?(youtube\.com/watch\?v=|youtu\.be/)[\w-]+(&\S*)?$" |
| return re.match(pattern, url) is not None |
|
|
| @app.route('/download', methods=['GET']) |
| def download_by_resolution(): |
| url = request.args.get('url') |
| resolution = request.args.get('resolution', '720p') |
|
|
| if not url: |
| return jsonify({"error": "'url' パラメーターが必要です。"}), 400 |
|
|
| if not is_valid_youtube_url(url): |
| return jsonify({"error": "無効なYouTube URLです。"}), 400 |
|
|
| success, error_message = download_video(url, resolution) |
|
|
| if success: |
| return jsonify({"message": f"{resolution}の動画を正常にダウンロードしました。"}), 200 |
| else: |
| return jsonify({"error": error_message}), 500 |
|
|
| @app.route('/video_info', methods=['GET']) |
| def video_info(): |
| url = request.args.get('url') |
|
|
| if not url: |
| return jsonify({"error": "'url' パラメーターが必要です。"}), 400 |
|
|
| if not is_valid_youtube_url(url): |
| return jsonify({"error": "無効なYouTube URLです。"}), 400 |
|
|
| info, error_message = get_video_info(url) |
|
|
| if info: |
| return jsonify(info), 200 |
| else: |
| return jsonify({"error": error_message}), 500 |
|
|
| if __name__ == '__main__': |
| app.run(debug=True, host="0.0.0.0", port=7860) |
|
|