The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Explainer: PDF and Word sources are read, and summarised when long
Claude724d81ad4d09
diff --git a/src/app/api/explainer/document/route.ts b/src/app/api/explainer/document/route.tsnew file mode 100644index 00000000..76dd637a--- /dev/null+++ b/src/app/api/explainer/document/route.ts@@ -0,0 +1,16 @@+import { EngineSchema, FacelessError, handle, MAX_DOCUMENT_BYTES, readDocument } from "@/server/faceless";++/**+ * A PDF or Word source (multipart: "file", "engine"): the text is read on the server and, when the+ * document is longer than the script writer reads, summarised. The file itself isn't kept.+ */+export async function POST(request: Request) {+ return handle(async () => {+ const form = await request.formData().catch(() => null);+ const file = form?.get("file");+ if (!(file instanceof File)) throw new FacelessError("Choose a PDF or a Word file (.docx)");+ if (file.size > MAX_DOCUMENT_BYTES) throw new FacelessError(`${file.name} is over ${MAX_DOCUMENT_BYTES / 1024 / 1024} MB — add the part that matters, or paste its text into the prompt`, 413);+ const engine = EngineSchema.safeParse(form?.get("engine"));+ return Response.json(await readDocument({ name: file.name, data: Buffer.from(await file.arrayBuffer()), type: file.type }, engine.success ? engine.data : "cloud"));+ });+}diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxindex 4ae6344c..9936ccea 100644--- a/src/components/explainer/explainer-studio.tsx+++ b/src/components/explainer/explainer-studio.tsx@@ -34,33 +34,41 @@ import {import { cn } from "@/lib/utils";import { EpisodeTile } from "../faceless/cards";import { EstimateLine, Segmented, ToggleRow } from "../faceless/controls";-import { readLink, useCreateExplainer, useEstimate, useExplainers, useLikeEpisode } from "../faceless/hooks";+import { readDocument, readLink, useCreateExplainer, useEstimate, useExplainers, useLikeEpisode } from "../faceless/hooks";import { NarratorChip } from "../faceless/narrator";import { StyleArt, StyleGrid } from "../faceless/style-art";const DOC_TYPES = /\.(txt|md|markdown|csv|srt|vtt|json)$/i;const MAX_DOC = 20_000;+/** PDF and Word files are read on the server. */+const READ_TYPES = /\.(pdf|docx)$/i;+const READ_MIME = /^application\/(pdf|vnd\.openxmlformats-officedocument\.wordprocessingml\.document)$/;+const MAX_READ_MB = 20;-type Draft = { kind: "image"; id: string; url: string; name: string; preview: string; uploading?: boolean } | Exclude<ExplainerSource, { kind: "image" }>;+type Draft =+ | { kind: "image"; id: string; url: string; name: string; preview: string; uploading?: boolean }+ /** A PDF or Word file being read on the server. */+ | { kind: "reading"; id: string; name: string }+ | Exclude<ExplainerSource, { kind: "image" }>;const STEPS = [{ icon: Sparkles, title: "Choose Preset", text: "One of 22 looks: whiteboard, pixel art, paper diorama…" },- { icon: Paperclip, title: "Attach a file or just prompt", text: "Images, a document or a link — or only a topic." },+ { icon: Paperclip, title: "Attach a file or just prompt", text: "Images, a PDF, Word or text document, or a link — or only a topic." },{ icon: Download, title: "Download your result", text: "A narrated, subtitled video; fix any scene in the timeline." },];function SourceChip({ s, onRemove }: { s: Draft; onRemove: () => void }) {- const label = s.kind === "image" ? s.name : s.kind === "text" ? s.name : (s.title ?? s.url);+ const label = s.kind === "link" ? (s.title ?? s.url) : s.name;return (<span className="inline-flex h-9 max-w-full min-w-0 items-center gap-1.5 rounded-full bg-secondary pr-1 pl-1 text-[12px] font-medium">{s.kind === "image" ? (// eslint-disable-next-line @next/next/no-img-element<img src={s.preview} alt="" className="size-7 rounded-full object-cover" />) : (- <span className="grid size-7 place-items-center rounded-full bg-background text-muted-foreground">{s.kind === "text" ? <FileText className="size-3.5" /> : <Link2 className="size-3.5" />}</span>+ <span className="grid size-7 place-items-center rounded-full bg-background text-muted-foreground">{s.kind === "link" ? <Link2 className="size-3.5" /> : <FileText className="size-3.5" />}</span>)}<span className="min-w-0 truncate">{label}</span>- {s.kind === "image" && s.uploading && <Loader2 className="size-3.5 shrink-0 animate-spin" />}+ {((s.kind === "image" && s.uploading) || s.kind === "reading") && <Loader2 className="size-3.5 shrink-0 animate-spin" aria-label="Reading" />}<button type="button" onClick={onRemove} className="grid size-6 shrink-0 place-items-center rounded-full hover:bg-accent" aria-label={`Remove ${label}`}><X className="size-3.5" /></button>@@ -192,10 +200,29 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {}room--;setSources((xs) => [...xs, { kind: "text", name: f.name, text }]);- } else if (/\.(pdf|docx?|odt|rtf|pages|pptx?|key)$/i.test(f.name) || /pdf|word|officedocument|opendocument|rtf/.test(f.type)) {- toast.error(`${f.name}: PDF and Word files aren't read yet — save it as .txt, or paste the text into the prompt`);+ } else if (READ_TYPES.test(f.name) || READ_MIME.test(f.type)) {+ if (f.size > MAX_READ_MB * 1024 * 1024) {+ toast.error(`${f.name} is over ${MAX_READ_MB} MB — add the part that matters, or paste its text into the prompt`);+ continue;+ }+ room--;+ const id = `${f.name}:${Date.now()}:${room}`;+ setSources((xs) => [...xs, { kind: "reading", id, name: f.name }]);+ readDocument(f, engine).then(+ (r) => {+ // A source removed while it's read stays removed.+ setSources((xs) => xs.map((x) => (x.kind === "reading" && x.id === id ? r.source : x)));+ toast.success(`Read ${f.name}${r.pages ? ` (${r.pages} page${r.pages === 1 ? "" : "s"})` : ""}${r.summarized ? " and summarised it for the script" : ""}`);+ },+ (e: Error) => {+ setSources((xs) => xs.filter((x) => !(x.kind === "reading" && x.id === id)));+ toast.error(e.message);+ },+ );+ } else if (/\.(doc|odt|rtf|pages|pptx?|key)$/i.test(f.name) || /msword|opendocument|rtf|presentation/.test(f.type)) {+ toast.error(`${f.name}: save it as PDF or Word (.docx), or paste the text into the prompt`);} else {- toast.error(`${f.name}: add an image (PNG, JPEG, WebP) or a text document (.txt, .md, .csv)`);+ toast.error(`${f.name}: add an image (PNG, JPEG, WebP), a PDF, a Word file (.docx) or a text file (.txt, .md, .csv)`);}}};@@ -204,8 +231,10 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {if (!prompt.trim() && !sources.length) return void toast("Add a prompt, or attach a file or link", { id: "faceless-blocker" });if (manualBad) return void toast("Duration must be Auto or a whole number of seconds between 15 and 600", { id: "faceless-blocker" });if (sources.some((s) => s.kind === "image" && s.uploading)) return void toast("Uploading…", { id: "faceless-blocker" });+ const reading = sources.find((s) => s.kind === "reading");+ if (reading) return void toast(`Reading ${reading.name}…`, { id: "faceless-blocker" });if (engine === "open" && settings.voice?.kind !== "sample" && estimate.data?.error) return void toast(estimate.data.error, { id: "faceless-blocker" });- const payload: ExplainerSource[] = sources.map((s) => (s.kind === "image" ? { kind: "image", url: s.url, name: s.name } : s));+ const payload: ExplainerSource[] = sources.flatMap((s): ExplainerSource[] => (s.kind === "image" ? [{ kind: "image", url: s.url, name: s.name }] : s.kind === "reading" ? [] : [s]));create.mutate({ prompt: prompt.trim(), sources: payload, settings, review },{@@ -279,7 +308,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {ref={file}type="file"multiple- accept="image/png,image/jpeg,image/webp,.txt,.md,.markdown,.csv,text/plain,text/markdown"+ accept="image/png,image/jpeg,image/webp,.pdf,.docx,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.txt,.md,.markdown,.csv,text/plain,text/markdown"hiddenonChange={(e) => {const fs = [...(e.target.files ?? [])];diff --git a/src/components/faceless/hooks.ts b/src/components/faceless/hooks.tsindex 4c58e5f1..d4914257 100644--- a/src/components/faceless/hooks.ts+++ b/src/components/faceless/hooks.ts@@ -253,6 +253,14 @@ export function useCreateExplainer() {export const readLink = (url: string, engine: Engine) => send<Extract<ExplainerSource, { kind: "link" }>>("/api/explainer/link", "POST", { url, engine });+/** A PDF or Word source: read (and, when long, summarised) on the server; the file itself isn't kept. */+export async function readDocument(file: File, engine: Engine) {+ const form = new FormData();+ form.append("file", file);+ form.append("engine", engine);+ return json<{ source: Extract<ExplainerSource, { kind: "text" }>; pages?: number; summarized: boolean }>(await fetch("/api/explainer/document", { method: "POST", body: form }));+}+export function useLikeEpisode() {const qc = useQueryClient();return useMutation({diff --git a/src/server/assist/docx.ts b/src/server/assist/docx.tsnew file mode 100644index 00000000..065decda--- /dev/null+++ b/src/server/assist/docx.ts@@ -0,0 +1,73 @@+import "server-only";+import { unzip, ZipError } from "./unzip";++/**+ * The text of a Word document (.docx): the paragraphs of word/document.xml in order (table cells+ * separated by tabs, line and page breaks kept), and the title from docProps/core.xml. Read with the+ * bounded unzip: only those two entries are inflated, so pictures in the file cost nothing. Deleted+ * text (tracked changes) and field codes are left out. Old binary .doc files are refused with a hint.+ */++export class DocxError extends Error {}++const DOCUMENT = "word/document.xml";+const CORE = "docProps/core.xml";+/** An OLE compound file: the old binary .doc (also .xls / .ppt). */+const OLE = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]);++const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };++function decodeXml(s: string): string {+ return s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e: string) => {+ if (e[0] !== "#") return ENTITIES[e] ?? m;+ const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1));+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;+ });+}++// Markers that can't appear in XML text (C0 controls are not allowed there).+const TAB = "\u0001";+const BREAK = "\u0002";++/** The visible text of a document.xml, paragraph by paragraph. */+export function documentXmlText(xml: string): string {+ const marked = xml+ // Alternate content repeats itself in its fallback (text boxes); deleted text and field codes aren't shown.+ .replace(/<mc:Fallback\b[\s\S]*?<\/mc:Fallback>/g, "")+ .replace(/<w:(delText|instrText)\b[^>]*>[\s\S]*?<\/w:\1>/g, "")+ .replace(/<w:(?:tab|ptab)\b[^>]*\/>/g, TAB)+ .replace(/<w:(?:br|cr)\b[^>]*\/>/g, BREAK)+ // A table row is one line, its cells separated by tabs (a cell's paragraphs run on with spaces).+ .replace(/<w:tc\b[^>]*>([\s\S]*?)<\/w:tc>/g, (_, cell: string) => `${cell.replace(/<\/w:p>/g, " ")}${TAB}`)+ .replace(/<\/w:(?:p|tr)>|<w:p\b[^>]*\/>/g, BREAK);+ let out = "";+ for (const m of marked.matchAll(/<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>|\u0001|\u0002/g)) {+ out += m[1] !== undefined ? decodeXml(m[1]) : m[0] === TAB ? "\t" : "\n";+ }+ return out+ .split("\n")+ .map((l) => l.replace(/[ \t\u00a0]+$/g, "").replace(/[ \u00a0]*\t[ \u00a0]*/g, "\t").replace(/[ \u00a0]{2,}/g, " "))+ .join("\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++export function docxText(data: Buffer, opts: { maxChars: number }): { text: string; title?: string } {+ if (data.subarray(0, 8).equals(OLE)) throw new DocxError("This is an older Word file (.doc) — save it as .docx or PDF and add it again");+ let entries: { name: string; data: Buffer }[];+ try {+ entries = unzip(data, { maxEntries: 20_000, maxFileBytes: 40_000_000, maxTotalBytes: 45_000_000, only: (n) => n === DOCUMENT || n === CORE });+ } catch (e) {+ if (e instanceof ZipError && /over|more than/.test(e.message)) throw new DocxError("This Word file's text is too large to read — split it, or save the part you need as PDF");+ if (e instanceof ZipError && /password/.test(e.message)) throw new DocxError("This Word file is password-protected — remove the password and add it again");+ throw new DocxError("This file is damaged or isn't a Word document (.docx)");+ }+ const doc = entries.find((e) => e.name === DOCUMENT);+ if (!doc) throw new DocxError("This file isn't a Word document (.docx) — it has no document text inside");+ const text = documentXmlText(doc.data.toString("utf8")).slice(0, opts.maxChars);+ if (!text.trim()) throw new DocxError("This Word file has no text to read (it may only hold pictures) — paste the text into the prompt instead");+ const core = entries.find((e) => e.name === CORE)?.data.toString("utf8");+ const title = core && /<dc:title>([^<]*)<\/dc:title>/.exec(core)?.[1];+ const clean = title ? decodeXml(title).trim() : "";+ return { text, ...(clean && { title: clean }) };+}diff --git a/src/server/assist/unzip.ts b/src/server/assist/unzip.tsindex d50d591f..bd834d57 100644--- a/src/server/assist/unzip.ts+++ b/src/server/assist/unzip.ts@@ -2,8 +2,9 @@ import "server-only";import zlib from "node:zlib";/**- * A small, bounded ZIP reader for skill uploads (.zip / .skill): stored and deflated entries only,- * read into memory with per-file and total size caps (a zip bomb stops at the cap). Nothing is+ * A small, bounded ZIP reader for skill uploads (.zip / .skill) and Word documents (.docx): stored and+ * deflated entries only, read into memory with per-file and total size caps (a zip bomb stops at the+ * cap). `only` picks the entries to read; the others are skipped without being inflated. Nothing is* written to disk, so entry paths are only names.*/@@ -18,7 +19,7 @@ const EOCD = 0x06054b50;const CENTRAL = 0x02014b50;const LOCAL = 0x04034b50;-export function unzip(buf: Buffer, limits: { maxEntries?: number; maxFileBytes?: number; maxTotalBytes?: number } = {}): ZipEntry[] {+export function unzip(buf: Buffer, limits: { maxEntries?: number; maxFileBytes?: number; maxTotalBytes?: number; only?: (name: string) => boolean } = {}): ZipEntry[] {const maxEntries = limits.maxEntries ?? 300;const maxFile = limits.maxFileBytes ?? 2_000_000;const maxTotal = limits.maxTotalBytes ?? 8_000_000;@@ -50,7 +51,7 @@ export function unzip(buf: Buffer, limits: { maxEntries?: number; maxFileBytes?:const local = buf.readUInt32LE(p + 42);const name = buf.subarray(p + 46, p + 46 + nameLen).toString(flags & 0x800 ? "utf8" : "latin1");p += 46 + nameLen + extraLen + commentLen;- if (name.endsWith("/")) continue;+ if (name.endsWith("/") || (limits.only && !limits.only(name))) continue;if (flags & 0x1) throw new ZipError("The archive is password-protected");const tooBig = () => new ZipError(`${name} is over ${Math.round(maxFile / 1_000_000)} MB`);const tooMuch = () => new ZipError(`The archive unpacks to more than ${Math.round(maxTotal / 1_000_000)} MB`);diff --git a/src/server/faceless.ts b/src/server/faceless.tsindex 39559e17..f3cd9995 100644--- a/src/server/faceless.ts+++ b/src/server/faceless.ts@@ -73,6 +73,8 @@ import {} from "@/lib/catalog/faceless";import { routesFor } from "@/lib/catalog/plan";import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";+import { DocxError, docxText } from "./assist/docx";+import { PdfError, pdfText } from "./assist/pdf";import { db } from "./db";import { listElements } from "./elements";import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";@@ -539,7 +541,7 @@ async function writeScript(id: string, pasted: string, signal: AbortSignal): Proconst elements = listElements().filter((e) => e.kind !== "voice" && handles.has(e.handle.toLowerCase())).map((e) => ({ handle: e.handle, kind: e.kind, description: e.description }));- const textSources = ep.sources.flatMap((x) => (x.kind === "text" ? [`${x.name}: ${x.text.slice(0, 6000)}`] : x.kind === "link" ? [`${x.title ?? x.url} (${x.url}): ${x.text.slice(0, 6000)}`] : []));+ const textSources = ep.sources.flatMap((x) => (x.kind === "text" ? [`${x.name}: ${x.text.slice(0, SOURCE_CHARS)}`] : x.kind === "link" ? [`${x.title ?? x.url} (${x.url}): ${x.text.slice(0, SOURCE_CHARS)}`] : []));let failure = "";const ask = { onError: (m: string) => (failure = m), signal };let script: EpisodeScript;@@ -1328,6 +1330,57 @@ export async function summarizeLink(url: string, engine: Engine): Promise<Extracreturn { kind: "link", url: res.url, title: title?.slice(0, 160), text: (summary ?? text).slice(0, 6000) };}+/** The largest PDF or Word file the Explainer reads. */+export const MAX_DOCUMENT_BYTES = 20 * 1024 * 1024;+/** The script writer reads this much of each source; longer documents are summarised for it first. */+const SOURCE_CHARS = 6000;+/** What a document summary is written from (about a 40-page report; a local model's context holds it). */+const SUMMARY_INPUT_CHARS = 40_000;++export type DocumentKind = "pdf" | "docx";++/** What a file is, from its first bytes, name and type: a PDF, a Word file, or neither. */+export function documentKind(file: { name: string; data: Buffer; type?: string }): DocumentKind | null {+ const head = file.data.subarray(0, 5).toString("latin1");+ if (head === "%PDF-") return "pdf";+ if (head.startsWith("PK\x03\x04") && (/\.docx$/i.test(file.name) || /wordprocessingml/.test(file.type ?? ""))) return "docx";+ if (/\.pdf$/i.test(file.name) || file.type === "application/pdf") return "pdf"; // a damaged one: the reader says so+ if (/\.(docx?|dot[xm]?)$/i.test(file.name) || /msword|wordprocessingml/.test(file.type ?? "")) return "docx";+ return null;+}++/**+ * A PDF or Word source for the Explainer: its text is read on the server (PDF.js through unpdf, or+ * word/document.xml through the bounded unzip), and a document longer than the writer reads is+ * summarised by the engine's text model, like a link. With no text model the beginning is kept.+ */+export async function readDocument(+ file: { name: string; data: Buffer; type?: string },+ engine: Engine,+): Promise<{ source: Extract<ExplainerSource, { kind: "text" }>; pages?: number; summarized: boolean }> {+ if (file.data.length > MAX_DOCUMENT_BYTES) throw new FacelessError(`${file.name} is over ${MAX_DOCUMENT_BYTES / 1024 / 1024} MB — add the part that matters, or paste its text into the prompt`, 413);+ const kind = documentKind(file);+ if (!kind) throw new FacelessError(`${file.name} isn't a PDF or a Word file (.docx)`, 415);+ let read: { text: string; title?: string; pages?: number };+ try {+ read = kind === "pdf" ? await pdfText(file.data, { maxChars: SUMMARY_INPUT_CHARS, maxPages: 200 }) : docxText(file.data, { maxChars: SUMMARY_INPUT_CHARS });+ } catch (e) {+ if (e instanceof PdfError || e instanceof DocxError) throw new FacelessError(e.message, 422);+ throw new FacelessError(kind === "pdf" ? "Couldn't read that PDF — save it again, or paste its text into the prompt" : "Couldn't read that Word file — save it as PDF, or paste its text into the prompt", 422);+ }+ const name = file.name.slice(0, 200);+ const long = read.text.length > SOURCE_CHARS;+ const summary = long+ ? await askLlm(+ engine,+ "You summarise documents for a video script writer. Reply with the key facts, numbers, names, steps and explanations as short plain sentences (at most 300 words). No preamble.",+ `Document: ${read.title ?? name}\n\n${read.text}`,+ { timeoutMs: 2 * 60_000 },+ )+ : null;+ return { source: { kind: "text", name, text: (summary ?? read.text).slice(0, 20_000) }, ...(read.pages && { pages: read.pages }), summarized: !!summary };+}+// ---------------------------------------------------------------------------// Request schemas and the route helper (src/app/api/faceless/**, src/app/api/explainer/**)diff --git a/tests/explainer-documents.test.ts b/tests/explainer-documents.test.tsnew file mode 100644index 00000000..a654f835--- /dev/null+++ b/tests/explainer-documents.test.ts@@ -0,0 +1,276 @@+import fs from "node:fs";+import http from "node:http";+import os from "node:os";+import path from "node:path";+import zlib from "node:zlib";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++/*+ * The Explainer's PDF and Word sources: .docx text through the bounded unzip (word/document.xml only),+ * PDFs through Assist's unpdf reader, long documents summarised by the engine's text model (a stand-in+ * Ollama here), and the multipart route the source picker posts to. Fixtures are built in the test.+ */++vi.setConfig({ testTimeout: 60_000 });+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-explainer-docs-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const { probeOllama } = await import("@/server/providers/llm");+const { docxText, documentXmlText, DocxError } = await import("@/server/assist/docx");+const { unzip } = await import("@/server/assist/unzip");+const faceless = await import("@/server/faceless");+const documentRoute = await import("@/app/api/explainer/document/route");+const explainerRoute = await import("@/app/api/explainer/route");++// ---------------------------------------------------------------------------+// Fixtures++const crcTable = Array.from({ length: 256 }, (_, n) => {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ return c >>> 0;+});+const crc32 = (b: Buffer) => {+ let c = 0xffffffff;+ for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+};++/** A ZIP with deflated entries, the way Word writes a .docx. */+function zipDeflated(files: { name: string; data: Buffer }[]): Buffer {+ const locals: Buffer[] = [];+ const centrals: Buffer[] = [];+ let offset = 0;+ for (const f of files) {+ const name = Buffer.from(f.name, "utf8");+ const packed = zlib.deflateRawSync(f.data);+ const crc = crc32(f.data);+ const lh = Buffer.alloc(30);+ lh.writeUInt32LE(0x04034b50, 0);+ lh.writeUInt16LE(20, 4);+ lh.writeUInt16LE(8, 8);+ lh.writeUInt32LE(crc, 14);+ lh.writeUInt32LE(packed.length, 18);+ lh.writeUInt32LE(f.data.length, 22);+ lh.writeUInt16LE(name.length, 26);+ const ch = Buffer.alloc(46);+ ch.writeUInt32LE(0x02014b50, 0);+ ch.writeUInt16LE(20, 4);+ ch.writeUInt16LE(20, 6);+ ch.writeUInt16LE(8, 10);+ ch.writeUInt32LE(crc, 16);+ ch.writeUInt32LE(packed.length, 20);+ ch.writeUInt32LE(f.data.length, 24);+ ch.writeUInt16LE(name.length, 28);+ ch.writeUInt32LE(offset, 42);+ locals.push(lh, name, packed);+ centrals.push(ch, name);+ offset += 30 + name.length + packed.length;+ }+ const dirBuf = Buffer.concat(centrals);+ const end = Buffer.alloc(22);+ end.writeUInt32LE(0x06054b50, 0);+ end.writeUInt16LE(files.length, 8);+ end.writeUInt16LE(files.length, 10);+ end.writeUInt32LE(dirBuf.length, 12);+ end.writeUInt32LE(offset, 16);+ return Buffer.concat([...locals, dirBuf, end]);+}++const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"';+const para = (...runs: string[]) => `<w:p><w:pPr><w:pStyle w:val="Normal"/></w:pPr>${runs.map((r) => `<w:r><w:rPr><w:b/></w:rPr>${r}</w:r>`).join("")}</w:p>`;+const t = (s: string) => `<w:t xml:space="preserve">${s}</w:t>`;++/** A minimal Word document: the parts Word needs, the body paragraphs and a title. */+function makeDocx(body: string, opts: { title?: string; extra?: { name: string; data: Buffer }[] } = {}): Buffer {+ return zipDeflated([+ { name: "[Content_Types].xml", data: Buffer.from('<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>') },+ { name: "_rels/.rels", data: Buffer.from('<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>') },+ { name: "word/document.xml", data: Buffer.from(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:document ${W}>\n <w:body>\n ${body}\n <w:sectPr/>\n </w:body>\n</w:document>`) },+ ...(opts.title ? [{ name: "docProps/core.xml", data: Buffer.from(`<cp:coreProperties xmlns:cp="x" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>${opts.title}</dc:title></cp:coreProperties>`) }] : []),+ ...(opts.extra ?? []),+ ]);+}++/** A small valid PDF: one page per entry, each line drawn with Helvetica (as in assist-skills.test.ts). */+function makePdf(pages: string[][]): Buffer {+ const objs: string[] = [];+ const kids = pages.map((_, i) => `${4 + i * 2} 0 R`).join(" ");+ objs.push("<< /Type /Catalog /Pages 2 0 R >>");+ objs.push(`<< /Type /Pages /Kids [${kids}] /Count ${pages.length} >>`);+ objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");+ pages.forEach((lines, i) => {+ const ops = lines.map((l, k) => `BT /F1 12 Tf 72 ${720 - k * 18} Td (${l.replace(/[()\\]/g, "\\$&")}) Tj ET`).join("\n");+ objs.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${5 + i * 2} 0 R >>`);+ objs.push(`<< /Length ${Buffer.byteLength(ops)} >>\nstream\n${ops}\nendstream`);+ });+ let out = "%PDF-1.4\n";+ const offsets: number[] = [];+ objs.forEach((o, i) => {+ offsets.push(Buffer.byteLength(out));+ out += `${i + 1} 0 obj\n${o}\nendobj\n`;+ });+ const xref = Buffer.byteLength(out);+ out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n${offsets.map((o) => `${String(o).padStart(10, "0")} 00000 n \n`).join("")}`;+ out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;+ return Buffer.from(out, "latin1");+}++const upload = (name: string, data: Buffer, type = "", engine = "cloud") => {+ const form = new FormData();+ form.append("file", new File([new Uint8Array(data)], name, { type }));+ form.append("engine", engine);+ return new Request("http://x/api/explainer/document", { method: "POST", body: form });+};++// A stand-in Ollama for the summaries.+const asked: { system: string; user: string }[] = [];+const ollama = http.createServer((req, res) => {+ if (req.url === "/api/tags") return res.end(JSON.stringify({ models: [] }));+ let body = "";+ req.on("data", (c) => (body += c));+ req.on("end", () => {+ const m = (JSON.parse(body) as { messages: { content: string }[] }).messages;+ asked.push({ system: m[0].content, user: m[1].content });+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify({ message: { content: "The report says tides rise twice a day. The moon does most of the pulling." } }));+ });+});+let ollamaUrl = "";++beforeAll(async () => {+ await new Promise<void>((r) => ollama.listen(0, "127.0.0.1", r));+ ollamaUrl = `http://127.0.0.1:${(ollama.address() as { port: number }).port}`;+ setSetting("demoMode", "auto");+});+afterAll(() => {+ ollama.close();+ fs.rmSync(dir, { recursive: true, force: true });+});+beforeEach(async () => {+ asked.length = 0;+ // No text model unless a test turns Ollama on.+ setSetting("ollamaUrl", "http://127.0.0.1:9");+ await probeOllama(true);+});++// ---------------------------------------------------------------------------++describe("Word documents (.docx)", () => {+ it("reads paragraphs, tabs, breaks and table cells in order, without deleted text or field codes", () => {+ const xml = `<w:document ${W}><w:body>+ ${para(t("Tides & the Moon"))}+ ${para(t("Twice a day"), "<w:tab/>", t("the sea rises."), "<w:br/>", t("Then it falls."))}+ ${para(t("Kept "), "<w:delText>removed </w:delText>", t("text"), '<w:instrText xml:space="preserve"> PAGE </w:instrText>')}+ <w:tbl><w:tr><w:tc>${para(t("High"))}</w:tc><w:tc>${para(t("06:12"))}</w:tc></w:tr><w:tr><w:tc>${para(t("Low"))}</w:tc><w:tc>${para(t("12:30"))}</w:tc></w:tr></w:tbl>+ <w:p><w:r><mc:AlternateContent><mc:Choice Requires="wps">${t("In a box")}</mc:Choice><mc:Fallback>${t("In a box")}</mc:Fallback></mc:AlternateContent></w:r></w:p>+ ${para(t("“Quoted” <tag> café"))}+ <w:p/><w:p/><w:p/>+ ${para(t("The end."))}+ </w:body></w:document>`;+ expect(documentXmlText(xml)).toBe(["Tides & the Moon", "Twice a day\tthe sea rises.", "Then it falls.", "Kept text", "High\t06:12", "Low\t12:30", "In a box", "“Quoted” <tag> café", "", "The end."].join("\n"));+ });++ it("reads a .docx's text and title, inflating only the document (a large picture inside costs nothing)", () => {+ const picture = Buffer.alloc(60 * 1024 * 1024); // 60 MB of zeros: deflates to a few KB, would blow every cap if inflated+ const docx = makeDocx([para(t("Why the sea has tides.")), para(t("The Moon pulls the water."))].join(""), { title: "Tides & you", extra: [{ name: "word/media/image1.png", data: picture }] });+ expect(docx.length).toBeLessThan(200_000);+ expect(docxText(docx, { maxChars: 10_000 })).toEqual({ text: "Why the sea has tides.\nThe Moon pulls the water.", title: "Tides & you" });+ expect(docxText(docx, { maxChars: 12 }).text).toBe("Why the sea ");+ // The same archive read whole stops at the caps.+ expect(() => unzip(docx, { maxFileBytes: 40_000_000, maxTotalBytes: 45_000_000, maxEntries: 100 })).toThrow(/over 40 MB/);+ });++ it("says what's wrong with files it can't read", () => {+ const ole = Buffer.concat([Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]), Buffer.alloc(512)]);+ expect(() => docxText(ole, { maxChars: 100 })).toThrow(/older Word file \(\.doc\) — save it as \.docx or PDF/);+ expect(() => docxText(Buffer.from("just text"), { maxChars: 100 })).toThrow(/damaged or isn't a Word document/);+ expect(() => docxText(zipDeflated([{ name: "xl/workbook.xml", data: Buffer.from("<x/>") }]), { maxChars: 100 })).toThrow(/isn't a Word document \(\.docx\)/);+ expect(() => docxText(makeDocx('<w:p><w:r><w:drawing/></w:r></w:p>'), { maxChars: 100 })).toThrow(/no text to read/);+ expect(() => docxText(makeDocx('<w:p/>'), { maxChars: 100 })).toThrow(DocxError);+ });+});++describe("Explainer document sources", () => {+ it("knows a PDF and a Word file by their bytes and names", () => {+ expect(faceless.documentKind({ name: "x.bin", data: makePdf([["Hi"]]) })).toBe("pdf");+ expect(faceless.documentKind({ name: "notes.docx", data: makeDocx(para(t("Hi"))) })).toBe("docx");+ expect(faceless.documentKind({ name: "blob", data: makeDocx(para(t("Hi"))), type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" })).toBe("docx");+ expect(faceless.documentKind({ name: "old.doc", data: Buffer.alloc(8) })).toBe("docx"); // the Word reader explains .doc+ expect(faceless.documentKind({ name: "a.zip", data: makeDocx(para(t("Hi"))) })).toBeNull();+ expect(faceless.documentKind({ name: "notes.txt", data: Buffer.from("hello") })).toBeNull();+ });++ it("keeps a short document as it is, page count included", async () => {+ const r = await faceless.readDocument({ name: "tides.pdf", data: makePdf([["The tide rises twice a day."], ["The Moon pulls the sea."]]) }, "cloud");+ expect(r).toEqual({ source: { kind: "text", name: "tides.pdf", text: "The tide rises twice a day.\n\nThe Moon pulls the sea." }, pages: 2, summarized: false });+ const w = await faceless.readDocument({ name: "tides.docx", data: makeDocx(para(t("Spring tides follow the full Moon."))) }, "open");+ expect(w).toEqual({ source: { kind: "text", name: "tides.docx", text: "Spring tides follow the full Moon." }, summarized: false });+ expect(asked).toHaveLength(0);+ });++ it("summarises a long document with the engine's text model, and keeps the beginning without one", async () => {+ const lines = Array.from({ length: 400 }, (_, i) => para(t(`Paragraph ${i + 1}: the tide tables for the harbour list high and low water for every day of the month.`)));+ const docx = makeDocx(lines.join(""), { title: "Harbour tides" });+ // No text model: the beginning, up to what a source holds.+ const plain = await faceless.readDocument({ name: "harbour.docx", data: docx }, "cloud");+ expect(plain.summarized).toBe(false);+ expect(plain.source.text.startsWith("Paragraph 1: the tide tables")).toBe(true);+ expect(plain.source.text.length).toBe(20_000);+ // With Ollama: a summary, written from the document's text under its title.+ setSetting("ollamaUrl", ollamaUrl);+ await probeOllama(true);+ const sum = await faceless.readDocument({ name: "harbour.docx", data: docx }, "cloud");+ expect(sum).toEqual({ source: { kind: "text", name: "harbour.docx", text: "The report says tides rise twice a day. The moon does most of the pulling." }, summarized: true });+ expect(asked).toHaveLength(1);+ expect(asked[0].system).toMatch(/^You summarise documents for a video script writer/);+ expect(asked[0].user.startsWith("Document: Harbour tides\n\nParagraph 1:")).toBe(true);+ expect(asked[0].user.length).toBeLessThanOrEqual(40_000 + "Document: Harbour tides\n\n".length);+ });++ it("the route reads a multipart upload, and refuses what it can't read with a clear message", async () => {+ const ok = await documentRoute.POST(upload("brief.docx", makeDocx(para(t("Explain the water cycle for kids."))), "application/vnd.openxmlformats-officedocument.wordprocessingml.document"));+ expect(ok.status).toBe(200);+ const body = (await ok.json()) as { source: { kind: string; name: string; text: string } };+ expect(body.source).toEqual({ kind: "text", name: "brief.docx", text: "Explain the water cycle for kids." });+ const pdf = await documentRoute.POST(upload("brief.pdf", makePdf([["Clouds form when vapour cools."]]), "application/pdf", "open"));+ expect(await pdf.json()).toMatchObject({ source: { text: "Clouds form when vapour cools." }, pages: 1 });++ const cases: [Request, number, RegExp][] = [+ [upload("old.doc", Buffer.concat([Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]), Buffer.alloc(64)])), 422, /older Word file/],+ [upload("scan.pdf", makePdf([[]])), 422, /no text to read \(it may be scanned images\)/],+ [upload("broken.pdf", Buffer.from("%PDF-1.4 nothing else")), 422, /damaged or isn't a PDF/],+ [upload("notes.txt", Buffer.from("plain text")), 415, /isn't a PDF or a Word file/],+ [upload("huge.pdf", Buffer.alloc(faceless.MAX_DOCUMENT_BYTES + 1)), 413, /over 20 MB/],+ [new Request("http://x/api/explainer/document", { method: "POST", body: new FormData() }), 400, /Choose a PDF or a Word file/],+ ];+ for (const [req, status, error] of cases) {+ const res = await documentRoute.POST(req);+ expect(res.status, String(error)).toBe(status);+ expect(((await res.json()) as { error: string }).error).toMatch(error);+ }+ });++ it("a document source goes into an explainer like any text source", async () => {+ const { source } = await faceless.readDocument({ name: "volcano.docx", data: makeDocx(para(t("Magma rises through cracks in the crust."))) }, "cloud");+ const res = await explainerRoute.POST(+ new Request("http://x/api", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ prompt: "",+ sources: [source],+ review: true,+ settings: { engine: "cloud", length: 30, animation: "animated", aspect: "16:9", subtitles: true, music: false, styleId: "editorial-motion-graphics", styleRefs: [], voice: { kind: "preset", id: "Xb7hH8MSUJpSbSDYk0k2" }, elements: [] },+ }),+ }),+ );+ expect(res.status).toBe(201);+ const ep = (await res.json()) as { id: string; sources: unknown[] };+ expect(ep.sources).toEqual([{ kind: "text", name: "volcano.docx", text: "Magma rises through cracks in the crust." }]);+ await faceless.deleteEpisode(ep.id);+ });+});