// Below this number of extracted characters, a PDF is probably scanned. const OCR_TEXT_THRESHOLD = 100; // One upload path for the add-material dialog and drag & drop. With a server, // the file goes up for conversion/OCR and the local replica records the // answer. With no server (standalone desktop, offline browser), files are // ingested entirely locally: PDFs as they are; other formats rendered to PDF // by the desktop shell through the converters installed on the machine // (LibreOffice, pandoc). Bytes land in the content-addressed store, text and // page count come from pdf.js, metadata goes into the workspace doc. import { api, ApiError } from '../api'; import { endpoints } from '../endpoints'; import { ocrPdfBase64 } from '@synapse/ai-core'; import { ensurePdfjs } from '../pdfjs'; import { isTauri, standalone } from '../platform'; import { ownAiCallConfig } from '../ai/generation'; import { converterArgs } from './converters'; import { imageFileToPdf, isImageFile } from './imageToPdf'; import { SUPPORTED_EXTENSIONS, isSupportedFile } from './formats'; import { fromBase64, toBase64 } from '../sync/base64'; import { m } from '../../paraglide/messages'; import { newId } from '../data/id'; import { nowIso } from '../data/workspace'; import * as blobs from '../data/blobs'; import * as documentsRepo from '../data/repos/documents'; import type { CourseDocument } from '../types'; export async function uploadMaterial( file: File, courseId: string, topicId: string | null, onProgress: (percent: number) => void = () => undefined, ): Promise<{ id: string; via: 'server' | 'local' }> { // Reject anything we cannot make into a viewable document up front, with a // clear message, instead of handing it to a converter that reads it as // garbage and hangs (which is what a dropped, say, .zip or .mp4 did). if (!isSupportedFile(file.name)) { throw new Error(m.course_upload_unsupported_type({ types: SUPPORTED_EXTENSIONS.join(', ') })); } // Images are viewable content, not documents to convert: wrap them into a // one-page PDF on the device before anything else, so every path (server // upload or local ingest) sees a plain PDF and the viewer just renders it. // The server never had to accept image types, and the desktop shell never // feeds an image to pandoc (which reads it as garbage markdown and hangs). if (isImageFile(file.name, file.type)) { file = await imageFileToPdf(file); } // A standalone shell or demo build has no server at all; don't even try. if (!standalone()) { const fd = new FormData(); fd.append('file', file); const res = await api.uploadWithProgress( endpoints.documentUpload, fd, onProgress, ); if (res.isOk()) { // The server converted and stored the file; where the document sits // (course, chapter) is the local replica's business alone. const up = await documentsRepo.upsertFromServer({ ...res.value, course_id: courseId, topic_id: topicId, }); if (up.isErr()) throw up.error; return { id: res.value.id, via: 'server' }; } // A real server answer (unsupported type, conversion failure) is a // message the user should see; only an unreachable server goes local. if (!(res.error instanceof ApiError) || res.error.status !== 0) throw res.error; } return { id: await ingestLocally(file, courseId, topicId), via: 'local' }; } // Stashes a PDF's bytes in the content-addressed store WITHOUT registering a // document. Used by the split wizard so a book carved into chapters never creates // a throwaway whole-book document first. Returns the content hash the wizard then // slices from. export async function stashPdfForSplit(file: File): Promise<{ hash: string; name: string }> { if (!/\.pdf$/i.test(file.name)) throw new Error(m.course_upload_needs_server()); const bytes = new Uint8Array(await file.arrayBuffer()); const hash = await blobs.putLocal( new Blob([bytes.slice()], { type: 'application/pdf' }), 'application/pdf', ); void blobs.pushToServer(hash); return { hash, name: file.name }; } // Renders the viewer's PDF preview for a non-PDF upload, or null for a PDF // (which is its own preview). Images are already turned into PDFs upstream in // uploadMaterial, so here it is only office and markup formats, rendered by // the desktop shell (LibreOffice or pandoc); in a plain browser they need a // server. async function toPdfBytes(file: File, original: Uint8Array): Promise { if (/\.pdf$/i.test(file.name)) return null; if (!isTauri()) throw new Error(m.course_upload_needs_server()); const { invoke } = await import('@tauri-apps/api/core'); try { const pdfB64 = await invoke('convert_to_pdf', { filename: file.name, bytesB64: toBase64(original), ...converterArgs(), }); return fromBase64(pdfB64); } catch (e) { throw new Error(typeof e === 'string' ? e : (e as Error).message, { cause: e }); } } async function ingestLocally( file: File, courseId: string, topicId: string | null, ): Promise { const original = new Uint8Array(await file.arrayBuffer()); const render = await toPdfBytes(file, original); const contentHash = await blobs.putLocal( new Blob([original], { type: file.type || 'application/octet-stream' }), render ? file.type || 'application/octet-stream' : 'application/pdf', ); let renderHash: string | null = null; if (render) { renderHash = await blobs.putLocal( new Blob([render.slice()], { type: 'application/pdf' }), 'application/pdf', ); } const pdfBytes = render ?? original; const extracted = await extractPdf(pdfBytes); const pageCount = extracted.pageCount; const textHash = await ocrAndStoreText(pdfBytes, extracted.text); const id = newId(); const up = await documentsRepo.upsertFromServer({ id, course_id: courseId, topic_id: topicId, original_name: file.name, page_count: pageCount, uploaded_at: nowIso(), has_preview: !!renderHash, content_hash: contentHash, render_hash: renderHash, text_hash: textHash, }); if (up.isErr()) throw up.error; // Best-effort: if a server is merely unreachable right now, these fail // silently; peers still get the bytes over LAN sync or file packs. void blobs.pushToServer(contentHash); if (renderHash) void blobs.pushToServer(renderHash); if (textHash) void blobs.pushToServer(textHash); return id; } interface PdfjsLib { getDocument(src: { data: Uint8Array }): { promise: Promise<{ numPages: number; getPage(n: number): Promise<{ getTextContent(): Promise<{ items: { str?: string }[] }>; }>; destroy(): Promise; }>; }; } async function extractPdf(bytes: Uint8Array): Promise<{ pageCount: number; text: string }> { await ensurePdfjs(); const pdfjs = (window as unknown as { pdfjsLib: PdfjsLib }).pdfjsLib; // pdf.js transfers the buffer to its worker, so it gets its own copy. const doc = await pdfjs.getDocument({ data: bytes.slice() }).promise; let text = ''; for (let p = 1; p <= doc.numPages; p++) { const page = await doc.getPage(p); const content = await page.getTextContent(); text += content.items.map((item) => item.str ?? '').join(' ') + '\n'; } const pageCount = doc.numPages; await doc.destroy(); return { pageCount, text }; } // Given a PDF and whatever text pdf.js already pulled from it, OCR it when that // text is too thin to be a real text layer (a scanned page), then store the text // in the blob store. Returns the text hash, or null when there is nothing usable. // OCR is best-effort and never throws: a chapter still imports without a text // layer, generation just says so later. Exported so the split wizard can run the // same step per chapter AFTER the book is carved, instead of OCRing the whole // book up front (most of which is then discarded). export async function ocrAndStoreText( pdfBytes: Uint8Array, extractedText: string, ): Promise { let text = extractedText; if (text.trim().length < OCR_TEXT_THRESHOLD) { const ai = ownAiCallConfig(); if (ai.provider !== 'local' && ai.apiKey) { try { const transcribed = await ocrPdfBase64(ai, toBase64(pdfBytes)); if (transcribed.trim().length >= OCR_TEXT_THRESHOLD) text = transcribed; } catch { // Keep whatever pdf.js extracted; generation will flag thin text. } } } if (!text.trim()) return null; return blobs.putLocal(new Blob([text], { type: 'text/plain' }), 'text/plain; charset=utf-8'); } // Extract a PDF's text layer alone (no OCR), for callers that already hold bytes. export async function extractPdfText(bytes: Uint8Array): Promise { return (await extractPdf(bytes)).text; }