archiving community contributions on YouTube: unpublished captions, title and description translations and caption credits
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

315 行
10 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. import signal
  8. from youtube_dl.utils import DownloadError
  9. import tracker
  10. from youtube_dl import YoutubeDL
  11. from shutil import make_archive, rmtree
  12. from queue import Queue
  13. from gc import collect
  14. from discovery import getmetadata
  15. from export import subprrun
  16. batchcontent = []
  17. def batchfunc():
  18. while len(batchcontent) < 500:
  19. batchcontent.append(tracker.request_item_from_tracker())
  20. def submitfunc(submitqueue):
  21. while not submitqueue.empty():
  22. itype, ival = submitqueue.get()
  23. tracker.add_item_to_tracker(itype, ival)
  24. WORKER_VERSION = 1
  25. SERVER_BASE_URL = "http://localhost:5000"
  26. langs = ['ab', 'aa', 'af', 'sq', 'ase', 'am', 'ar', 'arc', 'hy', 'as', 'ay', 'az', 'bn', 'ba', 'eu', 'be', 'bh', 'bi', 'bs', 'br',
  27. 'bg', 'yue', 'yue-HK', 'ca', 'chr', 'zh-CN', 'zh-HK', 'zh-Hans', 'zh-SG', 'zh-TW', 'zh-Hant', 'cho', 'co', 'hr', 'cs', 'da', 'nl',
  28. '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',
  29. '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',
  30. 'iw', 'hi', 'hi-Latn', 'ho', 'hu', 'is', 'ig', 'id', 'ia', 'ie', 'iu', 'ik', 'ga', 'it', 'ja', 'jv', 'kn', 'ks', 'kk', 'km', 'rw',
  31. 'tlh', 'ko', 'ku', 'ky', 'lo', 'la', 'lv', 'ln', 'lt', 'lb', 'mk', 'mg', 'ms', 'ml', 'mt', 'mni', 'mi', 'mr', 'mas', 'nan',
  32. 'nan-TW', 'lus', 'mo', 'mn', 'my', 'na', 'nv', 'ne', 'no', 'oc', 'or', 'om', 'ps', 'fa', 'fa-AF', 'fa-IR', 'pl', 'pt', 'pt-BR',
  33. 'pt-PT', 'pa', 'qu', 'ro', 'rm', 'rn', 'ru', 'ru-Latn', 'sm', 'sg', 'sa', 'sc', 'gd', 'sr', 'sr-Cyrl', 'sr-Latn', 'sh', 'sdp', 'sn',
  34. 'scn', 'sd', 'si', 'sk', 'sl', 'so', 'st', 'es', 'es-419', 'es-MX', 'es-ES', 'es-US', 'su', 'sw', 'ss', 'sv', 'tl', 'tg', 'ta',
  35. 'tt', 'te', 'th', 'bo', 'ti', 'tpi', 'to', 'ts', 'tn', 'tr', 'tk', 'tw', 'uk', 'ur', 'uz', 'vi', 'vo', 'vor', 'cy', 'fy', 'wo',
  36. 'xh', 'yi', 'yo', 'zu']
  37. #useful Queue example: https://stackoverflow.com/a/54658363
  38. jobs = Queue()
  39. ccenabledl = []
  40. recvids = set()
  41. recchans = set()
  42. recmixes = set()
  43. recplayl = set()
  44. #HSID, SSID, SID cookies required
  45. if "HSID" in environ.keys() and "SSID" in environ.keys() and "SID" in environ.keys():
  46. cookies = {"HSID": environ["HSID"], "SSID": environ["SSID"], "SID": environ["SID"]}
  47. elif isfile("config.json"):
  48. cookies = loads(open("config.json").read())
  49. else:
  50. print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  51. assert False
  52. if not (cookies["HSID"] and cookies["SSID"] and cookies["SID"]):
  53. print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  54. assert False
  55. mysession = requests.session()
  56. mysession.headers.update({"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",})
  57. open("cookies.txt", "w").write(""".youtube.com TRUE / FALSE 1663793455 SID [SID]
  58. .youtube.com TRUE / FALSE 1663793455 HSID [HSID]
  59. .youtube.com TRUE / TRUE 1663793455 SSID [SSID]""".replace("[SID]", cookies["SID"]).replace("[HSID]", cookies["HSID"]).replace("[SSID]", cookies["SSID"]))
  60. del cookies
  61. #Graceful Shutdown
  62. class GracefulKiller:
  63. kill_now = False
  64. def __init__(self):
  65. signal.signal(signal.SIGINT, self.exit_gracefully)
  66. signal.signal(signal.SIGTERM, self.exit_gracefully)
  67. def exit_gracefully(self,signum, frame):
  68. self.kill_now = True
  69. gkiller = GracefulKiller()
  70. def prrun():
  71. while not jobs.empty():
  72. global recvids
  73. global recchans
  74. global recmixes
  75. global recplayl
  76. global ccenabledl
  77. item = jobs.get()
  78. print("Video ID:", str(item).strip())
  79. while True:
  80. try:
  81. info = getmetadata(str(item).strip())
  82. break
  83. except BaseException as e:
  84. print(e)
  85. print("Error in retrieving information, waiting 30 seconds")
  86. #raise
  87. sleep(30)
  88. 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})
  89. for chaninfo in info[3]:
  90. if chaninfo not in recchans:
  91. while True:
  92. try:
  93. y = ydl.extract_info("https://www.youtube.com/channel/"+chaninfo, download=False)
  94. break
  95. except:
  96. sleep(30)
  97. sleep(5) #prevent error 429
  98. for itemyv in y["entries"]:
  99. recvids.add(itemyv["id"])
  100. for playlinfo in info[5]:
  101. if playlinfo not in recplayl:
  102. while True:
  103. try:
  104. y = ydl.extract_info("https://www.youtube.com/playlist?list="+playlinfo, download=False)
  105. break
  106. except:
  107. sleep(30)
  108. sleep(5) #prevent error 429
  109. for itemyvp in y["entries"]:
  110. recvids.add(itemyvp["id"])
  111. # Add any discovered videos
  112. recvids.update(info[2])
  113. recchans.update(info[3])
  114. recmixes.update(info[4])
  115. recplayl.update(info[5])
  116. if info[0] or info[1]: # ccenabled or creditdata
  117. if not isdir("out/"+str(item).strip()):
  118. mkdir("out/"+str(item).strip())
  119. if info[1]: # creditdata
  120. open("out/"+str(item).strip()+"/"+str(item).strip()+"_published_credits.json", "w").write(dumps(info[1]))
  121. if info[0]: #ccenabled
  122. ccenabledl.append(item)
  123. jobs.task_done()
  124. return True
  125. while not gkiller.kill_now:
  126. collect() #cleanup
  127. try:
  128. mkdir("out")
  129. except:
  130. pass
  131. batchcontent.clear()
  132. # Get a batch ID
  133. batchthreads = []
  134. for r in range(50):
  135. batchrunthread = Thread(target=batchfunc)
  136. batchrunthread.start()
  137. batchthreads.append(batchrunthread)
  138. del batchrunthread
  139. for xc in batchthreads:
  140. xc.join() #bug (occurred once: the script ended before the last thread finished)
  141. batchthreads.remove(xc)
  142. del xc
  143. #for ir in range(501):
  144. # batchcontent.append(tracker.request_item_from_tracker())
  145. for desit in batchcontent:
  146. if desit:
  147. if desit.split(":", 1)[0] == "video":
  148. jobs.put(desit.split(":", 1)[1])
  149. else:
  150. print("Ignoring item for now", desit)
  151. else:
  152. print("Ignoring item for now", desit)
  153. threads = []
  154. for i in range(50):
  155. runthread = Thread(target=prrun)
  156. runthread.start()
  157. threads.append(runthread)
  158. del runthread
  159. for x in threads:
  160. x.join()
  161. threads.remove(x)
  162. del x
  163. print("Sending discoveries to tracker...")
  164. submitjobs = Queue()
  165. #don't send channels and playlists as those have already been converted for video IDs
  166. #IDK how to handle mixes so send them for now
  167. print(len(recvids))
  168. for itemvid in recvids:
  169. submitjobs.put((tracker.ItemType.Video, itemvid))
  170. print(len(recmixes))
  171. for itemmix in recmixes:
  172. submitjobs.put((tracker.ItemType.MixPlaylist, itemmix))
  173. #open("out/discoveries.json", "w").write(dumps({"recvids": sorted(recvids), "recchans": sorted(recchans), "recmixes": sorted(recmixes), "recplayl": sorted(recplayl)}))
  174. #clear
  175. recvids.clear()
  176. recchans.clear()
  177. recmixes.clear()
  178. recplayl.clear()
  179. submitthreads = []
  180. for r in range(50):
  181. submitrunthread = Thread(target=submitfunc, args=(submitjobs,))
  182. submitrunthread.start()
  183. submitthreads.append(submitrunthread)
  184. del submitrunthread
  185. for xb in submitthreads:
  186. xb.join() #bug (occurred once: the script ended before the last thread finished)
  187. submitthreads.remove(xb)
  188. del xb
  189. sleep(1)
  190. subtjobs = Queue()
  191. while ccenabledl:
  192. langcontent = langs.copy()
  193. intvid = ccenabledl.pop(0)
  194. while langcontent:
  195. subtjobs.put((langcontent.pop(0), intvid, "default"))
  196. del intvid
  197. del langcontent
  198. subthreads = []
  199. for r in range(50):
  200. subrunthread = Thread(target=subprrun, args=(subtjobs,mysession))
  201. subrunthread.start()
  202. subthreads.append(subrunthread)
  203. del subrunthread
  204. for xa in subthreads:
  205. xa.join() #bug (occurred once: the script ended before the last thread finished)
  206. subthreads.remove(xa)
  207. del xa
  208. sleep(1) #wait a second to hopefully allow the other threads to finish
  209. for fol in listdir("out"): #remove extra folders
  210. try:
  211. if isdir("out/"+fol):
  212. rmdir("out/"+fol)
  213. except:
  214. pass
  215. #https://stackoverflow.com/a/11968881
  216. # TODO: put the data somewhere...
  217. # TODO: put the discoveries somewhere...
  218. for fol in listdir("out"):
  219. if isdir("out/"+fol):
  220. make_archive("out/"+fol, "zip", "out/"+fol) #check this
  221. targetloc = None
  222. while not targetloc:
  223. targetloc = tracker.request_upload_target()
  224. if targetloc:
  225. break
  226. else:
  227. print("Waiting 5 minutes...")
  228. sleep(300)
  229. for zipf in listdir("out"):
  230. if isfile(zipf) in zipf.endswith(".zip"):
  231. if targetloc.startswith("rsync"):
  232. system("rsync out/"+zipf+" "+targetloc)
  233. elif targetloc.startswith("http"):
  234. upzipf = open("out/"+zipf, "rb")
  235. requests.post(targetloc, data=upzipf)
  236. upzipf.close()
  237. #upload it!
  238. # Report the batch as complete
  239. for itemb in batchcontent:
  240. if isfile("out/"+itemb.split(":", 1)[1]+".zip"):
  241. size = getsize("out/"+itemb.split(":", 1)[1]+".zip")
  242. else:
  243. size = 0
  244. tracker.mark_item_as_done(itemb, size)
  245. # clear the output directory
  246. rmtree("out")