archiving community contributions on YouTube: unpublished captions, title and description translations and caption credits
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

277 строки
18 KiB

  1. from threading import Thread
  2. import requests
  3. from time import sleep
  4. from os import mkdir, rmdir, listdir, system, environ
  5. from os.path import isdir, isfile, getsize
  6. from json import dumps, loads
  7. HEROKU = False
  8. if isfile("../Procfile") and isfile("../requirements.txt"):
  9. print("Heroku detected... using 20 threads instead of 50.")
  10. HEROKU = True
  11. import signal
  12. import tracker
  13. from youtube_dl import YoutubeDL
  14. from shutil import rmtree, which
  15. from queue import Queue
  16. from gc import collect
  17. from discovery import getmetadata
  18. from export import subprrun
  19. #useful Queue example: https://stackoverflow.com/a/54658363
  20. jobs = Queue()
  21. try:
  22. mkdir("out")
  23. except:
  24. pass
  25. try:
  26. mkdir("directory")
  27. except:
  28. pass
  29. langs = ['ab', 'aa', 'af', 'sq', 'ase', 'am', 'ar', 'arc', 'hy', 'as', 'ay', 'az', 'bn', 'ba', 'eu', 'be', 'bh', 'bi', 'bs', 'br',
  30. 'bg', 'yue', 'yue-HK', 'ca', 'chr', 'zh-CN', 'zh-HK', 'zh-Hans', 'zh-SG', 'zh-TW', 'zh-Hant', 'cho', 'co', 'hr', 'cs', 'da', 'nl',
  31. 'nl-BE', 'nl-NL', 'dz', 'en', 'en-CA', 'en-IN', 'en-IE', 'en-GB', 'en-US', 'eo', 'et', 'fo', 'fj', 'fil', 'fi', 'fr', 'fr-BE',
  32. 'fr-CA', 'fr-FR', 'fr-CH', 'ff', 'gl', 'ka', 'de', 'de-AT', 'de-DE', 'de-CH', 'el', 'kl', 'gn', 'gu', 'ht', 'hak', 'hak-TW', 'ha',
  33. 'iw', 'hi', 'hi-Latn', 'ho', 'hu', 'is', 'ig', 'id', 'ia', 'ie', 'iu', 'ik', 'ga', 'it', 'ja', 'jv', 'kn', 'ks', 'kk', 'km', 'rw',
  34. 'tlh', 'ko', 'ku', 'ky', 'lo', 'la', 'lv', 'ln', 'lt', 'lb', 'mk', 'mg', 'ms', 'ml', 'mt', 'mni', 'mi', 'mr', 'mas', 'nan',
  35. 'nan-TW', 'lus', 'mo', 'mn', 'my', 'na', 'nv', 'ne', 'no', 'oc', 'or', 'om', 'ps', 'fa', 'fa-AF', 'fa-IR', 'pl', 'pt', 'pt-BR',
  36. 'pt-PT', 'pa', 'qu', 'ro', 'rm', 'rn', 'ru', 'ru-Latn', 'sm', 'sg', 'sa', 'sc', 'gd', 'sr', 'sr-Cyrl', 'sr-Latn', 'sh', 'sdp', 'sn',
  37. 'scn', 'sd', 'si', 'sk', 'sl', 'so', 'st', 'es', 'es-419', 'es-MX', 'es-ES', 'es-US', 'su', 'sw', 'ss', 'sv', 'tl', 'tg', 'ta',
  38. 'tt', 'te', 'th', 'bo', 'ti', 'tpi', 'to', 'ts', 'tn', 'tr', 'tk', 'tw', 'uk', 'ur', 'uz', 'vi', 'vo', 'vor', 'cy', 'fy', 'wo',
  39. 'xh', 'yi', 'yo', 'zu']
  40. assert which("zip") and which("rsync") and which("curl"), "Please ensure the zip, rsync, and curl commands are installed on your system."
  41. #HSID, SSID, SID cookies required
  42. if "HSID" in environ.keys() and "SSID" in environ.keys() and "SID" in environ.keys():
  43. cookies = {"HSID": environ["HSID"], "SSID": environ["SSID"], "SID": environ["SID"]}
  44. elif isfile("config.json"):
  45. cookies = loads(open("config.json").read())
  46. else:
  47. print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  48. assert False
  49. if not (cookies["HSID"] and cookies["SSID"] and cookies["SID"]):
  50. print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  51. assert False
  52. mysession = requests.session()
  53. allheaders = {"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",}
  54. mysession.headers.update({"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",})
  55. validationtest = mysession.get("https://www.youtube.com/timedtext_editor?action_mde_edit_form=1&v=1iNTtHUwvq4&lang=en&bl=vmp&ui=hd&ref=player&tab=captions&o=U")
  56. assert not "accounts.google.com" in validationtest.url, "Please ensure you have correctly specified account cookies."
  57. assert """<button class="yt-uix-button yt-uix-button-size-default yt-uix-button-default yt-uix-button-has-icon" type="button" onclick=";return false;" id="yt-picker-language-button" data-button-action="yt.www.picker.load" data-button-menu-id="arrow-display" data-picker-key="language" data-picker-position="footer" data-button-toggle="true"><span class="yt-uix-button-icon-wrapper"><span class="yt-uix-button-icon yt-uix-button-icon-footer-language yt-sprite"></span></span><span class="yt-uix-button-content"> <span class="yt-picker-button-label">
  58. Language:
  59. </span>
  60. English
  61. </span><span class="yt-uix-button-arrow yt-sprite"></span></button>""" in validationtest.text, "Please make sure your YouTube and Google account language is set to English (United States)"
  62. del validationtest
  63. open("cookies.txt", "w").write("""# HTTP Cookie File
  64. .youtube.com TRUE / FALSE 1663793455 SID [SID]
  65. .youtube.com TRUE / FALSE 1663793455 HSID [HSID]
  66. .youtube.com TRUE / TRUE 1663793455 SSID [SSID]""".replace("[SID]", cookies["SID"]).replace("[HSID]", cookies["HSID"]).replace("[SSID]", cookies["SSID"]))
  67. del cookies
  68. #Graceful Shutdown
  69. class GracefulKiller:
  70. kill_now = False
  71. def __init__(self):
  72. signal.signal(signal.SIGINT, self.exit_gracefully)
  73. signal.signal(signal.SIGTERM, self.exit_gracefully)
  74. def exit_gracefully(self, signum, frame):
  75. print("Graceful exit process initiated, no longer accepting new tasks but finishing existing ones...")
  76. self.kill_now = True
  77. gkiller = GracefulKiller()
  78. #microtasks
  79. def threadrunner():
  80. jobs = Queue()
  81. ydl = YoutubeDL({"extract_flat": "in_playlist", "simulate": True, "skip_download": True, "quiet": True, "cookiefile": "cookies.txt", "source_address": "0.0.0.0", "call_home": False})
  82. while True:
  83. if not jobs.empty():
  84. task, vid, args = jobs.get()
  85. if task == "submitdiscovery":
  86. tracker.add_item_to_tracker(args, vid)
  87. elif task == "discovery":
  88. while True:
  89. try:
  90. info = getmetadata(mysession, str(vid).strip(), allheaders)
  91. break
  92. except BaseException as e:
  93. print(e)
  94. print("Error in retrieving information, waiting 30 seconds and trying again")
  95. #raise
  96. sleep(30)
  97. if info[0] or info[1]: # ccenabled or creditdata
  98. if not isdir("out/"+str(vid).strip()):
  99. mkdir("out/"+str(vid).strip())
  100. if info[1]:
  101. open("out/"+str(vid).strip()+"/"+str(vid).strip()+"_published_credits.json", "w").write(dumps(info[1]))
  102. if info[0]:
  103. for langcode in langs:
  104. jobs.put(("subtitles", vid, langcode))
  105. for langcode in langs:
  106. jobs.put(("subtitles-forceedit-metadata", vid, langcode))
  107. for langcode in langs:
  108. jobs.put(("subtitles-forceedit-captions", vid, langcode))
  109. jobs.put(("complete", None, "video:"+vid))
  110. for videodisc in info[2]:
  111. jobs.put(("submitdiscovery", videodisc, tracker.ItemType.Video))
  112. for channeldisc in info[3]:
  113. jobs.put(("submitdiscovery", channeldisc, tracker.ItemType.Channel))
  114. for mixdisc in info[4]:
  115. jobs.put(("submitdiscovery", mixdisc, tracker.ItemType.MixPlaylist))
  116. for playldisc in info[5]:
  117. jobs.put(("submitdiscovery", playldisc, tracker.ItemType.Playlist))
  118. elif task == "subtitles":
  119. subprrun(mysession, args, vid, "default", needforcemetadata, needforcecaptions, allheaders)
  120. elif task == "subtitles-forceedit-captions":
  121. subprrun(mysession, args, vid, "forceedit-captions", needforcemetadata, needforcecaptions, allheaders)
  122. elif task == "subtitles-forceedit-metadata":
  123. subprrun(mysession, args, vid, "forceedit-metadata", needforcemetadata, needforcecaptions, allheaders)
  124. elif task == "channel":
  125. try:
  126. y = ydl.extract_info("https://www.youtube.com/channel/"+desit.split(":", 1)[1], download=False)
  127. for itemyv in y["entries"]:
  128. jobs.put(("submitdiscovery", itemyv["id"], tracker.ItemType.Video))
  129. jobs.put(("complete", None, "channel:"+args))
  130. except:
  131. print("YouTube-DL error, ignoring but not marking as complete...", "https://www.youtube.com/channel/"+desit.split(":", 1)[1])
  132. elif task == "playlist":
  133. try:
  134. y = ydl.extract_info("https://www.youtube.com/playlist?list="+desit.split(":", 1)[1], download=False)
  135. for itemyvp in y["entries"]:
  136. jobs.put(("submitdiscovery", itemyvp["id"], tracker.ItemType.Video))
  137. jobs.put(("complete", None, "playlist:"+args))
  138. except:
  139. print("YouTube-DL error, ignoring but not marking as complete...", "https://www.youtube.com/playlist?list="+desit.split(":", 1)[1])
  140. elif task == "complete":
  141. size = 0
  142. if ":" in args:
  143. if args.split(":", 1)[0] == "video":
  144. #check if dir is empty, make zip if needed
  145. if isdir("out/"+args.split(":", 1)[1]):
  146. if not listdir("out/"+args.split(":", 1)[1]):
  147. rmdir("out/"+args.split(":", 1)[1])
  148. else:
  149. #zip it up
  150. if not isdir("directory/"+args.split(":", 1)[1]):
  151. mkdir("directory/"+args.split(":", 1)[1])
  152. while not isfile("directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip"):
  153. print("Attempting to zip item...")
  154. system("zip -9 -r -j directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip out/"+args.split(":", 1)[1])
  155. #get a target
  156. targetloc = None
  157. while not targetloc:
  158. targetloc = tracker.request_upload_target()
  159. if targetloc:
  160. break
  161. else:
  162. print("Waiting 5 minutes...")
  163. sleep(300)
  164. if targetloc.startswith("rsync"):
  165. system("rsync -rltv --timeout=300 --contimeout=300 --progress --bwlimit 0 --recursive --partial --partial-dir .rsync-tmp --min-size 1 --no-compress --compress-level 0 directory/"+args.split(":", 1)[1]+"/ "+targetloc)
  166. elif targetloc.startswith("http"):
  167. system("curl -F "+args.split(":", 1)[1]+".zip=@directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip "+targetloc)
  168. size = getsize("directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip")
  169. #cleanup
  170. try:
  171. del langcnt[args.split(":", 1)[1]]
  172. rmtree("directory/"+args.split(":", 1)[1]+"/")
  173. rmdir("directory/"+args.split(":", 1)[1]+"/")
  174. rmtree("out/"+args.split(":", 1)[1]+"/")
  175. rmdir("out/"+args.split(":", 1)[1]+"/")
  176. except:
  177. pass
  178. tracker.mark_item_as_done(args, size)
  179. jobs.task_done()
  180. else:
  181. if not gkiller.kill_now:
  182. # get a new task from tracker
  183. collect() #cleanup
  184. desit = tracker.request_item_from_tracker()
  185. print("New task:", desit)
  186. if desit:
  187. if desit.split(":", 1)[0] == "video":
  188. needforcemetadata = {'ab': None, 'aa': None, 'af': None, 'sq': None, 'ase': None, 'am': None, 'ar': None, 'arc': None, 'hy': None, 'as': None, 'ay': None, 'az': None, 'bn': None, 'ba': None, 'eu': None, 'be': None, 'bh': None, 'bi': None, 'bs': None, 'br': None,
  189. 'bg': None, 'yue': None, 'yue-HK': None, 'ca': None, 'chr': None, 'zh-CN': None, 'zh-HK': None, 'zh-Hans': None, 'zh-SG': None, 'zh-TW': None, 'zh-Hant': None, 'cho': None, 'co': None, 'hr': None, 'cs': None, 'da': None, 'nl': None,
  190. 'nl-BE': None, 'nl-NL': None, 'dz': None, 'en': None, 'en-CA': None, 'en-IN': None, 'en-IE': None, 'en-GB': None, 'en-US': None, 'eo': None, 'et': None, 'fo': None, 'fj': None, 'fil': None, 'fi': None, 'fr': None, 'fr-BE': None,
  191. 'fr-CA': None, 'fr-FR': None, 'fr-CH': None, 'ff': None, 'gl': None, 'ka': None, 'de': None, 'de-AT': None, 'de-DE': None, 'de-CH': None, 'el': None, 'kl': None, 'gn': None, 'gu': None, 'ht': None, 'hak': None, 'hak-TW': None, 'ha': None,
  192. 'iw': None, 'hi': None, 'hi-Latn': None, 'ho': None, 'hu': None, 'is': None, 'ig': None, 'id': None, 'ia': None, 'ie': None, 'iu': None, 'ik': None, 'ga': None, 'it': None, 'ja': None, 'jv': None, 'kn': None, 'ks': None, 'kk': None, 'km': None, 'rw': None,
  193. 'tlh': None, 'ko': None, 'ku': None, 'ky': None, 'lo': None, 'la': None, 'lv': None, 'ln': None, 'lt': None, 'lb': None, 'mk': None, 'mg': None, 'ms': None, 'ml': None, 'mt': None, 'mni': None, 'mi': None, 'mr': None, 'mas': None, 'nan': None,
  194. 'nan-TW': None, 'lus': None, 'mo': None, 'mn': None, 'my': None, 'na': None, 'nv': None, 'ne': None, 'no': None, 'oc': None, 'or': None, 'om': None, 'ps': None, 'fa': None, 'fa-AF': None, 'fa-IR': None, 'pl': None, 'pt': None, 'pt-BR': None,
  195. 'pt-PT': None, 'pa': None, 'qu': None, 'ro': None, 'rm': None, 'rn': None, 'ru': None, 'ru-Latn': None, 'sm': None, 'sg': None, 'sa': None, 'sc': None, 'gd': None, 'sr': None, 'sr-Cyrl': None, 'sr-Latn': None, 'sh': None, 'sdp': None, 'sn': None,
  196. 'scn': None, 'sd': None, 'si': None, 'sk': None, 'sl': None, 'so': None, 'st': None, 'es': None, 'es-419': None, 'es-MX': None, 'es-ES': None, 'es-US': None, 'su': None, 'sw': None, 'ss': None, 'sv': None, 'tl': None, 'tg': None, 'ta': None,
  197. 'tt': None, 'te': None, 'th': None, 'bo': None, 'ti': None, 'tpi': None, 'to': None, 'ts': None, 'tn': None, 'tr': None, 'tk': None, 'tw': None, 'uk': None, 'ur': None, 'uz': None, 'vi': None, 'vo': None, 'vor': None, 'cy': None, 'fy': None, 'wo': None,
  198. 'xh': None, 'yi': None, 'yo': None, 'zu': None}
  199. needforcecaptions = {'ab': None, 'aa': None, 'af': None, 'sq': None, 'ase': None, 'am': None, 'ar': None, 'arc': None, 'hy': None, 'as': None, 'ay': None, 'az': None, 'bn': None, 'ba': None, 'eu': None, 'be': None, 'bh': None, 'bi': None, 'bs': None, 'br': None,
  200. 'bg': None, 'yue': None, 'yue-HK': None, 'ca': None, 'chr': None, 'zh-CN': None, 'zh-HK': None, 'zh-Hans': None, 'zh-SG': None, 'zh-TW': None, 'zh-Hant': None, 'cho': None, 'co': None, 'hr': None, 'cs': None, 'da': None, 'nl': None,
  201. 'nl-BE': None, 'nl-NL': None, 'dz': None, 'en': None, 'en-CA': None, 'en-IN': None, 'en-IE': None, 'en-GB': None, 'en-US': None, 'eo': None, 'et': None, 'fo': None, 'fj': None, 'fil': None, 'fi': None, 'fr': None, 'fr-BE': None,
  202. 'fr-CA': None, 'fr-FR': None, 'fr-CH': None, 'ff': None, 'gl': None, 'ka': None, 'de': None, 'de-AT': None, 'de-DE': None, 'de-CH': None, 'el': None, 'kl': None, 'gn': None, 'gu': None, 'ht': None, 'hak': None, 'hak-TW': None, 'ha': None,
  203. 'iw': None, 'hi': None, 'hi-Latn': None, 'ho': None, 'hu': None, 'is': None, 'ig': None, 'id': None, 'ia': None, 'ie': None, 'iu': None, 'ik': None, 'ga': None, 'it': None, 'ja': None, 'jv': None, 'kn': None, 'ks': None, 'kk': None, 'km': None, 'rw': None,
  204. 'tlh': None, 'ko': None, 'ku': None, 'ky': None, 'lo': None, 'la': None, 'lv': None, 'ln': None, 'lt': None, 'lb': None, 'mk': None, 'mg': None, 'ms': None, 'ml': None, 'mt': None, 'mni': None, 'mi': None, 'mr': None, 'mas': None, 'nan': None,
  205. 'nan-TW': None, 'lus': None, 'mo': None, 'mn': None, 'my': None, 'na': None, 'nv': None, 'ne': None, 'no': None, 'oc': None, 'or': None, 'om': None, 'ps': None, 'fa': None, 'fa-AF': None, 'fa-IR': None, 'pl': None, 'pt': None, 'pt-BR': None,
  206. 'pt-PT': None, 'pa': None, 'qu': None, 'ro': None, 'rm': None, 'rn': None, 'ru': None, 'ru-Latn': None, 'sm': None, 'sg': None, 'sa': None, 'sc': None, 'gd': None, 'sr': None, 'sr-Cyrl': None, 'sr-Latn': None, 'sh': None, 'sdp': None, 'sn': None,
  207. 'scn': None, 'sd': None, 'si': None, 'sk': None, 'sl': None, 'so': None, 'st': None, 'es': None, 'es-419': None, 'es-MX': None, 'es-ES': None, 'es-US': None, 'su': None, 'sw': None, 'ss': None, 'sv': None, 'tl': None, 'tg': None, 'ta': None,
  208. 'tt': None, 'te': None, 'th': None, 'bo': None, 'ti': None, 'tpi': None, 'to': None, 'ts': None, 'tn': None, 'tr': None, 'tk': None, 'tw': None, 'uk': None, 'ur': None, 'uz': None, 'vi': None, 'vo': None, 'vor': None, 'cy': None, 'fy': None, 'wo': None,
  209. 'xh': None, 'yi': None, 'yo': None, 'zu': None}
  210. jobs.put(("discovery", desit.split(":", 1)[1], None))
  211. elif desit.split(":", 1)[0] == "channel":
  212. jobs.put(("channel", None, desit.split(":", 1)[1]))
  213. elif desit.split(":", 1)[0] == "playlist":
  214. jobs.put(("playlist", None, desit.split(":", 1)[1]))
  215. else:
  216. print("Ignoring item for now", desit)
  217. else:
  218. print("Ignoring item for now", desit)
  219. else:
  220. break
  221. threads = []
  222. THREADCNT = 50
  223. if HEROKU:
  224. THREADCNT = 20
  225. #now create the rest of the threads
  226. for i in range(THREADCNT):
  227. runthread = Thread(target=threadrunner)
  228. runthread.start()
  229. threads.append(runthread)
  230. del runthread
  231. #https://stackoverflow.com/a/11968881
  232. for x in threads:
  233. x.join()
  234. threads.remove(x)
  235. del x
  236. print("Exiting...")