app.py 4.6 KB

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