app.py 4.5 KB

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