Skip to content

Instantly share code, notes, and snippets.

@mikeri
Created June 7, 2026 09:49
Show Gist options
  • Select an option

  • Save mikeri/e098e257aad2f8abc5b653a790a8e6e9 to your computer and use it in GitHub Desktop.

Select an option

Save mikeri/e098e257aad2f8abc5b653a790a8e6e9 to your computer and use it in GitHub Desktop.
Youtube AI summary
// ==UserScript==
// @name YouTube AI Summary (Open WebUI)
// @namespace https://mikeri.net/youtube-summary
// @version 1.0.0
// @description Summarize the current YouTube video with an OpenAI-compatible API (Open WebUI). Adds a "Summary" button between Thanks and the ⋯ menu, and shows the result in the sidebar above the suggestions.
// @match https://www.youtube.com/watch*
// @run-at document-idle
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @connect *
// ==/UserScript==
(function () {
'use strict';
/* ------------------------------------------------------------------ *
* Configuration *
* ------------------------------------------------------------------ */
const CFG = {
baseUrl: () => GM_getValue('baseUrl', ''), // e.g. https://owui.example.com
apiKey: () => GM_getValue('apiKey', ''), // Open WebUI API key
model: () => GM_getValue('model', 'gpt-4o-mini'), // model id available in your Open WebUI
prompt: () => GM_getValue('prompt', DEFAULT_PROMPT),
};
const DEFAULT_PROMPT =
'You are a concise assistant that summarizes YouTube videos. You are given the ' +
'video title and its transcript.\n\n' +
'FIRST, judge whether the title is clickbait — i.e. it poses a question, teases a ' +
'result, withholds a key fact, or uses hype ("you won\'t believe…", "the REAL reason…", ' +
'"I tried X for 30 days") to make people watch.\n\n' +
'If the title IS clickbait: your very first line must be a **bold spoiler** that directly ' +
'answers the question or reveals the withheld payoff in one sentence — get to the point ' +
'before anything else. Prefix it with "**Spoiler:** ". Then add the summary below it.\n\n' +
'If the title is NOT clickbait: skip the spoiler line and just summarize.\n\n' +
'For the summary: a one-sentence TL;DR, then 4-8 bullet points of the key ideas, then any ' +
'concrete takeaways or conclusions. Use Markdown.';
// Max characters of transcript sent to the model (keeps within context limits).
const MAX_TRANSCRIPT_CHARS = 48000;
function configure() {
const baseUrl = prompt('Open WebUI base URL (e.g. https://owui.example.com):', CFG.baseUrl());
if (baseUrl !== null) GM_setValue('baseUrl', baseUrl.trim().replace(/\/+$/, ''));
const apiKey = prompt('Open WebUI API key:', CFG.apiKey());
if (apiKey !== null) GM_setValue('apiKey', apiKey.trim());
const model = prompt('Model id:', CFG.model());
if (model !== null) GM_setValue('model', model.trim());
alert('YouTube AI Summary configured.');
}
GM_registerMenuCommand('Configure YouTube AI Summary', configure);
/* ------------------------------------------------------------------ *
* Transcript retrieval *
* ------------------------------------------------------------------ */
function currentVideoId() {
return new URLSearchParams(location.search).get('v');
}
function gmFetch(url, opts = {}) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: opts.method || 'GET',
url,
headers: opts.headers || {},
data: opts.data,
onload: (r) => resolve(r),
onerror: (e) => reject(new Error('Network error: ' + (e && e.error))),
ontimeout: () => reject(new Error('Request timed out')),
timeout: opts.timeout || 60000,
});
});
}
// Same-origin fetch for youtube.com resources. Unlike GM_xmlhttpRequest these
// show up in the page's Network tab and send the page's cookies.
async function pageFetch(url) {
const res = await fetch(url, { credentials: 'include' });
const text = await res.text();
return { status: res.status, text };
}
// Extract a top-level JSON object that follows `marker` in `text`, by balancing
// braces (robust against the many `};` sequences inside YouTube's blob — a
// non-greedy regex stops at the wrong one).
function extractJsonAfter(text, marker) {
const i = text.indexOf(marker);
if (i === -1) return null;
const start = text.indexOf('{', i);
if (start === -1) return null;
let depth = 0, inStr = false, esc = false;
for (let j = start; j < text.length; j++) {
const c = text[j];
if (inStr) {
if (esc) esc = false;
else if (c === '\\') esc = true;
else if (c === '"') inStr = false;
} else if (c === '"') inStr = true;
else if (c === '{') depth++;
else if (c === '}') {
if (--depth === 0) return text.slice(start, j + 1);
}
}
return null;
}
// Fetch the watch page once and return both the parsed player response and the
// raw HTML (the HTML also carries the InnerTube transcript params + api key).
// Refetching per-summary keeps us correct across YouTube's SPA navigation.
async function getWatchPage(videoId) {
const res = await pageFetch('https://www.youtube.com/watch?v=' + encodeURIComponent(videoId));
if (res.status < 200 || res.status >= 300) {
throw new Error('Could not load video page (HTTP ' + res.status + ')');
}
const blob = extractJsonAfter(res.text, 'ytInitialPlayerResponse');
let player = {};
if (blob) {
try {
player = JSON.parse(blob);
} catch (e) {
console.error('[YT AI Summary] player JSON parse failed:', blob.slice(0, 200));
}
}
return { player, html: res.text };
}
// Decode a JSON string body (handles \uXXXX escapes) captured from raw HTML.
function decodeJsonString(raw) {
try {
return JSON.parse('"' + raw + '"');
} catch (e) {
return raw;
}
}
// Recursively collect transcript segment text from a get_transcript response.
function collectTranscriptSegments(obj, out) {
if (!obj || typeof obj !== 'object') return;
if (Array.isArray(obj)) {
for (const x of obj) collectTranscriptSegments(x, out);
return;
}
const snippet = obj.transcriptSegmentRenderer?.snippet || obj.transcriptCueRenderer?.cue;
if (snippet) {
const txt = (snippet.runs || []).map((r) => r.text).join('') || snippet.simpleText || '';
if (txt) out.push(txt);
return;
}
for (const k in obj) collectTranscriptSegments(obj[k], out);
}
// Primary transcript path: YouTube's InnerTube get_transcript endpoint — the
// same call the "Show transcript" panel makes. Unlike the timedtext baseUrl it
// works with just the page cookies + params (no proof-of-origin token needed).
async function fetchTranscriptViaInnerTube(html) {
const pm = html.match(/"getTranscriptEndpoint":\{"params":"([^"]+)"/);
if (!pm) throw new Error('no transcript endpoint in page');
const params = decodeJsonString(pm[1]);
const apiKey = (html.match(/"INNERTUBE_API_KEY":"([^"]+)"/) || [])[1] || '';
const ver =
(html.match(/"INNERTUBE_CONTEXT_CLIENT_VERSION":"([^"]+)"/) || [])[1] ||
(html.match(/"clientVersion":"([\d.]+)"/) || [])[1] ||
'2.20240101.00.00';
const url =
'https://www.youtube.com/youtubei/v1/get_transcript' +
(apiKey ? '?key=' + apiKey : '');
const res = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
context: { client: { clientName: 'WEB', clientVersion: ver } },
params,
}),
});
const txt = await res.text();
console.log('[YT AI Summary] get_transcript:', {
status: res.status,
length: txt.length,
sample: txt.slice(0, 200),
});
if (res.status < 200 || res.status >= 300 || !txt.trim()) {
throw new Error('get_transcript HTTP ' + res.status);
}
const data = JSON.parse(txt);
const segs = [];
collectTranscriptSegments(data, segs);
const text = segs.join(' ').replace(/\s+/g, ' ').trim();
if (!text) throw new Error('get_transcript returned no segments');
console.log('[YT AI Summary] innertube transcript chars:', text.length);
return text;
}
function pickCaptionTrack(player) {
const tracks =
player?.captions?.playerCaptionsTracklistRenderer?.captionTracks || [];
if (!tracks.length) return null;
// Prefer a manual English track, then any English, then any non-ASR, then first.
const byLang = (t) => (t.languageCode || '').toLowerCase().startsWith('en');
return (
tracks.find((t) => byLang(t) && t.kind !== 'asr') ||
tracks.find((t) => byLang(t)) ||
tracks.find((t) => t.kind !== 'asr') ||
tracks[0]
);
}
async function fetchTranscriptText(track) {
const base = track.baseUrl;
const sep = base.includes('?') ? '&' : '?';
console.groupCollapsed('[YT AI Summary] caption fetch');
console.log('track:', { lang: track.languageCode, kind: track.kind, name: track.name?.simpleText });
console.log('baseUrl:', base);
// Preferred: json3 — clean, structured text without XML escaping headaches.
const j = await pageFetch(base + sep + 'fmt=json3');
console.log('json3:', { status: j.status, length: j.text.length, sample: j.text.slice(0, 200) });
if (j.status >= 200 && j.status < 300 && j.text.trim()) {
try {
const data = JSON.parse(j.text);
const text = (data.events || [])
.map((e) => (e.segs || []).map((s) => s.utf8).join(''))
.join(' ')
.replace(/\s+/g, ' ')
.trim();
if (text) {
console.log('json3 transcript chars:', text.length);
console.groupEnd();
return text;
}
} catch (e) {
console.warn('[YT AI Summary] json3 parse failed, trying XML:', e);
}
}
// Fallback: the default XML caption format. (json3 sometimes returns an
// empty body for certain videos / sessions.)
const x = await pageFetch(base);
console.log('xml:', { status: x.status, length: x.text.length, sample: x.text.slice(0, 200) });
console.groupEnd();
if (x.status < 200 || x.status >= 300 || !x.text.trim()) {
throw new Error('Captions endpoint returned no data');
}
const doc = new DOMParser().parseFromString(x.text, 'text/xml');
const text = Array.from(doc.getElementsByTagName('text'))
.map((n) => n.textContent)
.join(' ')
.replace(/\s+/g, ' ')
.trim();
if (!text) throw new Error('Could not read caption text');
return text;
}
async function getVideoContent(videoId) {
const { player, html } = await getWatchPage(videoId);
const details = player?.videoDetails || {};
const title = details.title || document.title.replace(/ - YouTube$/, '');
const author = details.author || '';
const allTracks =
player?.captions?.playerCaptionsTracklistRenderer?.captionTracks || [];
console.log('[YT AI Summary] video:', videoId, '| caption tracks found:', allTracks.length,
allTracks.map((t) => t.languageCode + (t.kind === 'asr' ? '(auto)' : '')));
let body;
// 1. Preferred: InnerTube get_transcript (works despite pot-token gating).
try {
body = await fetchTranscriptViaInnerTube(html);
} catch (e) {
console.warn('[YT AI Summary] InnerTube transcript failed:', e.message);
}
// 2. Fallback: the timedtext caption URL (json3/xml) — may be empty if pot-gated.
if (!body) {
const track = pickCaptionTrack(player);
if (track) {
try {
body = await fetchTranscriptText(track);
} catch (e) {
console.warn('[YT AI Summary] timedtext transcript failed:', e.message);
}
} else {
console.warn('[YT AI Summary] no caption tracks in player response');
}
}
if (!body) {
// Fall back to the description when no captions exist.
const desc = details.shortDescription || '';
if (!desc) throw new Error('This video has no captions and no description to summarize.');
body = '[No transcript available — summarizing the description]\n\n' + desc;
}
if (body.length > MAX_TRANSCRIPT_CHARS) {
body = body.slice(0, MAX_TRANSCRIPT_CHARS) + '\n\n[transcript truncated]';
}
return { title, author, body };
}
/* ------------------------------------------------------------------ *
* AI request *
* ------------------------------------------------------------------ */
async function requestSummary({ title, author, body }) {
const base = CFG.baseUrl();
const key = CFG.apiKey();
if (!base || !key) {
throw new Error('Not configured. Open the userscript menu → "Configure YouTube AI Summary".');
}
const userContent =
`Video title: ${title}\n` +
(author ? `Channel: ${author}\n` : '') +
`\nTranscript:\n${body}`;
const payload = {
model: CFG.model(),
stream: false,
messages: [
{ role: 'system', content: CFG.prompt() },
{ role: 'user', content: userContent },
],
};
const url = base + '/api/chat/completions';
const data = JSON.stringify(payload);
// Mask the key in logs but keep enough to confirm it's the right one.
const maskedKey = key.length > 8 ? key.slice(0, 4) + '…' + key.slice(-4) : '****';
console.groupCollapsed('[YT AI Summary] API request');
console.log('URL:', url);
console.log('Authorization:', 'Bearer ' + maskedKey);
console.log('model:', payload.model);
console.log('payload:', payload);
console.log('curl:',
`curl -sS ${JSON.stringify(url)} ` +
`-H ${JSON.stringify('Authorization: Bearer ' + key)} ` +
`-H ${JSON.stringify('Content-Type: application/json')} ` +
`-d ${JSON.stringify(data)}`);
console.groupEnd();
let res;
try {
res = await gmFetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + key,
},
data,
timeout: 120000,
});
} catch (e) {
console.error('[YT AI Summary] request failed (network/CORS):', e);
throw e;
}
console.groupCollapsed('[YT AI Summary] API response (HTTP ' + res.status + ')');
console.log('status:', res.status, res.statusText || '');
console.log('responseHeaders:', res.responseHeaders);
console.log('raw body:', res.responseText);
console.groupEnd();
if (res.status < 200 || res.status >= 300) {
throw new Error('API error (HTTP ' + res.status + '): ' + res.responseText.slice(0, 300));
}
let json;
try {
json = JSON.parse(res.responseText);
} catch (e) {
console.error('[YT AI Summary] could not parse response body:', res.responseText);
throw new Error('Could not parse API response.');
}
console.log('[YT AI Summary] parsed response:', json);
const content = json?.choices?.[0]?.message?.content;
if (!content) {
console.error('[YT AI Summary] no choices[0].message.content in:', json);
throw new Error('API returned no content.');
}
return content;
}
/* ------------------------------------------------------------------ *
* Tiny Markdown renderer (headings, bold, italics, lists, code) *
* *
* Builds real DOM nodes — never HTML strings — because YouTube's *
* Trusted Types CSP (require-trusted-types-for 'script') blocks *
* innerHTML assignments. *
* ------------------------------------------------------------------ */
// Turn one line of text into inline nodes (code / bold / italic / text).
function inlineNodes(text) {
const frag = document.createDocumentFragment();
const re = /(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)/g;
let last = 0;
let m;
while ((m = re.exec(text))) {
if (m.index > last) {
frag.appendChild(document.createTextNode(text.slice(last, m.index)));
}
const tok = m[0];
let el;
if (tok.startsWith('`')) {
el = document.createElement('code');
el.textContent = tok.slice(1, -1);
} else if (tok.startsWith('**')) {
el = document.createElement('strong');
el.textContent = tok.slice(2, -2);
} else {
el = document.createElement('em');
el.textContent = tok.slice(1, -1);
}
frag.appendChild(el);
last = m.index + tok.length;
}
if (last < text.length) {
frag.appendChild(document.createTextNode(text.slice(last)));
}
return frag;
}
function renderMarkdown(md) {
const frag = document.createDocumentFragment();
let ul = null;
for (const raw of md.split('\n')) {
const line = raw.trimEnd();
if (/^\s*[-*]\s+/.test(line)) {
if (!ul) {
ul = document.createElement('ul');
frag.appendChild(ul);
}
const li = document.createElement('li');
li.appendChild(inlineNodes(line.replace(/^\s*[-*]\s+/, '')));
ul.appendChild(li);
continue;
}
ul = null;
const h = line.match(/^(#{1,4})\s+(.*)$/);
if (h) {
const level = Math.min(6, h[1].length + 2); // map #→h3 so it fits the sidebar
const el = document.createElement('h' + level);
el.appendChild(inlineNodes(h[2]));
frag.appendChild(el);
} else if (line !== '') {
const p = document.createElement('p');
p.appendChild(inlineNodes(line));
frag.appendChild(p);
}
}
return frag;
}
/* ------------------------------------------------------------------ *
* Sidebar panel *
* ------------------------------------------------------------------ */
const PANEL_ID = 'yt-ai-summary-panel';
function ensurePanel() {
let panel = document.getElementById(PANEL_ID);
if (panel) return panel;
const secondary =
document.querySelector('#secondary #secondary-inner') ||
document.querySelector('#secondary-inner') ||
document.querySelector('#secondary');
if (!secondary) return null;
panel = document.createElement('div');
panel.id = PANEL_ID;
const header = document.createElement('div');
header.className = 'yas-header';
const title = document.createElement('span');
title.className = 'yas-title';
title.textContent = 'AI Summary';
const close = document.createElement('button');
close.className = 'yas-close';
close.title = 'Close';
close.textContent = '✕';
close.addEventListener('click', () => panel.remove());
header.appendChild(title);
header.appendChild(close);
const body = document.createElement('div');
body.className = 'yas-body';
panel.appendChild(header);
panel.appendChild(body);
// Insert above the suggestions / panels.
secondary.insertBefore(panel, secondary.firstChild);
return panel;
}
// `content` may be a plain string (set as text) or a DOM node / fragment.
function setPanelContent(content) {
const panel = ensurePanel();
if (!panel) return;
const body = panel.querySelector('.yas-body');
body.replaceChildren(
typeof content === 'string' ? document.createTextNode(content) : content
);
}
/* ------------------------------------------------------------------ *
* Action button *
* ------------------------------------------------------------------ */
const BTN_ID = 'yt-ai-summary-button';
let busy = false;
async function onSummaryClick() {
if (busy) return;
const videoId = currentVideoId();
if (!videoId) return;
busy = true;
const btn = document.getElementById(BTN_ID);
if (btn) btn.classList.add('yas-busy');
setPanelContent('Fetching transcript…');
try {
const content = await getVideoContent(videoId);
setPanelContent('Summarizing…');
const summary = await requestSummary(content);
setPanelContent(renderMarkdown(summary));
} catch (err) {
setPanelContent('⚠️ ' + (err && err.message ? err.message : String(err)));
} finally {
busy = false;
if (btn) btn.classList.remove('yas-busy');
}
}
function buildButton() {
const btn = document.createElement('button');
btn.id = BTN_ID;
btn.className = 'yas-action-button';
btn.title = 'Summarize this video with AI';
const svgNS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(svgNS, 'svg');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('width', '24');
svg.setAttribute('height', '24');
svg.setAttribute('aria-hidden', 'true');
const path = document.createElementNS(svgNS, 'path');
path.setAttribute('fill', 'currentColor');
path.setAttribute('d', 'M5 4h14v2H5V4zm0 4h14v2H5V8zm0 4h10v2H5v-2zm0 4h14v2H5v-2z');
svg.appendChild(path);
const label = document.createElement('span');
label.textContent = 'Summary';
btn.appendChild(svg);
btn.appendChild(label);
btn.addEventListener('click', onSummaryClick);
return btn;
}
// Insert the button between the last top-level action (Thanks) and the ⋯ menu.
function injectButton() {
if (document.getElementById(BTN_ID)) return true;
const menu = document.querySelector('ytd-watch-metadata #actions ytd-menu-renderer') ||
document.querySelector('ytd-watch-metadata ytd-menu-renderer');
if (!menu) return false;
const topLevel = menu.querySelector('#top-level-buttons-computed');
if (!topLevel) return false;
// The ⋯ "More actions" overflow button is a sibling of #top-level-buttons-computed
// inside the menu renderer. Appending here puts us after Thanks, before the ⋯.
topLevel.appendChild(buildButton());
return true;
}
/* ------------------------------------------------------------------ *
* Styles *
* ------------------------------------------------------------------ */
function injectStyles() {
if (document.getElementById('yas-styles')) return;
const style = document.createElement('style');
style.id = 'yas-styles';
// Explicit, theme-aware colors. YouTube sets the `dark` attribute on <html>
// in dark mode; the older --yt-spec-* tokens this build drops aren't relied on.
style.textContent = `
#${BTN_ID} {
display: inline-flex;
align-items: center;
gap: 6px;
height: 36px;
padding: 0 14px;
margin-left: 8px;
border: none;
border-radius: 18px;
background: rgba(0,0,0,0.05);
color: #0f0f0f;
font-family: "Roboto","Arial",sans-serif;
font-size: 14px;
font-weight: 500;
line-height: 36px;
cursor: pointer;
white-space: nowrap;
}
#${BTN_ID}:hover { background: rgba(0,0,0,0.1); }
#${BTN_ID} svg { display: block; flex: 0 0 auto; }
#${BTN_ID} span { display: inline-block; }
#${BTN_ID}.yas-busy { opacity: 0.6; pointer-events: none; }
#${BTN_ID}.yas-busy span::after { content: "…"; }
html[dark] #${BTN_ID} { background: rgba(255,255,255,0.1); color: #f1f1f1; }
html[dark] #${BTN_ID}:hover { background: rgba(255,255,255,0.2); }
#${PANEL_ID} {
margin-bottom: 16px;
padding: 12px 16px;
border: 1px solid rgba(0,0,0,0.1);
border-radius: 12px;
background: rgba(0,0,0,0.03);
color: #0f0f0f;
font-family: "Roboto","Arial",sans-serif;
font-size: 14px;
line-height: 1.5;
}
html[dark] #${PANEL_ID} {
border-color: rgba(255,255,255,0.15);
background: rgba(255,255,255,0.05);
color: #f1f1f1;
}
#${PANEL_ID} .yas-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
#${PANEL_ID} .yas-title { font-size: 16px; font-weight: 700; }
#${PANEL_ID} .yas-close {
border: none; background: transparent; cursor: pointer;
color: inherit; opacity: 0.7; font-size: 14px;
}
#${PANEL_ID} .yas-close:hover { opacity: 1; }
#${PANEL_ID} .yas-body h3,
#${PANEL_ID} .yas-body h4 { margin: 10px 0 4px; font-size: 15px; }
#${PANEL_ID} .yas-body p { margin: 6px 0; }
#${PANEL_ID} .yas-body ul { margin: 6px 0; padding-left: 20px; }
#${PANEL_ID} .yas-body li { margin: 3px 0; }
#${PANEL_ID} .yas-body code {
background: rgba(127,127,127,0.25);
padding: 1px 4px; border-radius: 4px; font-size: 13px;
}`;
document.head.appendChild(style);
}
/* ------------------------------------------------------------------ *
* Bootstrap + SPA navigation handling *
* ------------------------------------------------------------------ */
function tryInject() {
injectStyles();
injectButton();
}
// YouTube swaps content without full reloads; re-inject on navigation and
// whenever the action bar (re)renders.
function start() {
tryInject();
const observer = new MutationObserver(() => {
if (location.pathname === '/watch' && !document.getElementById(BTN_ID)) {
tryInject();
}
});
observer.observe(document.documentElement, { childList: true, subtree: true });
window.addEventListener('yt-navigate-finish', () => {
// New video → drop the old panel and re-add the button.
const panel = document.getElementById(PANEL_ID);
if (panel) panel.remove();
setTimeout(tryInject, 300);
});
}
start();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment