app.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import logging
  2. import cachetools
  3. import yt_dlp
  4. from flask import Flask, request
  5. logging.basicConfig(format='%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d %(message)s',
  6. datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
  7. app = Flask(__name__)
  8. def get_key(url: str) -> str:
  9. return f"v2:{url}"
  10. @cachetools.cached(cache=cachetools.TTLCache(maxsize=100000, ttl=60 * 5))
  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. def convert_dto(info):
  20. thumbnails = []
  21. for item in info.get("thumbnails", []):
  22. if item.get("width"):
  23. thumbnails.append({
  24. "url": item.get("url", ""),
  25. "width": f"{item.get('width', 0)}",
  26. "height": f"{item.get('height', 0)}",
  27. })
  28. formats = []
  29. for item in info.get("formats", []):
  30. if item.get("resolution") != "audio only" and item.get("url") and item.get("acodec") and item.get(
  31. "acodec") != "none" and item.get("vcodec"):
  32. formats.append({
  33. "width": f"{item.get('width', 0)}",
  34. "height": f"{item.get('height', 0)}",
  35. "type": item.get("format", ""),
  36. "quality": f'{item.get("format_note", "")}',
  37. "itag": 0,
  38. "fps": "0",
  39. "bitrate": "0",
  40. "url": item.get("url", ""),
  41. "ext": item.get("ext"),
  42. "vcodec": item.get("vcodec", ""),
  43. "acodec": item.get("acodec", ""),
  44. "vbr": "0",
  45. "abr": "0",
  46. "container": item.get("container")
  47. })
  48. result = {
  49. "code": 200,
  50. "msg": "",
  51. "data": {
  52. "videoDetails": {
  53. "isLiveContent": info.get("is_live", False),
  54. "title": info.get("title", ""),
  55. "thumbnails": thumbnails,
  56. "description": info.get("description", ""),
  57. "lengthSeconds": f"{int(info.get('duration', 0) / 100)}",
  58. "viewCount": f"{info.get('view_count', 0)}",
  59. "keywords": [],
  60. "author": info.get("uploader", info.get("channel", "")),
  61. "channelID": info.get("channel_id", ""),
  62. "recommendInfo": [],
  63. "channelURL": info.get("channel_url", ""),
  64. "videoId": info.get("display_id", "")
  65. },
  66. "streamingData": {
  67. "formats": formats
  68. }
  69. },
  70. "id": "MusicDetailViewModel_detail_url"
  71. }
  72. return result
  73. @app.route("/extract", methods=["GET", "POST"])
  74. def extract():
  75. url: str = request.json.get("url")
  76. logging.info(f"url: {url}")
  77. info = fetch_info(url=url)
  78. return convert_dto(info=info)
  79. if __name__ == '__main__':
  80. app.run(host='0.0.0.0', port=80, debug=True)