pi-yt-summarizer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 x0d7x
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # pi-yt-summarizer
2
+
3
+ A Pi coding agent extension that fetches YouTube video info, descriptions, and transcripts for summarization. Also generates video ideas on any topic.
4
+
5
+ ## Features
6
+
7
+ - **`summarize_youtube` tool** — LLM can automatically fetch video info when you share a YouTube link
8
+ - **`/yt <url>`** — Command to pre-fill editor with a summarization prompt
9
+ - **`/yt-ideas <topic>`** — Generate 5–10 YouTube video ideas on any topic
10
+
11
+ ## Requirements
12
+
13
+ - [yt-dlp](https://github.com/yt-dlp/yt-dlp) installed and in PATH
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ pi install npm:pi-yt-summarizer
19
+ # or
20
+ pi install git:github.com/x0d7x/pi-yt-summarizer
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```
26
+ # Ask the LLM directly:
27
+ Summarize https://www.youtube.com/watch?v=oL9neMViXAI
28
+
29
+ # Or use commands:
30
+ /yt https://www.youtube.com/watch?v=oL9neMViXAI
31
+ /yt-ideas linux distro review
32
+ ```
33
+
34
+ ## License
35
+
36
+ MIT
@@ -0,0 +1,233 @@
1
+ /**
2
+ * YouTube Video Summarizer Extension
3
+ *
4
+ * Fetches video info and transcript from a YouTube URL and returns it
5
+ * for summarization. Uses yt-dlp under the hood.
6
+ *
7
+ * Usage:
8
+ * - Ask the LLM: "Summarize https://youtube.com/watch?v=..."
9
+ * - Or run /yt <url>
10
+ * - Or run /yt-ideas <topic>
11
+ */
12
+
13
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
+ import { Type } from "typebox";
15
+ import { readFile, unlink } from "node:fs/promises";
16
+ import { existsSync } from "node:fs";
17
+
18
+ function formatDuration(ms: number): string {
19
+ const totalSec = Math.floor(ms / 1000);
20
+ const h = Math.floor(totalSec / 3600);
21
+ const m = Math.floor((totalSec % 3600) / 60);
22
+ const s = totalSec % 60;
23
+ if (h > 0) return `${h}h${m}m${s}s`;
24
+ if (m > 0) return `${m}m${s}s`;
25
+ return `${s}s`;
26
+ }
27
+
28
+ interface TranscriptEvent {
29
+ tStartMs?: number;
30
+ dDurationMs?: number;
31
+ segs?: Array<{ utf8?: string }>;
32
+ }
33
+
34
+ /** Parse yt-dlp json3 transcript and return clean text + structured segments */
35
+ async function parseTranscript(jsonPath: string): Promise<{
36
+ fullText: string;
37
+ segments: Array<{ time: string; text: string }>;
38
+ }> {
39
+ const raw = await readFile(jsonPath, "utf-8");
40
+ const data = JSON.parse(raw);
41
+ const events: TranscriptEvent[] = data.events ?? [];
42
+
43
+ const segments: Array<{ time: string; text: string }> = [];
44
+ const fullLines: string[] = [];
45
+
46
+ for (const ev of events) {
47
+ const segs = ev.segs ?? [];
48
+ const text = segs.map((s) => s.utf8 ?? "").join("").trim();
49
+ if (!text) continue;
50
+
51
+ const timeStr = ev.tStartMs !== undefined ? formatDuration(ev.tStartMs) : "";
52
+ segments.push({ time: timeStr, text });
53
+ fullLines.push(text);
54
+ }
55
+
56
+ return {
57
+ fullText: fullLines.join(" "),
58
+ segments,
59
+ };
60
+ }
61
+
62
+ function extractYouTubeId(url: string): string | null {
63
+ const patterns = [
64
+ /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/,
65
+ /^([a-zA-Z0-9_-]{11})$/,
66
+ ];
67
+ for (const p of patterns) {
68
+ const m = url.match(p);
69
+ if (m) return m[1];
70
+ }
71
+ return null;
72
+ }
73
+
74
+ export default function (pi: ExtensionAPI) {
75
+ // ── Custom tool ──────────────────────────────────────────────
76
+ pi.registerTool({
77
+ name: "summarize_youtube",
78
+ label: "YouTube Summarizer",
79
+ description: "Fetch video info, description, and transcript from a YouTube URL. Returns structured data for summarization.",
80
+ promptSnippet: "Summarize or fetch information from YouTube videos",
81
+ promptGuidelines: [
82
+ "Use summarize_youtube when the user shares a YouTube link and asks you to summarize, explain, or extract information from it.",
83
+ ],
84
+ parameters: Type.Object({
85
+ url: Type.String({ description: "YouTube video URL (e.g. https://youtube.com/watch?v=...)" }),
86
+ }),
87
+
88
+ async execute(_toolCallId, params, signal, _onUpdate, _ctx) {
89
+ const url = params.url.trim();
90
+ const videoId = extractYouTubeId(url);
91
+ if (!videoId) {
92
+ return {
93
+ content: [{ type: "text", text: `Invalid YouTube URL: ${url}` }],
94
+ details: { error: "Could not extract video ID" },
95
+ isError: true,
96
+ };
97
+ }
98
+
99
+ let infoResult: { stdout: string; stderr: string; code: number; killed?: boolean };
100
+ let transcriptPath = "";
101
+
102
+ try {
103
+ // 1. Get title & description
104
+ infoResult = await pi.exec("yt-dlp", [
105
+ "--print", "title",
106
+ "--print", "description",
107
+ "-s", url,
108
+ ], { signal });
109
+
110
+ const lines = infoResult.stdout.trim().split("\n");
111
+ const title = lines[0] ?? "Unknown";
112
+ const description = lines.slice(1).join("\n").trim();
113
+
114
+ // 2. Download auto-generated transcript (json3 format)
115
+ const ts = Date.now();
116
+ transcriptPath = `/tmp/pi_yt_${ts}`;
117
+ await pi.exec("yt-dlp", [
118
+ "--write-auto-subs", "--sub-langs", "en",
119
+ "--skip-download", "--sub-format", "json3",
120
+ "-o", transcriptPath, url,
121
+ ], { signal });
122
+
123
+ // 3. Parse transcript
124
+ const jsonPath = `${transcriptPath}.en.json3`;
125
+ let transcriptText = "(no transcript available)";
126
+ let segments: Array<{ time: string; text: string }> = [];
127
+
128
+ if (existsSync(jsonPath)) {
129
+ const parsed = await parseTranscript(jsonPath);
130
+ transcriptText = parsed.fullText;
131
+ segments = parsed.segments;
132
+ }
133
+
134
+ // If English subs not found, try auto-detected language
135
+ if (!transcriptText || transcriptText === "(no transcript available)") {
136
+ const autoJsonPath = `${transcriptPath}.en-orig.json3`;
137
+ if (existsSync(autoJsonPath)) {
138
+ const parsed = await parseTranscript(autoJsonPath);
139
+ transcriptText = parsed.fullText;
140
+ segments = parsed.segments;
141
+ }
142
+ }
143
+
144
+ // 4. Build structured output
145
+ const resultParts: string[] = [
146
+ `## ${title}`,
147
+ ``,
148
+ `**URL:** ${url}`,
149
+ `**Duration:** ${segments.length > 0 ? segments[segments.length - 1]?.time ?? "?" : "?"}`,
150
+ ``,
151
+ `### Description`,
152
+ description || "(no description)",
153
+ ``,
154
+ ];
155
+
156
+ if (transcriptText && transcriptText !== "(no transcript available)") {
157
+ // Truncate transcript to avoid blowing up context
158
+ const maxTranscriptLen = 15000;
159
+ const truncated = transcriptText.length > maxTranscriptLen
160
+ ? transcriptText.slice(0, maxTranscriptLen) + `\n\n[...transcript truncated at ${maxTranscriptLen} chars, full length: ${transcriptText.length} chars]`
161
+ : transcriptText;
162
+
163
+ resultParts.push(`### Transcript (${transcriptText.length} chars)`);
164
+ resultParts.push(truncated);
165
+ } else {
166
+ resultParts.push("*(No transcript available for this video)*");
167
+ }
168
+
169
+ return {
170
+ content: [{ type: "text", text: resultParts.join("\n") }],
171
+ details: {
172
+ title,
173
+ description: description.slice(0, 2000),
174
+ transcriptLength: transcriptText.length,
175
+ segmentCount: segments.length,
176
+ },
177
+ };
178
+ } catch (err: any) {
179
+ const msg = err?.message ?? String(err);
180
+ return {
181
+ content: [{ type: "text", text: `Error fetching video: ${msg}` }],
182
+ details: { error: msg },
183
+ isError: true,
184
+ };
185
+ } finally {
186
+ // Cleanup temp files
187
+ if (transcriptPath) {
188
+ try { await unlink(`${transcriptPath}.en.json3`); } catch {}
189
+ try { await unlink(`${transcriptPath}.en.vtt`); } catch {}
190
+ try { await unlink(`${transcriptPath}.en-orig.json3`); } catch {}
191
+ }
192
+ }
193
+ },
194
+ });
195
+
196
+ // ── /yt command for direct use ──────────────────────────────
197
+ pi.registerCommand("yt", {
198
+ description: "Summarize a YouTube video (usage: /yt <url>)",
199
+ handler: async (args, ctx) => {
200
+ const url = args.trim();
201
+ if (!url) {
202
+ ctx.ui.notify("Usage: /yt <youtube-url>", "warning");
203
+ return;
204
+ }
205
+
206
+ ctx.ui.setEditorText(`Summarize this YouTube video: ${url}`);
207
+ ctx.ui.notify("Press Enter to summarize", "info");
208
+ },
209
+ });
210
+
211
+ // ── /yt-ideas command ────────────────────────────────────────
212
+ pi.registerCommand("yt-ideas", {
213
+ description: "Generate YouTube video ideas on a topic (usage: /yt-ideas <topic>)",
214
+ handler: async (args, ctx) => {
215
+ const topic = args.trim();
216
+ if (!topic) {
217
+ ctx.ui.notify("Usage: /yt-ideas <topic>", "warning");
218
+ return;
219
+ }
220
+
221
+ ctx.ui.setEditorText(
222
+ `Generate 5-10 YouTube video ideas about "${topic}". ` +
223
+ `For each idea include:\n` +
224
+ `- Catchy title\n` +
225
+ `- Target audience\n` +
226
+ `- Key points to cover\n` +
227
+ `- Estimated video length\n` +
228
+ `- Why it would perform well`
229
+ );
230
+ ctx.ui.notify("Press Enter to generate video ideas", "info");
231
+ },
232
+ });
233
+ }
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "pi-yt-summarizer",
3
+ "version": "0.1.0",
4
+ "description": "YouTube summarizer extension for Pi — fetch video info, transcript, and generate video ideas",
5
+ "keywords": ["pi-package", "pi-extension", "youtube", "summarizer", "transcript"],
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/x0d7x/pi-yt-summarizer.git"
10
+ },
11
+ "pi": {
12
+ "extensions": ["./extensions/youtube-summarizer.ts"]
13
+ },
14
+ "peerDependencies": {
15
+ "@earendil-works/pi-coding-agent": "*",
16
+ "typebox": "*"
17
+ }
18
+ }