Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103import type { ResultAsync } from 'neverthrow';import * as blobs from '@web/lib/data/blobs';import * as coursesRepo from '@web/lib/data/repos/courses';import * as documentsRepo from '@web/lib/data/repos/documents';import { newId } from '@web/lib/data/id';import { nowIso, DataError, run } from '@web/lib/data/workspace';import { extractPdfText, ocrAndStoreText } from '@web/lib/documents/upload';
export interface SplitRange { // 1-based inclusive page bounds. from: number; to: number; name: string;}
export interface SplitSource { courseId: string; // The source PDF in the blob store. hash: string; // A document to remove once the slices exist (the pre-existing whole-book doc); // omitted when the book was stashed for splitting and never became a document. removeDocumentId?: string;}
// Slice a source PDF into one new chapter per range. Runs on the device via// pdf-lib; the slices land in the blob store and each becomes a document in a new// chapter of the same course. Any pre-existing whole-book document is removed.export function splitPdfIntoChapters( source: SplitSource, ranges: SplitRange[],): ResultAsync<null, DataError> { return run(async () => { if (!source.hash) throw new DataError('This document has no PDF to split', 400); const clean = ranges .map((r) => ({ from: Math.round(r.from), to: Math.round(r.to), name: r.name.trim() })) .filter((r) => r.from >= 1 && r.to >= r.from && r.name); if (!clean.length) throw new DataError('No valid page ranges to split', 400);
const blob = await blobs.getOrFetch(source.hash); if (!blob) throw new DataError('The source PDF could not be loaded', 404); const bytes = new Uint8Array(await blob.arrayBuffer());
const { PDFDocument } = await import('pdf-lib'); const src = await PDFDocument.load(bytes); const pageCount = src.getPageCount();
for (const r of clean) { const to = Math.min(r.to, pageCount); const indices = []; for (let p = r.from; p <= to; p++) indices.push(p - 1); if (!indices.length) continue;
const out = await PDFDocument.create(); const pages = await out.copyPages(src, indices); for (const page of pages) out.addPage(page); const outBytes = await out.save();
const hash = await blobs.putLocal( new Blob([outBytes.slice()], { type: 'application/pdf' }), 'application/pdf', ); void blobs.pushToServer(hash);
// Extract (and, for a scanned chapter, OCR) text now that the book is // carved, so each chapter carries only its own text and nothing is // transcribed twice or wasted on discarded front/back matter. Text is a // nice-to-have for generation; if pdf.js/OCR fails, the chapter still // imports without a text layer. const chapterBytes = outBytes.slice(); let textHash: string | null; try { textHash = await ocrAndStoreText(chapterBytes, await extractPdfText(chapterBytes)); if (textHash) void blobs.pushToServer(textHash); } catch { textHash = null; }
const topic = await coursesRepo.addTopic(source.courseId, r.name); if (topic.isErr()) throw topic.error;
const res = await documentsRepo.upsertFromServer({ id: newId(), course_id: source.courseId, topic_id: topic.value.id, original_name: `${r.name}.pdf`, page_count: indices.length, uploaded_at: nowIso(), has_preview: false, content_hash: hash, render_hash: null, text_hash: textHash, }); if (res.isErr()) throw res.error; }
if (source.removeDocumentId) { const removed = await documentsRepo.remove(source.removeDocumentId); if (removed.isErr()) throw removed.error; } return null; });}