app.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import logging
  2. import yt_dlp
  3. from flask import Flask, request
  4. from tinydb import TinyDB
  5. app = Flask(__name__)
  6. db = TinyDB('data.json')
  7. def get_key(url: str) -> str:
  8. return f"v1:{url}"
  9. @app.route("/extract", methods=["GET", "POST"])
  10. def extract():
  11. url = request.json.get("url")
  12. logging.info(f"url: ${url}")
  13. key = get_key(url=url)
  14. result = db.search(lambda x: x["key"] == key)
  15. if result:
  16. logging.info("find from data.json, so return")
  17. if result[0].get("result"):
  18. return result[0].get("result")
  19. with yt_dlp.YoutubeDL({"flat-playlist": True, "extract_flat": "flat-playlist"}) as ydl:
  20. info = ydl.extract_info(url, download=False)
  21. thumbnails = []
  22. for item in info.get("thumbnails", []):
  23. if item.get("width"):
  24. thumbnails.append({
  25. "url": item.get("url", ""),
  26. "width": item.get("width", 0),
  27. "height": item.get("height", 0),
  28. })
  29. formats = []
  30. for item in info.get("formats", []):
  31. if item.get("resolution") != "audio only" and item.get("url") and item.get("acodec") and item.get(
  32. "acodec") != "none" and item.get("vcodec"):
  33. formats.append({
  34. "width": item.get("width", 0),
  35. "height": item.get("height", 0),
  36. "type": item.get("format", ""),
  37. "quality": f'{item.get("format_note", "")}',
  38. "itag": 0,
  39. "fps": 0,
  40. "bitrate": 0,
  41. "url": item.get("url", ""),
  42. "ext": item.get("ext"),
  43. "vcodec": item.get("vcodec", ""),
  44. "acodec": item.get("acodec", ""),
  45. "vbr": 0,
  46. "abr": 0,
  47. "container": item.get("container")
  48. })
  49. result = {
  50. "code": 200,
  51. "msg": "",
  52. "data": {
  53. "videoDetails": {
  54. "isLiveContent": info.get("is_live", False),
  55. "title": info.get("title", ""),
  56. "thumbnails": thumbnails,
  57. "description": info.get("description", ""),
  58. "lengthSeconds": int(info.get("duration", 0) / 100),
  59. "viewCount": f"{info.get('view_count', 0)}",
  60. "keywords": [],
  61. "author": info.get("uploader", info.get("channel", "")),
  62. "channelID": info.get("channel_id", ""),
  63. "recommendInfo": [],
  64. "channelURL": info.get("channel_url", ""),
  65. "videoId": info.get("display_id", "")
  66. },
  67. "streamingData": {
  68. "formats": formats
  69. }
  70. },
  71. "id": "MusicDetailViewModel_detail_url"
  72. }
  73. db.insert({"result": result, "key": key})
  74. return result
  75. if __name__ == '__main__':
  76. app.run(host='0.0.0.0', port=80, debug=True)