You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
10 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. from __future__ import unicode_literals
  2. import json
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_str
  6. from ..utils import int_or_none
  7. class TEDIE(InfoExtractor):
  8. IE_NAME = 'ted'
  9. _VALID_URL = r'''(?x)
  10. (?P<proto>https?://)
  11. (?P<type>www|embed(?:-ssl)?)(?P<urlmain>\.ted\.com/
  12. (
  13. (?P<type_playlist>playlists(?:/\d+)?) # We have a playlist
  14. |
  15. ((?P<type_talk>talks)) # We have a simple talk
  16. |
  17. (?P<type_watch>watch)/[^/]+/[^/]+
  18. )
  19. (/lang/(.*?))? # The url may contain the language
  20. /(?P<name>[\w-]+) # Here goes the name and then ".html"
  21. .*)$
  22. '''
  23. _TESTS = [{
  24. 'url': 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html',
  25. 'md5': 'fc94ac279feebbce69f21c0c6ee82810',
  26. 'info_dict': {
  27. 'id': '102',
  28. 'ext': 'mp4',
  29. 'title': 'The illusion of consciousness',
  30. 'description': ('Philosopher Dan Dennett makes a compelling '
  31. 'argument that not only don\'t we understand our own '
  32. 'consciousness, but that half the time our brains are '
  33. 'actively fooling us.'),
  34. 'uploader': 'Dan Dennett',
  35. 'width': 854,
  36. 'duration': 1308,
  37. }
  38. }, {
  39. 'url': 'http://www.ted.com/watch/ted-institute/ted-bcg/vishal-sikka-the-beauty-and-power-of-algorithms',
  40. 'md5': '226f4fb9c62380d11b7995efa4c87994',
  41. 'info_dict': {
  42. 'id': 'vishal-sikka-the-beauty-and-power-of-algorithms',
  43. 'ext': 'mp4',
  44. 'title': 'Vishal Sikka: The beauty and power of algorithms',
  45. 'thumbnail': 're:^https?://.+\.jpg',
  46. 'description': 'Adaptive, intelligent, and consistent, algorithms are emerging as the ultimate app for everything from matching consumers to products to assessing medical diagnoses. Vishal Sikka shares his appreciation for the algorithm, charting both its inherent beauty and its growing power.',
  47. }
  48. }, {
  49. 'url': 'http://www.ted.com/talks/gabby_giffords_and_mark_kelly_be_passionate_be_courageous_be_your_best',
  50. 'info_dict': {
  51. 'id': '1972',
  52. 'ext': 'mp4',
  53. 'title': 'Be passionate. Be courageous. Be your best.',
  54. 'uploader': 'Gabby Giffords and Mark Kelly',
  55. 'description': 'md5:5174aed4d0f16021b704120360f72b92',
  56. 'duration': 1128,
  57. },
  58. }, {
  59. 'url': 'http://www.ted.com/playlists/who_are_the_hackers',
  60. 'info_dict': {
  61. 'id': '10',
  62. 'title': 'Who are the hackers?',
  63. },
  64. 'playlist_mincount': 6,
  65. }, {
  66. # contains a youtube video
  67. 'url': 'https://www.ted.com/talks/douglas_adams_parrots_the_universe_and_everything',
  68. 'add_ie': ['Youtube'],
  69. 'info_dict': {
  70. 'id': '_ZG8HBuDjgc',
  71. 'ext': 'mp4',
  72. 'title': 'Douglas Adams: Parrots the Universe and Everything',
  73. 'description': 'md5:01ad1e199c49ac640cb1196c0e9016af',
  74. 'uploader': 'University of California Television (UCTV)',
  75. 'uploader_id': 'UCtelevision',
  76. 'upload_date': '20080522',
  77. },
  78. 'params': {
  79. 'skip_download': True,
  80. },
  81. }, {
  82. # YouTube video
  83. 'url': 'http://www.ted.com/talks/jeffrey_kluger_the_sibling_bond',
  84. 'add_ie': ['Youtube'],
  85. 'info_dict': {
  86. 'id': 'aFBIPO-P7LM',
  87. 'ext': 'mp4',
  88. 'title': 'The hidden power of siblings: Jeff Kluger at TEDxAsheville',
  89. 'description': 'md5:3d7a4f50d95ca5dd67104e2a20f43fe1',
  90. 'uploader': 'TEDx Talks',
  91. 'uploader_id': 'TEDxTalks',
  92. 'upload_date': '20111216',
  93. },
  94. 'params': {
  95. 'skip_download': True,
  96. },
  97. }]
  98. _NATIVE_FORMATS = {
  99. 'low': {'preference': 1, 'width': 320, 'height': 180},
  100. 'medium': {'preference': 2, 'width': 512, 'height': 288},
  101. 'high': {'preference': 3, 'width': 854, 'height': 480},
  102. }
  103. def _extract_info(self, webpage):
  104. info_json = self._search_regex(r'q\("\w+.init",({.+})\)</script>',
  105. webpage, 'info json')
  106. return json.loads(info_json)
  107. def _real_extract(self, url):
  108. m = re.match(self._VALID_URL, url, re.VERBOSE)
  109. if m.group('type').startswith('embed'):
  110. desktop_url = m.group('proto') + 'www' + m.group('urlmain')
  111. return self.url_result(desktop_url, 'TED')
  112. name = m.group('name')
  113. if m.group('type_talk'):
  114. return self._talk_info(url, name)
  115. elif m.group('type_watch'):
  116. return self._watch_info(url, name)
  117. else:
  118. return self._playlist_videos_info(url, name)
  119. def _playlist_videos_info(self, url, name):
  120. '''Returns the videos of the playlist'''
  121. webpage = self._download_webpage(url, name,
  122. 'Downloading playlist webpage')
  123. info = self._extract_info(webpage)
  124. playlist_info = info['playlist']
  125. playlist_entries = [
  126. self.url_result('http://www.ted.com/talks/' + talk['slug'], self.ie_key())
  127. for talk in info['talks']
  128. ]
  129. return self.playlist_result(
  130. playlist_entries,
  131. playlist_id=compat_str(playlist_info['id']),
  132. playlist_title=playlist_info['title'])
  133. def _talk_info(self, url, video_name):
  134. webpage = self._download_webpage(url, video_name)
  135. self.report_extraction(video_name)
  136. talk_info = self._extract_info(webpage)['talks'][0]
  137. external = talk_info.get('external')
  138. if external:
  139. service = external['service']
  140. self.to_screen('Found video from %s' % service)
  141. ext_url = None
  142. if service.lower() == 'youtube':
  143. ext_url = external.get('code')
  144. return {
  145. '_type': 'url',
  146. 'url': ext_url or external['uri'],
  147. }
  148. formats = [{
  149. 'url': format_url,
  150. 'format_id': format_id,
  151. 'format': format_id,
  152. } for (format_id, format_url) in talk_info['nativeDownloads'].items() if format_url is not None]
  153. if formats:
  154. for f in formats:
  155. finfo = self._NATIVE_FORMATS.get(f['format_id'])
  156. if finfo:
  157. f.update(finfo)
  158. for format_id, resources in talk_info['resources'].items():
  159. if format_id == 'h264':
  160. for resource in resources:
  161. bitrate = int_or_none(resource.get('bitrate'))
  162. formats.append({
  163. 'url': resource['file'],
  164. 'format_id': '%s-%sk' % (format_id, bitrate),
  165. 'tbr': bitrate,
  166. })
  167. elif format_id == 'rtmp':
  168. streamer = talk_info.get('streamer')
  169. if not streamer:
  170. continue
  171. for resource in resources:
  172. formats.append({
  173. 'format_id': '%s-%s' % (format_id, resource.get('name')),
  174. 'url': streamer,
  175. 'play_path': resource['file'],
  176. 'ext': 'flv',
  177. 'width': int_or_none(resource.get('width')),
  178. 'height': int_or_none(resource.get('height')),
  179. 'tbr': int_or_none(resource.get('bitrate')),
  180. })
  181. elif format_id == 'hls':
  182. hls_formats = self._extract_m3u8_formats(
  183. resources.get('stream'), video_name, 'mp4', m3u8_id=format_id)
  184. for f in hls_formats:
  185. if f.get('format_id') == 'hls-meta':
  186. continue
  187. if not f.get('height'):
  188. f['vcodec'] = 'none'
  189. else:
  190. f['acodec'] = 'none'
  191. formats.extend(hls_formats)
  192. audio_download = talk_info.get('audioDownload')
  193. if audio_download:
  194. formats.append({
  195. 'url': audio_download,
  196. 'format_id': 'audio',
  197. 'vcodec': 'none',
  198. 'preference': -0.5,
  199. })
  200. self._sort_formats(formats)
  201. video_id = compat_str(talk_info['id'])
  202. thumbnail = talk_info['thumb']
  203. if not thumbnail.startswith('http'):
  204. thumbnail = 'http://' + thumbnail
  205. return {
  206. 'id': video_id,
  207. 'title': talk_info['title'].strip(),
  208. 'uploader': talk_info['speaker'],
  209. 'thumbnail': thumbnail,
  210. 'description': self._og_search_description(webpage),
  211. 'subtitles': self._get_subtitles(video_id, talk_info),
  212. 'formats': formats,
  213. 'duration': talk_info.get('duration'),
  214. }
  215. def _get_subtitles(self, video_id, talk_info):
  216. languages = [lang['languageCode'] for lang in talk_info.get('languages', [])]
  217. if languages:
  218. sub_lang_list = {}
  219. for l in languages:
  220. sub_lang_list[l] = [
  221. {
  222. 'url': 'http://www.ted.com/talks/subtitles/id/%s/lang/%s/format/%s' % (video_id, l, ext),
  223. 'ext': ext,
  224. }
  225. for ext in ['ted', 'srt']
  226. ]
  227. return sub_lang_list
  228. else:
  229. return {}
  230. def _watch_info(self, url, name):
  231. webpage = self._download_webpage(url, name)
  232. config_json = self._html_search_regex(
  233. r'"pages\.jwplayer"\s*,\s*({.+?})\s*\)\s*</script>',
  234. webpage, 'config')
  235. config = json.loads(config_json)['config']
  236. video_url = config['video']['url']
  237. thumbnail = config.get('image', {}).get('url')
  238. title = self._html_search_regex(
  239. r"(?s)<h1(?:\s+class='[^']+')?>(.+?)</h1>", webpage, 'title')
  240. description = self._html_search_regex(
  241. [
  242. r'(?s)<h4 class="[^"]+" id="h3--about-this-talk">.*?</h4>(.*?)</div>',
  243. r'(?s)<p><strong>About this talk:</strong>\s+(.*?)</p>',
  244. ],
  245. webpage, 'description', fatal=False)
  246. return {
  247. 'id': name,
  248. 'url': video_url,
  249. 'title': title,
  250. 'thumbnail': thumbnail,
  251. 'description': description,
  252. }