#!/usr/bin/env python3 """ repoire_embed.py: the Quantum Repoire desktop client. Embeds your message ON YOUR OWN COMPUTER and writes a .rpv file holding a single 1024-number vector (the normalised sum of your sentence embeddings). Your text never leaves your machine; you upload only the .rpv file. It can also match your own sentences privately against anyone's submission: it downloads their vector and does the scoring locally. Setup (once; Python 3.9+): python3 -m venv repoire-env source repoire-env/bin/activate (Windows: repoire-env\\Scripts\\activate) pip install -U llama-cpp-python huggingface_hub numpy Make a submission: python repoire_embed.py make my_message.txt -> my_message.rpv python repoire_embed.py make (paste text, end with Ctrl-D / Ctrl-Z) Then upload the .rpv file at https://www.quantumrepoire.com/submit.html Match privately against a submission: python repoire_embed.py match rp-k3f9q2xm my_sentences.txt python repoire_embed.py match rp-k3f9q2xm (type sentences one by one) python repoire_embed.py match someones_file.rpv my_sentences.txt The first run downloads the embedding model (Qwen3-Embedding-0.6B, ~640 MB) and the site's small reference files; both are cached afterwards. Write one idea per line or ordinary sentences; each sentence is embedded separately. """ import argparse import json import os import sys import urllib.parse import urllib.request import numpy as np SERVER = "https://www.quantumrepoire.com" CLIENT_PATH = "/repoire/client/" CGI = "/cgi-bin/repoire.cgi" CACHE = os.path.join(os.path.expanduser("~"), ".repoire") WS = " \t\n\r\f\v" # same whitespace set as C isspace() def _words(s): return [w for w in "".join(" " if c in WS else c for c in s).split(" ") if w] # ---------------------------------------------------------------- shared rules def split_sentences(text): """Must match repoire::split_sentences in util.cpp.""" out = [] for line in text.split("\n"): start = 0 for i, c in enumerate(line): if c in ".!?" and i + 1 < len(line) and line[i + 1] in WS: piece = line[start:i + 1].strip(WS) if len(_words(piece)) >= 2: out.append(piece) start = i + 1 piece = line[start:].strip(WS) if len(_words(piece)) >= 2: out.append(piece) return out def write_rpv(path, model_tag, v): with open(path, "w", encoding="ascii") as f: f.write(f"repoire-vec 1\nmodel {model_tag}\ndims {len(v)}\n") for i in range(0, len(v), 8): f.write(" ".join(f"{x:.9g}" for x in v[i:i + 8]) + "\n") def parse_rpv(text): tok = text.split() if tok[:2] != ["repoire-vec", "1"] or tok[2] != "model" or tok[4] != "dims": raise ValueError("not a repoire-vec 1 file") dims = int(tok[5]) v = np.array([float(x) for x in tok[6:6 + dims]], np.float32) if len(v) != dims or len(tok) != 6 + dims: raise ValueError("vector length does not match dims") return tok[3], v / np.linalg.norm(v) # ---------------------------------------------------------------- server files def fetch(url): req = urllib.request.Request(url, headers={"User-Agent": "repoire-client/1"}) with urllib.request.urlopen(req, timeout=60) as r: return r.read() def load_reference(server): """Downloads (once) the public background mean and reference matrix.""" manifest = json.loads(fetch(server + CLIENT_PATH + "manifest.json")) d = os.path.join(CACHE, manifest["model_tag"]) os.makedirs(d, exist_ok=True) for name in ("mu.f32", "reference.f32"): p = os.path.join(d, name) cached_manifest = os.path.join(d, "manifest.json") stale = not os.path.exists(cached_manifest) or json.load(open(cached_manifest)) != manifest if stale or not os.path.exists(p): with open(p, "wb") as f: f.write(fetch(server + CLIENT_PATH + name)) json.dump(manifest, open(os.path.join(d, "manifest.json"), "w")) dims = manifest["dims"] mu = np.fromfile(os.path.join(d, "mu.f32"), dtype="> 30)) * 0xBF58476D1CE4E5B9) & M z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & M z ^= z >> 31 acc[i] += 2.0 * ((z >> 11) / 9007199254740992.0) - 1.0 n = np.linalg.norm(acc) return (acc / n if n else acc).astype(np.float32) class Embedder: def __init__(self, manifest): self.dims = manifest["dims"] if os.environ.get("REPOIRE_STUB"): self.raw = stub_embed return import llama_cpp from llama_cpp import Llama print(f"Loading {manifest['model_file']} (first run downloads it)...", file=sys.stderr) self.llm = Llama.from_pretrained( repo_id=manifest["model_repo"], filename=manifest["model_file"], embedding=True, pooling_type=llama_cpp.LLAMA_POOLING_TYPE_LAST, n_ctx=512, n_batch=512, n_ubatch=512, n_gpu_layers=-1, verbose=False) # Same tokenisation as the server: add_special=True, parse_special=False, no manual EOS. self.raw = lambda t: np.asarray(self.llm.embed(t, normalize=True), np.float32) def sentence(self, text, mu): """embed -> truncate -> normalise -> subtract mu -> normalise (matches util.cpp).""" v = self.raw(text)[: self.dims].astype(np.float32) v /= np.linalg.norm(v) v = v - mu return v / np.linalg.norm(v) # ---------------------------------------------------------------- commands def read_text(path): if path: return open(path, encoding="utf-8").read() print("Paste your text, then press Ctrl-D (macOS/Linux) or Ctrl-Z Enter (Windows):", file=sys.stderr) return sys.stdin.read() def privacy_note(n): if n < 15: return ("very few sentences: anyone holding your vector can likely read your topics and may " "recover the gist of your most distinctive sentences") if n < 40: return "your topics are readable from the vector; individual sentences are harder to recover" return "more sentences give more cover, but each one matches others less sharply" def cmd_make(a): manifest, mu, _ = load_reference(a.server) sentences = split_sentences(read_text(a.file)) lo = max(1, manifest.get("min_sentences", 0)) if len(sentences) < lo: sys.exit(f"Found {len(sentences)} sentences; the server needs at least {lo}.") emb = Embedder(manifest) S = np.zeros(manifest["dims"], np.float32) for i, s in enumerate(sentences, 1): S += emb.sentence(s, mu) print(f"\r embedded {i}/{len(sentences)}", end="", file=sys.stderr) print(file=sys.stderr) S /= np.linalg.norm(S) out = a.output or (os.path.splitext(a.file)[0] + ".rpv" if a.file else "message.rpv") write_rpv(out, manifest["model_tag"], S) print(f"Wrote {out} ({len(sentences)} sentences -> {manifest['dims']} numbers)") print(f"Privacy: {privacy_note(len(sentences))}.") print(f"Upload it at {a.server}/submit.html") def cmd_match(a): manifest, mu, R = load_reference(a.server) if os.path.exists(a.target): model, S = parse_rpv(open(a.target).read()) else: url = a.server + CGI + "?" + urllib.parse.urlencode({"a": "vector", "name": a.target}) model, S = parse_rpv(fetch(url).decode()) if model != manifest["model_tag"]: sys.exit(f"That vector was made with '{model}', but the site now uses '{manifest['model_tag']}'.") ref = R @ S m0, s0 = float(ref.mean()), float(ref.std()) emb = Embedder(manifest) zs, zl, zw = manifest.get("z_strong", 4), manifest.get("z_likely", 3), manifest.get("z_weak", 2) def verdict(z): return ("strong match" if z >= zs else "likely match" if z >= zl else "weak / same general area" if z >= zw else "no match") if a.file: sentences = split_sentences(open(a.file, encoding="utf-8").read()) rows = [] for s in sentences: z = (float(emb.sentence(s, mu) @ S) - m0) / s0 rows.append((z, s)) rows.sort(reverse=True) for z, s in rows: print(f"z = {z:5.1f} {verdict(z):<25} {s[:90]}") hits = sum(1 for z, _ in rows if z >= zl) print(f"\nCoverage: {hits}/{len(rows)} of your sentences match ({hits / max(1, len(rows)):.0%}).") print("Share this fraction (not your sentences) with the other person to compute a mutual score.") else: print("Type a sentence and press Enter (empty line to quit).") while True: try: s = input("> ").strip() except EOFError: break if not s: break z = (float(emb.sentence(s, mu) @ S) - m0) / s0 print(f" z = {z:5.1f} {verdict(z)}") def main(): p = argparse.ArgumentParser(description="Quantum Repoire desktop client") p.add_argument("--server", default=SERVER) sub = p.add_subparsers(dest="cmd", required=True) m = sub.add_parser("make", help="embed a message into a .rpv file") m.add_argument("file", nargs="?") m.add_argument("-o", "--output") t = sub.add_parser("match", help="match your sentences against a submission, locally") t.add_argument("target", help="submission name (rp-...) or a .rpv file") t.add_argument("file", nargs="?", help="file with your sentences (omit for interactive)") a = p.parse_args() a.server = a.server.rstrip("/") cmd_make(a) if a.cmd == "make" else cmd_match(a) if __name__ == "__main__": main()