Compare commits

...

5 Commits

Author SHA1 Message Date
dirkf
dfc2c1560d
Merge 97c1053ba81c29cb34066e9ce3fd5c353d1fcf84 into 673277e510ebd996b62a2fcc76169bf3cce29910 2025-03-03 06:52:20 +00:00
dirkf
673277e510
[YouTube] Fix 91b1569 2025-02-28 01:02:20 +00:00
dirkf
91b1569f68
[YouTube] Fix channel playlist extraction (#33074)
* [YouTube] Extract playlist items from LOCKUP_VIEW_MODEL_...
* resolves #33073
* thx seproDev (yt-dlp/yt-dlp#11615)

Co-authored-by: sepro <sepro@sepr0.com>
2025-02-28 00:02:10 +00:00
dirkf
97c1053ba8 Implement @dstftw review comments 2021-04-18 20:02:54 +01:00
df
13d2684263 Support BBC World (etc) pages with data in SIMORGH_DATA JSON 2021-04-18 20:02:52 +01:00
2 changed files with 158 additions and 8 deletions

View File

@ -25,6 +25,7 @@ from ..utils import (
get_element_by_class,
int_or_none,
js_to_json,
parse_bitrate,
parse_duration,
parse_iso8601,
strip_or_none,
@ -647,9 +648,7 @@ class BBCIE(BBCCoUkIE):
'skip_download': True,
}
}, {
# article with single video embedded with data-playable containing XML playlist
# with direct video links as progressiveDownloadUrl (for now these are extracted)
# and playlist with f4m and m3u8 as streamingUrl
# article with single video (formerly) embedded, now using SIMORGH_DATA JSON
'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
'info_dict': {
'id': '150615_telabyad_kentin_cogu',
@ -661,12 +660,13 @@ class BBCIE(BBCCoUkIE):
},
'params': {
'skip_download': True,
}
},
'skip': 'Video no longer embedded, 2021',
}, {
# single video embedded with data-playable containing XML playlists (regional section)
# single video embedded, legacy media, in promo object of SIMORGH_DATA JSON
'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
'info_dict': {
'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
'id': '39275083',
'ext': 'mp4',
'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
@ -845,6 +845,18 @@ class BBCIE(BBCCoUkIE):
'upload_date': '20190604',
'categories': ['Psychology'],
},
}, {
# BBC World Service etc: media nested in content object of SIMORGH_DATA JSON
'url': 'http://www.bbc.co.uk/scotland/articles/cm49v4x1r9lo',
'info_dict': {
'id': 'p06p040v',
'ext': 'mp4',
'title': 'Five things ants can teach us about management',
'description': 'They may be tiny, but us humans could learn a thing or two from ants.',
'duration': 191,
'thumbnail': r're:https?://.+/p06p0qzv.jpg',
'upload_date': '20181016',
},
}]
@classmethod
@ -1107,6 +1119,99 @@ class BBCIE(BBCCoUkIE):
'subtitles': subtitles,
}
# simorgh-based playlist (see https://github.com/bbc/simorgh)
# JSON assigned to window.SIMORGH_DATA in a <script> element
simorgh_data = self._parse_json(
self._search_regex(
r'window\.SIMORGH_DATA\s*=\s*(\{[^<]+})\s*</',
webpage, 'simorgh playlist', default='{}'),
playlist_id, fatal=False)
# legacy media, video in promo object (eg, http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw)
playlist = try_get(simorgh_data, lambda x: x['pageData']['promo']['media']['playlist']) or []
if playlist:
media = simorgh_data['pageData']['promo']
if media['media'].get('format') == 'video':
media.update(media['media'])
title = (dict_get(media.get('headlines') or {},
('shortHeadline', 'headline'))
or playlist_title),
programme_id = media.get('id')
if programme_id and title:
formats = []
keys = {'url', 'format', 'format_id', 'language', 'quality', 'tbr', 'resolution'}
for format in playlist:
if not (format.get('url') and format.get('format')):
continue
bitrate = format.pop('bitrate')
format['tbr'] = int_or_none(bitrate, scale=1000) or parse_bitrate(bitrate)
format['language'] = media.get('language')
# format id: penultimate item from the url split on _ and .
(fmt,) = re.split('[_.]', format['url'])[-2:][:1]
format['format_id'] = '%s_%s' % (format['format'], fmt)
# try to set resolution using any available data
aspect_ratio = re.split(r'[xX:]', media.get('aspectRatio') or '')
if len(aspect_ratio) != 2:
aspect_ratio = None
else:
aspect_ratio = float_or_none(aspect_ratio[0], scale=aspect_ratio[1])
# these may not be present, but try anyway
width = int_or_none(format.get('width'))
height = int_or_none(format.get('height'))
if (not height) and aspect_ratio:
height = int(width / aspect_ratio)
elif (not width) and aspect_ratio:
width = int(height * aspect_ratio)
format['resolution'] = ('%dx%d' % (width, height) if width and height
else dict_get(format, ('resolution', 'res'), default=fmt))
format['quality'] = -1
formats.append(dict((k, format[k]) for k in keys))
self._sort_formats(formats)
return {
'id': programme_id,
'title': title,
'description': media.get('summary') or playlist_description,
'formats': formats,
'subtitles': None,
'thumbnail': try_get(media, lambda x: x['image']['href']),
'timestamp': int_or_none(media.get('timestamp'), scale=1000)
}
# general case: media nested in content object
# test: https://www.bbc.co.uk/scotland/articles/cm49v4x1r9lo
if simorgh_data:
def extract_media_from_simorgh(model):
if not isinstance(model, dict):
return
for block in model.get('blocks') or {}:
if block.get('type') == 'aresMediaMetadata':
vpid = try_get(block, lambda x: x['model']['versions'][0]['versionId'])
if vpid:
formats, subtitles = self._download_media_selector(vpid)
self._sort_formats(formats)
model = block['model']
version = model['versions'][0]
thumbnail = model.get('imageUrl')
return {
'id': vpid,
'title': model.get('title') or 'unnamed clip',
'description': dict_get(model.get('synopses') or {}, ('long', 'medium', 'short')),
'duration': (int_or_none(version.get('duration'))
or parse_duration(version.get('durationISO8601'))),
'timestamp': version.get('availableFrom'),
'thumbnail': urljoin(url, thumbnail.replace('$recipe', 'raw')) if thumbnail else None,
'formats': formats,
'subtitles': subtitles,
}
else:
entry = extract_media_from_simorgh(block.get('model'))
if entry:
return entry
playlist = extract_media_from_simorgh(try_get(simorgh_data, lambda x: x['pageData']['content']['model']))
if playlist:
return playlist
preload_state = self._parse_json(self._search_regex(
r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
'preload state', default='{}'), playlist_id, fatal=False)

View File

@ -27,6 +27,7 @@ from ..compat import (
)
from ..jsinterp import JSInterpreter
from ..utils import (
bug_reports_message,
clean_html,
dict_get,
error_to_compat_str,
@ -65,6 +66,7 @@ from ..utils import (
url_or_none,
urlencode_postdata,
urljoin,
variadic,
)
@ -460,6 +462,26 @@ class YoutubeBaseInfoExtractor(InfoExtractor):
'uploader': uploader,
}
@staticmethod
def _extract_thumbnails(data, *path_list, **kw_final_key):
"""
Extract thumbnails from thumbnails dict
@param path_list: path list to level that contains 'thumbnails' key
"""
final_key = kw_final_key.get('final_key', 'thumbnails')
return traverse_obj(data, ((
tuple(variadic(path) + (final_key, Ellipsis)
for path in path_list or [()])), {
'url': ('url', T(url_or_none),
# Sometimes youtube gives a wrong thumbnail URL. See:
# https://github.com/yt-dlp/yt-dlp/issues/233
# https://github.com/ytdl-org/youtube-dl/issues/28023
T(lambda u: update_url(u, query=None) if u and 'maxresdefault' in u else u)),
'height': ('height', T(int_or_none)),
'width': ('width', T(int_or_none)),
}, T(lambda t: t if t.get('url') else None)))
def _search_results(self, query, params):
data = {
'context': {
@ -3183,8 +3205,12 @@ class YoutubeTabIE(YoutubeBaseInfoExtractor):
expected_type=txt_or_none)
def _grid_entries(self, grid_renderer):
for item in grid_renderer['items']:
if not isinstance(item, dict):
for item in traverse_obj(grid_renderer, ('items', Ellipsis, T(dict))):
lockup_view_model = traverse_obj(item, ('lockupViewModel', T(dict)))
if lockup_view_model:
entry = self._extract_lockup_view_model(lockup_view_model)
if entry:
yield entry
continue
renderer = self._extract_grid_item_renderer(item)
if not isinstance(renderer, dict):
@ -3268,6 +3294,25 @@ class YoutubeTabIE(YoutubeBaseInfoExtractor):
continue
yield self._extract_video(renderer)
def _extract_lockup_view_model(self, view_model):
content_id = view_model.get('contentId')
if not content_id:
return
content_type = view_model.get('contentType')
if content_type not in ('LOCKUP_CONTENT_TYPE_PLAYLIST', 'LOCKUP_CONTENT_TYPE_PODCAST'):
self.report_warning(
'Unsupported lockup view model content type "{0}"{1}'.format(content_type, bug_reports_message()), only_once=True)
return
return merge_dicts(self.url_result(
update_url_query('https://www.youtube.com/playlist', {'list': content_id}),
ie=YoutubeTabIE.ie_key(), video_id=content_id), {
'title': traverse_obj(view_model, (
'metadata', 'lockupMetadataViewModel', 'title', 'content', T(compat_str))),
'thumbnails': self._extract_thumbnails(view_model, (
'contentImage', 'collectionThumbnailViewModel', 'primaryThumbnail',
'thumbnailViewModel', 'image'), final_key='sources'),
})
def _video_entry(self, video_renderer):
video_id = video_renderer.get('videoId')
if video_id: