app.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import logging
  2. import boto3
  3. import requests
  4. import yt_dlp
  5. from flask import Flask, request
  6. logging.basicConfig(format='%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d %(message)s',
  7. datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
  8. app = Flask(__name__)
  9. def get_key(url: str) -> str:
  10. return f"v2:{url}"
  11. def fetch_info(url):
  12. logging.info(f"fetching: {url}")
  13. with yt_dlp.YoutubeDL({
  14. "flat-playlist": True,
  15. "extract_flat": "flat-playlist"
  16. }) as ydl:
  17. info = ydl.extract_info(url, download=False)
  18. return info
  19. @app.route("/p", methods=["GET", "POST"])
  20. def p():
  21. video_id = request.args.get("videoId")
  22. format_id = request.args.get("formatId")
  23. if video_id and format_id:
  24. info = fetch_info(url=f"https://www.youtube.com/watch?v={video_id}")
  25. if info:
  26. for item in info.get("formats", []):
  27. if item.get("format_id") == format_id:
  28. url = item.get("url")
  29. response = requests.get(url)
  30. return response.content, response.status_code, response.headers.items()
  31. return {"status": 0}
  32. def convert_dto(info):
  33. thumbnails = []
  34. for item in info.get("thumbnails", []):
  35. if item.get("width"):
  36. thumbnails.append({
  37. "url": item.get("url", ""),
  38. "width": f"{item.get('width', 0)}",
  39. "height": f"{item.get('height', 0)}",
  40. })
  41. formats = []
  42. for item in info.get("formats", []):
  43. if item.get("resolution") != "audio only" and item.get("url") and item.get("acodec") and item.get(
  44. "acodec") != "none" and item.get("vcodec"):
  45. format_id = item.get("format_id")
  46. if format_id:
  47. formats.append({
  48. "width": f"{item.get('width', 0)}",
  49. "height": f"{item.get('height', 0)}",
  50. "type": item.get("format", ""),
  51. "quality": f'{item.get("format_note", "")}',
  52. "itag": 0,
  53. "fps": "0",
  54. "bitrate": "0",
  55. "url": f"http://d2rueqse8qhuiu.cloudfront.net/p?videoId={info['display_id']}&formatId={format_id}",
  56. "ext": item.get("ext"),
  57. "vcodec": item.get("vcodec", ""),
  58. "acodec": item.get("acodec", ""),
  59. "vbr": "0",
  60. "abr": "0",
  61. "container": item.get("container")
  62. })
  63. result = {
  64. "code": 200,
  65. "msg": "",
  66. "data": {
  67. "videoDetails": {
  68. "isLiveContent": info.get("is_live", False),
  69. "title": info.get("title", ""),
  70. "thumbnails": thumbnails,
  71. "description": info.get("description", ""),
  72. "lengthSeconds": f"{int(info.get('duration', 0) / 100)}",
  73. "viewCount": f"{info.get('view_count', 0)}",
  74. "keywords": [],
  75. "author": info.get("uploader", info.get("channel", "")),
  76. "channelID": info.get("channel_id", ""),
  77. "recommendInfo": [],
  78. "channelURL": info.get("channel_url", ""),
  79. "videoId": info.get("display_id", "")
  80. },
  81. "streamingData": {
  82. "formats": formats
  83. }
  84. },
  85. "id": "MusicDetailViewModel_detail_url"
  86. }
  87. return result
  88. @app.route("/extract", methods=["GET", "POST"])
  89. def extract():
  90. url: str = request.json.get("url")
  91. logging.info(f"url: {url}")
  92. info = fetch_info(url=url)
  93. return convert_dto(info=info)
  94. @app.route("/health", methods=["GET"])
  95. def health():
  96. return {
  97. "status": 1
  98. }
  99. @app.route("/refresh", methods=["GET"])
  100. def refresh():
  101. autoscaling = boto3.client(
  102. 'autoscaling',
  103. region_name="us-east-1",
  104. aws_access_key_id="AKIA2TBT2JUNG6X3W737",
  105. aws_secret_access_key="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")
  106. response = autoscaling.start_instance_refresh(
  107. AutoScalingGroupName="be-ytb-as")
  108. return {
  109. "response": response
  110. }
  111. if __name__ == '__main__':
  112. app.run(host='0.0.0.0', port=80, debug=True)