ted.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import itertools
  2. import re
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. int_or_none,
  6. parse_duration,
  7. str_to_int,
  8. try_get,
  9. unified_strdate,
  10. url_or_none,
  11. )
  12. class TedBaseIE(InfoExtractor):
  13. _VALID_URL_BASE = r'https?://www\.ted\.com/(?:{type})(?:/lang/[^/#?]+)?/(?P<id>[\w-]+)'
  14. def _parse_playlist(self, playlist):
  15. for entry in try_get(playlist, lambda x: x['videos']['nodes'], list):
  16. if entry.get('__typename') == 'Video' and entry.get('canonicalUrl'):
  17. yield self.url_result(entry['canonicalUrl'], TedTalkIE.ie_key())
  18. class TedTalkIE(TedBaseIE):
  19. _VALID_URL = TedBaseIE._VALID_URL_BASE.format(type='talks')
  20. _TESTS = [{
  21. 'url': 'https://www.ted.com/talks/candace_parker_how_to_break_down_barriers_and_not_accept_limits',
  22. 'md5': '47e82c666d9c3261d4fe74748a90aada',
  23. 'info_dict': {
  24. 'id': '86532',
  25. 'ext': 'mp4',
  26. 'title': 'How to break down barriers and not accept limits',
  27. 'description': 'md5:000707cece219d1e165b11550d612331',
  28. 'view_count': int,
  29. 'tags': ['personal growth', 'equality', 'activism', 'motivation', 'social change', 'sports'],
  30. 'uploader': 'Candace Parker',
  31. 'duration': 676.0,
  32. 'upload_date': '20220114',
  33. 'release_date': '20211201',
  34. 'thumbnail': r're:http.*\.jpg',
  35. },
  36. }]
  37. def _real_extract(self, url):
  38. display_id = self._match_id(url)
  39. webpage = self._download_webpage(url, display_id)
  40. talk_info = self._search_nextjs_data(webpage, display_id)['props']['pageProps']['videoData']
  41. video_id = talk_info['id']
  42. player_data = self._parse_json(talk_info.get('playerData'), video_id)
  43. http_url = None
  44. formats, subtitles = [], {}
  45. for format_id, resources in (player_data.get('resources') or {}).items():
  46. if format_id == 'hls':
  47. stream_url = url_or_none(try_get(resources, lambda x: x['stream']))
  48. if not stream_url:
  49. continue
  50. m3u8_formats, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
  51. stream_url, video_id, 'mp4', m3u8_id=format_id, fatal=False)
  52. formats.extend(m3u8_formats)
  53. subtitles = self._merge_subtitles(subtitles, m3u8_subs)
  54. continue
  55. if not isinstance(resources, list):
  56. continue
  57. if format_id == 'h264':
  58. for resource in resources:
  59. h264_url = resource.get('file')
  60. if not h264_url:
  61. continue
  62. bitrate = int_or_none(resource.get('bitrate'))
  63. formats.append({
  64. 'url': h264_url,
  65. 'format_id': f'{format_id}-{bitrate}k',
  66. 'tbr': bitrate,
  67. })
  68. if re.search(r'\d+k', h264_url):
  69. http_url = h264_url
  70. elif format_id == 'rtmp':
  71. streamer = talk_info.get('streamer')
  72. if not streamer:
  73. continue
  74. formats.extend({
  75. 'format_id': '{}-{}'.format(format_id, resource.get('name')),
  76. 'url': streamer,
  77. 'play_path': resource['file'],
  78. 'ext': 'flv',
  79. 'width': int_or_none(resource.get('width')),
  80. 'height': int_or_none(resource.get('height')),
  81. 'tbr': int_or_none(resource.get('bitrate')),
  82. } for resource in resources if resource.get('file'))
  83. if http_url:
  84. m3u8_formats = [f for f in formats if f.get('protocol') == 'm3u8' and f.get('vcodec') != 'none']
  85. for m3u8_format in m3u8_formats:
  86. bitrate = self._search_regex(r'(\d+k)', m3u8_format['url'], 'bitrate', default=None)
  87. if not bitrate:
  88. continue
  89. bitrate_url = re.sub(r'\d+k', bitrate, http_url)
  90. if not self._is_valid_url(
  91. bitrate_url, video_id, f'{bitrate} bitrate'):
  92. continue
  93. f = m3u8_format.copy()
  94. f.update({
  95. 'url': bitrate_url,
  96. 'format_id': m3u8_format['format_id'].replace('hls', 'http'),
  97. 'protocol': 'http',
  98. })
  99. if f.get('acodec') == 'none':
  100. del f['acodec']
  101. formats.append(f)
  102. audio_download = talk_info.get('audioDownload')
  103. if audio_download:
  104. formats.append({
  105. 'url': audio_download,
  106. 'format_id': 'audio',
  107. 'vcodec': 'none',
  108. })
  109. if not formats:
  110. external = player_data.get('external') or {}
  111. service = external.get('service') or ''
  112. ext_url = external.get('code') if service.lower() == 'youtube' else None
  113. return self.url_result(ext_url or external['uri'])
  114. thumbnail = player_data.get('thumb') or self._og_search_property('image', webpage)
  115. if thumbnail:
  116. # trim thumbnail resize parameters
  117. thumbnail = thumbnail.split('?')[0]
  118. return {
  119. 'id': video_id,
  120. 'title': talk_info.get('title') or self._og_search_title(webpage),
  121. 'uploader': talk_info.get('presenterDisplayName'),
  122. 'thumbnail': thumbnail,
  123. 'description': talk_info.get('description') or self._og_search_description(webpage),
  124. 'subtitles': subtitles,
  125. 'formats': formats,
  126. 'duration': talk_info.get('duration') or parse_duration(self._og_search_property('video:duration', webpage)),
  127. 'view_count': str_to_int(talk_info.get('viewedCount')),
  128. 'upload_date': unified_strdate(talk_info.get('publishedAt')),
  129. 'release_date': unified_strdate(talk_info.get('recordedOn')),
  130. 'tags': try_get(player_data, lambda x: x['targeting']['tag'].split(',')),
  131. }
  132. class TedSeriesIE(TedBaseIE):
  133. _VALID_URL = fr'{TedBaseIE._VALID_URL_BASE.format(type=r"series")}(?:#season_(?P<season>\d+))?'
  134. _TESTS = [{
  135. 'url': 'https://www.ted.com/series/small_thing_big_idea',
  136. 'info_dict': {
  137. 'id': '3',
  138. 'title': 'Small Thing Big Idea',
  139. 'series': 'Small Thing Big Idea',
  140. 'description': 'md5:6869ca52cec661aef72b3e9f7441c55c',
  141. },
  142. 'playlist_mincount': 16,
  143. }, {
  144. 'url': 'https://www.ted.com/series/the_way_we_work#season_2',
  145. 'info_dict': {
  146. 'id': '8_2',
  147. 'title': 'The Way We Work Season 2',
  148. 'series': 'The Way We Work',
  149. 'description': 'md5:59469256e533e1a48c4aa926a382234c',
  150. 'season_number': 2,
  151. },
  152. 'playlist_mincount': 8,
  153. }]
  154. def _real_extract(self, url):
  155. display_id, season = self._match_valid_url(url).group('id', 'season')
  156. webpage = self._download_webpage(url, display_id, 'Downloading series webpage')
  157. info = self._search_nextjs_data(webpage, display_id)['props']['pageProps']
  158. entries = itertools.chain.from_iterable(
  159. self._parse_playlist(s) for s in info['seasons'] if season in [None, s.get('seasonNumber')])
  160. series_id = try_get(info, lambda x: x['series']['id'])
  161. series_name = try_get(info, lambda x: x['series']['name']) or self._og_search_title(webpage, fatal=False)
  162. return self.playlist_result(
  163. entries,
  164. f'{series_id}_{season}' if season and series_id else series_id,
  165. f'{series_name} Season {season}' if season else series_name,
  166. self._og_search_description(webpage),
  167. series=series_name, season_number=int_or_none(season))
  168. class TedPlaylistIE(TedBaseIE):
  169. _VALID_URL = TedBaseIE._VALID_URL_BASE.format(type=r'playlists(?:/\d+)?')
  170. _TESTS = [{
  171. 'url': 'https://www.ted.com/playlists/171/the_most_popular_talks_of_all',
  172. 'info_dict': {
  173. 'id': '171',
  174. 'title': 'The most popular talks of all time',
  175. 'description': 'md5:d2f22831dc86c7040e733a3cb3993d78',
  176. },
  177. 'playlist_mincount': 25,
  178. }]
  179. def _real_extract(self, url):
  180. display_id = self._match_id(url)
  181. webpage = self._download_webpage(url, display_id)
  182. playlist = self._search_nextjs_data(webpage, display_id)['props']['pageProps']['playlist']
  183. return self.playlist_result(
  184. self._parse_playlist(playlist), playlist.get('id'),
  185. playlist.get('title') or self._og_search_title(webpage, default='').replace(' | TED Talks', '') or None,
  186. self._og_search_description(webpage))
  187. class TedEmbedIE(InfoExtractor):
  188. _VALID_URL = r'https?://embed(?:-ssl)?\.ted\.com/'
  189. _EMBED_REGEX = [rf'<iframe[^>]+?src=(["\'])(?P<url>{_VALID_URL}.+?)\1']
  190. _TESTS = [{
  191. 'url': 'https://embed.ted.com/talks/janet_stovall_how_to_get_serious_about_diversity_and_inclusion_in_the_workplace',
  192. 'info_dict': {
  193. 'id': '21802',
  194. 'ext': 'mp4',
  195. 'title': 'How to get serious about diversity and inclusion in the workplace',
  196. 'description': 'md5:0978aafe396e05341f8ecc795d22189d',
  197. 'view_count': int,
  198. 'tags': list,
  199. 'uploader': 'Janet Stovall',
  200. 'duration': 664.0,
  201. 'upload_date': '20180822',
  202. 'release_date': '20180719',
  203. 'thumbnail': r're:http.*\.jpg',
  204. },
  205. }]
  206. def _real_extract(self, url):
  207. return self.url_result(re.sub(r'://embed(-ssl)?', '://www', url), TedTalkIE.ie_key())