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: a long PDF says how many of its pages were read
Claude993ea6f27d9a
diff --git a/src/components/explainer/explainer-studio.tsx b/src/components/explainer/explainer-studio.tsxindex 9936ccea..82f5bdd3 100644--- a/src/components/explainer/explainer-studio.tsx+++ b/src/components/explainer/explainer-studio.tsx@@ -45,6 +45,10 @@ const READ_TYPES = /\.(pdf|docx)$/i;const READ_MIME = /^application\/(pdf|vnd\.openxmlformats-officedocument\.wordprocessingml\.document)$/;const MAX_READ_MB = 20;+/** " (12 pages)", or " (the first 20 of 150 pages)" when a long PDF was read only in part. */+const pagesNote = (r: { pages?: number; readPages?: number }) =>+ !r.pages ? "" : r.readPages ? ` (the first ${r.readPages} of ${r.pages} pages)` : ` (${r.pages} page${r.pages === 1 ? "" : "s"})`;+type Draft =| { kind: "image"; id: string; url: string; name: string; preview: string; uploading?: boolean }/** A PDF or Word file being read on the server. */@@ -212,7 +216,7 @@ export function ExplainerStudio({ picker }: { picker: PickerData }) {(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" : ""}`);+ toast.success(`Read ${f.name}${pagesNote(r)}${r.summarized ? " and summarised it for the script" : ""}`);},(e: Error) => {setSources((xs) => xs.filter((x) => !(x.kind === "reading" && x.id === id)));diff --git a/src/components/faceless/hooks.ts b/src/components/faceless/hooks.tsindex d4914257..dac56590 100644--- a/src/components/faceless/hooks.ts+++ b/src/components/faceless/hooks.ts@@ -258,7 +258,7 @@ 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 }));+ return json<{ source: Extract<ExplainerSource, { kind: "text" }>; pages?: number; readPages?: number; summarized: boolean }>(await fetch("/api/explainer/document", { method: "POST", body: form }));}export function useLikeEpisode() {diff --git a/src/server/assist/pdf.ts b/src/server/assist/pdf.tsindex 62027985..4ccdd1ac 100644--- a/src/server/assist/pdf.ts+++ b/src/server/assist/pdf.ts@@ -9,7 +9,8 @@ import "server-only";export class PdfError extends Error {}-export async function pdfText(data: Buffer, opts: { maxChars: number; maxPages?: number }): Promise<{ text: string; pages: number; title?: string }> {+/** `pages` is the document's page count; `pagesRead` how many of them were read before a limit stopped it. */+export async function pdfText(data: Buffer, opts: { maxChars: number; maxPages?: number }): Promise<{ text: string; pages: number; pagesRead: number; title?: string }> {const { getDocumentProxy } = await import("unpdf");let pdf: Awaited<ReturnType<typeof getDocumentProxy>>;try {@@ -23,7 +24,9 @@ export async function pdfText(data: Buffer, opts: { maxChars: number; maxPages?:const pages = Math.min(pdf.numPages, opts.maxPages ?? 300);const parts: string[] = [];let chars = 0;+ let read = 0;for (let n = 1; n <= pages && chars < opts.maxChars; n++) {+ read = n;const page = await pdf.getPage(n);const content = await page.getTextContent();let line = "";@@ -46,7 +49,7 @@ export async function pdfText(data: Buffer, opts: { maxChars: number; maxPages?:if (!text.trim()) throw new PdfError("This PDF has no text to read (it may be scanned images) — paste the text as a note instead");const meta = await pdf.getMetadata().catch(() => null);const title = typeof (meta?.info as { Title?: unknown } | undefined)?.Title === "string" ? ((meta!.info as { Title: string }).Title.trim() || undefined) : undefined;- return { text, pages: pdf.numPages, ...(title && { title }) };+ return { text, pages: pdf.numPages, pagesRead: read, ...(title && { title }) };} finally {await pdf.loadingTask.destroy().catch(() => {});}diff --git a/src/server/faceless.ts b/src/server/faceless.tsindex f3cd9995..26cdffc0 100644--- a/src/server/faceless.ts+++ b/src/server/faceless.ts@@ -1357,11 +1357,11 @@ export function documentKind(file: { name: string; data: Buffer; type?: string }export async function readDocument(file: { name: string; data: Buffer; type?: string },engine: Engine,-): Promise<{ source: Extract<ExplainerSource, { kind: "text" }>; pages?: number; summarized: boolean }> {+): Promise<{ source: Extract<ExplainerSource, { kind: "text" }>; pages?: number; readPages?: 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 };+ let read: { text: string; title?: string; pages?: number; pagesRead?: number };try {read = kind === "pdf" ? await pdfText(file.data, { maxChars: SUMMARY_INPUT_CHARS, maxPages: 200 }) : docxText(file.data, { maxChars: SUMMARY_INPUT_CHARS });} catch (e) {@@ -1378,7 +1378,9 @@ export async function readDocument({ 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 };+ // A PDF read only in part (its first SUMMARY_INPUT_CHARS) says how many of its pages were read.+ const partial = read.pages && read.pagesRead !== undefined && read.pagesRead < read.pages ? { readPages: read.pagesRead } : {};+ return { source: { kind: "text", name, text: (summary ?? read.text).slice(0, 20_000) }, ...(read.pages && { pages: read.pages }), ...partial, summarized: !!summary };}// ---------------------------------------------------------------------------diff --git a/tests/explainer-documents.test.ts b/tests/explainer-documents.test.tsindex e17e6711..ef3b426f 100644--- a/tests/explainer-documents.test.ts+++ b/tests/explainer-documents.test.ts@@ -245,6 +245,17 @@ describe("Explainer document sources", () => {expect(asked).toHaveLength(0);});+ it("says how many pages of a long PDF were read", async () => {+ const line = "High water at the harbour is about twelve hours and twenty-five minutes apart.";+ const pdf = makePdf(Array.from({ length: 30 }, () => Array.from({ length: 36 }, () => line)));+ const r = await faceless.readDocument({ name: "tables.pdf", data: pdf }, "cloud");+ // 30 pages of about 2,900 characters: the 40,000 the summary is written from run into page 15.+ expect(r).toMatchObject({ pages: 30, readPages: 15, summarized: false });+ const short = await faceless.readDocument({ name: "two.pdf", data: makePdf([[line], [line]]) }, "cloud");+ expect(short.pages).toBe(2);+ expect(short.readPages).toBeUndefined();+ });+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" });