Spaces:
Paused

embed-compare / app.py
baiango's picture
Upload app.py with huggingface_hub
60f56a6 verified
Raw History Blame Contribute Delete
15 kB
"""Demo: where does a sentence fall among 627 place nouns?
Embeds the input text and every noun in generic_nouns.txt with
Octen-Embedding-0.6B through llama.cpp, L2-normalises both sides, and ranks
the nouns by cosine similarity. This is a browser front end for the
`embed_compare.py` command-line tool shipped alongside it (`python3
embed_compare.py "some text"`), using the same model, pooling, and ranking.
The noun matrix is built once per process and cached on disk (see
`.embed_cache/`), so a request only embeds the visitor's text: one short
forward pass, then a dot product against the matrix.
"""
import os
import sys
import threading
from array import array
from pathlib import Path
import numpy as np
import gradio as gr
import embed_compare as ec
HERE = Path(__file__).resolve().parent
# The 396 MB GGUF is not committed; it is pulled from the Hub at build time.
MODEL_REPO = "mradermacher/Octen-Embedding-0.6B-GGUF"
MODEL_FILE = "Octen-Embedding-0.6B.Q4_K_M.gguf"
MODEL_PATH = Path(os.environ.get("EMBED_MODEL", ec.DEFAULT_MODEL))
CACHE_DIR = Path(os.environ.get("EMBED_CACHE_DIR", ec.DEFAULT_CACHE))
NOUNS_PATH = Path(os.environ.get("EMBED_NOUNS", ec.DEFAULT_NOUNS))
# Pinned rather than left to the model default, so the Space says what it does.
POOLING = os.environ.get("EMBED_POOLING", "last")
PREFIX_NOUN = os.environ.get("EMBED_PREFIX_NOUN", "")
PREFIX_TEXT = os.environ.get("EMBED_PREFIX_TEXT", "")
EXAMPLES = [
"We hiked along the ridge above the fjord and camped by the lake.",
"Cold rain on the moors, wind over the fell; the beck ran high past "
"the sheepfold.",
"Sunday roast in the pub, then a walk past the allotments to the church.",
"The tidal flats stretch for miles at low water; cockles at dawn.",
"Send the invoice to the depot behind the retail park.",
]
_lock = threading.RLock() # setup() calls get_embedder(), which locks again
_state = {"ready": False, "nouns": [], "matrix": None, "error": None}
_embedder = {"emb": None}
# ------------------------------------------------------------------ setup
def _matrix_from_cache(cache, nouns):
"""Load the build-time float32 matrix, or None if absent/stale."""
meta = cache.load()
p = cache.path.with_name(cache.path.stem + "-f32.bin")
if not meta or not p.is_file():
return None
dims = int(meta.get("dims") or 1024)
flat = array("f")
with open(p, "rb") as f:
flat.frombytes(f.read())
if sys.byteorder != "little":
flat.byteswap()
if len(flat) != len(nouns) * dims:
print(f"cache shape mismatch: {len(flat)} floats, "
f"expected {len(nouns) * dims}", file=sys.stderr)
return None
return np.array(flat, dtype=np.float32).reshape(len(nouns), dims)
def ensure_model():
"""Download the GGUF from the Hub if it isn't already on disk."""
if MODEL_PATH.is_file():
return MODEL_PATH
from huggingface_hub import hf_hub_download
MODEL_PATH.parent.mkdir(parents=True, exist_ok=True)
print(f"downloading {MODEL_REPO}/{MODEL_FILE}...", file=sys.stderr)
got = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
print(f"downloaded to {got}", file=sys.stderr)
return Path(got)
def setup():
"""Load nouns + the precomputed matrix. Idempotent; safe under a lock."""
with _lock:
if _state["ready"] or _state["error"]:
return _state
try:
path = ensure_model()
if "EMBED_MODEL" not in os.environ and path != MODEL_PATH:
# Point the rest of the app (cache key, embedder) at the download.
globals()["MODEL_PATH"] = path
nouns = ec.load_nouns(NOUNS_PATH)
if not nouns:
raise RuntimeError(f"no noun entries in {NOUNS_PATH}")
key = ec.cache_key({"path": str(MODEL_PATH),
"sha256": ec.sha256_file(MODEL_PATH)},
nouns, pooling=POOLING, prefix_noun=PREFIX_NOUN)
cache = ec.VectorCache(CACHE_DIR, key)
mat = _matrix_from_cache(cache, nouns)
if mat is None:
# No matching matrix for this model/pooling: build it here.
# Slow on 1 vCPU (~6 min), which is why the default key ships.
print(f"cold cache, embedding {len(nouns)} nouns "
f"(pooling={POOLING!r})...", file=sys.stderr)
vecs = get_embedder()([PREFIX_NOUN + n for n in nouns])
mat = np.array(vecs, dtype=np.float32)
_state.update(ready=True, nouns=nouns, matrix=mat)
print(f"ready: {mat.shape[0]} nouns x {mat.shape[1]} dims "
f"({MODEL_PATH.name}, pooling {POOLING})", file=sys.stderr)
except Exception as e: # keep the UI up and say what broke
_state["error"] = f"{type(e).__name__}: {e}"
print(f"setup failed: {_state['error']}", file=sys.stderr)
return _state
def get_embedder():
"""Return the shared embedder, creating it once.
Called both from setup() (which already holds _lock) and from request
handlers, so the lock must be reentrant.
"""
with _lock:
if _embedder["emb"] is None:
# cpu-basic has 1 vCPU; the text embeddings here are short, so
# llama.cpp's own default is the best choice. Pinning to the
# affinity mask measured slower (75 s vs 50 s per request).
_embedder["emb"] = ec.Embedder(MODEL_PATH, pooling=POOLING)
return _embedder["emb"]
def embed_one(text):
v = np.asarray(get_embedder()([PREFIX_TEXT + text])[0], dtype=np.float32)
n = float(np.linalg.norm(v))
return v / n if n else v
def _table(header, rows, highlight=()):
th = "".join(f"<th>{h}</th>" for h in header)
body = []
for r in rows:
cls = ' class="hit"' if r[-1] in highlight else ""
body.append(f"<tr{cls}>" + "".join(f"<td>{c}</td>" for c in r) + "</tr>")
return (f"<table class='rank'><thead><tr>{th}</tr></thead>"
f"<tbody>{''.join(body)}</tbody></table>")
def _ranked(sc, nouns, k):
order = np.argsort(-sc)[:k]
return order, [[f"{i + 1}", f"{float(sc[j]):.4f}", nouns[j]]
for i, j in enumerate(order)]
def _rarest(sc, nouns, k):
"""The k least similar nouns, rarest first (rank 1 = lowest score)."""
order = np.argsort(sc)[:k]
return [[f"{i + 1}", f"{float(sc[j]):.4f}", nouns[j]]
for i, j in enumerate(order)]
# ------------------------------------------------------------------- demo
def compare(text_a, text_b, top_k):
"""Rank the 627 generic place nouns by similarity to your text.
Args:
text_a: a sentence or paragraph (required).
text_b: optional second text, ranked side by side. Empty to skip.
top_k: how many nouns to show per ranking (5-50).
Returns:
(html, html, markdown) — most similar nouns, least similar nouns, and
a short summary line.
"""
st = setup()
if st["error"]:
raise gr.Error(f"Model failed to load: {st['error']}")
text_a = (text_a or "").strip()
text_b = (text_b or "").strip()
if not text_a:
raise gr.Error("Enter some text to compare against the nouns.")
k = max(1, min(50, int(top_k or 15)))
nouns, mat = st["nouns"], st["matrix"]
# Both sides are unit length, so the dot product is the cosine.
if not text_b:
sc = mat @ embed_one(text_a)
order, rows = _ranked(sc, nouns, k)
bottom = _rarest(sc, nouns, k)
top = nouns[int(order[0])]
last = bottom[0][2]
return (_table(["#", "score", "noun"], rows),
_table(["#", "score", "noun"], bottom),
f"**Top match:** `{top}` — cosine {float(sc[order[0]]):.4f}. "
f"**Rarest:** `{last}` — cosine {float(bottom[0][1]):.4f} "
f"across all {len(nouns)} nouns.")
va, vb = embed_one(text_a), embed_one(text_b)
sa, sb = mat @ va, mat @ vb
oa, ra = _ranked(sa, nouns, k)
ob, rb = _ranked(sb, nouns, k)
shared = set(oa.tolist()) & set(ob.tolist())
rows = [["{0}".format(i + 1)] + ra[i][1:] + rb[i][1:] for i in range(k)]
# Rarest = lowest mean similarity to both texts, so "far from each" wins.
mean_sc = (sa + sb) / 2.0
bottom = _rarest(mean_sc, nouns, k)
note = (f"**Text A vs Text B:** cosine {float(np.dot(va, vb)):.4f}. "
f"**Rarest to both:** `{bottom[0][2]}`, "
f"mean cosine {float(bottom[0][1]):.4f}.")
if shared:
note += (" In both top lists: "
+ ", ".join(f"`{nouns[j]}`" for j in oa if j in shared) + ".")
return (_table(["#", "score A", "noun A", "score B", "noun B"], rows,
highlight=shared),
_table(["#", "score", "noun"], bottom), note)
def lookup(noun, top_k):
"""Show the nouns closest to a chosen noun in embedding space.
Args:
noun: a noun that appears in generic_nouns.txt (e.g. "valley").
top_k: how many neighbours to show (5-50).
Returns:
(html, html, markdown) — nearest nouns, least similar nouns (both
excluding the noun itself), and a summary line.
"""
st = setup()
if st["error"]:
raise gr.Error(f"Model failed to load: {st['error']}")
noun = (noun or "").strip().lower()
if noun not in st["nouns"]:
raise gr.Error(f"'{noun}' is not in the noun list.")
k = max(1, min(50, int(top_k or 15)))
i = st["nouns"].index(noun)
sims = st["matrix"] @ st["matrix"][i]
order = [j for j in np.argsort(-sims).tolist() if j != i]
far = sorted((j for j in order), key=lambda j: sims[j])[:k]
rows = [[f"{r + 1}", f"{float(sims[j]):.4f}", st["nouns"][j]]
for r, j in enumerate(order[:k])]
bottom = [[f"{r + 1}", f"{float(sims[j]):.4f}", st["nouns"][j]]
for r, j in enumerate(far)]
return (_table(["#", "score", "noun"], rows),
_table(["#", "score", "noun"], bottom),
f"**Nearest to `{noun}`:** `{st['nouns'][order[0]]}`. "
f"**Rarest:** `{st['nouns'][far[0]]}` — "
f"among all {len(st['nouns'])} nouns.")
def noun_choices():
return setup()["nouns"] or ["valley"]
CSS = """
table.rank { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }
table.rank th, table.rank td { padding: 4px 10px; border-bottom: 1px solid var(--border-color-primary); text-align: left; }
table.rank th { font-weight: 600; opacity: 0.75; }
table.rank td:first-child, table.rank td:nth-child(2) { color: var(--body-text-color-subdued, #888); }
table.rank tr.hit td { background: var(--color-accent-soft, rgba(120,120,255,0.12)); }
table.rank td:nth-child(3), table.rank th:nth-child(3) { max-width: 22ch; overflow-wrap: anywhere; }
"""
with gr.Blocks(title="Embed Compare — place nouns") as demo:
gr.Markdown(
"# Where does your sentence land among 627 place nouns?\n"
"Every noun in `generic_nouns.txt` is embedded with "
"**Octen-Embedding-0.6B** (Qwen3-Embedding base, Q4_K_M, llama.cpp) — "
"the same model, pooling and ranking as the `embed_compare.py` CLI in "
"this repo. Paste a sentence to rank all 627 against it, or start from "
"a single noun to see its nearest neighbours.\n\n"
"*Similarity is a rough signal: with last-token pooling, a long "
"sentence mostly reflects how it ends.*"
)
with gr.Tab("Text vs. nouns"):
with gr.Row():
with gr.Column(scale=2, min_width=320):
gr.Markdown(
"Embeds your sentence and ranks all 627 nouns against it."
)
a = gr.Textbox(label="Text A", lines=3,
placeholder="We hiked along the ridge above the fjord…")
b = gr.Textbox(label="Text B (optional — compare two texts)",
lines=3, placeholder="Leave empty to rank a single text.")
k = gr.Slider(5, 50, value=15, step=1, label="Nouns to show")
btn = gr.Button("Rank nouns", variant="primary")
summary = gr.Markdown()
gr.Examples(EXAMPLES, inputs=a, label="Try one")
with gr.Column(scale=3, min_width=360):
out = gr.HTML(label="Ranked nouns")
with gr.Accordion("Rarest nouns", open=True):
out_lo = gr.HTML()
btn.click(compare, [a, b, k], [out, out_lo, summary], api_name="compare")
a.submit(compare, [a, b, k], [out, out_lo, summary])
with gr.Tab("Noun → nearest nouns"):
with gr.Row():
with gr.Column(scale=2, min_width=320):
gr.Markdown("Pick a noun to see which other place nouns sit "
"closest to it in embedding space. Instant: this "
"is a dot product against the precomputed matrix.")
pick = gr.Dropdown(choices=noun_choices(), value="valley",
label="Noun", filterable=True)
k2 = gr.Slider(5, 50, value=15, step=1, label="Neighbours")
btn2 = gr.Button("Find neighbours", variant="primary")
summary2 = gr.Markdown()
with gr.Column(scale=3, min_width=360):
out2 = gr.HTML()
with gr.Accordion("Rarest nouns", open=True):
out2_lo = gr.HTML()
btn2.click(lookup, [pick, k2], [out2, out2_lo, summary2],
api_name="lookup")
with gr.Accordion("How it works", open=False):
gr.Markdown(
f"- **Model:** `Octen-Embedding-0.6B.Q4_K_M.gguf` — 1024 dims, "
f"last-token pooling, L2-normalised, no instruction prefix "
f"(per the model card).\n"
f"- **Nouns:** {len(ec.load_nouns(NOUNS_PATH))} entries from "
f"`generic_nouns.txt`. Their vectors ship with the repo as a "
f"2.6 MB float32 matrix, so startup never re-embeds them.\n"
f"- **Score:** cosine similarity. Both sides are unit length, so "
f"this is the dot product.\n"
f"- **CLI:** `python3 embed_compare.py \"your text\" --top 10`; "
f"`--text a.txt --text b.txt`; `--lookup valley`.\n"
f"- **Licenses:** Octen-Embedding-0.6B is Apache-2.0; llama.cpp "
f"(via llama-cpp-python) is MIT."
)
if __name__ == "__main__":
# The model is preloaded by Spaces (see `preload_from_hub` in README.md),
# so ensure_model() normally finds it already on disk. setup() warms the
# embedder and builds the noun matrix on first boot if it is missing.
setup()
# Gradio 6 moved theme/css from the Blocks constructor to launch().
demo.queue(max_size=32).launch(
mcp_server=True, theme=gr.themes.Soft(), css=CSS)