[YouTube] Refactor subtitle processing

* move to internal function
* use `traverse-obj()`
This commit is contained in:
dirkf 2025-01-06 01:24:30 +00:00
parent ab7c61ca29
commit 00ad2b8ca1

View File

@ -2415,9 +2415,9 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
'is_live': is_live, 'is_live': is_live,
} }
pctr = try_get( pctr = traverse_obj(
player_response, player_response,
lambda x: x['captions']['playerCaptionsTracklistRenderer'], dict) ('captions', 'playerCaptionsTracklistRenderer', T(dict)))
if pctr: if pctr:
def process_language(container, base_url, lang_code, query): def process_language(container, base_url, lang_code, query):
lang_subs = [] lang_subs = []
@ -2431,9 +2431,10 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
}) })
container[lang_code] = lang_subs container[lang_code] = lang_subs
def process_subtitles():
subtitles = {} subtitles = {}
for caption_track in (pctr.get('captionTracks') or []): for caption_track in traverse_obj(pctr, (
base_url = caption_track.get('baseUrl') 'captionTracks', lambda _, v: v.get('baseUrl'))):
if not base_url: if not base_url:
continue continue
if caption_track.get('kind') != 'asr': if caption_track.get('kind') != 'asr':
@ -2444,16 +2445,17 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
subtitles, base_url, lang_code, {}) subtitles, base_url, lang_code, {})
continue continue
automatic_captions = {} automatic_captions = {}
for translation_language in (pctr.get('translationLanguages') or []): for translation_language in traverse_obj(pctr, (
translation_language_code = translation_language.get('languageCode') 'translationLanguages', lambda _, v: v.get('languageCode'))):
if not translation_language_code: translation_language_code = translation_language['languageCode']
continue
process_language( process_language(
automatic_captions, base_url, translation_language_code, automatic_captions, base_url, translation_language_code,
{'tlang': translation_language_code}) {'tlang': translation_language_code})
info['automatic_captions'] = automatic_captions info['automatic_captions'] = automatic_captions
info['subtitles'] = subtitles info['subtitles'] = subtitles
process_subtitles()
parsed_url = compat_urllib_parse_urlparse(url) parsed_url = compat_urllib_parse_urlparse(url)
for component in (parsed_url.fragment, parsed_url.query): for component in (parsed_url.fragment, parsed_url.query):
query = compat_parse_qs(component) query = compat_parse_qs(component)