archiving community contributions on YouTube: unpublished captions, title and description translations and caption credits
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

289 lines
18 KiB

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