Skip to content

About

Mirror physical paperback book highlights and hand-drawn pen markings directly onto your digital PDF copies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Marginalia — Digital Inkwell Sync

Mirror physical paperback book highlights and hand-drawn pen markings directly onto your digital PDF copies.

Photograph a page you underlined or highlighted on paper. A computer-vision pass straightens the image and detects ink regions, Google Gemini Vision transcribes the marked text, and a sliding-window token matcher aligns the quote against the PDF's word-level index — producing native highlight annotations you can review, adjust, and export.


Features

  • Client-Side PDF Indexing: Extracts per-word token bounding boxes (x,y,w,h) directly in the browser via pdfjs-dist without streaming large PDF files to serverless endpoints.
  • Canvas 2D Preprocessing: Decodes EXIF tags, crops paper quadrilaterals, corrects perspective via bilinear homography warping, and scans ink stroke regions.
  • Durable Postgres Job Queue: Lock-protected background task execution powered by Postgres FOR UPDATE SKIP LOCKED RPCs with exponential backoff and dead-letter retry.
  • Direct Google Gemini Vision API: Invokes gemini-1.5-flash with candidate spatial hints for verbatim marked quote transcription.
  • Fuzzy Token Matcher: Normalizes NFKD accents and punctuation, executing sliding-window token alignment (50% coverage, 35% sequence order, 15% density score).
  • Interactive Review Queue: Matches below your confidence threshold sit in a Review panel for manual confirmation or drag-and-drop position adjustment.
  • Durable Revision History: Immutable before/after state snapshots (annotation_revisions) enable device-wide Undo & Redo.
  • Native PDF Export: Paints BlendMode.Multiply highlight bands and injects native PDF /Highlight annotation dictionaries using pdf-lib.

End-to-End System Architecture

flowchart TD
    subgraph Client["Browser Client (React / TanStack Start)"]
        A["PDF Upload"] --> B["pdfjs-dist Token Indexer"]
        C["Phone Photo Capture"] --> D["Canvas 2D Preprocessing"]
        D --> E["Upload JPEG & Enqueue Job"]
    end

    subgraph Backend["Postgres & Storage (Supabase)"]
        B --> F[("book_pages Word Bounding Boxes")]
        E --> G[("Object Storage: captures/")]
        E --> H[("public.jobs Queue: SKIP LOCKED")]
        N[("annotations Table")] --> O[("annotation_revisions Undo/Redo")]
    end

    subgraph Worker["Server Processing Worker"]
        H --> I["claim_jobs() RPC"]
        I --> J["Google Gemini 1.5 Flash Vision Pass"]
        J --> K["Verbatim Marked Quotes"]
        K --> L["matchQuote() Token Matcher"]
        L --> M{"Score >= Threshold?"}
        M -- "Yes" --> N
        M -- "No" --> P["Pending Review Queue"]
    end

    subgraph Export["PDF Output Engine"]
        N --> Q["pdf-lib Native Export"]
        Q --> R["Multiply Highlight Bands + /Highlight PDF Dictionaries"]
    end
Loading

Sequence Diagram: Photo Capture & Processing Flow

sequenceDiagram
    autonumber
    actor Reader as User
    participant Browser as Browser Client (Canvas 2D)
    participant Storage as Supabase Object Storage
    participant DB as Postgres Database
    participant Worker as Server Background Worker
    participant Gemini as Google Gemini Vision API

    Reader->>Browser: Snap photo of paper page
    Browser->>Browser: Decode EXIF, crop quad & warp perspective
    Browser->>Storage: Upload straightened photo JPEG
    Browser->>DB: Upsert job into public.jobs table
    Worker->>DB: Execute claim_jobs() via SKIP LOCKED
    DB-->>Worker: Lock job & return payload
    Worker->>Gemini: POST /chat/completions (Image + Spatial Hints)
    Gemini-->>Worker: Return JSON array of verbatim quotes
    Worker->>DB: Fetch book_pages word token bounding boxes
    Worker->>Worker: Run matchQuote() sliding window token alignment
    Worker->>DB: Insert annotations & record annotation_revisions
    Worker->>DB: Execute complete_job()
    DB-->>Browser: Real-time query refetch (Review / Reader UI updated)
Loading

System Component & Storage Topology

Component / Layer Technology Primary Responsibility Storage / State
Frontend Framework TanStack Start (Vite + React 19) Application shell, routing, PDF rendering & canvas overlays In-Memory React State & TanStack Query cache
PDF Text Extractor pdfjs-dist Extracts per-word token bounding boxes (x, y, w, h) Cached in book_pages.words JSONB
Image Preprocessor HTML5 Canvas 2D EXIF decoding, quad cropping, homography warp, line angle detection Ephemeral client ArrayBuffers
Job Queue Engine Postgres public.jobs Lock-protected durable background task orchestration FOR UPDATE SKIP LOCKED DB queue
AI Vision Model Google Gemini 1.5 Flash Verbatim marked text & margin note transcription Direct OpenAI-compatible v1beta API
Token Matcher matchQuote() TypeScript Sliding-window alignment scoring (coverage, sequence, density) Runs on server worker node
Revision History annotation_revisions Immutable audit log of before/after state for Undo/Redo DB table with JSONB snapshots
PDF Annotation Exporter pdf-lib Paints multiply-blended highlight bands & PDF /Highlight dictionaries Generates downloadable PDF ArrayBuffer

Environment & Configuration

Create a .env file in the root directory:

# Supabase Configuration
VITE_SUPABASE_URL=https://your-project-ref.supabase.co
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key

# Direct Google Gemini AI Studio Key
GEMINI_API_KEY=your_google_ai_studio_api_key

# Background Worker Tick Secret
WORKER_TICK_SECRET=your_random_worker_tick_secret

Development Quickstart

  1. Install dependencies:

    npm install
  2. Start development server:

    npm run dev

    Open http://localhost:8080 in your browser.

  3. Typecheck & Build:

    npx tsc --noEmit
    npm run build

About

Mirror physical paperback book highlights and hand-drawn pen markings directly onto your digital PDF copies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages