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.

export.py 12 KiB

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