Repository: yt-dlp/yt-dlp
File: yt_dlp/extractor/facebook.py (Python)

Code before:
            post = traverse_obj(post_data, (
                ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []
            snippet = traverse_obj(post, (..., 'video', ..., 'attachments', ..., lambda k, v: (
                k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict) or {}
            locale = self._html_search_meta(['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
            captions = get_first(snippet, 'video_available_captions_locales', 'captions_url')
            useIsVideoBroadcast = get_first(snippet, ('is_video_broadcast')) or False
            automatic_captions = {}
            subtitles = {}
            if isinstance(captions, str):
                subtitles[locale] = [{'ext': determine_ext(captions, default_ext='srt'), 'url': captions}]
            elif isinstance(captions, list):
                if len(captions) > 1:
                    captions = sorted(captions, key=lambda c: (c['locale'] != locale, c['locale']))
                for c in captions:
                    s = {
                        'ext': determine_ext(c['captions_url'], default_ext='srt'),
                        'url': c['captions_url'],
                        'name': (c['localized_language']
                                 + (' (' + c['localized_country'] + ')' if c['localized_country'] else '')
                                 + (' (' + c['localized_creation_method'] + ')' if c['localized_creation_method'] else '')),
                    }
                    if c['localized_creation_method'] or useIsVideoBroadcast:
                        automatic_captions.setdefault(c['locale'], []).append(s)
                    else:
                        subtitles.setdefault(c['locale'], []).append(s)
            media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
                k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
            title = get_first(media, ('title', 'text'))
            description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
            uploader_data = (
                get_first(media, ('owner', {dict}))
                or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
                or get_first(post, ('node', 'actors', ..., {dict})) or {})

            page_title = title or self._html_search_regex((
                r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
                r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
                self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
            ), webpage, 'title', default=None, group='content')
            description = description or self._html_search_meta(
                ['description', 'og:description', 'twitter:description'],
                webpage, 'description', default=None)
            uploader = uploader_data.get('name') or (
                clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
                or self._search_regex(
                    (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))

            timestamp = int_or_none(self._search_regex(
                r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
                'timestamp', default=None))

Review comment (refactor):
We need to make everything here non-fatal

Sorting is not necessary

I'd prefer to simplify the `name` -- are the parentheses necessary? `join_nonempty` would clean this up nicely if you're ok with a `-` delimiter (or you can change it by passing a `delim` kwarg)

Instead of instance checking we can just try to traverse `captions` as if it was a list of dicts
```suggestion
            # or snippet had 'video_available_captions_locales' 
            for caption in traverse_obj(captions, lambda _, v: v['captions_url'] and v['locale']):
                subs = {
                    'url': caption['captions_url'],
                    'name': join_nonempty(
                        'localized_language', 'localized_country',
                        'localized_creation_method', from_dict=caption),
                }
                if caption.get('localized_creation_method') or is_video_broadcast:
                    automatic_captions.setdefault(caption['locale'], []).append(subs)
                else:
                    subtitles.setdefault(caption['locale'], []).append(subs)
```

Code after:
                r'data-sjs>({.*?ScheduledServerJS.*?})</script>', webpage)]
            post = traverse_obj(post_data, (
                ..., 'require', ..., ..., ..., '__bbox', 'require', ..., ..., ..., '__bbox', 'result', 'data'), expected_type=dict) or []

            automatic_captions, subtitles = {}, {}
            subs_data = traverse_obj(post, (..., 'video', ..., 'attachments', ..., lambda k, v: (
                k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')))
            is_video_broadcast = get_first(subs_data, 'is_video_broadcast', expected_type=bool)
            captions = get_first(subs_data, 'video_available_captions_locales', 'captions_url')
            if url_or_none(captions):  # if subs_data only had a 'captions_url'
                locale = self._html_search_meta(['og:locale', 'twitter:locale'], webpage, 'locale', default='en_US')
                subtitles[locale] = [{'url': captions}]
            # or else subs_data had 'video_available_captions_locales', a list of dicts
            for caption in traverse_obj(captions, (
                {lambda x: sorted(x, key=lambda c: c['locale'])}, lambda _, v: v['captions_url'])
            ):
                lang = caption.get('localized_language') or ''
                subs = {
                    'url': caption['captions_url'],
                    'name': format_field(caption, 'localized_country', f'{lang} (%s)', default=lang),
                }
                if caption.get('localized_creation_method') or is_video_broadcast:
                    automatic_captions.setdefault(caption['locale'], []).append(subs)
                else:
                    subtitles.setdefault(caption['locale'], []).append(subs)

            media = traverse_obj(post, (..., 'attachments', ..., lambda k, v: (
                k == 'media' and str(v['id']) == video_id and v['__typename'] == 'Video')), expected_type=dict)
            title = get_first(media, ('title', 'text'))
            description = get_first(media, ('creation_story', 'comet_sections', 'message', 'story', 'message', 'text'))
            uploader_data = (
                get_first(media, ('owner', {dict}))
                or get_first(post, (..., 'video', lambda k, v: k == 'owner' and v['name']))
                or get_first(post, ('node', 'actors', ..., {dict})) or {})

            page_title = title or self._html_search_regex((
                r'<h2\s+[^>]*class="uiHeaderTitle"[^>]*>(?P<content>[^<]*)</h2>',
                r'(?s)<span class="fbPhotosPhotoCaption".*?id="fbPhotoPageCaption"><span class="hasCaption">(?P<content>.*?)</span>',
                self._meta_regex('og:title'), self._meta_regex('twitter:title'), r'<title>(?P<content>.+?)</title>'
            ), webpage, 'title', default=None, group='content')
            description = description or self._html_search_meta(
                ['description', 'og:description', 'twitter:description'],
                webpage, 'description', default=None)
            uploader = uploader_data.get('name') or (
                clean_html(get_element_by_id('fbPhotoPageAuthorName', webpage))
                or self._search_regex(
                    (r'ownerName\s*:\s*"([^"]+)"', *self._og_regexes('title')), webpage, 'uploader', fatal=False))

            timestamp = int_or_none(self._search_regex(
                r'<abbr[^>]+data-utime=["\'](\d+)', webpage,
                'timestamp', default=None))