Skip to content

Commit 3a98dc6

Browse files
fix(transcribe): serve real captions instead of canned demo text
YouTube timedtext is empty without a PO token; use the iOS Innertube player for signed captions, and fail closed on TikTok/podcasts until Whisper keys are set. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 49d42f5 commit 3a98dc6

12 files changed

Lines changed: 1012 additions & 272 deletions

File tree

‎backend/app/ai/transcriber.py‎

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,10 @@ async def transcribe_audio_file(self, audio_path: str, language: str = "en") ->
3939
except Exception as e:
4040
print(f"[Transcriber] OpenAI Whisper failed: {e}")
4141

42-
# 3. Fallback: Local Whisper CLI / Mock parser for testing environment
43-
return self._local_or_mock_transcribe(processed_path)
42+
raise RuntimeError(
43+
"No speech-to-text provider is configured. Set GROQ_API_KEY or OPENAI_API_KEY, "
44+
"or install a local Whisper runtime. Canned demo transcripts are disabled."
45+
)
4446

4547
def _preprocess_audio(self, input_path: str) -> str:
4648
"""Convert any audio/video file to 16kHz mono MP3 for high compression and Whisper compatibility."""
@@ -110,24 +112,8 @@ async def _transcribe_with_openai(self, audio_path: str, language: str) -> Tuple
110112
return full_text, segments
111113

112114
def _local_or_mock_transcribe(self, audio_path: str) -> Tuple[str, List[TranscriptSegment]]:
113-
"""Generate structured transcript if no external API key is active."""
114-
# Check audio length via ffprobe
115-
duration = 60.0
116-
try:
117-
probe = subprocess.run(
118-
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", audio_path],
119-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
120-
)
121-
duration = float(probe.stdout.strip())
122-
except Exception:
123-
duration = 60.0
124-
125-
sample_segments = [
126-
TranscriptSegment(start=0.0, end=min(15.0, duration), text="Welcome to this episode. Today we are breaking down multi-platform media intelligence and agentic workflows."),
127-
TranscriptSegment(start=min(15.0, duration), end=min(35.0, duration), text="We are exploring how automated transcript extraction and Model Context Protocol (MCP) transform unstructured audio into actionable knowledge."),
128-
TranscriptSegment(start=min(35.0, duration), end=duration, text="By indexing YouTube, TikTok, and podcasts natively, autonomous agents can search soundbites and reason over rich media in real-time.")
129-
]
130-
full_text = " ".join([s.text for s in sample_segments])
131-
return full_text, sample_segments
115+
raise RuntimeError(
116+
f"Refusing canned transcript for {audio_path}. Configure GROQ_API_KEY or OPENAI_API_KEY."
117+
)
132118

133119
transcriber = AudioTranscriber()

‎backend/app/parsers/youtube.py‎

Lines changed: 122 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import tempfile
44
import asyncio
55
from typing import Optional, List
6+
import httpx
67
import yt_dlp
78
from youtube_transcript_api import YouTubeTranscriptApi
89
from youtube_transcript_api._errors import TranscriptsDisabled, NoTranscriptFound, VideoUnavailable
@@ -12,6 +13,8 @@
1213
from app.ai.transcriber import transcriber
1314
from app.config import settings
1415

16+
IOS_PLAYER_UA = "com.google.ios.youtube/21.02.3 (iPhone16,2; U; CPU iOS 18_3_2 like Mac OS X;)"
17+
1518
YOUTUBE_REGEX = re.compile(
1619
r'(?:https?://)?(?:www\.|m\.|music\.)?(?:youtube\.com/(?:watch\?v=|embed/|v/|shorts/)|youtu\.be/)([\w-]{11})'
1720
)
@@ -68,8 +71,14 @@ async def extract_transcript(self, url: str, language: str = "en") -> Transcript
6871
raise ValueError(f"Invalid YouTube URL: {url}")
6972

7073
metadata_task = self.extract_metadata(url)
71-
72-
# 1. Try fast direct caption extraction via YouTubeTranscriptApi
74+
75+
ios_captions = await self._fetch_ios_captions(video_id, language)
76+
if ios_captions:
77+
metadata = await metadata_task
78+
raw_captions, lang = ios_captions
79+
return self._captions_to_response(raw_captions, lang, language, metadata)
80+
81+
# 1. Try youtube-transcript-api (often blocked without a PO token)
7382
def _get_yt_captions():
7483
try:
7584
ytt = YouTubeTranscriptApi()
@@ -105,37 +114,7 @@ def _get_yt_captions():
105114
metadata = await metadata_task
106115

107116
if raw_captions:
108-
segments: List[TranscriptSegment] = []
109-
text_parts = []
110-
for item in raw_captions:
111-
if isinstance(item, dict):
112-
start = float(item.get('start', 0.0))
113-
duration = float(item.get('duration', 0.0))
114-
text = str(item.get('text', '')).replace('\n', ' ').strip()
115-
else:
116-
start = float(getattr(item, 'start', 0.0))
117-
duration = float(getattr(item, 'duration', 0.0))
118-
text = str(getattr(item, 'text', '')).replace('\n', ' ').strip()
119-
120-
if text:
121-
segments.append(TranscriptSegment(
122-
start=round(start, 2),
123-
end=round(start + duration, 2),
124-
text=text
125-
))
126-
text_parts.append(text)
127-
128-
full_text = " ".join(text_parts)
129-
word_count = len(full_text.split())
130-
131-
return TranscriptResponse(
132-
metadata=metadata,
133-
language=lang or language,
134-
full_text=full_text,
135-
segments=segments,
136-
source_type="youtube_captions",
137-
word_count=word_count
138-
)
117+
return self._captions_to_response(raw_captions, lang, language, metadata)
139118

140119
# 2. Fallback: Download audio stream and transcribe via Whisper
141120
audio_path = await self._download_youtube_audio(video_id)
@@ -157,6 +136,116 @@ def _get_yt_captions():
157136
except Exception:
158137
pass
159138

139+
def _captions_to_response(self, raw_captions, lang, language, metadata) -> TranscriptResponse:
140+
segments: List[TranscriptSegment] = []
141+
text_parts = []
142+
for item in raw_captions:
143+
if isinstance(item, dict):
144+
start = float(item.get("start", 0.0))
145+
duration = float(item.get("duration", 0.0))
146+
text = str(item.get("text", "")).replace("\n", " ").strip()
147+
else:
148+
start = float(getattr(item, "start", 0.0))
149+
duration = float(getattr(item, "duration", 0.0))
150+
text = str(getattr(item, "text", "")).replace("\n", " ").strip()
151+
if text:
152+
segments.append(
153+
TranscriptSegment(
154+
start=round(start, 2),
155+
end=round(start + duration, 2),
156+
text=text,
157+
)
158+
)
159+
text_parts.append(text)
160+
161+
full_text = " ".join(text_parts)
162+
return TranscriptResponse(
163+
metadata=metadata,
164+
language=lang or language,
165+
full_text=full_text,
166+
segments=segments,
167+
source_type="youtube_captions",
168+
word_count=len(full_text.split()),
169+
)
170+
171+
async def _fetch_ios_captions(self, video_id: str, language: str):
172+
"""Fetch captions via the iOS Innertube player client (no PO token required)."""
173+
payload = {
174+
"context": {
175+
"client": {
176+
"clientName": "IOS",
177+
"clientVersion": "21.02.3",
178+
"deviceMake": "Apple",
179+
"deviceModel": "iPhone16,2",
180+
"osName": "iPhone",
181+
"osVersion": "18.3.2.22D82",
182+
"hl": "en",
183+
"gl": "US",
184+
}
185+
},
186+
"videoId": video_id,
187+
"contentCheckOk": True,
188+
"racyCheckOk": True,
189+
}
190+
headers = {
191+
"Content-Type": "application/json",
192+
"User-Agent": IOS_PLAYER_UA,
193+
"X-YouTube-Client-Name": "5",
194+
}
195+
try:
196+
async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client:
197+
player = await client.post(
198+
"https://www.youtube.com/youtubei/v1/player?prettyPrint=false",
199+
json=payload,
200+
headers=headers,
201+
)
202+
if player.status_code != 200:
203+
return None
204+
data = player.json()
205+
tracks = (
206+
data.get("captions", {})
207+
.get("playerCaptionsTracklistRenderer", {})
208+
.get("captionTracks", [])
209+
)
210+
if not tracks:
211+
return None
212+
wanted = (language or "en").lower()
213+
def score(t):
214+
lang = str(t.get("languageCode") or "").lower()
215+
n = 0
216+
if lang == wanted:
217+
n += 100
218+
elif lang.startswith(wanted):
219+
n += 80
220+
elif lang.startswith("en"):
221+
n += 20
222+
if t.get("kind") != "asr":
223+
n += 10
224+
return n
225+
track = sorted(tracks, key=score, reverse=True)[0]
226+
base = track.get("baseUrl")
227+
if not base:
228+
return None
229+
cap_url = base if "fmt=" in base else f"{base}&fmt=json3"
230+
cap = await client.get(cap_url, headers={"User-Agent": IOS_PLAYER_UA})
231+
if cap.status_code != 200 or not cap.content:
232+
return None
233+
events = cap.json().get("events") or []
234+
raw = []
235+
for ev in events:
236+
segs = ev.get("segs") or []
237+
text = " ".join(s.get("utf8") or "" for s in segs).replace("\n", " ").strip()
238+
if not text:
239+
continue
240+
start = (ev.get("tStartMs") or 0) / 1000.0
241+
dur = (ev.get("dDurationMs") or 2000) / 1000.0
242+
raw.append({"start": start, "duration": dur, "text": text})
243+
if not raw:
244+
return None
245+
return raw, track.get("languageCode") or language
246+
except Exception:
247+
return None
248+
160249
async def _download_youtube_audio(self, video_id: str) -> str:
161250
temp_out = tempfile.mktemp(suffix=".mp3", dir=settings.TEMP_STORAGE_DIR)
162251
ydl_opts = {

‎frontend/.env.example‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Optional FastAPI backend. When unset, /api/transcribe runs in this Next.js app.
2+
BACKEND_URL=
3+
4+
# Required for TikTok-without-captions, podcasts, and direct audio.
5+
GROQ_API_KEY=
6+
OPENAI_API_KEY=

0 commit comments

Comments
 (0)