app.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import logging
  2. import yt_dlp
  3. from flask import Flask, request
  4. from tinydb import TinyDB
  5. from tinydb.table import Document
  6. app = Flask(__name__)
  7. db = TinyDB('data.json')
  8. @app.route("/extract", methods=["GET", "POST"])
  9. def extract():
  10. url = request.json.get("url")
  11. result = db.get(doc_id=url)
  12. if result:
  13. logging.info("find from data.json, so return")
  14. return result
  15. logging.info(f"url: ${url}")
  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. }
  69. db.upsert(Document(value=result, doc_id=url))
  70. return result
  71. if __name__ == '__main__':
  72. app.run(host='0.0.0.0', port=80, debug=True)