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