MARCmin · Run it offline · Draft recipe

Catalog search on one small device, no internet needed

The index, a small model and the patron's question all live on one machine in the branch. Questions never leave the building. This page is a starting recipe for three sizes of hardware.

Not yet tested on these devices. The code below has been run on real catalog records, but not on a Raspberry Pi or mini PC. Speeds depend on the device, model and settings, so measure your own. If you try it, tell us how it went.

Pick a size

Start small. Keyword search alone needs no AI model at all, and it is the cheapest place to begin.

Kiosk

Raspberry Pi 5 with 8 GB, or a similar single-board computer

  • Keyword search over a branch or system catalog
  • Meaning-based search with a small embedding model
  • Short answers from a small language model, slowly

Best as a self-service catalog kiosk. Build the index elsewhere and copy it over.

Branch

A fanless mini PC with 16 GB of memory

  • Everything the kiosk does, faster
  • A small language model that reads the top few records and answers
  • Several staff or patron screens on the branch network

The likely sweet spot for a branch or a bookmobile.

System

A desktop or server with a graphics card, or a library's existing server

  • Building and refreshing indexes for every branch
  • Larger embedding and language models
  • Testing which model is the smallest that still works

Runs inside the library's own network, so it stays private without being offline.

How much room the index needs

Vectors for 100,000 records from a small 384-dimension embedding model, before index overhead. From the calculator in Chapter 2.

154 MBfull precision (32-bit)
38 MB8-bit, which usually loses little
4.8 MB1-bit, best as a fast first pass with a re-check

Binary vectors keep about 96% of retrieval quality when the top results are re-checked (Hugging Face, 2024).

The recipe

  1. Export your records

    Use your library system's standard MARC export, the same kind sent to discovery services. Prefer UTF-8. Nothing is written back to the system.

  2. Pre-encode them

    Turn each record into labeled, readable text with the starter code. Save one JSON line per record: an id and the text.

  3. Build the index on a bigger machine

    Create a keyword index and an 8-bit vector for each record in one SQLite file (code below). This is the slow step, and it only runs when records change.

  4. Copy it to the device

    Copy the database and the model files. After the first download, set HF_HUB_OFFLINE=1 so the model loads with no network.

  5. Serve a local search page

    Run the search script behind a simple local web page, and open it in a browser in kiosk mode.

  6. Add answers, optionally

    Give a small local language model, run with llama.cpp or Ollama, only the top 3 to 5 records and ask it to answer from them with citations.

  7. Refresh on a schedule

    Re-export nightly or weekly. Only records whose 005 timestamp changed need re-encoding.

Starter code

Two short Python scripts: one builds the index, the other searches it. They combine search by meaning with keyword search, and use one SQLite file for both. Requires pip install sentence-transformers numpy.

build_index.py, run once on a bigger machine

# build_index.py: run once on a bigger machine. Reads pre-encoded records, writes catalog.db.
import json, sqlite3
import numpy as np
from sentence_transformers import SentenceTransformer

records = [json.loads(line) for line in open("records.jsonl")]  # {"id": ..., "text": pre-encoded record}
db = sqlite3.connect("catalog.db")
db.execute("CREATE VIRTUAL TABLE IF NOT EXISTS books USING fts5(id UNINDEXED, text)")
db.executemany("INSERT INTO books VALUES (?, ?)", [(r["id"], r["text"]) for r in records])

model = SentenceTransformer("BAAI/bge-small-en-v1.5")  # 384 dimensions
vecs = model.encode([r["text"] for r in records], normalize_embeddings=True, batch_size=32)
q8 = np.clip(np.round(vecs * 127), -127, 127).astype(np.int8)  # 8-bit: a quarter of the size
db.execute("CREATE TABLE IF NOT EXISTS vectors (id TEXT PRIMARY KEY, v BLOB)")
db.executemany("INSERT INTO vectors VALUES (?, ?)", [(r["id"], v.tobytes()) for r, v in zip(records, q8)])
db.commit()

search.py, runs on the device

python search.py fossils of the South Dakota badlands
# search.py: runs on the device. No network needed once the model files are copied over.
import sqlite3, sys
import numpy as np
from sentence_transformers import SentenceTransformer

db = sqlite3.connect("catalog.db")
ids, blobs = zip(*db.execute("SELECT id, v FROM vectors"))
matrix = np.frombuffer(b"".join(blobs), dtype=np.int8).reshape(len(ids), -1).astype(np.float32) / 127
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
prefix = "Represent this sentence for searching relevant passages: "

def search(question, k=5):
    q = model.encode(prefix + question, normalize_embeddings=True)
    by_meaning = [ids[i] for i in np.argsort(-(matrix @ q))[:k]]
    words = " OR ".join(w.lower() for w in question.split() if w.isalnum())  # lowercase: FTS5 treats OR/AND/NOT as operators
    by_words = [r[0] for r in db.execute("SELECT id FROM books WHERE books MATCH ? ORDER BY rank LIMIT ?", (words, k))] if words else []
    return list(dict.fromkeys(by_meaning + by_words))[:k]  # meaning first, then keyword hits

for book_id in search(" ".join(sys.argv[1:])):
    print(db.execute("SELECT text FROM books WHERE id = ?", (book_id,)).fetchone()[0].split("\n")[0])

What it doesn't do

It does not replace the library system or its public catalog. Live status, such as whether a copy is on the shelf, still comes from the library system. Offline search is only as current as the last export. Reading full books offline needs those books on the device too; catalog search does not. See how it fits beside your library system.

Try it on real hardware

Developers and library IT staff: test the recipe on a Raspberry Pi or a mini PC and share what you measure.