app.py 2.9 KB

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