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.
 
 

346 lines
22 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. from youtube_channel import main
  8. import signal
  9. import tracker
  10. from youtube_dl import YoutubeDL
  11. from shutil import rmtree, which
  12. from queue import Queue
  13. from gc import collect
  14. from discovery import getmetadata
  15. from export import subprrun
  16. #useful Queue example: https://stackoverflow.com/a/54658363
  17. jobs = Queue()
  18. try:
  19. mkdir("out")
  20. except:
  21. pass
  22. try:
  23. mkdir("directory")
  24. except:
  25. pass
  26. HEROKU = False
  27. if isfile("../Procfile"):
  28. HEROKU = True
  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. mysession.headers.update({"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",})
  54. 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")
  55. assert not "accounts.google.com" in validationtest.url, "Please ensure you have correctly specified account cookies."
  56. 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">
  57. Language:
  58. </span>
  59. English
  60. </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)"
  61. del validationtest
  62. open("cookies.txt", "w").write("""# HTTP Cookie File
  63. .youtube.com TRUE / FALSE 1663793455 SID [SID]
  64. .youtube.com TRUE / FALSE 1663793455 HSID [HSID]
  65. .youtube.com TRUE / TRUE 1663793455 SSID [SSID]""".replace("[SID]", cookies["SID"]).replace("[HSID]", cookies["HSID"]).replace("[SSID]", cookies["SSID"]))
  66. del cookies
  67. validationtimes = 0
  68. shouldgetjob = True
  69. #Graceful Shutdown
  70. class GracefulKiller:
  71. kill_now = False
  72. def __init__(self):
  73. signal.signal(signal.SIGINT, self.exit_gracefully)
  74. signal.signal(signal.SIGTERM, self.exit_gracefully)
  75. def exit_gracefully(self, signum, frame):
  76. print("Graceful exit process initiated, no longer accepting new tasks but finishing existing ones...")
  77. self.kill_now = True
  78. gkiller = GracefulKiller()
  79. #REMOVED PANIC MECHANISM!
  80. """
  81. enres = getmetadata(mysession, "IjJKfe-0Ty0", True)[0]
  82. if not enres:
  83. print("Community Contribution discovery has been disabled for this account, please report this on our Discord as this may have caused some videos to be incorrectly marked as having community contributions disabled.")
  84. shouldgetjob = False
  85. gkiller.kill_now = True #exit the script
  86. del enres
  87. """
  88. #microtasks
  89. def threadrunner():
  90. global shouldgetjob
  91. global validationtimes
  92. jobs = Queue()
  93. 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})
  94. while True:
  95. if not jobs.empty():
  96. task, vid, args = jobs.get()
  97. if task == "submitdiscovery":
  98. tracker.add_item_to_tracker(args, vid)
  99. #pass
  100. elif task == "discovery":
  101. while True:
  102. try:
  103. info = getmetadata(mysession, str(vid).strip())
  104. break
  105. except BaseException as e:
  106. print(e)
  107. print("Error in retrieving information, waiting 30 seconds and trying again")
  108. sleep(30)
  109. if info[0]: # ccenabled or creditdata
  110. if not isdir("out/"+str(vid).strip()):
  111. mkdir("out/"+str(vid).strip())
  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[1]:
  121. jobs.put(("submitdiscovery", videodisc, tracker.ItemType.Video))
  122. for channeldisc in info[2]:
  123. jobs.put(("submitdiscovery", channeldisc, tracker.ItemType.Channel))
  124. for mixdisc in info[3]:
  125. jobs.put(("submitdiscovery", mixdisc, tracker.ItemType.MixPlaylist))
  126. for playldisc in info[4]:
  127. jobs.put(("submitdiscovery", playldisc, tracker.ItemType.Playlist))
  128. #jobs.put(("complete", None, "video:"+vid))
  129. #pass
  130. elif task == "subtitles":
  131. subprrun(mysession, args, vid, "default", needforcemetadata, needforcecaptions)
  132. elif task == "subtitles-forceedit-captions":
  133. subprrun(mysession, args, vid, "forceedit-captions", needforcemetadata, needforcecaptions)
  134. elif task == "subtitles-forceedit-metadata":
  135. subprrun(mysession, args, vid, "forceedit-metadata", needforcemetadata, needforcecaptions)
  136. elif task == "channel":
  137. try:
  138. y = ydl.extract_info("https://www.youtube.com/channel/"+desit.split(":", 1)[1], download=False)
  139. for itemyv in y["entries"]:
  140. jobs.put(("submitdiscovery", itemyv["id"], tracker.ItemType.Video))
  141. #channel created playlists
  142. y = main(desit.split(":", 1)[1])
  143. for itemyv in y["playlists"]:
  144. jobs.put(("submitdiscovery", itemyv, tracker.ItemType.Playlist))
  145. for itemyv in y["channels"]:
  146. jobs.put(("submitdiscovery", itemyv, tracker.ItemType.Channel))
  147. jobs.put(("complete", None, "channel:"+args))
  148. except:
  149. print("YouTube-DL error, ignoring but not marking as complete...", "https://www.youtube.com/channel/"+desit.split(":", 1)[1])
  150. elif task == "playlist":
  151. try:
  152. y = ydl.extract_info("https://www.youtube.com/playlist?list="+desit.split(":", 1)[1], download=False)
  153. #TODO: extract owner channel in other projects
  154. #TODO: handle channels in other projects, not needed here because we will get it from the video
  155. for itemyvp in y["entries"]:
  156. jobs.put(("submitdiscovery", itemyvp["id"], tracker.ItemType.Video))
  157. jobs.put(("complete", None, "playlist:"+args))
  158. except:
  159. print("YouTube-DL error, ignoring but not marking as complete...", "https://www.youtube.com/playlist?list="+desit.split(":", 1)[1])
  160. elif task == "mixplaylist":
  161. try:
  162. wptext = mysession.get("https://www.youtube.com/watch?v=jNQXAC9IVRw&list="+desit.split(":", 1)[1]).text
  163. #chanl = set()
  164. #channel handling not needed here because we will get it from the video
  165. for line in wptext.splitlines():
  166. if line.strip().startswith('window["ytInitialData"] = '):
  167. initdata = loads(line.split('window["ytInitialData"] = ', 1)[1].strip()[:-1])
  168. for itemyvp in initdata["contents"]["twoColumnWatchNextResults"]["playlist"]["playlist"]["contents"]:
  169. jobs.put(("submitdiscovery", itemyvp["playlistPanelVideoRenderer"]["videoId"], tracker.ItemType.Video))
  170. #chanl.add(itemyvp["playlistPanelVideoRenderer"]["longBylineText"]["runs"][0]["navigationEndpoint"]["browseEndpoint"]["browseId"])
  171. #for itemn in chanl:
  172. # jobs.put(("submitdiscovery", itemn, tracker.ItemType.Channel))
  173. jobs.put(("complete", None, "mixplaylist:"+args))
  174. except:
  175. print("Mix Playlist error, ignoring but not marking as complete...", "https://www.youtube.com/watch?v=jNQXAC9IVRw&list="+desit.split(":", 1)[1])
  176. elif task == "complete":
  177. size = 0
  178. if ":" in args:
  179. if args.split(":", 1)[0] == "video":
  180. #check if dir is empty, make zip if needed
  181. if isdir("out/"+args.split(":", 1)[1]):
  182. if not listdir("out/"+args.split(":", 1)[1]):
  183. rmdir("out/"+args.split(":", 1)[1])
  184. else:
  185. #zip it up
  186. if not isdir("directory/"+args.split(":", 1)[1]):
  187. mkdir("directory/"+args.split(":", 1)[1])
  188. while not isfile("directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip"):
  189. print("Attempting to zip item...")
  190. system("zip -9 -r -j directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip out/"+args.split(":", 1)[1])
  191. #get a target
  192. targetloc = None
  193. while not targetloc:
  194. targetloc = tracker.request_upload_target()
  195. if targetloc:
  196. break
  197. else:
  198. print("Waiting 5 minutes...")
  199. sleep(300)
  200. if targetloc.startswith("rsync"):
  201. 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)
  202. elif targetloc.startswith("http"):
  203. system("curl -F "+args.split(":", 1)[1]+".zip=@directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip "+targetloc)
  204. size = getsize("directory/"+args.split(":", 1)[1]+"/"+args.split(":", 1)[1]+".zip")
  205. #cleanup
  206. try:
  207. del langcnt[args.split(":", 1)[1]]
  208. rmtree("directory/"+args.split(":", 1)[1]+"/")
  209. rmdir("directory/"+args.split(":", 1)[1]+"/")
  210. rmtree("out/"+args.split(":", 1)[1]+"/")
  211. rmdir("out/"+args.split(":", 1)[1]+"/")
  212. except:
  213. pass
  214. tracker.mark_item_as_done(args, size)
  215. jobs.task_done()
  216. else:
  217. if not gkiller.kill_now:
  218. # get a new task from tracker
  219. collect() #cleanup
  220. #Protection Mechanism Disarmed
  221. """
  222. #check that the account has community contributions enabled every 50th item
  223. validationtimes += 1
  224. if not validationtimes % 50:
  225. enres = getmetadata(mysession, "IjJKfe-0Ty0", True)[0]
  226. if not enres:
  227. print("Community Contribution discovery has been disabled for this account, please report this on our Discord as this may have caused some videos to be incorrectly marked as having community contributions disabled.")
  228. shouldgetjob = False
  229. gkiller.kill_now = True #exit the script
  230. del enres
  231. """
  232. if shouldgetjob:
  233. desit = tracker.request_item_from_tracker()
  234. print("New task:", desit)
  235. if desit:
  236. if desit.split(":", 1)[0] == "video":
  237. 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,
  238. '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,
  239. '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,
  240. '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,
  241. '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,
  242. '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,
  243. '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,
  244. '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,
  245. '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,
  246. '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,
  247. 'xh': None, 'yi': None, 'yo': None, 'zu': None}
  248. 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,
  249. '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,
  250. '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,
  251. '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,
  252. '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,
  253. '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,
  254. '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,
  255. '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,
  256. '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,
  257. '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,
  258. 'xh': None, 'yi': None, 'yo': None, 'zu': None}
  259. jobs.put(("discovery", desit.split(":", 1)[1], None))
  260. elif desit.split(":", 1)[0] == "channel":
  261. jobs.put(("channel", None, desit.split(":", 1)[1]))
  262. elif desit.split(":", 1)[0] == "playlist":
  263. jobs.put(("playlist", None, desit.split(":", 1)[1]))
  264. elif desit.split(":", 1)[0] == "mixplaylist":
  265. jobs.put(("mixplaylist", None, desit.split(":", 1)[1]))
  266. else:
  267. print("Ignoring item for now", desit)
  268. else:
  269. print("Ignoring item for now", desit)
  270. else:
  271. break
  272. else:
  273. break
  274. threads = []
  275. THREADCNT = 50
  276. if HEROKU:
  277. THREADCNT = 20
  278. #now create the rest of the threads
  279. for i in range(THREADCNT):
  280. runthread = Thread(target=threadrunner)
  281. runthread.start()
  282. threads.append(runthread)
  283. del runthread
  284. #https://stackoverflow.com/a/11968881
  285. for x in threads:
  286. x.join()
  287. threads.remove(x)
  288. del x
  289. if not shouldgetjob:
  290. print("PROTECTION MECHANISM #3 WAS SOMEHOW TRIGERRED")
  291. print("Community Contribution discovery has been disabled for this account, please report this on our Discord as this may have caused some videos to be incorrectly marked as having community contributions disabled.")
  292. print("Exiting...")