#!/usr/bin/env python3 """Rank the generic place nouns by embedding similarity to an input text. This is the Space port of the command-line script `embed_compare.py`. The CLI shelled out to llama.cpp's `llama-embedding` binary once per batch; here we call the same llama.cpp through `llama_cpp.Llama.embed()`, so the only change is how the vectors are produced. Pooling, normalisation and ranking are unchanged, and the two paths agree to float32 precision (~5e-08). Model: Octen-Embedding-0.6B.Q4_K_M.gguf (Qwen3-Embedding-0.6B base: last-token pooling, L2 normalised, 1024 dims). The model card encodes bare text with no instruction prefix, so none is added by default. generic_nouns.txt is a commented record file: '#' lines and blank lines are skipped, everything else is one noun. We embed the class nouns as-is; the file is a record, not a blocklist. # rank all nouns against a text, show the top 25 python3 embed_compare.py "We hiked along the ridge above the fjord." # compare two texts side by side + the nouns best matching each python3 embed_compare.py --text a.txt --text b.txt --top 10 # find where one noun sits among the others (nearest neighbours) python3 embed_compare.py --lookup valley --top 15 # warm the vector cache (later runs skip re-embedding the nouns) python3 embed_compare.py --build-cache Options that matter: --pooling last|mean|cls pooling type (default: model default = last) --prefix-text S string prepended to the input text only --prefix-noun S string prepended to each noun only --json OUT.json write the full ranking as JSON --no-cache re-embed the nouns instead of using the cache --threads N CPU threads for llama.cpp (default: llama.cpp's) Exit status: 0 on success, 2 on bad input (missing file, no nouns, etc.). """ import argparse import hashlib import json import math import os import re import sys from pathlib import Path HERE = Path(__file__).resolve().parent DEFAULT_MODEL = HERE / "models" / "Octen-Embedding-0.6B.Q4_K_M.gguf" DEFAULT_NOUNS = HERE / "generic_nouns.txt" DEFAULT_CACHE = HERE / ".embed_cache" # ---------------------------------------------------------------- loading def load_nouns(path): """Return the noun entries of generic_nouns.txt in file order. Lines starting with '#' and blank lines are skipped. An entry may occur in several sections; the first occurrence wins so order stays stable. """ nouns, seen = [], set() with open(path, encoding="utf-8") as f: for raw in f: line = raw.strip() if not line or line.startswith("#"): continue if line not in seen: seen.add(line) nouns.append(line) return nouns def die(msg): print(msg, file=sys.stderr) sys.exit(2) def read_input(item, from_file_option): """An input is an existing file path, otherwise the literal text. A --text value is unambiguous, so a path-shaped value that does not exist is an error rather than silently being embedded as a sentence. """ p = Path(item) if p.is_file(): return p.read_text(encoding="utf-8").strip() if from_file_option and (p.suffix or "/" in item) and not p.exists(): die(f"error: --text file not found: {item}") return item.strip() def sha256_file(path, chunk=1 << 20): h = hashlib.sha256() with open(path, "rb") as f: for block in iter(lambda: f.read(chunk), b""): h.update(block) return h.hexdigest() # ------------------------------------------------------------- embedding class Embedder: """Embed texts with llama.cpp, one batch at a time. Pooling is pinned to `last` rather than left to the model default so the Space matches the CLI's default explicitly. Embeddings are returned normalised and L2-normalised again here, which is idempotent and keeps the scale obvious at the call site. """ def __init__(self, model, *, pooling="last", threads=None, batch_size=2048, n_ctx=8192, n_batch=None, verbose=False): self.model = Path(model) if not self.model.is_file(): die(f"error: model not found: {self.model}") from llama_cpp import Llama # imported late: the CLI path needs no wheel self.llm = Llama( model_path=str(self.model), embedding=True, n_ctx=n_ctx, n_batch=n_batch or max(batch_size, 512), n_threads=threads, pooling_type=POOLING_TYPES[pooling], n_gpu_layers=0, logits_all=False, verbose=verbose, ) self.batch_size = batch_size @staticmethod def _one_line(text): return re.sub(r"\s+", " ", text).strip() or "(empty)" def __call__(self, texts): if not texts: return [] out = [] for i in range(0, len(texts), self.batch_size): chunk = [self._one_line(t) for t in texts[i:i + self.batch_size]] res = self.llm.embed(chunk, normalize=True) out.extend(l2_normalize(list(map(float, v))) for v in res) return out # llama.cpp pooling enum: LLAMA_POOLING_TYPE_NONE=0, MEAN=1, CLS=2, LAST=3, RANK=4 POOLING_TYPES = {"none": 0, "mean": 1, "cls": 2, "last": 3, "rank": 4} def l2_normalize(v): n = math.sqrt(sum(x * x for x in v)) return [x / n for x in v] if n else list(v) def cosine(a, b): # Both sides are already unit length; this is just the dot product. return sum(x * y for x, y in zip(a, b)) # ----------------------------------------------------------------- cache class VectorCache: """One JSON file per (model hash, pooling, prefix, noun set). Loading the 0.6B model costs a few seconds, so caching the noun vectors makes repeat comparisons nearly free. On the Space the cache is built once at image build time (see precompute_nouns.py), so the first visitor does not pay for it either. """ def __init__(self, directory, key): self.path = Path(directory) / f"{key}.json" def load(self): if not self.path.is_file(): return None try: with open(self.path, encoding="utf-8") as f: return json.load(f) except (json.JSONDecodeError, OSError): return None def save(self, payload): self.path.parent.mkdir(parents=True, exist_ok=True) tmp = self.path.with_suffix(".tmp") with open(tmp, "w", encoding="utf-8") as f: json.dump(payload, f) os.replace(tmp, self.path) def cache_key(model, nouns, *, pooling="", prefix_noun=""): h = hashlib.sha256() h.update(f"{model.get('sha256', model['path'])}|{pooling}|" f"{prefix_noun}".encode()) for n in nouns: h.update(b"\x00" + n.encode("utf-8")) return h.hexdigest()[:20] # ---------------------------------------------------------------- ranking def rank(nouns, noun_vecs, query_vec): scored = [(cosine(query_vec, v), n, v) for n, v in zip(nouns, noun_vecs)] scored.sort(key=lambda t: -t[0]) return scored def topk(scored, k): out = [] for i, (s, n, _) in enumerate(scored[:k], 1): out.append(f"{i:>3}. {s:6.4f} {n}") return "\n".join(out) def truncate(text, width=72): text = " ".join(text.split()) return text if len(text) <= width else text[: width - 1] + "\u2026" # ------------------------------------------------------------------- main def build_parser(): p = argparse.ArgumentParser( description="Rank the generic place nouns by embedding similarity to " "an input text (llama.cpp + Octen-Embedding-0.6B).", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__.split("Options that matter:")[1], ) p.add_argument("text", nargs="*", metavar="TEXT", help="input text, or a path to a text file; " "same as repeating --text") p.add_argument("--text", dest="texts", action="append", default=[], metavar="TEXT", help="input text or file path; repeat to compare several") p.add_argument("--lookup", metavar="NOUN", help="show the nouns nearest to this one instead") p.add_argument("--nouns", default=str(DEFAULT_NOUNS), metavar="FILE", help="noun list (default: generic_nouns.txt beside script)") p.add_argument("--model", default=str(DEFAULT_MODEL), metavar="GGUF") p.add_argument("--top", type=int, default=25, help="entries to show per ranking (default: 25; 0 = all)") p.add_argument("--bottom", action="store_true", help="also show the least similar entries") p.add_argument("--pooling", choices=["last", "mean", "cls", "rank"], default="last", help="pooling type (default: last)") p.add_argument("--prefix-text", default="", help="prepend this to the input text") p.add_argument("--prefix-noun", default="", help="prepend this to each noun") p.add_argument("--threads", type=int, help="CPU threads for llama.cpp") p.add_argument("--batch-size", type=int, default=2048) p.add_argument("--no-cache", action="store_true", help="re-embed the nouns instead of using the cache") p.add_argument("--build-cache", action="store_true", help="only build the noun-vector cache, then exit") p.add_argument("--cache-dir", default=str(DEFAULT_CACHE), metavar="DIR") p.add_argument("--json", metavar="OUT.json", help="write full rankings to this JSON file") return p def main(argv=None): args = build_parser().parse_args(argv) nouns = load_nouns(args.nouns) if not nouns: die(f"error: no noun entries in {args.nouns}") inputs = list(args.text) + list(args.texts) if not inputs and not args.lookup and not args.build_cache: die("error: give an input text, --text, --lookup or --build-cache") model_path = Path(args.model) if not model_path.is_file(): die(f"error: model not found: {model_path}") info = {"path": str(model_path), "sha256": sha256_file(model_path)} key = cache_key(info, nouns, pooling=args.pooling, prefix_noun=args.prefix_noun) cache = None if args.no_cache else VectorCache(args.cache_dir, key) cached = cache.load() if cache else None if cached and cached.get("nouns") != nouns: cached = None noun_vecs = cached["vectors"] if cached else None embedder = Embedder(model_path, pooling=args.pooling, threads=args.threads, batch_size=args.batch_size) if cache is None or cached is None: print(f"embedding {len(nouns)} nouns with " f"{model_path.name}\u2026", file=sys.stderr) noun_vecs = embedder([args.prefix_noun + n for n in nouns]) if cache is not None: cache.save({"nouns": nouns, "vectors": noun_vecs, "model": str(model_path), "sha256": info["sha256"], "pooling": args.pooling}) print(f"cached noun vectors in {cache.path}", file=sys.stderr) if args.build_cache and not inputs and not args.lookup: return 0 top = args.top if args.top > 0 else None report = {"model": str(model_path), "nouns": len(nouns), "pooling": args.pooling, "queries": []} if args.lookup: if args.lookup not in nouns: die(f"error: {args.lookup!r} is not in {args.nouns}") i = nouns.index(args.lookup) scored = rank(nouns, noun_vecs, noun_vecs[i])[1:] print(f"Nearest nouns to {args.lookup!r} ({args.pooling})") print(topk(scored, top)) if args.bottom: print("\nLeast similar:") print(topk(scored[::-1], min(top or len(scored), 10))) report["queries"].append({ "lookup": args.lookup, "ranking": [{"noun": n, "score": s} for s, n, _ in scored]}) else: # Positional values may be prose; --text values may also be paths. positional = [(t, False) for t in args.text] flagged = [(t, True) for t in args.texts] texts = [read_input(t, is_path_ok) for t, is_path_ok in positional + flagged] vecs = embedder([args.prefix_text + t for t in texts]) for text, vec in zip(texts, vecs): scored = rank(nouns, noun_vecs, vec) print(f"\n=== {truncate(text)}") print(topk(scored, top)) if args.bottom: print("\nLeast similar:") print(topk(scored[::-1], min(top or len(scored), 10))) report["queries"].append({ "text": text, "ranking": [{"noun": n, "score": s} for s, n, _ in scored]}) if len(texts) > 1: print("\n=== Input-vs-input similarity") for a in range(len(texts)): for b in range(a + 1, len(texts)): print(f" {cosine(vecs[a], vecs[b]):6.4f} " f"{truncate(texts[a], 32)} <-> " f"{truncate(texts[b], 32)}") if args.json: Path(args.json).write_text(json.dumps(report, indent=1), encoding="utf-8") print(f"wrote {args.json}", file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())