Spaces:
Paused
Paused
Upload app.py with huggingface_hub
Browse files151 unmodified lines1521531541551561575 unmodified lines16316416516616716816910 unmodified lines1801811821831841851861871882 unmodified lines1911921931941951961971981992002012024 unmodified lines2072082092102112122134 unmodified lines2182192202212222232242252262272286 unmodified lines2352362372382392408 unmodified lines249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281151 unmodified linesfor i, j in enumerate(order)]# ------------------------------------------------------------------- demodef compare(text_a, text_b, top_k):5 unmodified linestop_k: how many nouns to show per ranking (5-50).Returns:(html, markdown) — the ranked nouns and a short summary line."""st = setup()if st["error"]:10 unmodified linesif not text_b:sc = mat @ embed_one(text_a)order, rows = _ranked(sc, nouns, k)top = nouns[int(order[0])]return (_table(["#", "score", "noun"], rows),f"**Top match:** `{top}` — cosine {float(sc[order[0]]):.4f} "f"across all {len(nouns)} nouns.")va, vb = embed_one(text_a), embed_one(text_b)2 unmodified linesob, 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)]note = (f"**Text A vs Text B:** cosine {float(np.dot(va, vb)):.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), note)def lookup(noun, top_k):4 unmodified linestop_k: how many neighbours to show (5-50).Returns:(html, markdown) — nearest nouns excluding the noun itself, and a line."""st = setup()if st["error"]:4 unmodified linesk = 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][:k]rows = [[f"{r + 1}", f"{float(sims[j]):.4f}", st["nouns"][j]]for r, j in enumerate(order)]return (_table(["#", "score", "noun"], rows),f"**Nearest to `{noun}`** among all {len(st['nouns'])} nouns.")def noun_choices():6 unmodified linestable.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)); }"""with gr.Blocks(title="Embed Compare — place nouns") as demo:8 unmodified lines"sentence mostly reflects how it ends.*")with gr.Tab("Text vs. nouns"):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")out = gr.HTML(label="Ranked nouns")summary = gr.Markdown()gr.Examples(EXAMPLES, inputs=a, label="Try one")btn.click(compare, [a, b, k], [out, summary], api_name="compare")a.submit(compare, [a, b, k], [out, summary])with gr.Tab("Noun → nearest nouns"):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.")with gr.Row():pick = gr.Dropdown(choices=noun_choices(), value="valley",label="Noun", filterable=True, scale=3)k2 = gr.Slider(5, 50, value=15, step=1, label="Neighbours", scale=2)btn2 = gr.Button("Find neighbours", variant="primary")out2 = gr.HTML()summary2 = gr.Markdown()btn2.click(lookup, [pick, k2], [out2, summary2], api_name="lookup")with gr.Accordion("How it works", open=False):gr.Markdown(151 unmodified lines1521531541551561571581591601611621631645 unmodified lines17017117217317417517617710 unmodified lines1881891901911921931941951961971981992002 unmodified lines2032042052062072082092102112122132142152162172182192204 unmodified lines2252262272282292302312324 unmodified lines2372382392402412422432442452462472482492502512522536 unmodified lines2602612622632642652668 unmodified lines275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317151 unmodified linesfor 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)]# ------------------------------------------------------------------- demodef compare(text_a, text_b, top_k):5 unmodified linestop_k: how many nouns to show per ranking (5-50).Returns:(html, html, markdown) — most similar nouns, least similar nouns, anda short summary line."""st = setup()if st["error"]:10 unmodified linesif 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)2 unmodified linesob, 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.0bottom = _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):4 unmodified linestop_k: how many neighbours to show (5-50).Returns:(html, html, markdown) — nearest nouns, least similar nouns (bothexcluding the noun itself), and a summary line."""st = setup()if st["error"]:4 unmodified linesk = 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():6 unmodified linestable.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:8 unmodified lines"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(
app.py+68-32