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.
 
 

316 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. sleep(5)
  133. inttext = page.text
  134. try:
  135. initlang = page.text.split("'metadataLanguage': \"", 1)[1].split('"', 1)[0]
  136. except:
  137. initlang = ""
  138. del page
  139. filestring = "_community_draft"
  140. if '<li id="captions-editor-nav-captions" role="tab" data-state="published" class="published">' in inttext:
  141. filestring = "_community_published"
  142. if mode == "forceedit-captions":
  143. filestring = "_community_draft"
  144. if 'title="The video owner already provided subtitles/CC"' in inttext:
  145. filestring = "_uploader_provided"
  146. if not "forceedit" in mode:
  147. if '&amp;forceedit=metadata&amp;tab=metadata">See latest</a>' in inttext:
  148. print("Need forcemetadata")
  149. needforcemetadata[langcode] = True
  150. else:
  151. needforcemetadata[langcode] = False
  152. if '<li id="captions-editor-nav-captions" role="tab" data-state="published" class="published">' in inttext:
  153. print("Need forcecaptions")
  154. needforcecaptions[langcode] = True
  155. else:
  156. needforcecaptions[langcode] = False
  157. 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
  158. parser = MyHTMLParser()
  159. parser.feed(inttext)
  160. captiontext = False
  161. for item in parser.captions:
  162. if item["text"][:-9]:
  163. captiontext = True
  164. if captiontext and (mode == "default" or mode == "forceedit-captions"):
  165. myfs = open("out/"+vid+"/"+vid+"_"+langcode+filestring+".sbv", "w", encoding="utf-8")
  166. captions = parser.captions
  167. captions.pop(0) #get rid of the fake one
  168. while captions:
  169. item = captions.pop(0)
  170. myfs.write(timedelta_to_sbv_timestamp(timedelta(milliseconds=item["startTime"])) + "," + timedelta_to_sbv_timestamp(timedelta(milliseconds=item["endTime"])) + "\n" + item["text"][:-9] + "\n")
  171. del item
  172. if captions:
  173. myfs.write("\n")
  174. del captions
  175. myfs.close()
  176. del myfs
  177. del captiontext
  178. if (parser.title or parser.description[:-16]) and (mode == "default" or mode == "forceedit-metadata"):
  179. metadata = {}
  180. metadata["title"] = parser.title
  181. if metadata["title"] == False:
  182. metadata["title"] = ""
  183. metadata["description"] = parser.description[:-16]
  184. filestring = "_community_draft"
  185. if '<li id="captions-editor-nav-metadata" role="tab" data-state="published" class="published">' in inttext:
  186. filestring = "_community_published"
  187. if mode == "forceedit-metadata":
  188. filestring = "_community_draft"
  189. open("out/"+vid+"/"+vid+"_"+langcode+filestring+".json", "w", encoding="utf-8").write(dumps(metadata))
  190. del metadata
  191. if (parser.inittitle[9:-17] or parser.initdescription) and (mode == "default" or mode == "forceedit-metadata" and initlang):
  192. metadata = {}
  193. metadata["title"] = parser.inittitle[9:-17]
  194. if metadata["title"] == False:
  195. metadata["title"] = ""
  196. metadata["description"] = parser.initdescription
  197. filestring = "_uploader_provided"
  198. open("out/"+vid+"/"+vid+"_"+initlang+filestring+".json", "w", encoding="utf-8").write(dumps(metadata))
  199. del metadata
  200. del inttext
  201. del langcode
  202. del vid
  203. del pparams
  204. return True
  205. # if __name__ == "__main__":
  206. # from os import environ, mkdir
  207. # from os.path import isfile
  208. # from json import loads
  209. # #HSID, SSID, SID cookies required
  210. # if "HSID" in environ.keys() and "SSID" in environ.keys() and "SID" in environ.keys():
  211. # cookies = {"HSID": environ["HSID"], "SSID": environ["SSID"], "SID": environ["SID"]}
  212. # elif isfile("config.json"):
  213. # cookies = loads(open("config.json").read())
  214. # else:
  215. # print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  216. # assert False
  217. # if not (cookies["HSID"] and cookies["SSID"] and cookies["SID"]):
  218. # print("HSID, SSID, and SID cookies from youtube.com are required. Specify in config.json or as environment variables.")
  219. # assert False
  220. # mysession = requests.session()
  221. # mysession.headers.update({"cookie": "HSID="+cookies["HSID"]+"; SSID="+cookies["SSID"]+"; SID="+cookies["SID"], "Accept-Language": "en-US",})
  222. # del cookies
  223. # from sys import argv
  224. # from queue import Queue
  225. # from threading import Thread
  226. # langs = ['ab', 'aa', 'af', 'sq', 'ase', 'am', 'ar', 'arc', 'hy', 'as', 'ay', 'az', 'bn', 'ba', 'eu', 'be', 'bh', 'bi', 'bs', 'br',
  227. # 'bg', 'yue', 'yue-HK', 'ca', 'chr', 'zh-CN', 'zh-HK', 'zh-Hans', 'zh-SG', 'zh-TW', 'zh-Hant', 'cho', 'co', 'hr', 'cs', 'da', 'nl',
  228. # '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',
  229. # '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',
  230. # 'iw', 'hi', 'hi-Latn', 'ho', 'hu', 'is', 'ig', 'id', 'ia', 'ie', 'iu', 'ik', 'ga', 'it', 'ja', 'jv', 'kn', 'ks', 'kk', 'km', 'rw',
  231. # 'tlh', 'ko', 'ku', 'ky', 'lo', 'la', 'lv', 'ln', 'lt', 'lb', 'mk', 'mg', 'ms', 'ml', 'mt', 'mni', 'mi', 'mr', 'mas', 'nan',
  232. # 'nan-TW', 'lus', 'mo', 'mn', 'my', 'na', 'nv', 'ne', 'no', 'oc', 'or', 'om', 'ps', 'fa', 'fa-AF', 'fa-IR', 'pl', 'pt', 'pt-BR',
  233. # 'pt-PT', 'pa', 'qu', 'ro', 'rm', 'rn', 'ru', 'ru-Latn', 'sm', 'sg', 'sa', 'sc', 'gd', 'sr', 'sr-Cyrl', 'sr-Latn', 'sh', 'sdp', 'sn',
  234. # 'scn', 'sd', 'si', 'sk', 'sl', 'so', 'st', 'es', 'es-419', 'es-MX', 'es-ES', 'es-US', 'su', 'sw', 'ss', 'sv', 'tl', 'tg', 'ta',
  235. # 'tt', 'te', 'th', 'bo', 'ti', 'tpi', 'to', 'ts', 'tn', 'tr', 'tk', 'tw', 'uk', 'ur', 'uz', 'vi', 'vo', 'vor', 'cy', 'fy', 'wo',
  236. # 'xh', 'yi', 'yo', 'zu']
  237. # vidl = argv
  238. # vidl.pop(0)
  239. # try:
  240. # mkdir("out")
  241. # except:
  242. # pass
  243. # jobs = Queue()
  244. # for video in vidl:
  245. # try:
  246. # mkdir("out/"+video.strip())
  247. # except:
  248. # pass
  249. # for lang in langs:
  250. # jobs.put((lang, video, "default"))
  251. # subthreads = []
  252. # for r in range(50):
  253. # subrunthread = Thread(target=subprrun, args=(jobs,mysession))
  254. # subrunthread.start()
  255. # subthreads.append(subrunthread)
  256. # del subrunthread
  257. # for xa in subthreads:
  258. # xa.join() #bug (occurred once: the script ended before the last thread finished)
  259. # subthreads.remove(xa)
  260. # del xa