archiving community contributions on YouTube: unpublished captions, title and description translations and caption credits
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 

284 lignes
12 KiB

  1. # This function adapted from https://github.com/cdown/srt/blob/11089f1e021f2e074d04c33fc7ffc4b7b52e7045/srt.py, lines 69 and 189 (MIT License)
  2. def timedelta_to_sbv_timestamp(timedelta_timestamp):
  3. r"""
  4. Convert a :py:class:`~datetime.timedelta` to an SRT timestamp.
  5. .. doctest::
  6. >>> import datetime
  7. >>> delta = datetime.timedelta(hours=1, minutes=23, seconds=4)
  8. >>> timedelta_to_sbv_timestamp(delta)
  9. '01:23:04,000'
  10. :param datetime.timedelta timedelta_timestamp: A datetime to convert to an
  11. SBV timestamp
  12. :returns: The timestamp in SBV format
  13. :rtype: str
  14. """
  15. SECONDS_IN_HOUR = 3600
  16. SECONDS_IN_MINUTE = 60
  17. HOURS_IN_DAY = 24
  18. MICROSECONDS_IN_MILLISECOND = 1000
  19. hrs, secs_remainder = divmod(timedelta_timestamp.seconds, SECONDS_IN_HOUR)
  20. hrs += timedelta_timestamp.days * HOURS_IN_DAY
  21. mins, secs = divmod(secs_remainder, SECONDS_IN_MINUTE)
  22. msecs = timedelta_timestamp.microseconds // MICROSECONDS_IN_MILLISECOND
  23. return "%1d:%02d:%02d.%03d" % (hrs, mins, secs, msecs)
  24. from datetime import timedelta
  25. from json import dumps
  26. from gc import collect
  27. import requests
  28. from time import sleep
  29. # https://docs.python.org/3/library/html.parser.html
  30. from html.parser import HTMLParser
  31. class MyHTMLParser(HTMLParser):
  32. def __init__(self):
  33. HTMLParser.__init__(self)
  34. self.captions = []
  35. self.title = ""
  36. self.description = ""
  37. self.inittitle = ""
  38. self.initdescription = ""
  39. def check_attr(self, attrs, attr, value):
  40. for item in attrs:
  41. if item[0] == attr and item[1] == value:
  42. return True
  43. return False
  44. def get_attr(self, attrs, attr):
  45. for item in attrs:
  46. if item[0] == attr:
  47. return item[1]
  48. return False
  49. def handle_starttag(self, tag, attrs):
  50. if tag == "input" and self.check_attr(attrs, "class", "yt-uix-form-input-text event-time-field event-start-time"):
  51. self.captions.append({"startTime": int(self.get_attr(attrs, "data-start-ms")), "text": ""})
  52. elif tag == "input" and self.check_attr(attrs, "class", "yt-uix-form-input-text event-time-field event-end-time"):
  53. self.captions[len(self.captions)-1]["endTime"] = int(self.get_attr(attrs, "data-end-ms"))
  54. elif tag == "input" and self.check_attr(attrs, "id", "metadata-title"):
  55. self.title = self.get_attr(attrs, "value")
  56. elif tag == "textarea" and self.check_attr(attrs, "id", "metadata-description"):
  57. self.initdescription = self.get_attr(attrs, "data-original-description")
  58. def handle_data(self, data):
  59. if self.get_starttag_text() and self.get_starttag_text().startswith("<textarea "):
  60. if 'name="serve_text"' in self.get_starttag_text():
  61. self.captions[len(self.captions)-1]["text"] += data
  62. elif 'id="metadata-description"' in self.get_starttag_text():
  63. self.description += data
  64. elif self.get_starttag_text() and self.get_starttag_text().startswith('<div id="original-video-title"'):
  65. self.inittitle += data
  66. def subprrun(jobs, mysession):
  67. while not jobs.empty():
  68. collect() #cleanup memory
  69. langcode, vid, mode = jobs.get()
  70. vid = vid.strip()
  71. print(langcode, vid)
  72. while True:
  73. if mode == "default":
  74. pparams = (
  75. ("v", vid),
  76. ("lang", langcode),
  77. ("action_mde_edit_form", 1),
  78. ("bl", "vmp"),
  79. ("ui", "hd"),
  80. ("tab", "captions"),
  81. ("o", "U")
  82. )
  83. page = mysession.get("https://www.youtube.com/timedtext_editor", params=pparams)
  84. elif mode == "forceedit-metadata":
  85. pparams = (
  86. ("v", vid),
  87. ("lang", langcode),
  88. ("action_mde_edit_form", 1),
  89. ('forceedit', 'metadata'),
  90. ('tab', 'metadata')
  91. )
  92. page = mysession.get("https://www.youtube.com/timedtext_editor", params=pparams)
  93. elif mode == "forceedit-captions":
  94. pparams = (
  95. ("v", vid),
  96. ("lang", langcode),
  97. ("action_mde_edit_form", 1),
  98. ("bl", "vmp"),
  99. ("ui", "hd"),
  100. ('forceedit', 'captions'),
  101. ("tab", "captions"),
  102. ("o", "U")
  103. )
  104. page = mysession.get("https://www.youtube.com/timedtext_editor", params=pparams)
  105. if not "accounts.google.com" in page.url:
  106. break
  107. else:
  108. print("[Retrying in 30 seconds] Please supply authentication cookie information in config.json or environment variables. See README.md for more information.")
  109. sleep(30)
  110. inttext = page.text
  111. try:
  112. initlang = page.text.split("'metadataLanguage': \"", 1)[1].split('"', 1)[0]
  113. except:
  114. initlang = ""
  115. del page
  116. filestring = "_community_draft"
  117. if '<li id="captions-editor-nav-captions" role="tab" data-state="published" class="published">' in inttext:
  118. filestring = "_community_published"
  119. if mode == "forceedit-captions":
  120. filestring = "_community_draft"
  121. if 'title="The video owner already provided subtitles/CC"' in inttext:
  122. filestring = "_uploader_provided"
  123. if not "forceedit" in mode:
  124. if '&amp;forceedit=metadata&amp;tab=metadata">See latest</a>' in inttext:
  125. jobs.put((langcode, vid, "forceedit-metadata"))
  126. if '<li id="captions-editor-nav-captions" role="tab" data-state="published" class="published">' in inttext:
  127. jobs.put((langcode, vid, "forceedit-captions"))
  128. if 'id="reject-captions-button"' in inttext or 'id="reject-metadata-button"' in inttext or 'data-state="published"' in inttext or 'title="The video owner already provided subtitles/CC"' in inttext: #quick way of checking if this page is worth parsing
  129. parser = MyHTMLParser()
  130. parser.feed(inttext)
  131. captiontext = False
  132. for item in parser.captions:
  133. if item["text"][:-9]:
  134. captiontext = True
  135. if captiontext and (mode == "default" or mode == "forceedit-captions"):
  136. myfs = open("out/"+vid+"/"+vid+"_"+langcode+filestring+".sbv", "w", encoding="utf-8")
  137. captions = parser.captions
  138. captions.pop(0) #get rid of the fake one
  139. while captions:
  140. item = captions.pop(0)
  141. myfs.write(timedelta_to_sbv_timestamp(timedelta(milliseconds=item["startTime"])) + "," + timedelta_to_sbv_timestamp(timedelta(milliseconds=item["endTime"])) + "\n" + item["text"][:-9] + "\n")
  142. del item
  143. if captions:
  144. myfs.write("\n")
  145. del captions
  146. myfs.close()
  147. del myfs
  148. del captiontext
  149. if (parser.title or parser.description[:-16]) and (mode == "default" or mode == "forceedit-metadata"):
  150. metadata = {}
  151. metadata["title"] = parser.title
  152. if metadata["title"] == False:
  153. metadata["title"] = ""
  154. metadata["description"] = parser.description[:-16]
  155. filestring = "_community_draft"
  156. if '<li id="captions-editor-nav-metadata" role="tab" data-state="published" class="published">' in inttext:
  157. filestring = "_community_published"
  158. if mode == "forceedit-metadata":
  159. filestring = "_community_draft"
  160. open("out/"+vid+"/"+vid+"_"+langcode+filestring+".json", "w", encoding="utf-8").write(dumps(metadata))
  161. del metadata
  162. if (parser.inittitle[9:-17] or parser.initdescription) and (mode == "default" or mode == "forceedit-metadata" and initlang):
  163. metadata = {}
  164. metadata["title"] = parser.inittitle[9:-17]
  165. if metadata["title"] == False:
  166. metadata["title"] = ""
  167. metadata["description"] = parser.initdescription
  168. filestring = "_uploader_provided"
  169. open("out/"+vid+"/"+vid+"_"+initlang+filestring+".json", "w", encoding="utf-8").write(dumps(metadata))
  170. del metadata
  171. del inttext
  172. del langcode
  173. del vid
  174. del pparams
  175. jobs.task_done()
  176. return True
  177. if __name__ == "__main__":
  178. from os import environ, mkdir
  179. from os.path import isfile
  180. from json import loads
  181. #HSID, SSID, SID cookies required
  182. if "HSID" in environ.keys() and "SSID" in environ.keys() and "SID" in environ.keys():
  183. cookies = {"HSID": environ["HSID"], "SSID": environ["SSID"], "SID": environ["SID"]}
  184. elif isfile("config.json"):
  185. cookies = loads(open("config.json").read())
  186. else:
  187. print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  188. assert False
  189. if not (cookies["HSID"] and cookies["SSID"] and cookies["SID"]):
  190. print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  191. assert False
  192. mysession = requests.session()
  193. mysession.headers.update({"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",})
  194. del cookies
  195. from sys import argv
  196. from queue import Queue
  197. from threading import Thread
  198. langs = ['ab', 'aa', 'af', 'sq', 'ase', 'am', 'ar', 'arc', 'hy', 'as', 'ay', 'az', 'bn', 'ba', 'eu', 'be', 'bh', 'bi', 'bs', 'br',
  199. 'bg', 'yue', 'yue-HK', 'ca', 'chr', 'zh-CN', 'zh-HK', 'zh-Hans', 'zh-SG', 'zh-TW', 'zh-Hant', 'cho', 'co', 'hr', 'cs', 'da', 'nl',
  200. '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',
  201. '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',
  202. 'iw', 'hi', 'hi-Latn', 'ho', 'hu', 'is', 'ig', 'id', 'ia', 'ie', 'iu', 'ik', 'ga', 'it', 'ja', 'jv', 'kn', 'ks', 'kk', 'km', 'rw',
  203. 'tlh', 'ko', 'ku', 'ky', 'lo', 'la', 'lv', 'ln', 'lt', 'lb', 'mk', 'mg', 'ms', 'ml', 'mt', 'mni', 'mi', 'mr', 'mas', 'nan',
  204. 'nan-TW', 'lus', 'mo', 'mn', 'my', 'na', 'nv', 'ne', 'no', 'oc', 'or', 'om', 'ps', 'fa', 'fa-AF', 'fa-IR', 'pl', 'pt', 'pt-BR',
  205. 'pt-PT', 'pa', 'qu', 'ro', 'rm', 'rn', 'ru', 'ru-Latn', 'sm', 'sg', 'sa', 'sc', 'gd', 'sr', 'sr-Cyrl', 'sr-Latn', 'sh', 'sdp', 'sn',
  206. 'scn', 'sd', 'si', 'sk', 'sl', 'so', 'st', 'es', 'es-419', 'es-MX', 'es-ES', 'es-US', 'su', 'sw', 'ss', 'sv', 'tl', 'tg', 'ta',
  207. 'tt', 'te', 'th', 'bo', 'ti', 'tpi', 'to', 'ts', 'tn', 'tr', 'tk', 'tw', 'uk', 'ur', 'uz', 'vi', 'vo', 'vor', 'cy', 'fy', 'wo',
  208. 'xh', 'yi', 'yo', 'zu']
  209. vidl = argv
  210. vidl.pop(0)
  211. try:
  212. mkdir("out")
  213. except:
  214. pass
  215. jobs = Queue()
  216. for video in vidl:
  217. try:
  218. mkdir("out/"+video.strip())
  219. except:
  220. pass
  221. for lang in langs:
  222. jobs.put((lang, video, "default"))
  223. subthreads = []
  224. for r in range(50):
  225. subrunthread = Thread(target=subprrun, args=(jobs,mysession))
  226. subrunthread.start()
  227. subthreads.append(subrunthread)
  228. del subrunthread
  229. for xa in subthreads:
  230. xa.join() #bug (occurred once: the script ended before the last thread finished)
  231. subthreads.remove(xa)
  232. del xa