-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocial_video_extractor.py
More file actions
2503 lines (2180 loc) · 92.7 KB
/
Copy pathsocial_video_extractor.py
File metadata and controls
2503 lines (2180 loc) · 92.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import concurrent.futures
import contextlib
import datetime as dt
import html
import io
import json
import os
import re
import time as time_module
import urllib.parse
import wave
import xml.etree.ElementTree as ET
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Iterable
YOUTUBE_HOSTS = {
"youtube.com",
"www.youtube.com",
"m.youtube.com",
"music.youtube.com",
"youtu.be",
"www.youtu.be",
"youtube-nocookie.com",
"www.youtube-nocookie.com",
}
INSTAGRAM_HOSTS = {
"instagram.com",
"www.instagram.com",
"m.instagram.com",
}
class ExtractorError(RuntimeError):
pass
class URLValidationError(ValueError):
pass
class SilentYtdlpLogger:
def debug(self, message: str) -> None:
pass
def warning(self, message: str) -> None:
pass
def error(self, message: str) -> None:
pass
@dataclass
class TranscriptSegment:
start: float | None
duration: float | None
text: str
words: list[dict[str, Any]] | None = None
@dataclass
class TranscriptResult:
available: bool
text: str
segments: list[TranscriptSegment]
language: str | None
source: str | None
kind: str | None
note: str | None = None
engine: str | None = None
model: str | None = None
language_probability: float | None = None
audio_path: str | None = None
def detect_platform(url: str) -> str | None:
parsed = urllib.parse.urlparse(url)
host = parsed.netloc.lower().split("@")[-1].split(":")[0]
path = parsed.path.lower()
if host in YOUTUBE_HOSTS:
return "youtube"
if host in INSTAGRAM_HOSTS and re.search(r"/reels?/", path):
return "instagram_reel"
if host in INSTAGRAM_HOSTS and re.search(r"/p/", path):
return "instagram_post"
return None
def is_instagram_media(platform: str | None) -> bool:
return platform in {"instagram_reel", "instagram_post"}
def extract_youtube_video_id(url: str) -> str | None:
parsed = urllib.parse.urlparse(url)
host = parsed.netloc.lower().split(":")[0]
path_parts = [part for part in parsed.path.split("/") if part]
if host in {"youtu.be", "www.youtu.be"} and path_parts:
return path_parts[0]
query = urllib.parse.parse_qs(parsed.query)
if query.get("v"):
return query["v"][0]
if len(path_parts) >= 2 and path_parts[0] in {"embed", "shorts", "live"}:
return path_parts[1]
return None
def resolve_input_urls(args: argparse.Namespace) -> tuple[str, str]:
youtube_url = args.youtube_url
instagram_url = args.instagram_url
positional_urls = args.urls or []
if youtube_url or instagram_url:
if positional_urls:
raise URLValidationError("Use either named URL options or positional URLs, not both.")
if not youtube_url or not instagram_url:
raise URLValidationError("Both --youtube-url and --instagram-url are mandatory.")
else:
if len(positional_urls) != 2:
raise URLValidationError("Pass exactly two URLs: one YouTube URL and one Instagram media URL.")
platforms = {detect_platform(url): url for url in positional_urls}
youtube_url = platforms.get("youtube")
instagram_url = next((url for platform, url in platforms.items() if is_instagram_media(platform)), None)
if not youtube_url or not instagram_url:
raise URLValidationError("The two URLs must include one YouTube URL and one Instagram media URL.")
if detect_platform(youtube_url) != "youtube":
raise URLValidationError("--youtube-url must be a valid YouTube video URL.")
if not is_instagram_media(detect_platform(instagram_url)):
raise URLValidationError("--instagram-url must be a valid Instagram Reel or post URL.")
return youtube_url, instagram_url
def load_yt_dlp() -> Any:
try:
import yt_dlp # type: ignore
except ImportError as exc:
raise ExtractorError(
"Missing dependency: yt-dlp. Install dependencies with: pip install -r requirements.txt"
) from exc
return yt_dlp
def load_faster_whisper() -> Any:
try:
import faster_whisper # type: ignore
except ImportError as exc:
raise ExtractorError(
"Missing dependency: faster-whisper. Install dependencies with: pip install -r requirements.txt"
) from exc
return faster_whisper
def load_instaloader() -> Any:
try:
import instaloader # type: ignore
except ImportError as exc:
raise ExtractorError(
"Missing dependency: instaloader. Install dependencies with: pip install -r requirements.txt"
) from exc
return instaloader
def load_instagrapi() -> Any:
try:
import instagrapi # type: ignore
except ImportError as exc:
raise ExtractorError(
"Missing dependency: instagrapi. Install dependencies with: pip install -r requirements.txt"
) from exc
return instagrapi
def load_huggingface_hub() -> Any:
try:
import huggingface_hub # type: ignore
except ImportError as exc:
raise ExtractorError(
"Missing dependency: huggingface-hub. Install dependencies with: pip install -r requirements.txt"
) from exc
return huggingface_hub
def extract_info(
url: str,
*,
cookies: str | None,
cookies_from_browser: str | None,
fetch_comments: bool,
) -> dict[str, Any]:
yt_dlp = load_yt_dlp()
opts: dict[str, Any] = {
"quiet": True,
"no_warnings": True,
"logger": SilentYtdlpLogger(),
"skip_download": True,
"writesubtitles": True,
"writeautomaticsub": True,
"subtitleslangs": ["all"],
"socket_timeout": 30,
}
if cookies:
opts["cookiefile"] = cookies
if cookies_from_browser:
opts["cookiesfrombrowser"] = (cookies_from_browser,)
if fetch_comments:
opts["getcomments"] = True
with yt_dlp.YoutubeDL(opts) as ydl:
return ydl.extract_info(url, download=False)
def is_instagram_empty_media_error(exc: Exception) -> bool:
text = str(exc).lower()
return "instagram" in text and "empty media response" in text
def first_nested_url(value: Any) -> str | None:
if isinstance(value, str) and value.strip():
return value.strip()
if isinstance(value, dict):
url = value.get("url")
if isinstance(url, str) and url.strip():
return url.strip()
for child in value.values():
nested = first_nested_url(child)
if nested:
return nested
if isinstance(value, list):
for child in value:
nested = first_nested_url(child)
if nested:
return nested
return None
def timestamp_from_value(value: Any) -> int | None:
if isinstance(value, (int, float)):
return int(value)
if not isinstance(value, str) or not value.strip():
return None
text = value.strip().replace("Z", "+00:00")
try:
parsed = dt.datetime.fromisoformat(text)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=dt.timezone.utc)
return int(parsed.timestamp())
except ValueError:
return None
def instagram_fallback_info_from_supplement(url: str, supplement: dict[str, Any] | None) -> dict[str, Any]:
instagrapi = supplement_value(supplement, ["instagrapi"])
if not isinstance(instagrapi, dict) or not instagrapi.get("available"):
instagrapi = {}
media_info = instagrapi.get("media_info") if isinstance(instagrapi.get("media_info"), dict) else {}
user_info = instagrapi.get("user_info") if isinstance(instagrapi.get("user_info"), dict) else {}
media_user = media_info.get("user") if isinstance(media_info.get("user"), dict) else {}
shortcode = extract_instagram_shortcode(url)
direct_video_url = (
first_nested_url(media_info.get("video_url"))
or first_nested_url(media_info.get("video_versions"))
or first_nested_url(supplement_value(supplement, ["video_url"]))
)
thumbnail = (
first_nested_url(media_info.get("thumbnail_url"))
or first_nested_url(media_info.get("image_versions2"))
or first_nested_url(supplement_value(supplement, ["display_url"]))
)
caption = (
media_info.get("caption_text")
or supplement_value(supplement, ["caption"])
or media_info.get("title")
or supplement_value(supplement, ["title"])
)
username = user_info.get("username") or media_user.get("username") or supplement_value(supplement, ["owner_username"])
full_name = user_info.get("full_name") or media_user.get("full_name") or username
media_id = instagrapi.get("media_id") or media_info.get("id") or media_info.get("pk") or shortcode
duration = media_info.get("video_duration") or media_info.get("duration") or supplement_value(supplement, ["video_duration"])
timestamp = (
timestamp_from_value(media_info.get("taken_at"))
or timestamp_from_value(supplement_value(supplement, ["date_utc"]))
or timestamp_from_value(media_info.get("caption", {}).get("created_at_utc") if isinstance(media_info.get("caption"), dict) else None)
)
formats = []
if direct_video_url:
formats.append(
{
"format_id": "instagrapi_video",
"format_note": "Instagrapi direct video URL",
"url": direct_video_url,
"ext": "mp4",
"protocol": "https",
"width": media_info.get("width"),
"height": media_info.get("height"),
"vcodec": "unknown",
"acodec": "unknown",
}
)
return make_json_safe(
{
"id": str(media_id or shortcode or "instagram_media"),
"display_id": shortcode,
"extractor": "instagrapi_fallback",
"extractor_key": "Instagram",
"webpage_url": url,
"original_url": url,
"title": caption or f"Instagram media {shortcode or ''}".strip(),
"description": caption,
"uploader": full_name,
"uploader_id": user_info.get("pk") or media_user.get("pk") or supplement_value(supplement, ["owner_id"]),
"uploader_url": f"https://www.instagram.com/{username}/" if username else None,
"timestamp": timestamp,
"duration": duration,
"view_count": media_info.get("view_count") or media_info.get("play_count") or supplement_value(supplement, ["video_view_count"]),
"like_count": media_info.get("like_count") or supplement_value(supplement, ["likes"]),
"comment_count": media_info.get("comment_count") or supplement_value(supplement, ["comments"]),
"thumbnail": thumbnail,
"display_url": thumbnail,
"direct_media_url": direct_video_url,
"formats": formats,
"comments": [],
"availability": "authenticated_instagram_fallback",
}
)
def instagram_supplement_has_media(supplement: dict[str, Any] | None) -> bool:
return bool(
(
supplement_value(supplement, ["instagrapi", "available"])
and supplement_value(supplement, ["instagrapi", "media_info"])
)
or (supplement and supplement.get("available") and any(supplement.get(key) for key in ["video_url", "display_url", "caption", "mediaid"]))
)
def instagram_empty_media_message(supplement: dict[str, Any] | None = None) -> str:
instagrapi_error = supplement_value(supplement, ["instagrapi", "error"])
instaloader_error = supplement_value(supplement, ["error"])
details = []
if instagrapi_error:
details.append(f"Instagrapi error: {instagrapi_error}")
if instaloader_error:
details.append(f"Instaloader error: {instaloader_error}")
suffix = f" {' '.join(details)}" if details else ""
return (
"Instagram returned an empty media response to yt-dlp and no authenticated fallback produced media metadata. "
"Refresh the Instagrapi session/cookies and retry with an accessible public Reel/post."
f"{suffix}"
)
def download_audio_for_asr(
url: str,
*,
platform: str,
video_id: str | None,
cache_dir: Path,
cookies: str | None,
cookies_from_browser: str | None,
) -> Path:
yt_dlp = load_yt_dlp()
cache_dir.mkdir(parents=True, exist_ok=True)
safe_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", video_id or "media").strip("._") or "media"
output_template = str(cache_dir / f"{platform}_{safe_id}.%(ext)s")
opts: dict[str, Any] = {
"quiet": True,
"no_warnings": True,
"logger": SilentYtdlpLogger(),
"format": "bestaudio/best",
"outtmpl": output_template,
"noplaylist": True,
"socket_timeout": 30,
}
if cookies:
opts["cookiefile"] = cookies
if cookies_from_browser:
opts["cookiesfrombrowser"] = (cookies_from_browser,)
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=True)
candidates = downloaded_file_candidates(info, ydl)
for candidate in candidates:
path = Path(candidate)
if path.exists() and path.is_file():
return path
globbed = sorted(cache_dir.glob(f"{platform}_{safe_id}.*"), key=lambda item: item.stat().st_mtime, reverse=True)
for path in globbed:
if path.is_file():
return path
raise ExtractorError(f"Audio download completed, but no local media file was found for {url}")
def downloaded_file_candidates(info: dict[str, Any], ydl: Any) -> list[str]:
candidates: list[str] = []
for download in info.get("requested_downloads") or []:
if isinstance(download, dict):
for key in ["filepath", "filename", "__finaldir"]:
value = download.get(key)
if isinstance(value, str):
candidates.append(value)
for key in ["filepath", "_filename", "filename"]:
value = info.get(key)
if isinstance(value, str):
candidates.append(value)
try:
candidates.append(ydl.prepare_filename(info))
except Exception:
pass
return candidates
def instagram_sessionid_from_cookie_file(path: str | Path | None) -> str | None:
if not path:
return None
cookie_path = Path(path)
if not cookie_path.exists() or not cookie_path.is_file():
return None
try:
lines = cookie_path.read_text(encoding="utf-8", errors="replace").splitlines()
except OSError:
return None
for line in lines:
stripped = line.strip()
if not stripped or (stripped.startswith("#") and not stripped.startswith("#HttpOnly_")):
continue
if stripped.startswith("#HttpOnly_"):
stripped = stripped[len("#HttpOnly_") :]
parts = stripped.split("\t")
if len(parts) >= 7:
domain, _, _, _, _, name, value = parts[:7]
if "instagram.com" in domain and name == "sessionid" and value:
return value
elif "instagram.com" in stripped and "sessionid" in stripped:
match = re.search(r"(?:^|[;\s])sessionid=([^;\s]+)", stripped)
if match:
return match.group(1)
return None
def first_present(info: dict[str, Any], keys: list[str]) -> Any:
for key in keys:
value = info.get(key)
if value not in (None, "", [], {}):
return value
return None
def iso_upload_date(info: dict[str, Any]) -> str | None:
timestamp = info.get("timestamp") or info.get("release_timestamp") or info.get("modified_timestamp")
if timestamp:
try:
return dt.datetime.fromtimestamp(timestamp, tz=dt.timezone.utc).date().isoformat()
except (TypeError, ValueError, OSError):
pass
upload_date = info.get("upload_date") or info.get("release_date")
if isinstance(upload_date, str) and re.fullmatch(r"\d{8}", upload_date):
return f"{upload_date[:4]}-{upload_date[4:6]}-{upload_date[6:]}"
return None
def collect_hashtags(info: dict[str, Any]) -> list[str]:
tags = info.get("tags") or []
searchable_text = " ".join(
value
for value in [info.get("title"), info.get("fulltitle"), info.get("description")]
if isinstance(value, str)
)
hashtags: set[str] = set()
for tag in tags:
if not isinstance(tag, str):
continue
clean_tag = tag.strip().lstrip("#")
if clean_tag:
hashtags.add(clean_tag)
for match in re.findall(r"(?<!\w)#([\w.]+)", searchable_text, flags=re.UNICODE):
hashtags.add(match.strip("."))
return sorted(hashtags, key=str.lower)
def choose_caption_track(
info: dict[str, Any],
preferred_language: str,
) -> tuple[str, str, dict[str, Any]] | None:
for kind, captions in caption_groups(info):
if not isinstance(captions, dict) or not captions:
continue
language = choose_language(captions, preferred_language)
if not language:
continue
entries = captions.get(language) or []
if not isinstance(entries, list):
continue
entry = choose_caption_entry(entries)
if entry:
return kind, language, entry
return None
def caption_groups(info: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]:
return [
("manual", info.get("subtitles") or {}),
("automatic", info.get("automatic_captions") or {}),
]
def choose_language(captions: dict[str, Any], preferred_language: str) -> str | None:
languages = list(captions)
if preferred_language in captions:
return preferred_language
normalized = preferred_language.lower()
for language in languages:
if language.lower() == normalized or language.lower().startswith(f"{normalized}-"):
return language
for language in languages:
if normalized in language.lower():
return language
return languages[0] if languages else None
def caption_language_order(captions: dict[str, Any], preferred_language: str) -> list[str]:
languages = list(captions)
chosen = choose_language(captions, preferred_language)
ordered: list[str] = []
if chosen:
ordered.append(chosen)
normalized = preferred_language.lower()
for language in languages:
language_lower = language.lower()
if language not in ordered and (language_lower == normalized or language_lower.startswith(f"{normalized}-")):
ordered.append(language)
for language in languages:
if language not in ordered and not caption_entries_are_translated(captions.get(language) or []):
ordered.append(language)
for language in languages:
if language not in ordered:
ordered.append(language)
return ordered
def choose_caption_entry(entries: list[dict[str, Any]]) -> dict[str, Any] | None:
preferred_exts = ["json3", "vtt", "srt", "ttml", "srv3", "xml"]
for ext in preferred_exts:
for entry in entries:
if entry.get("url") and str(entry.get("ext", "")).lower() == ext:
return entry
for entry in entries:
if entry.get("url"):
return entry
return None
def caption_entry_candidates(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
preferred_exts = ["json3", "vtt", "srt", "ttml", "srv3", "xml"]
ordered: list[dict[str, Any]] = []
seen: set[str] = set()
def add(entry: dict[str, Any]) -> None:
url = entry.get("url")
if not isinstance(url, str) or not url or url in seen:
return
seen.add(url)
ordered.append(entry)
for ext in preferred_exts:
for entry in entries:
if str(entry.get("ext", "")).lower() == ext and not caption_url_is_translated(entry.get("url")):
add(entry)
for entry in entries:
if str(entry.get("ext", "")).lower() == ext:
add(entry)
for entry in entries:
add(entry)
return ordered
def caption_entries_are_translated(entries: list[dict[str, Any]]) -> bool:
usable = [entry for entry in entries if entry.get("url")]
return bool(usable) and all(caption_url_is_translated(entry.get("url")) for entry in usable)
def caption_url_is_translated(url: Any) -> bool:
if not isinstance(url, str):
return False
query = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
return bool(query.get("tlang"))
def raw_caption_entry_variant(entry: dict[str, Any]) -> dict[str, Any] | None:
url = entry.get("url")
if not caption_url_is_translated(url):
return None
parsed = urllib.parse.urlparse(str(url))
query = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
stripped_query = [(key, value) for key, value in query if key != "tlang"]
raw_url = urllib.parse.urlunparse(parsed._replace(query=urllib.parse.urlencode(stripped_query)))
if raw_url == url:
return None
raw_entry = dict(entry)
raw_entry["url"] = raw_url
return raw_entry
def transcript_track_candidates(info: dict[str, Any], preferred_language: str) -> list[tuple[str, str, dict[str, Any]]]:
candidates: list[tuple[str, str, dict[str, Any]]] = []
seen_urls: set[str] = set()
for kind, captions in caption_groups(info):
if not isinstance(captions, dict) or not captions:
continue
for language in caption_language_order(captions, preferred_language):
entries = captions.get(language) or []
if not isinstance(entries, list):
continue
for entry in caption_entry_candidates(entries):
raw_candidate = raw_caption_entry_variant(entry)
ordered_candidates = [raw_candidate, entry] if raw_candidate else [entry]
for candidate in ordered_candidates:
if not candidate:
continue
url = candidate.get("url")
if not isinstance(url, str) or not url or url in seen_urls:
continue
seen_urls.add(url)
candidates.append((kind, language, candidate))
return candidates
def fetch_caption_text(url: str) -> str:
try:
import requests # type: ignore
except ImportError as exc:
raise ExtractorError(
"Missing dependency: requests. Install dependencies with: pip install -r requirements.txt"
) from exc
response = requests.get(
url,
timeout=30,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
},
)
response.raise_for_status()
return response.text
def extract_transcript(info: dict[str, Any], preferred_language: str) -> TranscriptResult:
candidates = transcript_track_candidates(info, preferred_language)
if not candidates:
note = "No subtitle or caption track was exposed for this video."
if is_instagram_media(detect_platform(info.get("webpage_url") or "")):
note += " Instagram media often needs authenticated cookies and may not publish captions."
return TranscriptResult(False, "", [], None, None, None, note)
failures: list[str] = []
for kind, language, entry in candidates:
source_url = entry.get("url")
extension = str(entry.get("ext") or "").lower()
if not isinstance(source_url, str) or not source_url:
continue
try:
caption_text = fetch_caption_text(source_url)
segments = parse_caption(caption_text, extension)
except Exception as exc:
variant = "translated" if caption_url_is_translated(source_url) else "raw"
failures.append(f"{kind}/{language}/{variant}/{extension or 'unknown'}: {exc}")
continue
text = normalize_transcript_text(" ".join(segment.text for segment in segments))
if text:
return TranscriptResult(
True,
text,
segments,
language,
source_url,
kind,
None,
)
failures.append(f"{kind}/{language}/{extension or 'unknown'}: Caption track was empty.")
note = "Caption tracks were found but could not be read."
if failures:
note += " Tried: " + " | ".join(failures[:4])
if len(failures) > 4:
note += f" | plus {len(failures) - 4} more."
first_kind, first_language, first_entry = candidates[0]
return TranscriptResult(
False,
"",
[],
first_language,
first_entry.get("url"),
first_kind,
note,
)
def asr_transcript_is_suspicious(result: TranscriptResult, info: dict[str, Any]) -> bool:
if not result.available or result.kind != "asr":
return False
duration = info.get("duration")
if not isinstance(duration, (int, float)) or duration < 25:
return False
word_count = len(result.text.split())
min_words = max(12, int(float(duration) / 4))
return word_count < min_words
def suspicious_asr_result(result: TranscriptResult, info: dict[str, Any], original_note: str | None) -> TranscriptResult:
note = (
f"{original_note or 'No reliable platform transcript available'} "
f"ASR output looked suspiciously short for a {info.get('duration')} second video, so it was not indexed as reliable."
)
return TranscriptResult(
False,
"",
[],
result.language,
result.source,
result.kind,
note,
engine=result.engine,
model=result.model,
language_probability=result.language_probability,
audio_path=result.audio_path,
)
def resolve_transcript(
*,
info: dict[str, Any],
url: str,
platform: str,
preferred_caption_language: str,
transcribe_missing: bool,
asr_provider: str,
asr_model: str,
hf_asr_model: str,
hf_token: str | None,
asr_timeout_seconds: float,
asr_language: str | None,
asr_device: str,
asr_compute_type: str,
asr_cache_dir: Path,
keep_audio: bool,
cookies: str | None,
cookies_from_browser: str | None,
) -> TranscriptResult:
transcript = extract_transcript(info, preferred_caption_language)
if transcript.available or not transcribe_missing:
return transcript
original_note = transcript.note
audio_path: Path | None = None
asr_url = info.get("direct_media_url") if isinstance(info.get("direct_media_url"), str) else url
try:
audio_path = download_audio_for_asr(
asr_url,
platform=platform,
video_id=str(info.get("id") or ""),
cache_dir=asr_cache_dir,
cookies=cookies,
cookies_from_browser=cookies_from_browser,
)
asr_result = transcribe_audio(
audio_path,
provider=asr_provider,
model_name=asr_model,
hf_model=hf_asr_model,
hf_token=hf_token,
timeout_seconds=asr_timeout_seconds,
language=asr_language,
device=asr_device,
compute_type=asr_compute_type,
previous_note=original_note,
)
if asr_transcript_is_suspicious(asr_result, info):
selected_provider = choose_asr_provider(asr_provider, hf_token)
if selected_provider == "hf" and asr_provider != "hf":
try:
local_result = transcribe_audio(
audio_path,
provider="local",
model_name=asr_model,
hf_model=hf_asr_model,
hf_token=hf_token,
timeout_seconds=asr_timeout_seconds,
language=asr_language,
device=asr_device,
compute_type=asr_compute_type,
previous_note=f"{original_note or ''} Hosted ASR output looked suspiciously short; local ASR was retried.".strip(),
)
if not asr_transcript_is_suspicious(local_result, info):
return local_result
return suspicious_asr_result(local_result, info, original_note)
except Exception as local_exc:
asr_result.note = (
f"{asr_result.note or original_note or ''} Hosted ASR output looked suspiciously short; "
f"local ASR retry failed: {local_exc}"
).strip()
return suspicious_asr_result(asr_result, info, original_note)
return asr_result
except Exception as exc:
note = f"{original_note or 'No platform transcript available'} ASR fallback failed: {exc}"
return TranscriptResult(False, "", [], None, None, None, note)
finally:
if audio_path and not keep_audio:
try:
audio_path.unlink(missing_ok=True)
except OSError:
pass
def transcribe_audio(
audio_path: Path,
*,
provider: str,
model_name: str,
hf_model: str,
hf_token: str | None,
timeout_seconds: float,
language: str | None,
device: str,
compute_type: str,
previous_note: str | None,
) -> TranscriptResult:
selected_provider = choose_asr_provider(provider, hf_token)
if selected_provider == "hf":
try:
return transcribe_audio_with_hugging_face(
audio_path,
model_name=hf_model,
token=hf_token,
timeout_seconds=timeout_seconds,
previous_note=previous_note,
)
except Exception as exc:
if provider == "hf":
raise
previous_note = f"{previous_note or ''} Hosted ASR failed and local fallback was used: {exc}".strip()
return transcribe_audio_with_faster_whisper(
audio_path,
model_name=model_name,
language=language,
device=device,
compute_type=compute_type,
previous_note=previous_note,
)
def choose_asr_provider(provider: str, hf_token: str | None) -> str:
normalized = provider.lower()
if normalized not in {"auto", "local", "hf"}:
raise ExtractorError("--asr-provider must be one of: auto, local, hf")
if normalized == "auto":
return "hf" if hf_token else "local"
return normalized
def transcribe_audio_with_hugging_face(
audio_path: Path,
*,
model_name: str,
token: str | None,
timeout_seconds: float,
previous_note: str | None,
) -> TranscriptResult:
if not token:
raise ExtractorError("HF_TOKEN or --hf-token is required for --asr-provider hf.")
huggingface_hub = load_huggingface_hub()
wav_path = ensure_wav_for_hf(audio_path)
client = huggingface_hub.InferenceClient(
provider="hf-inference",
token=token,
timeout=timeout_seconds,
)
output = client.automatic_speech_recognition(str(wav_path), model=model_name)
payload = output.model_dump() if hasattr(output, "model_dump") else output
text = normalize_transcript_text(payload.get("text", "") if isinstance(payload, dict) else str(payload))
duration = audio_duration_seconds(wav_path)
segment = TranscriptSegment(start=0.0, duration=duration, text=text) if text else None
note = None
if previous_note:
note = f"Platform captions were unavailable; transcript generated with hosted ASR. {previous_note}"
return TranscriptResult(
bool(text),
text,
[segment] if segment else [],
None,
str(wav_path),
"asr",
note if text else "Hosted ASR ran but did not produce transcript text.",
engine="huggingface-inference",
model=model_name,
language_probability=None,
audio_path=str(audio_path),
)
def ensure_wav_for_hf(audio_path: Path) -> Path:
if audio_path.suffix.lower() == ".wav":
return audio_path
wav_path = audio_path.with_suffix(".wav")
if wav_path.exists() and wav_path.stat().st_mtime >= audio_path.stat().st_mtime:
return wav_path
try:
import av # type: ignore
except ImportError as exc:
raise ExtractorError("PyAV is required to convert media for hosted ASR.") from exc
container = av.open(str(audio_path))
stream = container.streams.audio[0]
resampler = av.audio.resampler.AudioResampler(format="s16", layout="mono", rate=16000)
with wave.open(str(wav_path), "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(16000)
for packet in container.demux(stream):
for frame in packet.decode():
for resampled in resampler.resample(frame):
wav_file.writeframes(resampled.to_ndarray().tobytes())
for resampled in resampler.resample(None):
wav_file.writeframes(resampled.to_ndarray().tobytes())
return wav_path
def audio_duration_seconds(audio_path: Path) -> float | None:
if audio_path.suffix.lower() == ".wav":
try:
with wave.open(str(audio_path), "rb") as wav_file:
return round(wav_file.getnframes() / float(wav_file.getframerate()), 3)
except Exception:
return None
return None
def transcribe_audio_with_faster_whisper(
audio_path: Path,
*,
model_name: str,
language: str | None,
device: str,
compute_type: str,
previous_note: str | None,
) -> TranscriptResult:
faster_whisper = load_faster_whisper()
model = faster_whisper.WhisperModel(model_name, device=device, compute_type=compute_type)
segments_iter, info = model.transcribe(
str(audio_path),
beam_size=5,
language=language,
vad_filter=True,
word_timestamps=True,
)
asr_segments = list(segments_iter)