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.
 
 

317 lignes
13 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. backend = "http3"
  32. from switchable_request import get
  33. class MyHTMLParser(HTMLParser):
  34. def __init__(self):
  35. HTMLParser.__init__(self)
  36. self.captions = []
  37. self.title = ""
  38. self.description = ""
  39. self.inittitle = ""
  40. self.initdescription = ""
  41. def check_attr(self, attrs, attr, value):
  42. for item in attrs:
  43. if item[0] == attr and item[1] == value:
  44. return True
  45. return False
  46. def get_attr(self, attrs, attr):
  47. for item in attrs:
  48. if item[0] == attr:
  49. return item[1]
  50. return False
  51. def handle_starttag(self, tag, attrs):
  52. if tag == "input" and self.check_attr(attrs, "class", "yt-uix-form-input-text event-time-field event-start-time"):
  53. self.captions.append({"startTime": int(self.get_attr(attrs, "data-start-ms")), "text": ""})
  54. elif tag == "input" and self.check_attr(attrs, "class", "yt-uix-form-input-text event-time-field event-end-time"):
  55. self.captions[len(self.captions)-1]["endTime"] = int(self.get_attr(attrs, "data-end-ms"))
  56. elif tag == "input" and self.check_attr(attrs, "id", "metadata-title"):
  57. self.title = self.get_attr(attrs, "value")
  58. elif tag == "textarea" and self.check_attr(attrs, "id", "metadata-description"):
  59. self.initdescription = self.get_attr(attrs, "data-original-description")
  60. def handle_data(self, data):
  61. if self.get_starttag_text() and self.get_starttag_text().startswith("<textarea "):
  62. if 'name="serve_text"' in self.get_starttag_text():
  63. self.captions[len(self.captions)-1]["text"] += data
  64. elif 'id="metadata-description"' in self.get_starttag_text():
  65. self.description += data
  66. elif self.get_starttag_text() and self.get_starttag_text().startswith('<div id="original-video-title"'):
  67. self.inittitle += data
  68. def subprrun(mysession, langcode, vid, mode, needforcemetadata, needforcecaptions, allheaders):
  69. global backend
  70. if mode == "forceedit-metadata":
  71. while needforcemetadata[langcode] == None: #extra logic
  72. print("Awaiting forcemetadata")
  73. sleep(1)
  74. if needforcemetadata[langcode] == False:
  75. #print("forcemetadata not needed")
  76. return True #nothing needs to be done, otherwise, continue
  77. if mode == "forceedit-captions":
  78. while needforcecaptions[langcode] == None: #extra logic
  79. print("Awaiting forcecaptions")
  80. sleep(1)
  81. if needforcecaptions[langcode] == False:
  82. #print("forcecaptions not needed")
  83. return True #nothing needs to be done, otherwise, continue
  84. collect() #cleanup memory
  85. vid = vid.strip()
  86. print(langcode, vid)
  87. while True:
  88. try:
  89. if mode == "default":
  90. pparams = (
  91. ("v", vid),
  92. ("lang", langcode),
  93. ("action_mde_edit_form", 1),
  94. ("bl", "vmp"),
  95. ("ui", "hd"),
  96. ("tab", "captions"),
  97. ("o", "U")
  98. )
  99. page = get("https://www.youtube.com/timedtext_editor", params=pparams, mysession=mysession, backend=backend, http3headers=allheaders)
  100. elif mode == "forceedit-metadata":
  101. pparams = (
  102. ("v", vid),
  103. ("lang", langcode),
  104. ("action_mde_edit_form", 1),
  105. ('forceedit', 'metadata'),
  106. ('tab', 'metadata')
  107. )
  108. page = get("https://www.youtube.com/timedtext_editor", params=pparams, mysession=mysession, backend=backend, http3headers=allheaders)
  109. elif mode == "forceedit-captions":
  110. pparams = (
  111. ("v", vid),
  112. ("lang", langcode),
  113. ("action_mde_edit_form", 1),
  114. ("bl", "vmp"),
  115. ("ui", "hd"),
  116. ('forceedit', 'captions'),
  117. ("tab", "captions"),
  118. ("o", "U")
  119. )
  120. page = get("https://www.youtube.com/timedtext_editor", params=pparams, mysession=mysession, backend=backend, http3headers=allheaders)
  121. if not "accounts.google.com" in page.url and page.status_code != 429 and 'Subtitles/CC' in page.text and 'Title &amp; description' in page.text:
  122. break
  123. else:
  124. if backend == "requests":
  125. backend = "http3"
  126. print("Rate limit or login failure, switching export to HTTP3/QUIC...")
  127. else:
  128. print("[Retrying in 30 seconds for rate limit or login failure] Please supply authentication cookie information in config.json or environment variables. See README.md for more information.")
  129. sleep(30)
  130. except:
  131. print("Error in request, retrying in 5 seconds...")
  132. raise
  133. sleep(5)
  134. inttext = page.text
  135. try:
  136. initlang = page.text.split("'metadataLanguage': \"", 1)[1].split('"', 1)[0]
  137. except:
  138. initlang = ""
  139. del page
  140. filestring = "_community_draft"
  141. if '<li id="captions-editor-nav-captions" role="tab" data-state="published" class="published">' in inttext:
  142. filestring = "_community_published"
  143. if mode == "forceedit-captions":
  144. filestring = "_community_draft"
  145. if 'title="The video owner already provided subtitles/CC"' in inttext:
  146. filestring = "_uploader_provided"
  147. if not "forceedit" in mode:
  148. if '&amp;forceedit=metadata&amp;tab=metadata">See latest</a>' in inttext:
  149. print("Need forcemetadata")
  150. needforcemetadata[langcode] = True
  151. else:
  152. needforcemetadata[langcode] = False
  153. if '<li id="captions-editor-nav-captions" role="tab" data-state="published" class="published">' in inttext:
  154. print("Need forcecaptions")
  155. needforcecaptions[langcode] = True
  156. else:
  157. needforcecaptions[langcode] = False
  158. 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
  159. parser = MyHTMLParser()
  160. parser.feed(inttext)
  161. captiontext = False
  162. for item in parser.captions:
  163. if item["text"][:-9]:
  164. captiontext = True
  165. if captiontext and (mode == "default" or mode == "forceedit-captions"):
  166. myfs = open("out/"+vid+"/"+vid+"_"+langcode+filestring+".sbv", "w", encoding="utf-8")
  167. captions = parser.captions
  168. captions.pop(0) #get rid of the fake one
  169. while captions:
  170. item = captions.pop(0)
  171. myfs.write(timedelta_to_sbv_timestamp(timedelta(milliseconds=item["startTime"])) + "," + timedelta_to_sbv_timestamp(timedelta(milliseconds=item["endTime"])) + "\n" + item["text"][:-9] + "\n")
  172. del item
  173. if captions:
  174. myfs.write("\n")
  175. del captions
  176. myfs.close()
  177. del myfs
  178. del captiontext
  179. if (parser.title or parser.description[:-16]) and (mode == "default" or mode == "forceedit-metadata"):
  180. metadata = {}
  181. metadata["title"] = parser.title
  182. if metadata["title"] == False:
  183. metadata["title"] = ""
  184. metadata["description"] = parser.description[:-16]
  185. filestring = "_community_draft"
  186. if '<li id="captions-editor-nav-metadata" role="tab" data-state="published" class="published">' in inttext:
  187. filestring = "_community_published"
  188. if mode == "forceedit-metadata":
  189. filestring = "_community_draft"
  190. open("out/"+vid+"/"+vid+"_"+langcode+filestring+".json", "w", encoding="utf-8").write(dumps(metadata))
  191. del metadata
  192. if (parser.inittitle[9:-17] or parser.initdescription) and (mode == "default" or mode == "forceedit-metadata" and initlang):
  193. metadata = {}
  194. metadata["title"] = parser.inittitle[9:-17]
  195. if metadata["title"] == False:
  196. metadata["title"] = ""
  197. metadata["description"] = parser.initdescription
  198. filestring = "_uploader_provided"
  199. open("out/"+vid+"/"+vid+"_"+initlang+filestring+".json", "w", encoding="utf-8").write(dumps(metadata))
  200. del metadata
  201. del inttext
  202. del langcode
  203. del vid
  204. del pparams
  205. return True
  206. # if __name__ == "__main__":
  207. # from os import environ, mkdir
  208. # from os.path import isfile
  209. # from json import loads
  210. # #HSID, SSID, SID cookies required
  211. # if "HSID" in environ.keys() and "SSID" in environ.keys() and "SID" in environ.keys():
  212. # cookies = {"HSID": environ["HSID"], "SSID": environ["SSID"], "SID": environ["SID"]}
  213. # elif isfile("config.json"):
  214. # cookies = loads(open("config.json").read())
  215. # else:
  216. # print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  217. # assert False
  218. # if not (cookies["HSID"] and cookies["SSID"] and cookies["SID"]):
  219. # print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  220. # assert False
  221. # mysession = requests.session()
  222. # mysession.headers.update({"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",})
  223. # del cookies
  224. # from sys import argv
  225. # from queue import Queue
  226. # from threading import Thread
  227. # langs = ['ab', 'aa', 'af', 'sq', 'ase', 'am', 'ar', 'arc', 'hy', 'as', 'ay', 'az', 'bn', 'ba', 'eu', 'be', 'bh', 'bi', 'bs', 'br',
  228. # 'bg', 'yue', 'yue-HK', 'ca', 'chr', 'zh-CN', 'zh-HK', 'zh-Hans', 'zh-SG', 'zh-TW', 'zh-Hant', 'cho', 'co', 'hr', 'cs', 'da', 'nl',
  229. # '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',
  230. # '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',
  231. # 'iw', 'hi', 'hi-Latn', 'ho', 'hu', 'is', 'ig', 'id', 'ia', 'ie', 'iu', 'ik', 'ga', 'it', 'ja', 'jv', 'kn', 'ks', 'kk', 'km', 'rw',
  232. # 'tlh', 'ko', 'ku', 'ky', 'lo', 'la', 'lv', 'ln', 'lt', 'lb', 'mk', 'mg', 'ms', 'ml', 'mt', 'mni', 'mi', 'mr', 'mas', 'nan',
  233. # 'nan-TW', 'lus', 'mo', 'mn', 'my', 'na', 'nv', 'ne', 'no', 'oc', 'or', 'om', 'ps', 'fa', 'fa-AF', 'fa-IR', 'pl', 'pt', 'pt-BR',
  234. # 'pt-PT', 'pa', 'qu', 'ro', 'rm', 'rn', 'ru', 'ru-Latn', 'sm', 'sg', 'sa', 'sc', 'gd', 'sr', 'sr-Cyrl', 'sr-Latn', 'sh', 'sdp', 'sn',
  235. # 'scn', 'sd', 'si', 'sk', 'sl', 'so', 'st', 'es', 'es-419', 'es-MX', 'es-ES', 'es-US', 'su', 'sw', 'ss', 'sv', 'tl', 'tg', 'ta',
  236. # 'tt', 'te', 'th', 'bo', 'ti', 'tpi', 'to', 'ts', 'tn', 'tr', 'tk', 'tw', 'uk', 'ur', 'uz', 'vi', 'vo', 'vor', 'cy', 'fy', 'wo',
  237. # 'xh', 'yi', 'yo', 'zu']
  238. # vidl = argv
  239. # vidl.pop(0)
  240. # try:
  241. # mkdir("out")
  242. # except:
  243. # pass
  244. # jobs = Queue()
  245. # for video in vidl:
  246. # try:
  247. # mkdir("out/"+video.strip())
  248. # except:
  249. # pass
  250. # for lang in langs:
  251. # jobs.put((lang, video, "default"))
  252. # subthreads = []
  253. # for r in range(50):
  254. # subrunthread = Thread(target=subprrun, args=(jobs,mysession))
  255. # subrunthread.start()
  256. # subthreads.append(subrunthread)
  257. # del subrunthread
  258. # for xa in subthreads:
  259. # xa.join() #bug (occurred once: the script ended before the last thread finished)
  260. # subthreads.remove(xa)
  261. # del xa