archiving community contributions on YouTube: unpublished captions, title and description translations and caption credits
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 

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