-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathvideo-extract.ts
More file actions
378 lines (320 loc) · 11.3 KB
/
video-extract.ts
File metadata and controls
378 lines (320 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { resolve, extname, basename, join, dirname } from "node:path";
import { homedir } from "node:os";
import { activityMonitor } from "./activity.js";
import { isGeminiWebAvailable, queryWithCookies } from "./gemini-web.js";
import { queryGeminiApiWithVideo, getApiKey, API_BASE } from "./gemini-api.js";
import { extractHeadingTitle, type ExtractedContent, type ExtractOptions, type FrameResult } from "./extract.js";
import { readExecError, trimErrorText, mapFfmpegError } from "./utils.js";
const CONFIG_PATH = join(homedir(), ".pi", "web-search.json");
const UPLOAD_BASE = "https://generativelanguage.googleapis.com/upload/v1beta";
const DEFAULT_VIDEO_PROMPT = `Extract the complete content of this video. Include:
1. Video title (infer from content if not explicit), duration
2. A brief summary (2-3 sentences)
3. Full transcript with timestamps
4. Descriptions of any code, terminal commands, diagrams, slides, or UI shown on screen
Format as markdown.`;
const VIDEO_EXTENSIONS: Record<string, string> = {
".mp4": "video/mp4",
".mov": "video/quicktime",
".webm": "video/webm",
".avi": "video/x-msvideo",
".mpeg": "video/mpeg",
".mpg": "video/mpeg",
".wmv": "video/x-ms-wmv",
".flv": "video/x-flv",
".3gp": "video/3gpp",
".3gpp": "video/3gpp",
};
function shouldRethrow(err: unknown): boolean {
const message = err instanceof Error ? err.message : String(err);
return message.startsWith("Failed to parse ");
}
interface VideoFileInfo {
absolutePath: string;
mimeType: string;
sizeBytes: number;
}
interface VideoConfig {
enabled: boolean;
preferredModel: string;
maxSizeMB: number;
}
function normalizePreferredModel(value: unknown, fallback: string): string {
if (typeof value !== "string") return fallback;
const normalized = value.trim();
return normalized.length > 0 ? normalized : fallback;
}
function normalizeEnabled(value: unknown, fallback: boolean): boolean {
return typeof value === "boolean" ? value : fallback;
}
function normalizeMaxSizeMB(value: unknown, fallback: number): number {
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
return value > 0 ? value : fallback;
}
const VIDEO_CONFIG_DEFAULTS: VideoConfig = {
enabled: true,
preferredModel: "gemini-3-flash-preview",
maxSizeMB: 50,
};
let cachedVideoConfig: VideoConfig | null = null;
function loadVideoConfig(): VideoConfig {
if (cachedVideoConfig) return cachedVideoConfig;
if (!existsSync(CONFIG_PATH)) {
cachedVideoConfig = { ...VIDEO_CONFIG_DEFAULTS };
return cachedVideoConfig;
}
const rawText = readFileSync(CONFIG_PATH, "utf-8");
let raw: { video?: { enabled?: boolean; preferredModel?: string; maxSizeMB?: number } };
try {
raw = JSON.parse(rawText) as { video?: { enabled?: boolean; preferredModel?: string; maxSizeMB?: number } };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
}
const v = raw.video ?? {};
cachedVideoConfig = {
enabled: normalizeEnabled(v.enabled, VIDEO_CONFIG_DEFAULTS.enabled),
preferredModel: normalizePreferredModel(v.preferredModel, VIDEO_CONFIG_DEFAULTS.preferredModel),
maxSizeMB: normalizeMaxSizeMB(v.maxSizeMB, VIDEO_CONFIG_DEFAULTS.maxSizeMB),
};
return cachedVideoConfig;
}
export function isVideoFile(input: string): VideoFileInfo | null {
const config = loadVideoConfig();
if (!config.enabled) return null;
const isFilePath = input.startsWith("/") || input.startsWith("./") || input.startsWith("../") || input.startsWith("file://");
if (!isFilePath) return null;
let filePath = input;
if (input.startsWith("file://")) {
try {
filePath = decodeURIComponent(new URL(input).pathname);
} catch {
return null;
}
}
const ext = extname(filePath).toLowerCase();
const mimeType = VIDEO_EXTENSIONS[ext];
if (!mimeType) return null;
const absolutePath = resolveFilePath(filePath);
if (!absolutePath) return null;
let stat: ReturnType<typeof statSync>;
try {
stat = statSync(absolutePath);
} catch {
return null;
}
if (!stat.isFile()) return null;
const maxBytes = config.maxSizeMB * 1024 * 1024;
if (stat.size > maxBytes) return null;
return { absolutePath, mimeType, sizeBytes: stat.size };
}
function resolveFilePath(filePath: string): string | null {
const absolutePath = resolve(filePath);
if (existsSync(absolutePath)) return absolutePath;
const dir = dirname(absolutePath);
const base = basename(absolutePath);
if (!existsSync(dir)) return null;
try {
const normalizedBase = normalizeSpaces(base);
const match = readdirSync(dir).find(f => normalizeSpaces(f) === normalizedBase);
return match ? join(dir, match) : null;
} catch {
return null;
}
}
function normalizeSpaces(s: string): string {
return s.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g, " ");
}
export async function extractVideo(
info: VideoFileInfo,
signal?: AbortSignal,
options?: ExtractOptions,
): Promise<ExtractedContent | null> {
const config = loadVideoConfig();
const effectivePrompt = options?.prompt ?? DEFAULT_VIDEO_PROMPT;
const effectiveModel = options?.model ?? config.preferredModel;
const displayName = basename(info.absolutePath);
const activityId = activityMonitor.logStart({ type: "fetch", url: `video:${displayName}` });
const result = await tryVideoGeminiApi(info, effectivePrompt, effectiveModel, signal)
?? await tryVideoGeminiWeb(info, effectivePrompt, effectiveModel, signal);
if (result) {
const thumbnail = await extractVideoFrame(info.absolutePath);
if (!("error" in thumbnail)) {
result.thumbnail = thumbnail;
}
activityMonitor.logComplete(activityId, 200);
return result;
}
if (signal?.aborted) {
activityMonitor.logComplete(activityId, 0);
return null;
}
activityMonitor.logError(activityId, "all video extraction paths failed");
return null;
}
function mapFfprobeError(err: unknown): string {
const { code, stderr, message } = readExecError(err);
if (code === "ENOENT") return "ffprobe is not installed. Install ffmpeg which includes ffprobe";
const snippet = trimErrorText(stderr || message);
return snippet ? `ffprobe failed: ${snippet}` : "ffprobe failed";
}
export async function extractVideoFrame(filePath: string, seconds: number = 1): Promise<FrameResult> {
try {
const buffer = execFileSync("ffmpeg", [
"-ss", String(seconds), "-i", filePath,
"-frames:v", "1", "-f", "image2pipe", "-vcodec", "mjpeg", "pipe:1",
], { maxBuffer: 5 * 1024 * 1024, timeout: 10000, stdio: ["pipe", "pipe", "pipe"] });
if (buffer.length === 0) return { error: "ffmpeg failed: empty output" };
return { data: buffer.toString("base64"), mimeType: "image/jpeg" };
} catch (err) {
return { error: mapFfmpegError(err) };
}
}
export async function getLocalVideoDuration(filePath: string): Promise<number | { error: string }> {
try {
const output = execFileSync("ffprobe", [
"-v", "quiet",
"-show_entries", "format=duration",
"-of", "csv=p=0",
filePath,
], { timeout: 10000, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
const duration = Number.parseFloat(output);
if (!Number.isFinite(duration)) return { error: "ffprobe failed: invalid duration output" };
return duration;
} catch (err) {
return { error: mapFfprobeError(err) };
}
}
async function tryVideoGeminiWeb(
info: VideoFileInfo,
prompt: string,
model: string,
signal?: AbortSignal,
): Promise<ExtractedContent | null> {
try {
const cookies = await isGeminiWebAvailable();
if (!cookies) return null;
if (signal?.aborted) return null;
const text = await queryWithCookies(prompt, cookies, {
files: [info.absolutePath],
model,
signal,
timeoutMs: 180000,
});
return {
url: info.absolutePath,
title: extractVideoTitle(text, info.absolutePath),
content: text,
error: null,
};
} catch (err) {
if (shouldRethrow(err)) throw err;
return null;
}
}
async function tryVideoGeminiApi(
info: VideoFileInfo,
prompt: string,
model: string,
signal?: AbortSignal,
): Promise<ExtractedContent | null> {
const apiKey = getApiKey();
if (!apiKey) return null;
if (signal?.aborted) return null;
let fileName: string | null = null;
try {
const uploaded = await uploadToFilesApi(info, apiKey, signal);
fileName = uploaded.name;
await pollFileState(fileName, apiKey, signal, 120000);
const text = await queryGeminiApiWithVideo(prompt, uploaded.uri, {
model,
mimeType: info.mimeType,
signal,
timeoutMs: 120000,
});
return {
url: info.absolutePath,
title: extractVideoTitle(text, info.absolutePath),
content: text,
error: null,
};
} catch (err) {
if (shouldRethrow(err)) throw err;
return null;
} finally {
if (fileName) deleteGeminiFile(fileName, apiKey);
}
}
async function uploadToFilesApi(
info: VideoFileInfo,
apiKey: string,
signal?: AbortSignal,
): Promise<{ name: string; uri: string }> {
const displayName = basename(info.absolutePath);
const initRes = await fetch(`${UPLOAD_BASE}/files`, {
method: "POST",
headers: {
"x-goog-api-key": apiKey,
"X-Goog-Upload-Protocol": "resumable",
"X-Goog-Upload-Command": "start",
"X-Goog-Upload-Header-Content-Length": String(info.sizeBytes),
"X-Goog-Upload-Header-Content-Type": info.mimeType,
"Content-Type": "application/json",
},
body: JSON.stringify({ file: { display_name: displayName } }),
signal,
});
if (!initRes.ok) {
const text = await initRes.text();
throw new Error(`File upload init failed: ${initRes.status} (${text.slice(0, 200)})`);
}
const uploadUrl = initRes.headers.get("x-goog-upload-url");
if (!uploadUrl) throw new Error("No upload URL in response headers");
const fileData = await readFile(info.absolutePath);
const uploadRes = await fetch(uploadUrl, {
method: "PUT",
headers: {
"Content-Length": String(info.sizeBytes),
"X-Goog-Upload-Offset": "0",
"X-Goog-Upload-Command": "upload, finalize",
},
body: fileData,
signal,
});
if (!uploadRes.ok) {
const text = await uploadRes.text();
throw new Error(`File upload failed: ${uploadRes.status} (${text.slice(0, 200)})`);
}
const result = await uploadRes.json() as { file: { name: string; uri: string } };
return result.file;
}
async function pollFileState(
fileName: string,
apiKey: string,
signal?: AbortSignal,
timeoutMs: number = 120000,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (signal?.aborted) throw new Error("Aborted");
const res = await fetch(`${API_BASE}/${fileName}?key=${apiKey}`, { signal });
if (!res.ok) throw new Error(`File state check failed: ${res.status}`);
const data = await res.json() as { state: string };
if (data.state === "ACTIVE") return;
if (data.state === "FAILED") throw new Error("File processing failed");
await new Promise(r => setTimeout(r, 5000));
}
throw new Error("File processing timed out");
}
function deleteGeminiFile(fileName: string, apiKey: string): void {
fetch(`${API_BASE}/${fileName}?key=${apiKey}`, { method: "DELETE" }).catch((err) => {
const message = err instanceof Error ? err.message : String(err);
console.error(`Failed to delete Gemini file ${fileName}: ${message}`);
});
}
function extractVideoTitle(text: string, filePath: string): string {
return extractHeadingTitle(text) ?? basename(filePath, extname(filePath));
}