Files
news-summary-bot/app/transcript.py
sm4640 dc4656e452
All checks were successful
news-summary-bot-cicd / build_push_deploy (push) Successful in 11m43s
Feat: [main] news-summary-bot 완성
2026-03-24 12:19:54 +09:00

56 lines
1.6 KiB
Python

import httpx
import yt_dlp
def extract_video_id(url: str) -> str:
"""YouTube URL에서 video ID 추출."""
if "youtu.be/" in url:
return url.split("youtu.be/")[1].split("?")[0]
if "v=" in url:
return url.split("v=")[1].split("&")[0]
raise ValueError(f"유효하지 않은 YouTube URL: {url}")
def fetch_transcript(video_id: str) -> str:
"""yt-dlp로 YouTube 자동생성 자막을 텍스트로 추출."""
url = f"https://www.youtube.com/watch?v={video_id}"
ydl_opts = {
"skip_download": True,
"writeautomaticsub": True,
"subtitleslangs": ["ko", "en"],
"subtitlesformat": "json3",
"quiet": True,
"no_warnings": True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
subs = info.get("automatic_captions", {})
lang = "ko" if "ko" in subs else "en" if "en" in subs else None
if not lang:
raise ValueError(f"자막을 찾을 수 없습니다: {video_id}")
sub_url = None
for fmt in subs[lang]:
if fmt["ext"] == "json3":
sub_url = fmt["url"]
break
if not sub_url:
raise ValueError(f"json3 자막 포맷을 찾을 수 없습니다: {video_id}")
resp = httpx.get(sub_url)
resp.raise_for_status()
data = resp.json()
texts = []
for event in data.get("events", []):
for seg in event.get("segs", []):
text = seg.get("utf8", "").strip()
if text and text != "\n":
texts.append(text)
return " ".join(texts)