Source Library
A digital library of historical primary sources with AI-aided OCR, translation, and scholarly curation.
๐ Visit Library โข ๐ Docs โข ๐บ๏ธ System Map โข ๐ค Contribute
</div>๐ฌ Experience Source Library
<div align="center"> <video width="100%" max-width="600" controls poster="https://images.sourcelibrary.org/video/hero-poster.jpg"> <source src="https://images.sourcelibrary.org/video/hero-bg.webm" type="video/webm"> <source src="https://images.sourcelibrary.org/video/hero-bg.mp4" type="video/mp4"> Your browser does not support the video tag. </video>Explore thousands of digitized historical texts with AI-enhanced translations and scholarly curation.
</div>๐ฏ About Source Library
Source Library is an open digital library dedicated to making early printed books and primary sources readable and citable. We specialize in alchemy, Hermetica, Kabbalah, Rosicrucianism, and early modern scienceโtexts that bridge historical scholarship with contemporary exploration.
๐ Why Source Library?
- โจ Originals First โ Read the original language text with AI-enhanced translations alongside
- ๐ Citable Scholarship โ Every book gets a DOI and scholarly metadata (USTC alignment, edition tracking)
- ๐๏ธ Partner Subdomains โ Institutions like the Bibliotheca Philosophica Hermetica curate reading rooms on their own domains
- ๐ Discovery โ Collections, galleries of illustrations, and semantic search surface overlooked texts
- โ Rigorous QA โ Manual verification, image quality scoring, and OCR validation before publication
The platform ingests ~15K pages monthly from Internet Archive, Gallica, Bodleian, Wellcome, and other digital heritage partners.
๐ Quick Start
๐ป Development Environment
# ๐ด Clone and install
git clone https://github.com/Embassy-of-the-Free-Mind/sourcelibrary-v2.git
cd sourcelibrary-v2
npm install
# โ๏ธ Configure environment (see .env.example for required variables)
# Must include: MongoDB Atlas connection, Google Gemini API key, Vercel Blob token
# โถ๏ธ Start dev server
npm run dev
๐ Tech Stack
<table> <tr> <td><strong>๐จ Frontend</strong></td> <td>Next.js 16, React 19, TailwindCSS, Lucide icons</td> </tr> <tr> <td><strong>โ๏ธ Backend</strong></td> <td>Next.js API routes, AWS Lambda for async processing</td> </tr> <tr> <td><strong>๐พ Database</strong></td> <td>MongoDB Atlas (primary), Supabase (embeddings)</td> </tr> <tr> <td><strong>๐ค AI/ML</strong></td> <td>Google Gemini 3.1 (OCR, translation, summarization)</td> </tr> <tr> <td><strong>๐๏ธ Storage</strong></td> <td>Vercel Blob (images), AWS S3 (archive), Cloudflare R2 (archive)</td> </tr> <tr> <td><strong>๐ Auth</strong></td> <td>NextAuth v5 with MongoDB adapter</td> </tr> <tr> <td><strong>๐ DevOps</strong></td> <td>Vercel (hosting), GitHub (VCS), Playwright (E2E tests)</td> </tr> <tr> <td><strong>โ๏ธ Testing</strong></td> <td>Vitest (unit/integration), Playwright (E2E)</td> </tr> <tr> <td><strong>๐ Search</strong></td> <td>PostgreSQL FTS + semantic search via Supabase</td> </tr> </table>๐ฆ Key Dependencies:
sharpโ Image resizing and cropping@google/generative-aiโ Gemini API integrationxml2jsโ USTC metadata parsing@modelcontextprotocol/sdkโ MCP server for agent integrationstripeโ Donation and subscription handling
๐ Core Features
๐ Reading & Navigation
- โก Page pagination โ Instant navigation between 100+ pages
- ๐ Full-text search โ Query across OCR'd text and translations
- ๐ Quote generation โ Copy and cite passages with DOI links
๐ Processing Pipeline
- ๐งฉ Smart split detection โ Automatic gutter detection for two-page spreads (Gemini AI or ML-based)
- โ๏ธ High-accuracy OCR โ Gemini Vision API with language-specific models (Latin, German, Greek, Arabic, etc.)
- ๐ฃ๏ธ Context-aware translation โ Maintains continuity across pages for scholarly accuracy
- ๐ผ๏ธ Gallery extraction โ AI-powered detection and cataloging of illustrations
๐จ Curation & Discovery
- ๐ Themed collections โ Editorial collections (e.g., "Alchemy & Transmutation," "Kabbalah & Mysticism")
- ๐๏ธ Gallery browsing โ Curated images from all books (museum-quality metadata)
- ๐ Related editions โ Link across translations, reprints, and derivative works
- ๐ Authority linking โ Connect to USTC, VIAF, and other scholarly databases
๐ค Scholarly Export
- ๐ฑ EPUB generation โ Multi-format ebook export
- ๐ PDF with annotations โ Preserve layout, add scholarly notes
- ๐ DOI minting โ Version books via Zenodo integration for long-term citation
๐ข Tenant Subdomains
- ๐๏ธ Isolated reading rooms โ Partners host curated subsets on custom domains (e.g.,
bph.sourcelibrary.org) - ๐จ Branding & navigation โ Full UI customization per tenant
- ๐ Access control โ Public or members-only collections
๐๏ธ Architecture Overview
๐ Data Model
๐ Books contain structured metadata:
- ๐๏ธ Bibliographic โ Title, author, language, publication date, USTC ID
- ๐ผ๏ธ Images โ Links to source (Internet Archive, Gallica, etc.), archival status
- โ๏ธ Processing โ OCR status, translation language, extraction metadata
- ๐จ Curation โ Collections, tier (featured/standard), visibility flags
๐ Pages store individual page data:
- ๐ธ Original image โ Source photo or PDF page
- โ๏ธ Split coordinates โ Crop boundaries (0-1000 scale) for two-page spreads
- โ๏ธ OCR output โ Raw Gemini extraction + language metadata
- ๐ฃ๏ธ Translation โ English translation with scholarly notes
- ๐ผ๏ธ Illustrations โ Detected images with quality scores and descriptions
๐ผ๏ธ Gallery images are extracted illustrations:
- ๐ท๏ธ Metadata โ Subject, figures, symbols, style, techniques, period
- โญ Quality score โ 0โ1.0 rating (filters below 0.5)
- ๐ Provenance โ Source book and page, linked back
๐จ Image Tier System
All page images are resized on-demand via /api/image:
| Tier | Dimensions | Quality | ๐ฑ Use Case |
|---|---|---|---|
| Thumbnail | 400px wide | 70% JPEG | Grids, navigation, social sharing |
| Display | 1200px wide | 80% JPEG | Main reading view, comfortable for annotation |
| Full | 2400px wide | 90% JPEG | Magnifier, fullscreen detail, printing |
Split pages are cropped non-destructively via coordinates; original images are always preserved.
๐ Processing Pipeline
๐ฅ Import โ โ๏ธ Split Detection โ โ๏ธ OCR โ ๐ฃ๏ธ Translation โ ๐จ Enrichment โ ๐ Publishing
- ๐ฅ Import โ Upload images, import from IA/Gallica via IIIF, or paste URLs
- โ๏ธ Split Detection โ Detect two-page spreads; mark crop boundaries
- โ๏ธ OCR โ Gemini Vision extracts text per page language
- ๐ฃ๏ธ Translation โ Gemini translates to English with prior-page context for continuity
- ๐จ Enrichment โ Extract illustrations, generate summaries, assign collections
- ๐ Publishing โ Set
visible: true, mint DOI, push to search index
Batch endpoints process up to 5 pages/request using Gemini Batch API (50% cheaper).
๐ API Routes (Key)
Base URL: https://sourcelibrary.org (production) or http://localhost:3000 (local dev with .env.local configured).
Common 404 mistake: paths like
/api/bph/booksor/api/bph/books/[id]do not exist. BPH catalogue APIs live under/api/embed/bph/.... There is also no top-level/api/[tenant]/booksroute โ tenant book listings use/api/books/libraryor the embed routes below.
Public read APIs (no auth required today)
| Endpoint | Method | Purpose |
|---|---|---|
/api/search?q=<query> | GET | Full-text search across books and page translations |
/api/books?limit=100&offset=0 | GET | Simple book list (global catalogue; visible: true, indexed only) |
/api/books/library?limit=100&skip=0 | GET | Rich browse API โ search, sort, filters, collections |
/api/books/[id] | GET | Book metadata (accepts Mongo id or slug) |
/api/books/[id]/quote?page=<n> | GET | Citable quote + formatted citations (inline, footnote, BibTeX, DOI) |
/api/gallery?limit=24 | GET | Illustration / artwork search |
/api/image?url=<encoded-url>&w=400 | GET | On-demand image resize & crop |
/api/embed/bph/books?limit=24 | GET | BPH catalogue (paginated, searchable) |
/api/embed/bph/books/[slug] | GET | Single BPH book detail |
/api/embed/bph/featured | GET | Featured BPH books |
/api/embed/bph/collections | GET | BPH collection list |
/api/embed/bph/languages | GET | BPH language facets |
/api/embed/bph/suggest?q=alch | GET | BPH search autocomplete |
/api/embed/bph/stats | GET | BPH catalogue stats |
Tenant-scoped listing (not /api/bph/...)
Use one of these patterns to filter by partner tenant (e.g. BPH):
| Approach | Example |
|---|---|
| Embed prefix (recommended for BPH) | GET /api/embed/bph/books?limit=24 |
| Library API + query param | GET /api/books/library?tenant_slug=bph&limit=24 |
| Host header (subdomain) | Call https://bph.sourcelibrary.org/api/books/library?limit=24 โ the proxy injects tenant context |
| Manual header (advanced) | curl -H "x-tenant-slug: bph" https://sourcelibrary.org/api/books/library?limit=24 |
The /api/[tenant]/books/[id]/... paths that exist in the codebase are editor/processing routes (batch OCR, index rebuild, etc.) โ not public catalogue listings.
Authenticated / internal APIs
These require a signed-in session cookie, editor role, or (for some dataset endpoints) a Bearer API key. Calling them without auth returns 401 or 403.
| Endpoint | Method | Purpose |
|---|---|---|
/api/books | POST | Create a new book (editor) |
/api/books/[id] | PATCH | Update book metadata (curator+) |
/api/books/[id]/batch-ocr-async | POST | Queue batch OCR job |
/api/books/[id]/batch-translate-async | POST | Queue batch translation job |
/api/pages/[id] | PATCH | Update page OCR/translation |
/api/jobs/[id]/process | POST | Async job processor (Lambda) |
Full narrative API walkthrough: docs/blog-source-library-api.md. MCP tools (search, quote, read): mcp-server/README.md.
๐งช Trying the API (curl, Postman, browser)
All examples below hit production and need no API key. Replace the base URL with http://localhost:3000 when running locally (MongoDB + env vars required).
curl
# Search translated text
curl -s "https://sourcelibrary.org/api/search?q=quintessence&limit=5" | jq .
# List books (global catalogue)
curl -s "https://sourcelibrary.org/api/books?limit=5" | jq .
# Browse with filters and sort
curl -s "https://sourcelibrary.org/api/books/library?limit=5&sort=recent-translation&has_translation=true" | jq .
# BPH catalogue โ note /api/embed/bph/, NOT /api/bph/
curl -s "https://sourcelibrary.org/api/embed/bph/books?limit=5&translated=true" | jq .
# BPH via tenant_slug on the library endpoint
curl -s "https://sourcelibrary.org/api/books/library?tenant_slug=bph&limit=5" | jq .
# Book metadata (id or slug)
curl -s "https://sourcelibrary.org/api/books/know-thyself-reger-von-ehrenhart" | jq .
# Citable quote for a page
curl -s "https://sourcelibrary.org/api/books/6836f8ee811c8ab472a49e36/quote?page=57" | jq .
# Gallery search
curl -s "https://sourcelibrary.org/api/gallery?subject=alchemy&limit=5" | jq .
Pretty-printing with jq is optional; omit | jq . to see raw JSON.
Postman
- Create a new GET request.
- Set URL to e.g.
https://sourcelibrary.org/api/embed/bph/books - On the Params tab add query keys:
limit=24,sort=title,translated=true - Leave Auth as No Auth for the public endpoints above.
- Send โ expect
200with JSON body.

Browser
Public GET endpoints can be opened directly:
๐ Directory Structure
src/
โโโ app/ # ๐จ Next.js App Router
โ โโโ book/[id]/ # ๐ Book detail, reading, processing
โ โ โโโ page.tsx # Main book hub
โ โ โโโ split/page.tsx # Split detection workflow
โ โ โโโ page/[pageId]/page.tsx # Individual page view
โ โโโ api/ # ๐ All API routes
โ โ โโโ books/ # Book CRUD & batch ops
โ โ โโโ pages/ # Page processing
โ โ โโโ image/ # Image proxy & cropping
โ โ โโโ jobs/ # Async job tracking
โ โ โโโ search/ # Full-text & semantic
โ โโโ [tenant]/ # ๐ข Tenant subdomain routes
โ โโโ gallery/ # ๐ผ๏ธ Illustration browsing
โ โโโ collections/ # ๐ Collection pages
โ โโโ admin/ # โ๏ธ Admin dashboard
โโโ hooks/ # ๐ฃ Reusable React hooks
โโโ lib/ # ๐ ๏ธ Business logic & utilities
โโโ mongodb.ts # Database operations
โโโ image-extraction.ts # Illustration detection
โโโ auth-helpers.ts # Authentication utilities
scripts/
โโโ workers/ # โ๏ธ Lambda worker functions
โ โโโ pipeline-orchestrator.mjs # Main processing pipeline
โ โโโ image-extract-worker.mjs # Gallery extraction
โ โโโ ...
โโโ maintenance/ # ๐ง One-off maintenance scripts
โโโ migrations/ # ๐ Database schema updates
โโโ audit-bph-leaks.mjs # ๐ Tenant security verification
tests/
โโโ unit/ # โ๏ธ Vitest unit tests
โโโ integration/ # ๐ Integration tests
prompts/ # ๐ค AI system prompts
โโโ ocr/
โโโ translation/
โโโ split-detection/
โโโ ...
.claude/ # ๐ง AI agent context
โโโ docs/ # ๐ Detailed architecture docs
โโโ skills/ # ๐ฏ Specialized agent skills
โโโ handoffs/ # ๐ Incident reports & lessons
๐ Common Workflows
๐ฅ Importing Books from Internet Archive
// From the UI or via API
POST /api/books
{
"ia_id": "thehermetic00fludd",
"title": "The Hermetic and Alchemical Writings",
"author": "Arthur Edward Waite",
"language": "en",
"ustc_id": "123456"
}
The system:
- ๐ฅ Fetches page images from IA IIIF
- โ๏ธ Detects splits and generates crop coordinates
- ๐ค Queues for OCR and translation
- ๐ Publishes when processing completes
โ๏ธ Processing a Split Book
- ๐ฅ๏ธ Visit
/book/[id]/split - ๐ฑ๏ธ Adjust split line visually (drag or Gemini AI auto-detection)
- โ Click "Apply Split" โ creates two virtual pages with crop coordinates
- ๐ธ Original images preserved; OCR runs on cropped versions
โ๏ธ Batch OCR with Gemini Batch API
POST /api/books/[id]/batch-ocr-async
{
"page_ids": ["page-1", "page-2", "page-3"],
"language": "la"
}
Returns a job ID; Gemini processes offline, saves results when complete. 50% cheaper than standard API.
๐ Generating a Scholarly Edition
POST /api/books/[id]/editions
{
"title": "The Emerald Tablet: First Complete English Translation",
"translator": "Jane Doe",
"language": "en",
"format": "epub"
}
System generates:
- ๐ Scholarly front matter (introduction, translator bio, etc.)
- ๐ฑ EPUB with TOC and metadata
- ๐ DOI via Zenodo integration
- ๐ Citation metadata (BibTeX, RIS)
๐งช Testing
๐ Run Tests
# Unit tests
npm run test:unit
# Integration tests
npm run test:integration
# End-to-end tests (Playwright)
npm run test:e2e
# Coverage report
npm run test:coverage
# Watch mode
npm run test:watch
โ E2E Test Examples
- ๐ฅ Book import โ Validate IA ingestion pipeline
- โ๏ธ Split detection โ Verify gutter detection accuracy
- ๐ Translation โ Confirm source/translation alignment
- ๐ Tenant subdomain โ Ensure content isolation (no leaks)
- ๐ Search โ Test full-text and semantic indexing
๐ Deployment
๐ Staging (Preview)
Every pushed branch auto-deploys to Vercel preview:
git push origin feat/my-feature
# โ Vercel builds and deploys
# โ Preview URL in GitHub PR
๐ Production
Merge to main via PR โ automatic Vercel deploy to sourcelibrary.org
โ Pre-deployment checklist:
- Tests pass (
npm run test) - TypeScript check passes (
npx tsc --noEmit) - No hardcoded secrets or credentials
- Tenant subdomain leak audit passes (
node scripts/audit-bph-leaks.mjs) - PR reviewed and approved
๐ Environment Variables
Required (.env.local):
MONGODB_URI=mongodb+srv://...
NEXTAUTH_SECRET=<random-secret>
GOOGLE_API_KEY=<gemini-key>
VERCEL_BLOB_TOKEN=<vercel-blob-token>
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
Optional:
STRIPE_SECRET_KEY=<for-donations>
ZENODO_TOKEN=<for-doi-minting>
SUPABASE_URL=<for-embeddings>
๐ Documentation
- ๐บ๏ธ System Map โ Comprehensive architecture diagram and file index
- ๐๏ธ ARCHITECTURE.md โ Data model, workflows, and design decisions
- ๐ค AGENTS.md โ Technical context for AI agents and automated workers
- ๐ CLAUDE.md โ Development workflow, PR conventions, critical invariants
- ๐ AUTH_IMPLEMENTATION.md โ NextAuth setup and tenant auth
- ๐ฆ Batch OCR Workflow โ Using Gemini Batch API
- ๐ API Documentation โ REST API reference
- ๐ผ๏ธ Image Processing โ How cropping and resizing works
๐ค Contributing
We welcome contributions! Please follow our development workflow:
-
๐ฟ Create a feature branch (off
main):# Using git worktree for multi-session safety git worktree add .claude/worktrees/feat-xyz feat/xyz cd .claude/worktrees/feat-xyz -
โ๏ธ Make changes and test:
npm run lint npm run test npm run test:e2e -
๐ค Push and create a PR:
git push origin feat/xyz gh pr create --base main -
๐ PR guidelines:
- One concern per PR โ Don't bundle refactors with features
- Verify deletions โ Always
grep -rnbefore deleting code - Run type check โ
npx tsc --noEmitbefore submitting - Describe scope โ State what's in scope AND out of scope
๐ฏ What We're Looking For
- ๐ Bug fixes with test coverage
- โจ Feature implementations aligned with project mission
- โก Performance improvements with benchmarks
- ๐ Documentation improvements
- โฟ UX/accessibility enhancements
- ๐ข Tenant integration examples
๐ข Reporting Issues
- ๐ Bugs โ Include reproduction steps, expected vs. actual behavior
- ๐ก Feature requests โ Explain the use case and user impact
- โ Questions โ Open an issue
๐ก๏ธ Security & Data Protection
- ๐ซ No deletion without approval โ All book/page deletions require explicit confirmation
- ๐ Tenant isolation โ Tenant subdomains are closed systems (no cross-tenant leaks)
- ๐ Secret management โ All secrets via environment variables, never hardcoded
- โ๏ธ AGPL licensing โ Contributions must respect AGPL-3.0-or-later
See CLAUDE.md Security for detailed security policies.
๐ Current Status
๐ Active Corpus:
- ๐ ~29K books with
visible: true - โ ~15K fully processed (OCR'd and translated)
- ๐ ~14K with full English translations
- ๐ผ๏ธ ~5K gallery images curated
โ๏ธ Processing Capacity:
- ๐ฅ 15K+ pages/month ingestion
- ๐ฃ๏ธ Multi-language support (Latin, German, Greek, Arabic, Sanskrit, Chinese, etc.)
- ๐ฐ Batch API for 50% cost reduction
๐ข Platform Tenants:
- ๐ฎ Bibliotheca Philosophica Hermetica โ Hermetica & esoterica
- โ๏ธ Kloss Collection โ Medical alchemy
- ๐ค Additional partners in development
๐ License
Source Library is licensed under the GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later). All contributions must respect this license.
See LICENSING.md for details on third-party licenses and attribution.
๐ Support & Community
- ๐ Found a bug? Open an issue
- ๐ค Want to collaborate? Contribute
- ๐ Visit the site โ sourcelibrary.org
<div align="center">
๐ Digitizing history. Making primary sources readable. Building open scholarship.
</div>src/
โโโ app/ # All routes, pages, and API endpoints
โ โโโ api/ # API routes
โ โโโ book/ # Book pages (detail, read, pipeline)
โ โโโ page.tsx # Homepage
โโโ components/ # Reusable React components
โโโ hooks/ # Reusable React hooks for component logic
โโโ lib/ # Business Logic, Utilities (mongodb, ai, types), and Services