app.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import logging
  2. import boto3
  3. import requests
  4. import yt_dlp
  5. from flask import Flask, request, Response
  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, stream=True)
  30. def generate():
  31. for chunk in response.iter_content(chunk_size=1024):
  32. yield chunk
  33. return Response(generate(), status=response.status_code, headers=dict(response.headers))
  34. return {"status": 0}
  35. def convert_dto(info):
  36. thumbnails = []
  37. for item in info.get("thumbnails", []):
  38. if item.get("width"):
  39. thumbnails.append({
  40. "url": item.get("url", ""),
  41. "width": f"{item.get('width', 0)}",
  42. "height": f"{item.get('height', 0)}",
  43. })
  44. formats = []
  45. for item in info.get("formats", []):
  46. if item.get("resolution") != "audio only" and item.get("url") and item.get("acodec") and item.get(
  47. "acodec") != "none" and item.get("vcodec"):
  48. format_id = item.get("format_id")
  49. if format_id:
  50. formats.append({
  51. "width": f"{item.get('width', 0)}",
  52. "height": f"{item.get('height', 0)}",
  53. "type": item.get("format", ""),
  54. "quality": f'{item.get("format_note", "")}',
  55. "itag": 0,
  56. "fps": "0",
  57. "bitrate": "0",
  58. # "url": f"http://d2rueqse8qhuiu.cloudfront.net/p?videoId={info['display_id']}&formatId={format_id}",
  59. "url": item.get("url"),
  60. "ext": item.get("ext"),
  61. "vcodec": item.get("vcodec", ""),
  62. "acodec": item.get("acodec", ""),
  63. "vbr": "0",
  64. "abr": "0",
  65. "container": item.get("container")
  66. })
  67. result = {
  68. "code": 200,
  69. "msg": "",
  70. "data": {
  71. "videoDetails": {
  72. "isLiveContent": info.get("is_live", False),
  73. "title": info.get("title", ""),
  74. "thumbnails": thumbnails,
  75. "description": info.get("description", ""),
  76. "lengthSeconds": f"{int(info.get('duration', 0) / 100)}",
  77. "viewCount": f"{info.get('view_count', 0)}",
  78. "keywords": [],
  79. "author": info.get("uploader", info.get("channel", "")),
  80. "channelID": info.get("channel_id", ""),
  81. "recommendInfo": [],
  82. "channelURL": info.get("channel_url", ""),
  83. "videoId": info.get("display_id", "")
  84. },
  85. "streamingData": {
  86. "formats": formats
  87. }
  88. },
  89. "id": "MusicDetailViewModel_detail_url"
  90. }
  91. return result
  92. @app.route("/extract", methods=["GET", "POST"])
  93. def extract():
  94. url: str = request.json.get("url")
  95. logging.info(f"url: {url}")
  96. info = fetch_info(url=url)
  97. return convert_dto(info=info)
  98. @app.route("/health", methods=["GET"])
  99. def health():
  100. return {
  101. "status": 1
  102. }
  103. @app.route("/refresh", methods=["GET"])
  104. def refresh():
  105. autoscaling = boto3.client(
  106. 'autoscaling',
  107. region_name="us-east-1",
  108. aws_access_key_id="AKIA2TBT2JUNG6X3W737",
  109. aws_secret_access_key="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")
  110. response = autoscaling.start_instance_refresh(
  111. AutoScalingGroupName="be-ytb-as")
  112. return {
  113. "response": response
  114. }
  115. if __name__ == '__main__':
  116. app.run(host='0.0.0.0', port=80, debug=True)