Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: attach youtube transcripts from pasted chat links (#8648)

Maheswar Kumar6c5385a11f02
diff --git a/studio/backend/core/youtube_transcript.py b/studio/backend/core/youtube_transcript.py
new file mode 100644
index 00000000000..9ec5cd27d44
--- /dev/null
+++ b/studio/backend/core/youtube_transcript.py
@@ -0,0 +1,326 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Read a YouTube video's captions as plain text, with no third-party client.
+
+Two hops, both against youtube.com. ``POST /youtubei/v1/player`` with the ANDROID
+InnerTube client lists the caption tracks and the video metadata, then the chosen
+track's ``baseUrl`` is downloaded as ``fmt=json3`` and flattened.
+
+The ANDROID client matters. Caption URLs taken from the watch page's
+``ytInitialPlayerResponse`` belong to the WEB client, and YouTube now answers those
+with 200 and an empty body unless the request carries a proof-of-origin token, which
+only its BotGuard JS can mint. The ANDROID client's URLs still resolve unsigned.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass
+from typing import Any, Optional, Sequence
+from urllib.parse import SplitResult, parse_qs, urlencode, urljoin, urlsplit, urlunsplit
+
+import httpx
+
+_CLIENT_VERSION = "20.10.38"
+_CLIENT_NAME_ID = "3"
+_USER_AGENT = f"com.google.android.youtube/{_CLIENT_VERSION} (Linux; U; Android 11) gzip"
+_PLAYER_URL = "https://www.youtube.com/youtubei/v1/player?prettyPrint=false"
+
+_VIDEO_ID_RE = re.compile(r"[A-Za-z0-9_-]{11}")
+# www. is stripped before the lookup, so only the bare forms are listed.
+_WATCH_HOSTS = frozenset(
+ {"youtube.com", "m.youtube.com", "music.youtube.com", "youtube-nocookie.com"}
+)
+_SHORT_HOSTS = frozenset({"youtu.be"})
+_ID_PATH_PREFIXES = ("/shorts/", "/embed/", "/live/", "/v/")
+_CAPTION_HOSTS = frozenset({"youtube.com", "www.youtube.com"})
+
+_TIMEOUT = httpx.Timeout(20.0)
+# Captions are text; a 4 MB track is already an outlier for a very long video.
+_MAX_CAPTION_BYTES = 4 * 1024 * 1024
+_MAX_PLAYER_BYTES = 4 * 1024 * 1024
+# Roughly 25k tokens. A three hour video's captions run past 200k characters, which
+# would swallow the model's context window on its own.
+_MAX_TRANSCRIPT_CHARS = 100_000
+# Timedtext normally answers 200, but a hop is re-validated rather than refused.
+_MAX_CAPTION_REDIRECTS = 3
+
+
+class TranscriptUnavailable(Exception):
+ """YouTube answered, but the video has no caption track we can read."""
+
+
+@dataclass(frozen = True)
+class Transcript:
+ video_id: str
+ title: str
+ author: str
+ length_seconds: int
+ language: str
+ language_code: str
+ is_generated: bool
+ text: str
+ truncated: bool
+
+
+def extract_video_id(url: str) -> Optional[str]:
+ """Return the 11-character video id in a YouTube URL, or None if it is not one.
+
+ Accepts ``/watch?v=``, ``youtu.be/<id>``, ``/shorts/``, ``/embed/``, ``/live/``
+ and ``/v/`` on the youtube.com, youtu.be and youtube-nocookie.com hosts.
+ """
+ try:
+ parsed = urlsplit(url.strip())
+ except ValueError:
+ return None
+ if parsed.scheme not in ("http", "https"):
+ return None
+ host = (parsed.hostname or "").lower()
+ if host.startswith("www."):
+ host = host[4:]
+
+ candidate = ""
+ if host in _SHORT_HOSTS:
+ candidate = parsed.path.lstrip("/").split("/", 1)[0]
+ elif host not in _WATCH_HOSTS:
+ return None
+ elif parsed.path.rstrip("/") == "/watch":
+ candidate = (parse_qs(parsed.query).get("v") or [""])[0]
+ else:
+ for prefix in _ID_PATH_PREFIXES:
+ if parsed.path.startswith(prefix):
+ candidate = parsed.path[len(prefix) :].split("/", 1)[0]
+ break
+ return candidate if _VIDEO_ID_RE.fullmatch(candidate) else None
+
+
+def watch_url(video_id: str) -> str:
+ return f"https://www.youtube.com/watch?v={video_id}"
+
+
+async def fetch_transcript(video_id: str, languages: Sequence[str] = ()) -> Transcript:
+ """Download the captions for ``video_id``, preferring ``languages`` in order.
+
+ Within a language a human-written track wins over an auto-generated one. With no
+ match the track YouTube pairs with the video's default audio track is used.
+ """
+ if not _VIDEO_ID_RE.fullmatch(video_id):
+ raise TranscriptUnavailable("That is not a YouTube video link.")
+
+ async with httpx.AsyncClient(timeout = _TIMEOUT, follow_redirects = True) as client:
+ player = await _fetch_player(client, video_id)
+ status = (player.get("playabilityStatus") or {}).get("status")
+ if status not in (None, "OK"):
+ raise TranscriptUnavailable(
+ (player.get("playabilityStatus") or {}).get("reason")
+ or "YouTube will not play this video."
+ )
+
+ tracklist = (player.get("captions") or {}).get("playerCaptionsTracklistRenderer") or {}
+ tracks = [t for t in (tracklist.get("captionTracks") or []) if t.get("baseUrl")]
+ if not tracks:
+ raise TranscriptUnavailable("This video has no captions.")
+
+ track = _select_track(tracks, tracklist, languages)
+ text = await _fetch_track_text(client, str(track["baseUrl"]))
+
+ if not text:
+ raise TranscriptUnavailable("This video's captions are empty.")
+ text, truncated = _truncate_transcript(text)
+
+ details = player.get("videoDetails") or {}
+ return Transcript(
+ video_id = video_id,
+ title = str(details.get("title") or ""),
+ author = str(details.get("author") or ""),
+ length_seconds = _as_int(details.get("lengthSeconds")),
+ language = _track_label(track),
+ language_code = str(track.get("languageCode") or ""),
+ is_generated = track.get("kind") == "asr",
+ text = text,
+ truncated = truncated,
+ )
+
+
+def _truncate_transcript(text: str) -> tuple[str, bool]:
+ """Bound the transcript so a long video cannot swallow the model's context."""
+ if len(text) <= _MAX_TRANSCRIPT_CHARS:
+ return text, False
+ return text[:_MAX_TRANSCRIPT_CHARS].rsplit("\n", 1)[0].rstrip(), True
+
+
+async def _fetch_player(client: httpx.AsyncClient, video_id: str) -> dict[str, Any]:
+ async with client.stream(
+ "POST",
+ _PLAYER_URL,
+ headers = {
+ "Content-Type": "application/json",
+ "User-Agent": _USER_AGENT,
+ "X-YouTube-Client-Name": _CLIENT_NAME_ID,
+ "X-YouTube-Client-Version": _CLIENT_VERSION,
+ },
+ json = {
+ "context": {
+ "client": {
+ "clientName": "ANDROID",
+ "clientVersion": _CLIENT_VERSION,
+ "androidSdkVersion": 30,
+ "osName": "Android",
+ "osVersion": "11",
+ "hl": "en",
+ "gl": "US",
+ },
+ },
+ "videoId": video_id,
+ "contentCheckOk": True,
+ "racyCheckOk": True,
+ },
+ ) as response:
+ response.raise_for_status()
+ body = await _read_capped(
+ response, _MAX_PLAYER_BYTES, "YouTube returned an unexpectedly large response."
+ )
+ try:
+ player = json.loads(body.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError) as error:
+ raise TranscriptUnavailable("YouTube returned an unreadable response.") from error
+ if not isinstance(player, dict):
+ raise TranscriptUnavailable("YouTube returned an unreadable response.")
+ return player
+
+
+def _select_track(
+ tracks: list[dict[str, Any]], tracklist: dict[str, Any], languages: Sequence[str]
+) -> dict[str, Any]:
+ for language in languages:
+ wanted = str(language).strip().lower()
+ if not wanted:
+ continue
+ base = wanted.split("-")[0]
+ for want_generated in (False, True):
+ candidates = [t for t in tracks if (t.get("kind") == "asr") is want_generated]
+ # exact locale before the base-language fallback: a pt-BR request must not
+ # take a pt-PT track just because it is listed first
+ for matches_wanted in (
+ lambda code: code == wanted,
+ lambda code: code.split("-")[0] == base,
+ ):
+ for track in candidates:
+ if matches_wanted(str(track.get("languageCode") or "").lower()):
+ return track
+ return tracks[_default_track_index(tracks, tracklist)]
+
+
+def _default_track_index(tracks: list[dict[str, Any]], tracklist: dict[str, Any]) -> int:
+ """Index of the caption track paired with the video's default audio track.
+
+ A multi-language video lists its tracks alphabetically, so track 0 is often an
+ unrelated translation rather than the language actually spoken.
+ """
+ audio_tracks = tracklist.get("audioTracks") or []
+ audio_index = tracklist.get("defaultAudioTrackIndex")
+ if isinstance(audio_index, int) and 0 <= audio_index < len(audio_tracks):
+ caption_index = (audio_tracks[audio_index] or {}).get("defaultCaptionTrackIndex")
+ if isinstance(caption_index, int) and 0 <= caption_index < len(tracks):
+ return caption_index
+ return 0
+
+
+def _validated_caption_url(url: str) -> SplitResult:
+ parsed = urlsplit(url)
+ if parsed.scheme != "https" or (parsed.hostname or "").lower() not in _CAPTION_HOSTS:
+ raise TranscriptUnavailable("YouTube returned a caption URL from an unexpected host.")
+ return parsed
+
+
+def _caption_url(base_url: str) -> str:
+ """Ask a caption baseUrl for json3, keeping the blank-valued params YouTube sends."""
+ parsed = _validated_caption_url(base_url)
+ query = parse_qs(parsed.query, keep_blank_values = True)
+ query["fmt"] = ["json3"]
+ return urlunsplit(parsed._replace(query = urlencode(query, doseq = True)))
+
+
+async def _read_capped(response: httpx.Response, limit: int, message: str) -> bytes:
+ body = bytearray()
+ async for chunk in response.aiter_bytes():
+ body.extend(chunk)
+ if len(body) > limit:
+ raise TranscriptUnavailable(message)
+ return bytes(body)
+
+
+async def _fetch_track_text(client: httpx.AsyncClient, base_url: str) -> str:
+ url = _caption_url(base_url)
+
+ body = b""
+ for _ in range(_MAX_CAPTION_REDIRECTS + 1):
+ # Redirects are followed by hand so the host allowlist covers every hop, not
+ # just the URL the player response handed us.
+ async with client.stream(
+ "GET", url, headers = {"User-Agent": _USER_AGENT}, follow_redirects = False
+ ) as response:
+ location = response.headers.get("location")
+ if response.is_redirect and location:
+ url = urljoin(url, location)
+ _validated_caption_url(url)
+ continue
+ response.raise_for_status()
+ body = await _read_capped(
+ response, _MAX_CAPTION_BYTES, "This video's captions are too large to attach."
+ )
+ break
+ else:
+ raise TranscriptUnavailable("YouTube redirected the caption request too many times.")
+ if not body:
+ raise TranscriptUnavailable("YouTube returned no caption text for this video.")
+
+ try:
+ payload = json.loads(body.decode("utf-8"))
+ except (UnicodeDecodeError, ValueError) as error:
+ raise TranscriptUnavailable("YouTube returned unreadable caption data.") from error
+ events = payload.get("events") if isinstance(payload, dict) else None
+ return _flatten_events(events or [])
+
+
+def _flatten_events(events: list[Any]) -> str:
+ lines: list[str] = []
+ for event in events:
+ if not isinstance(event, dict):
+ continue
+ # aAppend cues carry only the rolling-window newline between ASR lines.
+ if event.get("aAppend") == 1:
+ continue
+ segments = event.get("segs")
+ if not isinstance(segments, list):
+ continue
+ joined = "".join(
+ str(segment.get("utf8") or "") for segment in segments if isinstance(segment, dict)
+ )
+ line = " ".join(joined.split())
+ if line:
+ lines.append(line)
+ return "\n".join(lines)
+
+
+def _track_label(track: dict[str, Any]) -> str:
+ name = track.get("name")
+ if isinstance(name, dict):
+ simple = name.get("simpleText")
+ if isinstance(simple, str) and simple:
+ return simple
+ runs = name.get("runs")
+ if isinstance(runs, list):
+ label = "".join(str(run.get("text") or "") for run in runs if isinstance(run, dict))
+ if label:
+ return label
+ return str(track.get("languageCode") or "")
+
+
+def _as_int(value: Any) -> int:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return 0
diff --git a/studio/backend/main.py b/studio/backend/main.py
index b28d772476a..354680b8024 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -306,6 +306,7 @@ from routes import (
training_history_router,
training_router,
video_router,
+ youtube_router,
)
from routes.llama import router as llama_router
from routes.whisper import router as whisper_router
@@ -1376,6 +1377,7 @@ app.include_router(hub_inventory_router, prefix = "/api/hub", tags = ["hub"])
app.include_router(hub_datasets_router, prefix = "/api/hub/datasets", tags = ["hub"])
app.include_router(picker_templates_router, prefix = "/api/picker", tags = ["picker"])
app.include_router(hub_token_router, prefix = "/api/hub", tags = ["hub"])
+app.include_router(youtube_router, prefix = "/api/youtube", tags = ["youtube"])
# Re-wrap /v1/* client errors into OpenAI/Anthropic envelopes; non-/v1 keeps {"detail": ...}.
install_api_error_handlers(app)
diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.py
index c48b715af08..c15e5ab7c65 100644
--- a/studio/backend/routes/__init__.py
+++ b/studio/backend/routes/__init__.py
@@ -22,6 +22,7 @@ from routes.openai_codex_auth import router as openai_codex_auth_router
from routes.mcp_servers import router as mcp_servers_router
from routes.rag import router as rag_router
from routes.research_runs import router as research_runs_router
+from routes.youtube import router as youtube_router
__all__ = [
"training_router",
@@ -40,7 +41,8 @@ __all__ = [
"mcp_servers_router",
"rag_router",
"research_runs_router",
+ "youtube_router",
]
# Bind the re-export so the import-hoist verifier counts it as used.
-_ = (rag_router, video_router, research_runs_router)
+_ = (rag_router, video_router, research_runs_router, youtube_router)
diff --git a/studio/backend/routes/youtube.py b/studio/backend/routes/youtube.py
new file mode 100644
index 00000000000..470e2b09044
--- /dev/null
+++ b/studio/backend/routes/youtube.py
@@ -0,0 +1,81 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""API route backing the composer's "attach transcript" prompt for pasted YouTube links."""
+
+from __future__ import annotations
+
+from typing import Annotated
+
+import httpx
+from fastapi import APIRouter, Depends, HTTPException
+from pydantic import BaseModel, Field
+
+from auth.authentication import get_current_subject
+from core.youtube_transcript import (
+ TranscriptUnavailable,
+ extract_video_id,
+ fetch_transcript,
+ watch_url,
+)
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+router = APIRouter()
+
+
+class TranscriptRequest(BaseModel):
+ url: str = Field(max_length = 2048)
+ # Caption languages to prefer, best first. The UI forwards navigator.languages, so the
+ # per-tag cap has to clear a fully extended BCP 47 tag rather than reject the request.
+ languages: list[Annotated[str, Field(max_length = 64)]] = Field(
+ default_factory = list,
+ max_length = 8,
+ )
+
+
+class TranscriptResponse(BaseModel):
+ videoId: str
+ url: str
+ title: str
+ author: str
+ lengthSeconds: int
+ language: str
+ languageCode: str
+ isGenerated: bool
+ text: str
+ truncated: bool
+
+
[email protected]("/transcript", response_model = TranscriptResponse)
+async def get_transcript(
+ request: TranscriptRequest, current_subject: str = Depends(get_current_subject)
+) -> TranscriptResponse:
+ video_id = extract_video_id(request.url)
+ if video_id is None:
+ raise HTTPException(status_code = 400, detail = "That is not a YouTube video link.")
+
+ try:
+ transcript = await fetch_transcript(video_id, request.languages)
+ except TranscriptUnavailable as error:
+ raise HTTPException(status_code = 422, detail = str(error)) from error
+ except httpx.HTTPError as error:
+ logger.warning(f"YouTube transcript fetch failed for {video_id}: {error}")
+ raise HTTPException(
+ status_code = 502,
+ detail = "Could not reach YouTube.",
+ ) from error
+
+ return TranscriptResponse(
+ videoId = transcript.video_id,
+ url = watch_url(transcript.video_id),
+ title = transcript.title,
+ author = transcript.author,
+ lengthSeconds = transcript.length_seconds,
+ language = transcript.language,
+ languageCode = transcript.language_code,
+ isGenerated = transcript.is_generated,
+ text = transcript.text,
+ truncated = transcript.truncated,
+ )
diff --git a/studio/backend/tests/test_youtube_transcript.py b/studio/backend/tests/test_youtube_transcript.py
new file mode 100644
index 00000000000..f4e0b6588a2
--- /dev/null
+++ b/studio/backend/tests/test_youtube_transcript.py
@@ -0,0 +1,235 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for ``core.youtube_transcript``, which backs the composer's transcript offer.
+
+Covers the parts that decide what the model ends up reading: which URLs count as
+YouTube videos, which caption track is picked when several languages exist, how json3
+cues flatten into text, and the bounds on the caption fetch itself. All offline; the
+caption hop runs against an httpx MockTransport rather than YouTube."""
+
+import asyncio
+import json
+
+import httpx
+import pytest
+
+from core.youtube_transcript import (
+ _MAX_CAPTION_BYTES,
+ _MAX_TRANSCRIPT_CHARS,
+ TranscriptUnavailable,
+ _caption_url,
+ _default_track_index,
+ _fetch_track_text,
+ _flatten_events,
+ _select_track,
+ _truncate_transcript,
+ extract_video_id,
+)
+
+VIDEO_ID = "dQw4w9WgXcQ"
+CAPTION_URL = f"https://www.youtube.com/api/timedtext?v={VIDEO_ID}&lang=en"
+
+
+ "url",
+ [
+ f"https://www.youtube.com/watch?v={VIDEO_ID}",
+ f"https://youtube.com/watch?v={VIDEO_ID}&t=42s",
+ f"https://m.youtube.com/watch?v={VIDEO_ID}",
+ f"https://music.youtube.com/watch?v={VIDEO_ID}",
+ f"https://youtu.be/{VIDEO_ID}",
+ f"https://youtu.be/{VIDEO_ID}?t=42",
+ f"https://www.youtube.com/shorts/{VIDEO_ID}",
+ f"https://www.youtube.com/embed/{VIDEO_ID}",
+ f"https://www.youtube.com/live/{VIDEO_ID}",
+ f"https://www.youtube-nocookie.com/embed/{VIDEO_ID}",
+ f" https://www.youtube.com/watch?v={VIDEO_ID} ",
+ ],
+)
+def test_extract_video_id_accepts_youtube_link_shapes(url):
+ assert extract_video_id(url) == VIDEO_ID
+
+
+ "url",
+ [
+ # A path segment must never stand in for the host, or the route would fetch
+ # a player response for a video id an arbitrary site chose.
+ f"https://evil.com/youtube.com/watch?v={VIDEO_ID}",
+ f"https://youtube.com.evil.com/watch?v={VIDEO_ID}",
+ f"https://notyoutube.com/watch?v={VIDEO_ID}",
+ f"javascript:alert(1)//youtube.com/watch?v={VIDEO_ID}",
+ f"file:///etc/passwd#{VIDEO_ID}",
+ "https://www.youtube.com/watch?v=short",
+ "https://www.youtube.com/watch",
+ "https://www.youtube.com/@somechannel",
+ "not a url",
+ "",
+ ],
+)
+def test_extract_video_id_rejects_non_video_urls(url):
+ assert extract_video_id(url) is None
+
+
+def _track(code, kind = None):
+ return {
+ "baseUrl": f"https://www.youtube.com/api/timedtext?lang={code}",
+ "languageCode": code,
+ "kind": kind,
+ }
+
+
+def test_select_track_prefers_requested_language_and_human_captions():
+ tracks = [_track("ar"), _track("en", "asr"), _track("en"), _track("fr")]
+ assert _select_track(tracks, {}, ["en"])["kind"] is None
+ assert _select_track(tracks, {}, ["fr"])["languageCode"] == "fr"
+ # A regional tag falls back to its base language rather than missing the track.
+ assert _select_track([_track("en-GB")], {}, ["en-US"])["languageCode"] == "en-GB"
+ # Only an auto-generated track in that language: take it rather than another language.
+ assert _select_track([_track("ar"), _track("de", "asr")], {}, ["de"])["languageCode"] == "de"
+
+
+def test_select_track_prefers_an_exact_locale_over_an_earlier_regional_sibling():
+ # pt-PT is listed first and shares the base language, so a positional scan would
+ # hand a Brazilian viewer the European Portuguese transcript.
+ tracks = [_track("pt-PT"), _track("pt-BR")]
+ assert _select_track(tracks, {}, ["pt-BR"])["languageCode"] == "pt-BR"
+ assert _select_track(tracks, {}, ["pt-PT"])["languageCode"] == "pt-PT"
+ # No exact match for the region: the base language still answers.
+ assert _select_track(tracks, {}, ["pt-AO"])["languageCode"] == "pt-PT"
+ # A human base-language track outranks an auto-generated exact match.
+ assert (
+ _select_track([_track("pt"), _track("pt-BR", "asr")], {}, ["pt-BR"])["languageCode"] == "pt"
+ )
+
+
+def test_select_track_falls_back_to_the_default_audio_track_language():
+ # Multi-language videos list captions alphabetically, so index 0 is usually a
+ # translation of a language nobody in the video is speaking.
+ tracks = [_track("ar"), _track("cs"), _track("en")]
+ tracklist = {
+ "audioTracks": [{"defaultCaptionTrackIndex": 2}],
+ "defaultAudioTrackIndex": 0,
+ }
+ assert _select_track(tracks, tracklist, [])["languageCode"] == "en"
+ assert _select_track(tracks, tracklist, [" "])["languageCode"] == "en"
+
+
+ "tracklist",
+ [
+ {},
+ {"audioTracks": [], "defaultAudioTrackIndex": 0},
+ {"audioTracks": [{"defaultCaptionTrackIndex": 9}], "defaultAudioTrackIndex": 0},
+ {"audioTracks": [{}], "defaultAudioTrackIndex": "0"},
+ ],
+)
+def test_default_track_index_is_zero_when_the_pairing_is_missing(tracklist):
+ assert _default_track_index([_track("en"), _track("fr")], tracklist) == 0
+
+
+def test_flatten_events_drops_rolling_window_padding():
+ events = [
+ {"tStartMs": 0, "dDurationMs": 1119069, "id": 1},
+ {"segs": [{"utf8": "[Music]"}]},
+ # ASR tracks separate cues with an aAppend newline that is not transcript text.
+ {"aAppend": 1, "segs": [{"utf8": "\n"}]},
+ {"segs": [{"utf8": "This"}, {"utf8": " is"}, {"utf8": " a\nthree."}]},
+ {"segs": [{"utf8": " "}]},
+ "not an event",
+ ]
+ assert _flatten_events(events) == "[Music]\nThis is a three."
+
+
+def test_flatten_events_handles_an_empty_track():
+ assert _flatten_events([]) == ""
+
+
+def test_caption_url_keeps_blank_valued_parameters():
+ # parse_qs drops blank values by default, which would silently strip any key=
+ # parameter YouTube signs the timedtext URL with.
+ url = _caption_url(
+ "https://www.youtube.com/api/timedtext"
+ f"?v={VIDEO_ID}&opi=&caps=&exp=xbt&signature=XYZ&lang=en"
+ )
+ query = url.split("?", 1)[1].split("&")
+ assert "opi=" in query
+ assert "caps=" in query
+ assert "signature=XYZ" in query
+ assert "fmt=json3" in query
+
+
+ "base_url",
+ [
+ f"http://www.youtube.com/api/timedtext?v={VIDEO_ID}",
+ f"https://evil.com/api/timedtext?v={VIDEO_ID}",
+ f"https://youtube.com.evil.com/api/timedtext?v={VIDEO_ID}",
+ f"https://169.254.169.254/api/timedtext?v={VIDEO_ID}",
+ ],
+)
+def test_caption_url_rejects_hosts_outside_the_allowlist(base_url):
+ with pytest.raises(TranscriptUnavailable):
+ _caption_url(base_url)
+
+
+def test_truncate_transcript_caps_a_long_video_on_a_line_boundary():
+ short = "one\ntwo\nthree"
+ assert _truncate_transcript(short) == (short, False)
+
+ text = "\n".join("a line of caption text" * 4 for _ in range(20_000))
+ capped, truncated = _truncate_transcript(text)
+ assert truncated is True
+ assert len(capped) <= _MAX_TRANSCRIPT_CHARS
+ assert text.startswith(capped)
+ # A cut mid-sentence would hand the model a mangled final line.
+ assert capped.endswith("a line of caption text")
+
+
+def _fetch_captions(handler):
+ async def run():
+ transport = httpx.MockTransport(handler)
+ async with httpx.AsyncClient(transport = transport, follow_redirects = True) as client:
+ return await _fetch_track_text(client, CAPTION_URL)
+
+ return asyncio.run(run())
+
+
+def test_fetch_track_text_refuses_a_redirect_off_the_allowlist():
+ # The client follows redirects for the player hop, so the caption hop has to
+ # re-check the host itself or a 302 would stream a loopback body back.
+ def handler(request):
+ return httpx.Response(302, headers = {"location": "http://169.254.169.254/latest/meta-data"})
+
+ with pytest.raises(TranscriptUnavailable, match = "unexpected host"):
+ _fetch_captions(handler)
+
+
+def test_fetch_track_text_follows_a_redirect_that_stays_on_youtube():
+ events = {"events": [{"segs": [{"utf8": "hello"}]}]}
+
+ def handler(request):
+ if request.url.path == "/api/timedtext":
+ return httpx.Response(302, headers = {"location": "/api/timedtext/v2?fmt=json3"})
+ return httpx.Response(200, json = events)
+
+ assert _fetch_captions(handler) == "hello"
+
+
+def test_fetch_track_text_stops_a_redirect_loop():
+ def handler(request):
+ return httpx.Response(302, headers = {"location": "https://www.youtube.com/api/timedtext"})
+
+ with pytest.raises(TranscriptUnavailable, match = "too many times"):
+ _fetch_captions(handler)
+
+
+def test_fetch_track_text_caps_an_oversized_caption_body():
+ body = json.dumps({"events": [{"segs": [{"utf8": "x" * (_MAX_CAPTION_BYTES + 1024)}]}]})
+
+ def handler(request):
+ return httpx.Response(200, content = body)
+
+ with pytest.raises(TranscriptUnavailable, match = "too large"):
+ _fetch_captions(handler)
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index e80ab355811..ce71f94a3fe 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -39,9 +39,11 @@ import {
attachmentsPastedText,
isPastedTextFile,
pasteClipboardFiles,
+ extractYoutubeVideoId,
pasteLongTextAsFile,
isStudioDictationAvailable,
notifyStudioDictationUnavailable,
+ YoutubeTranscriptPrompt,
} from "@/features/chat";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
import {
@@ -2112,8 +2114,14 @@ const Composer: FC<{
);
const { inputProps, isComposing, isComposingRef } =
useImeComposerInputHandlers({ submitOnEnter: true });
+ // A pasted YouTube link offers a transcript attachment above the composer.
+ const [youtubeLink, setYoutubeLink] = useState<string | null>(null);
const handleFilePaste = useCallback(
(event: ClipboardEvent<HTMLTextAreaElement>) => {
+ const pastedText = event.clipboardData?.getData("text/plain") ?? "";
+ if (extractYoutubeVideoId(pastedText)) {
+ setYoutubeLink(pastedText.trim());
+ }
// Bulk text pastes attach as a file instead of filling the input, except
// in image-edit mode, whose submit path takes an inline instruction only.
const input = event.currentTarget;
@@ -2160,6 +2168,12 @@ const Composer: FC<{
);
const composerText = useAuiState(({ composer }) => composer.text);
+ // Derived, not cleared in an effect: the offer retracts as soon as the link
+ // leaves the draft, which also covers sending.
+ const youtubeOfferUrl =
+ youtubeLink !== null && composerText.includes(youtubeLink)
+ ? youtubeLink
+ : null;
// Expand only once the input wraps to a second line, not on first keystroke.
// Latch until cleared so it can't flip-flop at the wrap boundary.
const inputRef = useRef<HTMLTextAreaElement>(null);
@@ -3783,6 +3797,16 @@ const Composer: FC<{
onSubmit={handleSubmit}
>
<PromptQueueStack queueThreadIds={promptQueueThreadIds} />
+ {youtubeOfferUrl && !isDictating && !disabled ? (
+ // Keyed by URL: pasting a second link while the first is still fetching
+ // remounts the prompt, so its cleanup aborts the request that is no
+ // longer the one on offer.
+ <YoutubeTranscriptPrompt
+ key={youtubeOfferUrl}
+ url={youtubeOfferUrl}
+ onClose={() => setYoutubeLink(null)}
+ />
+ ) : null}
{isTauri ? (
// Phase 1 native model owns Tauri local-path drops. Restore browser
// attachment drops in Tauri once Phase 1d adds token bridging.
diff --git a/studio/frontend/src/features/chat/api/youtube-api.ts b/studio/frontend/src/features/chat/api/youtube-api.ts
new file mode 100644
index 00000000000..5d4b82e8e40
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/youtube-api.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { formatFastApiDetail } from "@/lib/format-fastapi-error";
+
+export interface YoutubeTranscript {
+ videoId: string;
+ url: string;
+ title: string;
+ author: string;
+ lengthSeconds: number;
+ language: string;
+ languageCode: string;
+ isGenerated: boolean;
+ text: string;
+ truncated: boolean;
+}
+
+/** Fetch a video's captions as plain text. `languages` is preference order. */
+export async function fetchYoutubeTranscript(
+ url: string,
+ languages: string[],
+ signal?: AbortSignal,
+): Promise<YoutubeTranscript> {
+ const response = await authFetch("/api/youtube/transcript", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url, languages }),
+ signal,
+ });
+ const body = await response.json().catch(() => null);
+ if (!response.ok) {
+ const detail =
+ body && typeof body === "object"
+ ? formatFastApiDetail((body as { detail?: unknown }).detail)
+ : null;
+ throw new Error(
+ detail ?? `Could not fetch the transcript (${response.status})`,
+ );
+ }
+ return body as YoutubeTranscript;
+}
diff --git a/studio/frontend/src/features/chat/components/youtube-transcript-prompt.tsx b/studio/frontend/src/features/chat/components/youtube-transcript-prompt.tsx
new file mode 100644
index 00000000000..eb1cbf3fb97
--- /dev/null
+++ b/studio/frontend/src/features/chat/components/youtube-transcript-prompt.tsx
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
+import { getLocale } from "@/i18n";
+import { toast } from "@/lib/toast";
+import { useAui } from "@assistant-ui/react";
+import { YoutubeIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ type YoutubeTranscript,
+ fetchYoutubeTranscript,
+} from "../api/youtube-api";
+
+// The route caps the list at 8; the UI locale leads, then whatever the browser reports.
+function preferredCaptionLanguages(): string[] {
+ const tags = [getLocale(), ...(globalThis.navigator?.languages ?? []), "en"];
+ return [
+ ...new Set(tags.filter((tag) => typeof tag === "string" && tag)),
+ ].slice(0, 8);
+}
+
+function formatDuration(seconds: number): string {
+ const hours = Math.floor(seconds / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ const rest = seconds % 60;
+ const padded = `${minutes.toString().padStart(hours > 0 ? 2 : 1, "0")}:${rest
+ .toString()
+ .padStart(2, "0")}`;
+ return hours > 0 ? `${hours}:${padded}` : padded;
+}
+
+function transcriptFileName(transcript: YoutubeTranscript): string {
+ const cleaned = transcript.title
+ // \p{C} covers the control characters a path separator check would miss.
+ .replace(/[\p{C}\\/:*?"<>|]+/gu, " ")
+ .replace(/\s+/g, " ")
+ .trim()
+ .slice(0, 80)
+ .trim();
+ return `${cleaned || `youtube-${transcript.videoId}`} transcript.txt`;
+}
+
+function transcriptFileText(transcript: YoutubeTranscript): string {
+ const header = [
+ transcript.title ? `Title: ${transcript.title}` : null,
+ transcript.author ? `Channel: ${transcript.author}` : null,
+ transcript.lengthSeconds > 0
+ ? `Duration: ${formatDuration(transcript.lengthSeconds)}`
+ : null,
+ `URL: ${transcript.url}`,
+ transcript.language ? `Captions: ${transcript.language}` : null,
+ transcript.truncated
+ ? "Note: this transcript was truncated and stops before the video ends."
+ : null,
+ ].filter((line): line is string => line !== null);
+ return `${header.join("\n")}\n\n${transcript.text}\n`;
+}
+
+type Composer = ReturnType<ReturnType<typeof useAui>["composer"]>;
+
+async function detachFile(composer: Composer, file: File): Promise<void> {
+ const added = composer
+ .getState()
+ .attachments.find((attachment) => attachment.file === file);
+ if (added) await composer.attachment({ id: added.id }).remove();
+}
+
+/**
+ * Offer to turn a pasted YouTube link into a transcript attachment. Sits above the
+ * composer surface, matching the prompt-queue stack, and closes once the user picks.
+ */
+export function YoutubeTranscriptPrompt({
+ url,
+ onClose,
+}: {
+ url: string;
+ onClose: () => void;
+}) {
+ const aui = useAui();
+ const [fetching, setFetching] = useState(false);
+ const abortRef = useRef<AbortController | null>(null);
+
+ // A link removed from the draft unmounts this mid-fetch; drop the in-flight
+ // request so the attachment does not land in a composer that moved on.
+ useEffect(() => () => abortRef.current?.abort(), []);
+
+ const attach = useCallback(async () => {
+ if (fetching) return;
+ const controller = new AbortController();
+ abortRef.current = controller;
+ setFetching(true);
+ const composer = aui.composer();
+ try {
+ const transcript = await fetchYoutubeTranscript(
+ url,
+ preferredCaptionLanguages(),
+ controller.signal,
+ );
+ const file = new File(
+ [transcriptFileText(transcript)],
+ transcriptFileName(transcript),
+ { type: "text/plain" },
+ );
+ if (controller.signal.aborted) return;
+ await composer.addAttachment(file);
+ // A send lands while addAttachment is still pending, and abort cannot recall it,
+ // so drop the file rather than let it ride along on the next message.
+ if (controller.signal.aborted) {
+ await detachFile(composer, file);
+ return;
+ }
+ onClose();
+ } catch (error) {
+ if (controller.signal.aborted) return;
+ setFetching(false);
+ toast.error("Could not attach the transcript", {
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ }, [aui, fetching, onClose, url]);
+
+ return (
+ <div
+ className="relative z-0 mx-7 mb-[-8px] rounded-t-[18px] rounded-b-none border border-border/45 bg-background/90 px-5 py-2 text-muted-foreground shadow-none backdrop-blur-md dark:bg-card/85"
+ aria-label="Attach YouTube transcript"
+ >
+ <div className="grid h-10 grid-cols-[minmax(0,1fr)_auto] items-center gap-2.5">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <HugeiconsIcon
+ icon={YoutubeIcon}
+ strokeWidth={2}
+ className="size-4 shrink-0 text-muted-foreground/70"
+ />
+ <div className="truncate text-sm">
+ {fetching
+ ? "Fetching the transcript…"
+ : "Attach this video's transcript?"}
+ </div>
+ </div>
+ {fetching ? (
+ <Spinner className="size-4 justify-self-end text-muted-foreground/70" />
+ ) : (
+ <div className="flex items-center gap-1.5">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2 text-xs text-muted-foreground"
+ onClick={onClose}
+ >
+ Dismiss
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ onClick={() => void attach()}
+ >
+ Attach transcript
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index e88b7528249..080eb3959aa 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -145,6 +145,8 @@ export type { ProjectRecord } from "./types";
export { clearAllChats, countAllChats } from "./utils/clear-all-chats";
export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";
export { pasteClipboardFiles } from "./utils/clipboard-files";
+export { extractYoutubeVideoId } from "./utils/youtube-url";
+export { YoutubeTranscriptPrompt } from "./components/youtube-transcript-prompt";
export {
PASTED_TEXT_PREVIEW_MAX_CHARS,
attachmentContentText,
diff --git a/studio/frontend/src/features/chat/utils/youtube-url.ts b/studio/frontend/src/features/chat/utils/youtube-url.ts
new file mode 100644
index 00000000000..1ea93329407
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/youtube-url.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Mirrors extract_video_id in studio/backend/core/youtube_transcript.py. The
+// backend re-parses the URL, so this only decides whether to offer the prompt.
+
+const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
+// `www.` is stripped before the lookup, so only the bare forms are listed.
+const WATCH_HOSTS = new Set([
+ "youtube.com",
+ "m.youtube.com",
+ "music.youtube.com",
+ "youtube-nocookie.com",
+]);
+const SHORT_HOSTS = new Set(["youtu.be"]);
+const ID_PATH_PREFIXES = ["/shorts/", "/embed/", "/live/", "/v/"];
+
+/** The 11-character video id in a YouTube URL, or null if it is not one. */
+export function extractYoutubeVideoId(value: string): string | null {
+ const trimmed = value.trim();
+ if (trimmed.length === 0 || trimmed.length > 2048) return null;
+
+ let parsed: URL;
+ try {
+ parsed = new URL(trimmed);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
+
+ const host = parsed.hostname.toLowerCase().replace(/^www\./, "");
+ let candidate = "";
+ if (SHORT_HOSTS.has(host)) {
+ candidate = parsed.pathname.replace(/^\//, "").split("/", 1)[0] ?? "";
+ } else if (!WATCH_HOSTS.has(host)) {
+ return null;
+ } else if (parsed.pathname.replace(/\/+$/, "") === "/watch") {
+ candidate = parsed.searchParams.get("v") ?? "";
+ } else {
+ const prefix = ID_PATH_PREFIXES.find((p) => parsed.pathname.startsWith(p));
+ if (prefix) {
+ candidate = parsed.pathname.slice(prefix.length).split("/", 1)[0] ?? "";
+ }
+ }
+ return VIDEO_ID.test(candidate) ? candidate : null;
+}
diff --git a/studio/frontend/tests/youtube-url.test.ts b/studio/frontend/tests/youtube-url.test.ts
new file mode 100644
index 00000000000..006e73422b8
--- /dev/null
+++ b/studio/frontend/tests/youtube-url.test.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { extractYoutubeVideoId } from "../src/features/chat/utils/youtube-url.ts";
+
+const ID = "dQw4w9WgXcQ";
+
+test("recognises the YouTube link shapes the composer offer covers", () => {
+ for (const url of [
+ `https://www.youtube.com/watch?v=${ID}`,
+ `https://youtube.com/watch?v=${ID}&t=42s`,
+ `https://m.youtube.com/watch?v=${ID}`,
+ `https://music.youtube.com/watch?v=${ID}`,
+ `https://youtu.be/${ID}`,
+ `https://youtu.be/${ID}?t=42`,
+ `https://www.youtube.com/shorts/${ID}`,
+ `https://www.youtube.com/embed/${ID}`,
+ `https://www.youtube.com/live/${ID}`,
+ `https://www.youtube-nocookie.com/embed/${ID}`,
+ ` https://www.youtube.com/watch?v=${ID} `,
+ ]) {
+ assert.equal(extractYoutubeVideoId(url), ID, url);
+ }
+});
+
+test("rejects look-alike hosts and non-video URLs", () => {
+ for (const url of [
+ // A path segment must not stand in for the host, or any site could trigger the offer.
+ `https://evil.com/youtube.com/watch?v=${ID}`,
+ `https://youtube.com.evil.com/watch?v=${ID}`,
+ `https://notyoutube.com/watch?v=${ID}`,
+ `javascript:alert(1)//youtube.com/watch?v=${ID}`,
+ "https://www.youtube.com/watch?v=short",
+ "https://www.youtube.com/watch",
+ "https://www.youtube.com/@somechannel",
+ "https://www.youtube.com/results?search_query=cats",
+ "look at this video",
+ "",
+ ]) {
+ assert.equal(extractYoutubeVideoId(url), null, url);
+ }
+});