MARCmin · Run it offline · Draft recipe
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.
Start small. Keyword search alone needs no AI model at all, and it is the cheapest place to begin.
Raspberry Pi 5 with 8 GB, or a similar single-board computer
Best as a self-service catalog kiosk. Build the index elsewhere and copy it over.
A fanless mini PC with 16 GB of memory
The likely sweet spot for a branch or a bookmobile.
A desktop or server with a graphics card, or a library's existing server
Runs inside the library's own network, so it stays private without being offline.
Vectors for 100,000 records from a small 384-dimension embedding model, before index overhead. From the calculator in Chapter 2.
Binary vectors keep about 96% of retrieval quality when the top results are re-checked (Hugging Face, 2024).
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.
Turn each record into labeled, readable text with the starter code. Save one JSON line per record: an id and the text.
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.
Copy the database and the model files. After the first download, set HF_HUB_OFFLINE=1 so the model loads with no network.
Run the search script behind a simple local web page, and open it in a browser in kiosk mode.
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.
Re-export nightly or weekly. Only records whose 005 timestamp changed need re-encoding.
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. 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. 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])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.
Developers and library IT staff: test the recipe on a Raspberry Pi or a mini PC and share what you measure.