app.py 2.9 KB

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