archiving community contributions on YouTube: unpublished captions, title and description translations and caption credits
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 

138 righe
5.2 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. import requests
  27. # https://docs.python.org/3/library/html.parser.html
  28. from html.parser import HTMLParser
  29. class MyHTMLParser(HTMLParser):
  30. def __init__(self):
  31. HTMLParser.__init__(self)
  32. self.captions = []
  33. self.title = ""
  34. self.description = ""
  35. def check_attr(self, attrs, attr, value):
  36. for item in attrs:
  37. if item[0] == attr and item[1] == value:
  38. return True
  39. return False
  40. def get_attr(self, attrs, attr):
  41. for item in attrs:
  42. if item[0] == attr:
  43. return item[1]
  44. return False
  45. def handle_starttag(self, tag, attrs):
  46. if tag == "input" and self.check_attr(attrs, "class", "yt-uix-form-input-text event-time-field event-start-time") and not ' data-segment-id="" ' in self.get_starttag_text():
  47. self.captions.append({"startTime": int(self.get_attr(attrs, "data-start-ms")), "text": ""})
  48. elif tag == "input" and self.check_attr(attrs, "class", "yt-uix-form-input-text event-time-field event-end-time") and not ' data-segment-id="" ' in self.get_starttag_text():
  49. self.captions[len(self.captions)-1]["endTime"] = int(self.get_attr(attrs, "data-end-ms"))
  50. elif tag == "input" and self.check_attr(attrs, "id", "metadata-title"):
  51. self.title = self.get_attr(attrs, "value")
  52. def handle_data(self, data):
  53. if self.get_starttag_text() and self.get_starttag_text().startswith("<textarea "):
  54. if 'name="serve_text"' in self.get_starttag_text() and not 'data-segment-id=""' in self.get_starttag_text():
  55. self.captions[len(self.captions)-1]["text"] += data
  56. elif 'id="metadata-description"' in self.get_starttag_text():
  57. self.description += data
  58. def subprrun(jobs, headers):
  59. while not jobs.empty():
  60. langcode, vid = jobs.get()
  61. vid = vid.strip()
  62. print(langcode, vid)
  63. pparams = (
  64. ("v", vid),
  65. ("lang", langcode),
  66. ("action_mde_edit_form", 1),
  67. ("bl", "vmp"),
  68. ("ui", "hd"),
  69. ("tab", "captions"),
  70. ("o", "U")
  71. )
  72. page = requests.get("https://www.youtube.com/timedtext_editor", headers=headers, params=pparams)
  73. assert not "accounts.google.com" in page.url, "Please supply authentication cookie information in config.json. See README.md for more information."
  74. inttext = page.text
  75. del page
  76. if 'id="reject-captions-button"' in inttext or 'id="reject-metadata-button"' in inttext: #quick way of checking if this page is worth parsing
  77. parser = MyHTMLParser()
  78. parser.feed(inttext)
  79. captiontext = False
  80. for item in parser.captions:
  81. if item["text"][:-9]:
  82. captiontext = True
  83. if captiontext:
  84. myfs = open("out/"+vid+"/"+vid+"_"+langcode+".sbv", "w", encoding="utf-8")
  85. captions = parser.captions
  86. captions.pop(0) #get rid of the fake one
  87. while captions:
  88. item = captions.pop(0)
  89. myfs.write(timedelta_to_sbv_timestamp(timedelta(milliseconds=item["startTime"])) + "," + timedelta_to_sbv_timestamp(timedelta(milliseconds=item["endTime"])) + "\n" + item["text"][:-9] + "\n")
  90. del item
  91. if captions:
  92. myfs.write("\n")
  93. del captions
  94. myfs.close()
  95. del myfs
  96. del captiontext
  97. if parser.title or parser.description[:-16]:
  98. metadata = {}
  99. metadata["title"] = parser.title
  100. if metadata["title"] == False:
  101. metadata["title"] = ""
  102. metadata["description"] = parser.description[:-16]
  103. open("out/"+vid+"/"+vid+"_"+langcode+".json", "w", encoding="utf-8").write(dumps(metadata))
  104. del metadata
  105. del inttext
  106. del langcode
  107. del vid
  108. del pparams
  109. jobs.task_done()
  110. return True