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

316 рядки
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("""# HTTP Cookie File
  58. .youtube.com TRUE / FALSE 1663793455 SID [SID]
  59. .youtube.com TRUE / FALSE 1663793455 HSID [HSID]
  60. .youtube.com TRUE / TRUE 1663793455 SSID [SSID]""".replace("[SID]", cookies["SID"]).replace("[HSID]", cookies["HSID"]).replace("[SSID]", cookies["SSID"]))
  61. del cookies
  62. #Graceful Shutdown
  63. class GracefulKiller:
  64. kill_now = False
  65. def __init__(self):
  66. signal.signal(signal.SIGINT, self.exit_gracefully)
  67. signal.signal(signal.SIGTERM, self.exit_gracefully)
  68. def exit_gracefully(self,signum, frame):
  69. self.kill_now = True
  70. gkiller = GracefulKiller()
  71. def prrun():
  72. while not jobs.empty():
  73. global recvids
  74. global recchans
  75. global recmixes
  76. global recplayl
  77. global ccenabledl
  78. item = jobs.get()
  79. print("Video ID:", str(item).strip())
  80. while True:
  81. try:
  82. info = getmetadata(str(item).strip())
  83. break
  84. except BaseException as e:
  85. print(e)
  86. print("Error in retrieving information, waiting 30 seconds")
  87. #raise
  88. sleep(30)
  89. 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})
  90. for chaninfo in info[3]:
  91. if chaninfo not in recchans:
  92. while True:
  93. try:
  94. y = ydl.extract_info("https://www.youtube.com/channel/"+chaninfo, download=False)
  95. break
  96. except:
  97. sleep(30)
  98. sleep(5) #prevent error 429
  99. for itemyv in y["entries"]:
  100. recvids.add(itemyv["id"])
  101. for playlinfo in info[5]:
  102. if playlinfo not in recplayl:
  103. while True:
  104. try:
  105. y = ydl.extract_info("https://www.youtube.com/playlist?list="+playlinfo, download=False)
  106. break
  107. except:
  108. sleep(30)
  109. sleep(5) #prevent error 429
  110. for itemyvp in y["entries"]:
  111. recvids.add(itemyvp["id"])
  112. # Add any discovered videos
  113. recvids.update(info[2])
  114. recchans.update(info[3])
  115. recmixes.update(info[4])
  116. recplayl.update(info[5])
  117. if info[0] or info[1]: # ccenabled or creditdata
  118. if not isdir("out/"+str(item).strip()):
  119. mkdir("out/"+str(item).strip())
  120. if info[1]: # creditdata
  121. open("out/"+str(item).strip()+"/"+str(item).strip()+"_published_credits.json", "w").write(dumps(info[1]))
  122. if info[0]: #ccenabled
  123. ccenabledl.append(item)
  124. jobs.task_done()
  125. return True
  126. while not gkiller.kill_now:
  127. collect() #cleanup
  128. try:
  129. mkdir("out")
  130. except:
  131. pass
  132. batchcontent.clear()
  133. # Get a batch ID
  134. batchthreads = []
  135. for r in range(50):
  136. batchrunthread = Thread(target=batchfunc)
  137. batchrunthread.start()
  138. batchthreads.append(batchrunthread)
  139. del batchrunthread
  140. for xc in batchthreads:
  141. xc.join() #bug (occurred once: the script ended before the last thread finished)
  142. batchthreads.remove(xc)
  143. del xc
  144. #for ir in range(501):
  145. # batchcontent.append(tracker.request_item_from_tracker())
  146. for desit in batchcontent:
  147. if desit:
  148. if desit.split(":", 1)[0] == "video":
  149. jobs.put(desit.split(":", 1)[1])
  150. else:
  151. print("Ignoring item for now", desit)
  152. else:
  153. print("Ignoring item for now", desit)
  154. threads = []
  155. for i in range(50):
  156. runthread = Thread(target=prrun)
  157. runthread.start()
  158. threads.append(runthread)
  159. del runthread
  160. for x in threads:
  161. x.join()
  162. threads.remove(x)
  163. del x
  164. print("Sending discoveries to tracker...")
  165. submitjobs = Queue()
  166. #don't send channels and playlists as those have already been converted for video IDs
  167. #IDK how to handle mixes so send them for now
  168. print(len(recvids))
  169. for itemvid in recvids:
  170. submitjobs.put((tracker.ItemType.Video, itemvid))
  171. print(len(recmixes))
  172. for itemmix in recmixes:
  173. submitjobs.put((tracker.ItemType.MixPlaylist, itemmix))
  174. #open("out/discoveries.json", "w").write(dumps({"recvids": sorted(recvids), "recchans": sorted(recchans), "recmixes": sorted(recmixes), "recplayl": sorted(recplayl)}))
  175. #clear
  176. recvids.clear()
  177. recchans.clear()
  178. recmixes.clear()
  179. recplayl.clear()
  180. submitthreads = []
  181. for r in range(50):
  182. submitrunthread = Thread(target=submitfunc, args=(submitjobs,))
  183. submitrunthread.start()
  184. submitthreads.append(submitrunthread)
  185. del submitrunthread
  186. for xb in submitthreads:
  187. xb.join() #bug (occurred once: the script ended before the last thread finished)
  188. submitthreads.remove(xb)
  189. del xb
  190. sleep(1)
  191. subtjobs = Queue()
  192. while ccenabledl:
  193. langcontent = langs.copy()
  194. intvid = ccenabledl.pop(0)
  195. while langcontent:
  196. subtjobs.put((langcontent.pop(0), intvid, "default"))
  197. del intvid
  198. del langcontent
  199. subthreads = []
  200. for r in range(50):
  201. subrunthread = Thread(target=subprrun, args=(subtjobs,mysession))
  202. subrunthread.start()
  203. subthreads.append(subrunthread)
  204. del subrunthread
  205. for xa in subthreads:
  206. xa.join() #bug (occurred once: the script ended before the last thread finished)
  207. subthreads.remove(xa)
  208. del xa
  209. sleep(1) #wait a second to hopefully allow the other threads to finish
  210. for fol in listdir("out"): #remove extra folders
  211. try:
  212. if isdir("out/"+fol):
  213. rmdir("out/"+fol)
  214. except:
  215. pass
  216. #https://stackoverflow.com/a/11968881
  217. # TODO: put the data somewhere...
  218. # TODO: put the discoveries somewhere...
  219. for fol in listdir("out"):
  220. if isdir("out/"+fol):
  221. make_archive("out/"+fol, "zip", "out/"+fol) #check this
  222. targetloc = None
  223. while not targetloc:
  224. targetloc = tracker.request_upload_target()
  225. if targetloc:
  226. break
  227. else:
  228. print("Waiting 5 minutes...")
  229. sleep(300)
  230. for zipf in listdir("out"):
  231. if isfile(zipf) in zipf.endswith(".zip"):
  232. if targetloc.startswith("rsync"):
  233. system("rsync out/"+zipf+" "+targetloc)
  234. elif targetloc.startswith("http"):
  235. upzipf = open("out/"+zipf, "rb")
  236. requests.post(targetloc, data=upzipf)
  237. upzipf.close()
  238. #upload it!
  239. # Report the batch as complete
  240. for itemb in batchcontent:
  241. if isfile("out/"+itemb.split(":", 1)[1]+".zip"):
  242. size = getsize("out/"+itemb.split(":", 1)[1]+".zip")
  243. else:
  244. size = 0
  245. tracker.mark_item_as_done(itemb, size)
  246. # clear the output directory
  247. rmtree("out")