]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/ted.py
[wrzuta] Remove extractor (closes #20684) (#20801)
[yt-dlp.git] / youtube_dl / extractor / ted.py
CommitLineData
f853f859
PH
1from __future__ import unicode_literals
2
9fd5ce0c
PH
3import json
4import re
5
a504ced0 6from .common import InfoExtractor
9fd5ce0c 7
66ee7b32 8from ..compat import compat_str
49174788 9from ..utils import (
cd3a3ff9 10 float_or_none,
49174788
S
11 int_or_none,
12 try_get,
cd3a3ff9 13 url_or_none,
49174788 14)
4ed3e510 15
f853f859 16
a504ced0 17class TEDIE(InfoExtractor):
cfbee8a4 18 IE_NAME = 'ted'
aab74fa1
PH
19 _VALID_URL = r'''(?x)
20 (?P<proto>https?://)
cd791a5e 21 (?P<type>www|embed(?:-ssl)?)(?P<urlmain>\.ted\.com/
bacac173
JMF
22 (
23 (?P<type_playlist>playlists(?:/\d+)?) # We have a playlist
24 |
25 ((?P<type_talk>talks)) # We have a simple talk
ac6c1048
PH
26 |
27 (?P<type_watch>watch)/[^/]+/[^/]+
bacac173
JMF
28 )
29 (/lang/(.*?))? # The url may contain the language
ac6c1048 30 /(?P<name>[\w-]+) # Here goes the name and then ".html"
aab74fa1 31 .*)$
bacac173 32 '''
ac6c1048 33 _TESTS = [{
f853f859 34 'url': 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html',
cd3a3ff9 35 'md5': 'b0ce2b05ca215042124fbc9e3886493a',
f853f859 36 'info_dict': {
7b9965ea
JMF
37 'id': '102',
38 'ext': 'mp4',
652bee05 39 'title': 'The illusion of consciousness',
bacac173 40 'description': ('Philosopher Dan Dennett makes a compelling '
9e1a5b84
JW
41 'argument that not only don\'t we understand our own '
42 'consciousness, but that half the time our brains are '
43 'actively fooling us.'),
652bee05 44 'uploader': 'Dan Dennett',
f628d800 45 'width': 853,
eb4cb42a 46 'duration': 1308,
cd3a3ff9
S
47 'view_count': int,
48 'comment_count': int,
49 'tags': list,
50 },
51 'params': {
52 'skip_download': True,
53 },
ac6c1048 54 }, {
cd3a3ff9
S
55 # missing HTTP bitrates
56 'url': 'https://www.ted.com/talks/vishal_sikka_the_beauty_and_power_of_algorithms',
ac6c1048 57 'info_dict': {
cd3a3ff9 58 'id': '6069',
ac6c1048 59 'ext': 'mp4',
cd3a3ff9 60 'title': 'The beauty and power of algorithms',
ec85ded8 61 'thumbnail': r're:^https?://.+\.jpg',
cd3a3ff9
S
62 'description': 'md5:734e352710fb00d840ab87ae31aaf688',
63 'uploader': 'Vishal Sikka',
64 },
65 'params': {
66 'skip_download': True,
f628d800 67 },
2d4c98db
JMF
68 }, {
69 'url': 'http://www.ted.com/talks/gabby_giffords_and_mark_kelly_be_passionate_be_courageous_be_your_best',
cd3a3ff9 70 'md5': 'e6b9617c01a7970ceac8bb2c92c346c0',
2d4c98db
JMF
71 'info_dict': {
72 'id': '1972',
5bec5748 73 'ext': 'mp4',
2d4c98db
JMF
74 'title': 'Be passionate. Be courageous. Be your best.',
75 'uploader': 'Gabby Giffords and Mark Kelly',
5bec5748 76 'description': 'md5:5174aed4d0f16021b704120360f72b92',
eb4cb42a 77 'duration': 1128,
2d4c98db 78 },
cd3a3ff9
S
79 'params': {
80 'skip_download': True,
81 },
22a6f150
PH
82 }, {
83 'url': 'http://www.ted.com/playlists/who_are_the_hackers',
84 'info_dict': {
85 'id': '10',
86 'title': 'Who are the hackers?',
87 },
88 'playlist_mincount': 6,
a72cbfac
JMF
89 }, {
90 # contains a youtube video
91 'url': 'https://www.ted.com/talks/douglas_adams_parrots_the_universe_and_everything',
92 'add_ie': ['Youtube'],
93 'info_dict': {
94 'id': '_ZG8HBuDjgc',
f22ba4bd 95 'ext': 'webm',
a72cbfac
JMF
96 'title': 'Douglas Adams: Parrots the Universe and Everything',
97 'description': 'md5:01ad1e199c49ac640cb1196c0e9016af',
98 'uploader': 'University of California Television (UCTV)',
99 'uploader_id': 'UCtelevision',
100 'upload_date': '20080522',
101 },
102 'params': {
103 'skip_download': True,
104 },
9a984265
S
105 }, {
106 # no nativeDownloads
107 'url': 'https://www.ted.com/talks/tom_thum_the_orchestra_in_my_mouth',
108 'info_dict': {
109 'id': '1792',
110 'ext': 'mp4',
111 'title': 'The orchestra in my mouth',
112 'description': 'md5:5d1d78650e2f8dfcbb8ebee2951ac29a',
113 'uploader': 'Tom Thum',
cd3a3ff9
S
114 'view_count': int,
115 'comment_count': int,
116 'tags': list,
9a984265
S
117 },
118 'params': {
119 'skip_download': True,
120 },
ac6c1048 121 }]
9fd5ce0c 122
0ba77818 123 _NATIVE_FORMATS = {
11fa3d7f 124 'low': {'width': 320, 'height': 180},
125 'medium': {'width': 512, 'height': 288},
126 'high': {'width': 854, 'height': 480},
652bee05 127 }
9fd5ce0c 128
ca1fee34 129 def _extract_info(self, webpage):
49174788
S
130 info_json = self._search_regex(
131 r'(?s)q\(\s*"\w+.init"\s*,\s*({.+})\)\s*</script>',
132 webpage, 'info json')
ca1fee34
JMF
133 return json.loads(info_json)
134
9fd5ce0c 135 def _real_extract(self, url):
bacac173 136 m = re.match(self._VALID_URL, url, re.VERBOSE)
cd791a5e 137 if m.group('type').startswith('embed'):
aab74fa1
PH
138 desktop_url = m.group('proto') + 'www' + m.group('urlmain')
139 return self.url_result(desktop_url, 'TED')
bacac173 140 name = m.group('name')
9fd5ce0c 141 if m.group('type_talk'):
bacac173 142 return self._talk_info(url, name)
ac6c1048
PH
143 elif m.group('type_watch'):
144 return self._watch_info(url, name)
bacac173 145 else:
ca1fee34 146 return self._playlist_videos_info(url, name)
9fd5ce0c 147
ca1fee34 148 def _playlist_videos_info(self, url, name):
9fd5ce0c 149 '''Returns the videos of the playlist'''
fc2ef392 150
ca1fee34 151 webpage = self._download_webpage(url, name,
9e1a5b84 152 'Downloading playlist webpage')
ca1fee34 153 info = self._extract_info(webpage)
49174788
S
154
155 playlist_info = try_get(
156 info, lambda x: x['__INITIAL_DATA__']['playlist'],
157 dict) or info['playlist']
9fd5ce0c 158
fc2ef392 159 playlist_entries = [
f07a9f6f 160 self.url_result('http://www.ted.com/talks/' + talk['slug'], self.ie_key())
49174788
S
161 for talk in try_get(
162 info, lambda x: x['__INITIAL_DATA__']['talks'],
163 dict) or info['talks']
fc2ef392
PH
164 ]
165 return self.playlist_result(
ca1fee34
JMF
166 playlist_entries,
167 playlist_id=compat_str(playlist_info['id']),
168 playlist_title=playlist_info['title'])
9fd5ce0c 169
bacac173
JMF
170 def _talk_info(self, url, video_name):
171 webpage = self._download_webpage(url, video_name)
a9a3876d 172
49174788
S
173 info = self._extract_info(webpage)
174
cd3a3ff9
S
175 data = try_get(info, lambda x: x['__INITIAL_DATA__'], dict) or info
176 talk_info = data['talks'][0]
49174788
S
177
178 title = talk_info['title'].strip()
a9a3876d 179
49174788 180 native_downloads = try_get(
9a984265
S
181 talk_info,
182 (lambda x: x['downloads']['nativeDownloads'],
183 lambda x: x['nativeDownloads']),
184 dict) or {}
49174788 185
652bee05 186 formats = [{
652bee05
JMF
187 'url': format_url,
188 'format_id': format_id,
189 'format': format_id,
49174788 190 } for (format_id, format_url) in native_downloads.items() if format_url is not None]
2d4c98db
JMF
191 if formats:
192 for f in formats:
193 finfo = self._NATIVE_FORMATS.get(f['format_id'])
194 if finfo:
195 f.update(finfo)
66ee7b32 196
49174788
S
197 player_talk = talk_info['player_talks'][0]
198
cd3a3ff9
S
199 external = player_talk.get('external')
200 if isinstance(external, dict):
201 service = external.get('service')
202 if isinstance(service, compat_str):
203 ext_url = None
204 if service.lower() == 'youtube':
205 ext_url = external.get('code')
d226c560
ER
206
207 return self.url_result(ext_url or external['uri'])
cd3a3ff9 208
49174788
S
209 resources_ = player_talk.get('resources') or talk_info.get('resources')
210
11fa3d7f 211 http_url = None
49174788 212 for format_id, resources in resources_.items():
66ee7b32
S
213 if format_id == 'h264':
214 for resource in resources:
11fa3d7f 215 h264_url = resource.get('file')
216 if not h264_url:
217 continue
66ee7b32
S
218 bitrate = int_or_none(resource.get('bitrate'))
219 formats.append({
11fa3d7f 220 'url': h264_url,
66ee7b32
S
221 'format_id': '%s-%sk' % (format_id, bitrate),
222 'tbr': bitrate,
223 })
ec85ded8 224 if re.search(r'\d+k', h264_url):
11fa3d7f 225 http_url = h264_url
66ee7b32
S
226 elif format_id == 'rtmp':
227 streamer = talk_info.get('streamer')
228 if not streamer:
229 continue
230 for resource in resources:
231 formats.append({
232 'format_id': '%s-%s' % (format_id, resource.get('name')),
233 'url': streamer,
234 'play_path': resource['file'],
235 'ext': 'flv',
236 'width': int_or_none(resource.get('width')),
237 'height': int_or_none(resource.get('height')),
238 'tbr': int_or_none(resource.get('bitrate')),
239 })
240 elif format_id == 'hls':
a94e7c19
RA
241 if not isinstance(resources, dict):
242 continue
cd3a3ff9
S
243 stream_url = url_or_none(resources.get('stream'))
244 if not stream_url:
245 continue
11fa3d7f 246 formats.extend(self._extract_m3u8_formats(
cd3a3ff9
S
247 stream_url, video_name, 'mp4', m3u8_id=format_id,
248 fatal=False))
11fa3d7f 249
250 m3u8_formats = list(filter(
ff99fe52 251 lambda f: f.get('protocol') == 'm3u8' and f.get('vcodec') != 'none',
11fa3d7f 252 formats))
253 if http_url:
254 for m3u8_format in m3u8_formats:
255 bitrate = self._search_regex(r'(\d+k)', m3u8_format['url'], 'bitrate', default=None)
256 if not bitrate:
257 continue
cd3a3ff9
S
258 bitrate_url = re.sub(r'\d+k', bitrate, http_url)
259 if not self._is_valid_url(
260 bitrate_url, video_name, '%s bitrate' % bitrate):
261 continue
11fa3d7f 262 f = m3u8_format.copy()
263 f.update({
cd3a3ff9 264 'url': bitrate_url,
11fa3d7f 265 'format_id': m3u8_format['format_id'].replace('hls', 'http'),
266 'protocol': 'http',
267 })
f28363ad
RA
268 if f.get('acodec') == 'none':
269 del f['acodec']
11fa3d7f 270 formats.append(f)
66ee7b32
S
271
272 audio_download = talk_info.get('audioDownload')
273 if audio_download:
274 formats.append({
275 'url': audio_download,
276 'format_id': 'audio',
736785ab 277 'vcodec': 'none',
66ee7b32
S
278 })
279
f628d800 280 self._sort_formats(formats)
652bee05 281
7b9965ea 282 video_id = compat_str(talk_info['id'])
a9a3876d 283
463a9087 284 return {
a9a3876d 285 'id': video_id,
49174788
S
286 'title': title,
287 'uploader': player_talk.get('speaker') or talk_info.get('speaker'),
288 'thumbnail': player_talk.get('thumb') or talk_info.get('thumb'),
652bee05 289 'description': self._og_search_description(webpage),
03091e37 290 'subtitles': self._get_subtitles(video_id, talk_info),
0d8cb1cc 291 'formats': formats,
cd3a3ff9
S
292 'duration': float_or_none(talk_info.get('duration')),
293 'view_count': int_or_none(data.get('viewed_count')),
294 'comment_count': int_or_none(
295 try_get(data, lambda x: x['comments']['count'])),
296 'tags': try_get(talk_info, lambda x: x['tags'], list),
0d8cb1cc
PH
297 }
298
a504ced0 299 def _get_subtitles(self, video_id, talk_info):
f2bb33a9
S
300 sub_lang_list = {}
301 for language in try_get(
302 talk_info,
303 (lambda x: x['downloads']['languages'],
304 lambda x: x['languages']), list):
305 lang_code = language.get('languageCode') or language.get('ianaCode')
306 if not lang_code:
307 continue
308 sub_lang_list[lang_code] = [
309 {
310 'url': 'http://www.ted.com/talks/subtitles/id/%s/lang/%s/format/%s' % (video_id, lang_code, ext),
311 'ext': ext,
312 }
313 for ext in ['ted', 'srt']
314 ]
315 return sub_lang_list
ac6c1048
PH
316
317 def _watch_info(self, url, name):
318 webpage = self._download_webpage(url, name)
319
320 config_json = self._html_search_regex(
de9bd74b 321 r'"pages\.jwplayer"\s*,\s*({.+?})\s*\)\s*</script>',
f628d800 322 webpage, 'config', default=None)
323 if not config_json:
324 embed_url = self._search_regex(
325 r"<iframe[^>]+class='pages-video-embed__video__object'[^>]+src='([^']+)'", webpage, 'embed url')
326 return self.url_result(self._proto_relative_url(embed_url))
de9bd74b 327 config = json.loads(config_json)['config']
ac6c1048
PH
328 video_url = config['video']['url']
329 thumbnail = config.get('image', {}).get('url')
330
331 title = self._html_search_regex(
332 r"(?s)<h1(?:\s+class='[^']+')?>(.+?)</h1>", webpage, 'title')
333 description = self._html_search_regex(
621f33c9
PH
334 [
335 r'(?s)<h4 class="[^"]+" id="h3--about-this-talk">.*?</h4>(.*?)</div>',
336 r'(?s)<p><strong>About this talk:</strong>\s+(.*?)</p>',
337 ],
ac6c1048
PH
338 webpage, 'description', fatal=False)
339
340 return {
341 'id': name,
342 'url': video_url,
343 'title': title,
344 'thumbnail': thumbnail,
345 'description': description,
346 }