"""
Discourse Compass — Gradio App for Linguists & General Public
=============================================================
• Interactive 3D Plotly scatter (rotate, zoom, pan)
• Custom naming for poles and discourses
• Plain-language results for non-technical users
• Sentence embeddings via all-mpnet-base-v2 (768-dim)
"""
import csv
import os
import gradio as gr
import numpy as np
import plotly.graph_objects as go
from sentence_transformers import SentenceTransformer
from sklearn.decomposition import PCA
from scipy.spatial.distance import cosine, euclidean
# ── Model ─────────────────────────────────────────────────────────────────────
MODEL_NAME = "all-mpnet-base-v2"
MODEL_DIM = 768
_model = None
def get_model():
global _model
if _model is None:
_model = SentenceTransformer(MODEL_NAME)
return _model
# ── Maths helpers ─────────────────────────────────────────────────────────────
def parse_sentences(text):
return [s.strip() for s in text.strip().splitlines() if s.strip()]
def unit(v):
n = np.linalg.norm(v)
return v / n if n > 1e-12 else v
def angle_between(u, v):
c = abs(float(np.dot(unit(u), unit(v))))
return float(np.degrees(np.arccos(min(c, 1.0))))
def thematic_breadth(vecs):
return float(np.linalg.norm(vecs - vecs.mean(axis=0), "fro"))
def principal_axis(vecs):
if vecs.shape[0] < 2:
return np.zeros(vecs.shape[1]), np.eye(vecs.shape[1])
vals, evecs = np.linalg.eigh(np.cov(vecs, rowvar=False))
order = np.argsort(vals)[::-1]
return vals[order], evecs[:, order]
def semantic_heart(vecs):
return vecs.mean(axis=0)
# ── Plain-language interpretation helpers ─────────────────────────────────────
def breadth_label(score, all_scores):
mn, mx = min(all_scores), max(all_scores)
if mx == mn:
return "moderate"
r = (score - mn) / (mx - mn)
if r < 0.33:
return "tightly focused"
if r < 0.66:
return "moderately varied"
return "wide-ranging"
def orientation_label(angle):
if angle < 20:
return "closely tracks the pole-to-pole spectrum"
if angle < 45:
return "partly follows the pole-to-pole spectrum"
if angle < 70:
return "drifts away from the pole-to-pole spectrum"
return "varies independently of the pole-to-pole spectrum"
def strength_label(pct):
if pct > 0.6:
return "very consistent — sentences cluster in one direction"
if pct > 0.35:
return "moderately consistent"
return "diverse — sentences spread in many directions"
def pull_label(cos_a, cos_b, name_a, name_b):
diff = abs(cos_a - cos_b)
closer = name_a if cos_a < cos_b else name_b
if diff < 0.05:
return f"sits roughly halfway between {name_a} and {name_b}"
elif diff < 0.15:
return f"leans toward {closer}"
else:
return f"clearly closer to {closer}"
# ── Plotly colour palette ─────────────────────────────────────────────────────
COLORS = {
"A": "#5aa8ff",
"B": "#ff6b6b",
"D1": "#3dd6a3",
"D2": "#ffcc55",
}
BG_COLOR = "#0d0f1c"
GRID_COLOR = "#1c2040"
TEXT_COLOR = "#cdd5f0"
# ── Interactive Plotly 3D renderer ────────────────────────────────────────────
def build_plotly_figure(
pts_a, pts_b, pts_d1, pts_d2,
c_a, c_b, c_d1, c_d2,
ev_a, ev_b, ev_d1, ev_d2,
pca_ev,
name_a, name_b, name_d1, name_d2,
):
fig = go.Figure()
# ── Sentence dots ─────────────────────────────────────────────────────
for pts, key, name, symbol in [
(pts_a, "A", name_a, "circle"),
(pts_b, "B", name_b, "circle"),
(pts_d1, "D1", name_d1, "square"),
(pts_d2, "D2", name_d2, "square"),
]:
fig.add_trace(go.Scatter3d(
x=pts[:, 0], y=pts[:, 1], z=pts[:, 2],
mode="markers",
marker=dict(size=5, color=COLORS[key], symbol=symbol,
opacity=0.7, line=dict(width=0.5, color="white")),
name=f"{name} sentences",
legendgroup=key,
hovertemplate=f"{name} sentence
(%{{x:.3f}}, %{{y:.3f}}, %{{z:.3f}})
(%{{x:.3f}}, %{{y:.3f}}, %{{z:.3f}})
"
f""
f"Drag to rotate · Scroll to zoom · {sum(pca_ev):.0%} of meaning variation shown"
),
x=0.5,
font=dict(size=16),
),
legend=dict(
bgcolor="rgba(19,22,42,0.9)",
bordercolor=GRID_COLOR,
borderwidth=1,
font=dict(size=10, color=TEXT_COLOR),
),
margin=dict(l=0, r=0, t=60, b=0),
height=620,
)
return fig
# ── Core analysis ─────────────────────────────────────────────────────────────
def run_analysis(text_a, text_b, text_d1, text_d2,
name_a, name_b, name_d1, name_d2):
# Default names if blank
name_a = name_a.strip() or "Pole A"
name_b = name_b.strip() or "Pole B"
name_d1 = name_d1.strip() or "Discourse 1"
name_d2 = name_d2.strip() or "Discourse 2"
sents_a = parse_sentences(text_a)
sents_b = parse_sentences(text_b)
sents_d1 = parse_sentences(text_d1)
sents_d2 = parse_sentences(text_d2)
errors = []
if not sents_a:
errors.append(f"{name_a} needs at least 1 sentence.")
if not sents_b:
errors.append(f"{name_b} needs at least 1 sentence.")
if not sents_d1:
errors.append(f"{name_d1} needs at least 1 sentence.")
if not sents_d2:
errors.append(f"{name_d2} needs at least 1 sentence.")
if errors:
return "⚠ " + " | ".join(errors), None
model = get_model()
all_sents = sents_a + sents_b + sents_d1 + sents_d2
all_vecs = model.encode(all_sents, normalize_embeddings=False,
show_progress_bar=False)
na, nb, nd1, nd2 = len(sents_a), len(sents_b), len(sents_d1), len(sents_d2)
vecs_a = all_vecs[:na]
vecs_b = all_vecs[na:na + nb]
vecs_d1 = all_vecs[na + nb:na + nb + nd1]
vecs_d2 = all_vecs[na + nb + nd1:]
# Semantic Hearts (centroids)
heart_a = semantic_heart(vecs_a)
heart_b = semantic_heart(vecs_b)
heart_d1 = semantic_heart(vecs_d1)
heart_d2 = semantic_heart(vecs_d2)
# Thematic Breadth (spread)
bread_a = thematic_breadth(vecs_a)
bread_b = thematic_breadth(vecs_b)
bread_d1 = thematic_breadth(vecs_d1)
bread_d2 = thematic_breadth(vecs_d2)
all_breads = [bread_a, bread_b, bread_d1, bread_d2]
# Pole Orientation (eigenanalysis)
pole_vec = heart_b - heart_a
def cloud_eigen(vecs):
vals, evecs = principal_axis(vecs)
main = evecs[:, 0]
ang = angle_between(main, pole_vec)
exp = vals[0] / vals.sum() if vals.sum() > 1e-12 else 0.0
return main, ang, exp
ev_a, ang_a, exp_a = cloud_eigen(vecs_a)
ev_b, ang_b, exp_b = cloud_eigen(vecs_b)
ev_d1, ang_d1, exp_d1 = cloud_eigen(vecs_d1)
ev_d2, ang_d2, exp_d2 = cloud_eigen(vecs_d2)
# Centroid projection onto pole axis (scalar position)
pole_dir = unit(pole_vec)
proj_d1 = float(np.dot(heart_d1 - heart_a, pole_dir))
proj_d2 = float(np.dot(heart_d2 - heart_a, pole_dir))
pole_len = float(np.linalg.norm(pole_vec))
pct_d1 = proj_d1 / pole_len if pole_len > 1e-12 else 0.5
pct_d2 = proj_d2 / pole_len if pole_len > 1e-12 else 0.5
# PCA to 3D (visualisation only)
stack = np.vstack([all_vecs, heart_a, heart_b, heart_d1, heart_d2])
pca = PCA(n_components=3, random_state=42)
proj_3d = pca.fit_transform(stack)
pca_ev = pca.explained_variance_ratio_
n = len(all_sents)
pts_a_3d = proj_3d[:na]
pts_b_3d = proj_3d[na:na + nb]
pts_d1_3d = proj_3d[na + nb:na + nb + nd1]
pts_d2_3d = proj_3d[na + nb + nd1:n]
c_a_3d, c_b_3d = proj_3d[n], proj_3d[n + 1]
c_d1_3d, c_d2_3d = proj_3d[n + 2], proj_3d[n + 3]
# Rotate eigenvectors into 3D PCA space
ev_a_3d = unit(pca.components_ @ ev_a)
ev_b_3d = unit(pca.components_ @ ev_b)
ev_d1_3d = unit(pca.components_ @ ev_d1)
ev_d2_3d = unit(pca.components_ @ ev_d2)
# Build interactive Plotly figure
fig = build_plotly_figure(
pts_a_3d, pts_b_3d, pts_d1_3d, pts_d2_3d,
c_a_3d, c_b_3d, c_d1_3d, c_d2_3d,
ev_a_3d, ev_b_3d, ev_d1_3d, ev_d2_3d,
pca_ev,
name_a, name_b, name_d1, name_d2,
)
# ── Build plain-language report ───────────────────────────────────────
# 1. Axis discriminability
pole_cos = float(cosine(heart_a, heart_b))
if pole_cos > 0.4:
sep_word = "well-defined"
sep_note = (f"The two poles occupy clearly distinct regions of meaning "
f"space — the axis is a reliable discriminator.")
elif pole_cos > 0.2:
sep_word = "adequately defined"
sep_note = (f"The two poles are sufficiently distinct for meaningful "
f"comparison. Adding more exemplar sentences to each pole "
f"would sharpen the axis further.")
else:
sep_word = "weakly defined"
sep_note = (f"The two poles overlap considerably in meaning space. "
f"Consider replacing some exemplar sentences with more "
f"clearly contrasting examples.")
# 2. Position bar
def position_bar(pct, width=40):
pos = max(0, min(1, pct))
idx = int(round(pos * width))
bar = "░" * idx + "●" + "░" * (width - idx)
return bar
# 3. Position description
def position_desc(pct, na, nb):
if pct <= 0.10:
return f"strongly oriented toward {na}"
elif pct <= 0.30:
return f"predominantly oriented toward {na}"
elif pct <= 0.45:
return f"leaning toward {na}, with some features of {nb}"
elif pct <= 0.55:
return f"positioned midway — drawing on both {na} and {nb} framings"
elif pct <= 0.70:
return f"leaning toward {nb}, with some features of {na}"
elif pct <= 0.90:
return f"predominantly oriented toward {nb}"
else:
return f"strongly oriented toward {nb}"
desc_d1 = position_desc(pct_d1, name_a, name_b)
desc_d2 = position_desc(pct_d2, name_a, name_b)
# 4. Separation between the two texts
gap = abs(pct_d1 - pct_d2)
if gap < 0.05:
gap_desc = "no discernible difference in discourse orientation"
gap_interp = ("The two texts occupy virtually the same position on this "
"axis — they share the same overall framing.")
elif gap < 0.15:
gap_desc = "a small but detectable difference in discourse orientation"
gap_interp = ("The two texts lean in different directions but remain "
"close — the framing contrast is subtle.")
elif gap < 0.30:
gap_desc = "a clear difference in discourse orientation"
gap_interp = ("The two texts show a meaningful difference in how they "
"frame their subject matter relative to this axis.")
elif gap < 0.50:
gap_desc = "a substantial difference in discourse orientation"
gap_interp = ("The two texts are clearly positioned on different sides "
"of this axis — their framings are genuinely divergent.")
else:
gap_desc = "a very large difference in discourse orientation"
gap_interp = ("The two texts sit at opposite ends of the spectrum — "
"their underlying value orientations are strongly contrasting.")
# 5. Internal discourse coherence (thematic spread)
def coherence_label(spread, all_spreads):
mn, mx = min(all_spreads), max(all_spreads)
r = (spread - mn) / (mx - mn) if mx > mn else 0.5
if r < 0.25:
return ("highly coherent — sentences cluster tightly, suggesting "
"a consistent and focused discourse style")
elif r < 0.50:
return ("moderately coherent — sentences share a common orientation "
"while covering a range of topics")
elif r < 0.75:
return ("thematically varied — sentences range across several "
"sub-topics, which is typical of a multi-section text")
else:
return ("thematically broad — sentences span a wide range of "
"sub-topics, each contributing its own framing to the average")
coh_d1 = coherence_label(bread_d1, all_breads)
coh_d2 = coherence_label(bread_d2, all_breads)
coh_a = coherence_label(bread_a, all_breads)
coh_b = coherence_label(bread_b, all_breads)
# 6. Discursive scope (does the text vary along THIS axis, or others?)
def scope_label(angle):
if angle < 30:
return ("variation within this text is primarily along this axis — "
"the axis captures the main dimension of internal contrast")
elif angle < 60:
return ("variation within this text runs partly along this axis and "
"partly along other semantic dimensions — the axis is one of "
"several active in this discourse")
else:
return ("variation within this text runs mostly along dimensions "
"other than this axis — sentences differ from each other "
"primarily on topics or registers not captured here, while "
"sharing a broadly consistent orientation on this spectrum")
scope_d1 = scope_label(ang_d1)
scope_d2 = scope_label(ang_d2)
# 7. Overall verdict
closer_to_a = name_d1 if pct_d1 < pct_d2 else name_d2
closer_to_b = name_d2 if pct_d1 < pct_d2 else name_d1
if gap < 0.05:
verdict = (f"No clear discursive difference: {name_d1} and {name_d2} "
f"occupy essentially the same position on the "
f"{name_a}↔{name_b} spectrum.")
else:
verdict = (f"{closer_to_a} is more strongly oriented toward {name_a} "
f"discourse; {closer_to_b} toward {name_b} discourse. "
f"The separation between them ({gap:.0%} of the full spectrum) "
f"represents {gap_desc}.")
# 8. Only flag genuinely problematic cases
caveats = []
if sep_word == "weakly defined":
caveats.append(
f"The axis is weakly defined: the {name_a} and {name_b} pole "
f"corpora are not sufficiently distinct in meaning space. "
f"Results should be treated with caution — consider revising "
f"or extending the exemplar sentences for each pole."
)
W = 62
report_lines = [
f"{'═' * W}",
f" DISCOURSE COMPASS — Results",
f"{'═' * W}",
f"",
f" AXIS: {name_a} ←{'─' * 16}→ {name_b}",
f" Axis quality: {sep_word}",
f" {sep_note}",
f" ({na} exemplar sentences at {name_a} pole · {nb} at {name_b} pole)",
f"",
f"{'─' * W}",
f" DISCOURSE ORIENTATION",
f"{'─' * W}",
f" How far along the spectrum does each text sit?",
f" Left = {name_a} Right = {name_b}",
f"",
f" {name_a} pole",
f" {'░' * 20}●{'░' * 20} (0%)",
f"",
f" {name_d1} ({nd1} sentences)",
f" {position_bar(pct_d1)} ({pct_d1:.0%})",
f" → {desc_d1}",
f"",
f" {name_d2} ({nd2} sentences)",
f" {position_bar(pct_d2)} ({pct_d2:.0%})",
f" → {desc_d2}",
f"",
f" {name_b} pole",
f" {'░' * 20}●{'░' * 20} (100%)",
f"",
f" Distance between {name_d1} and {name_d2}: {gap:.0%} of the spectrum",
f" → {gap_interp}",
f"",
f"{'─' * W}",
f" INTERNAL DISCOURSE COHERENCE",
f"{'─' * W}",
f" How consistent is the framing within each text?",
f" A tightly coherent text speaks with one voice on this axis.",
f" A thematically broad text covers many sub-topics, each",
f" contributing its own framing — both patterns are linguistically",
f" meaningful, not errors.",
f"",
f" {name_d1}: {coh_d1}.",
f" {name_d2}: {coh_d2}.",
f"",
f" For reference — coherence of the pole corpora:",
f" {name_a} pole: {coh_a}.",
f" {name_b} pole: {coh_b}.",
f"",
f"{'─' * W}",
f" DISCURSIVE SCOPE",
f"{'─' * W}",
f" Along which dimensions do sentences within each text vary?",
f" This reveals whether this axis captures the main source of",
f" internal contrast, or whether the text is doing more things",
f" at once than a single axis can describe.",
f"",
f" {name_d1}:",
f" {scope_d1}.",
f"",
f" {name_d2}:",
f" {scope_d2}.",
f"",
]
if caveats:
report_lines += [
f"{'─' * W}",
f" ⚠ NOTE",
f"{'─' * W}",
]
for c in caveats:
report_lines.append(f" • {c}")
report_lines.append(f"")
report_lines += [
f"{'─' * W}",
f" SUMMARY",
f"{'─' * W}",
f" {verdict}",
f"",
f"{'═' * W}",
f" Scores are computed in the full {MODEL_DIM}-dimensional semantic",
f" space of {MODEL_NAME}. The 3D map above is a",
f" dimensionality-reduced view for visual orientation only.",
f"{'═' * W}",
]
report = "\n".join(report_lines)
return report, fig
# ── Pole corpus loader ────────────────────────────────────────────────────────
def load_poles_from_tsv(filepath):
"""
Load aligned and misaligned pole texts from a TSV file.
Expected columns (tab-separated, with header row):
axis | label | text
where ``label`` is either ``aligned`` or ``misaligned``.
Returns two newline-joined strings ready for the Gradio Textbox defaults.
Falls back silently to empty strings if the file is missing or malformed.
"""
aligned_texts = []
misaligned_texts = []
try:
with open(filepath, newline="", encoding="utf-8") as fh:
reader = csv.DictReader(fh, delimiter="\t")
for row in reader:
label = row.get("label", "").strip().lower()
text = row.get("text", "").strip()
if not text:
continue
if label == "aligned":
aligned_texts.append(text)
elif label == "misaligned":
misaligned_texts.append(text)
except FileNotFoundError:
pass # handled by caller via empty lists
return "\n".join(aligned_texts), "\n".join(misaligned_texts)
# ── Locate and load all pole TSV files ───────────────────────────────────────
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
def _find_pole_file(filename):
"""Return path to a pole TSV, checking script dir then CWD."""
candidate = os.path.join(_SCRIPT_DIR, filename)
return candidate if os.path.isfile(candidate) else filename
# Any TSV matching this pattern is loaded and merged automatically.
# Add new files to this list to extend the pole corpus without changing code.
_POLE_FILES = ["h4rmony_poles.tsv", "h4rmony_poles_extra.tsv"]
_all_aligned, _all_misaligned = [], []
for _fname in _POLE_FILES:
_a, _m = load_poles_from_tsv(_find_pole_file(_fname))
if _a:
_all_aligned.append(_a)
if _m:
_all_misaligned.append(_m)
_ALIGNED_DEFAULT = "\n".join(_all_aligned)
_MISALIGNED_DEFAULT = "\n".join(_all_misaligned)
# ── Hard-coded fallbacks (used only if ALL TSV files are absent) ──────────────
if not _ALIGNED_DEFAULT:
_ALIGNED_DEFAULT = (
"The living world is not a collection of resources awaiting human use.\n"
"A tree does not need to be useful to deserve protection.\n"
"We are embedded in nature, not masters of it.\n"
"No economy can function beyond the boundaries of its ecosystem."
)
if not _MISALIGNED_DEFAULT:
_MISALIGNED_DEFAULT = (
"Economic growth remains the most reliable mechanism for improving human welfare.\n"
"Natural resources exist to serve human needs and desires.\n"
"Technology will solve the climate problem.\n"
"Voluntary corporate sustainability commitments are more effective than regulation."
)
# ── Discourse texts loader ────────────────────────────────────────────────────
def load_discourses_from_tsv(filepath):
"""
Load the two discourse text sets from a TSV file.
Expected columns (tab-separated, with header row):
discourse | label | text
where ``label`` is either ``d1`` or ``d2``.
Returns two newline-joined strings ready for the Gradio Textbox defaults.
Falls back silently to empty strings if the file is missing or malformed.
"""
d1_texts = []
d2_texts = []
try:
with open(filepath, newline="", encoding="utf-8") as fh:
reader = csv.DictReader(fh, delimiter="\t")
for row in reader:
label = row.get("label", "").strip().lower()
text = row.get("text", "").strip()
if not text:
continue
if label == "d1":
d1_texts.append(text)
elif label == "d2":
d2_texts.append(text)
except FileNotFoundError:
pass
return "\n".join(d1_texts), "\n".join(d2_texts)
_DISCOURSE_FILE = os.path.join(_SCRIPT_DIR, "h4rmony_discourses.tsv")
if not os.path.isfile(_DISCOURSE_FILE):
_DISCOURSE_FILE = "h4rmony_discourses.tsv"
_D1_DEFAULT, _D2_DEFAULT = load_discourses_from_tsv(_DISCOURSE_FILE)
# Hard-coded fallbacks if the discourse file is absent
if not _D1_DEFAULT:
_D1_DEFAULT = (
"Shares in the FTSE 100 climbed on stronger-than-expected retail sales data.\n"
"GDP expanded at an annualised rate of 2.8%, outpacing consensus forecasts.\n"
"The unemployment rate held at 3.9% with non-farm payrolls adding 187,000 jobs."
)
if not _D2_DEFAULT:
_D2_DEFAULT = (
"Global average surface temperatures in 2023 were 1.45 degrees above pre-industrial levels.\n"
"Arctic sea ice extent reached its second-lowest recorded minimum in September.\n"
"The number of people displaced by climate-related extreme weather reached 32.6 million."
)
# ── Explainer content ─────────────────────────────────────────────────────────
EXPLAINER_HOW = """
### How does this tool work?
Every sentence carries meaning. This tool uses an AI language model to translate
each sentence into a **point in meaning-space** — an invisible map where sentences
that mean similar things sit close together, and sentences with very different
meanings sit far apart.
You define **two poles** by giving example sentences for each — for instance,
*economic growth* vs *climate crisis*. These poles create a spectrum.
Then you enter two sets of text (the "discourses") and the tool measures
where each one sits on that spectrum. The results tell you:
- **Which pole each text is closer to** (and by how much)
- **How spread out** each set of sentences is (focused vs wide-ranging)
- **What direction** the sentences vary in (along the spectrum, or off to the side)
The 3D map lets you **see** the results — each dot is a sentence, and you can
rotate and zoom to explore how they cluster.
"""
# ── CSS ───────────────────────────────────────────────────────────────────────
CSS = """
body, .gradio-container { background: #0d0f1c !important; }
.gr-panel, .gr-form { background: #13162a !important;
border: 1px solid #1c2040 !important; }
textarea, input { background: #181b30 !important;
color: #dde4f8 !important;
border: 1px solid #262c50 !important;
border-radius: 8px !important; }
label span { color: #8892bb !important;
font-size: 0.84rem !important;
font-weight: 600 !important; }
.run-btn { background: linear-gradient(135deg, #4a7fff, #9b59f5)
!important;
border: none !important;
font-weight: 800 !important;
font-size: 1.05rem !important;
letter-spacing: 0.03em !important;
border-radius: 10px !important; }
.run-btn:hover { opacity: 0.86 !important; }
.output-text textarea { font-family: 'Courier New', monospace !important;
font-size: 0.79rem !important;
color: #7dd8f8 !important;
line-height: 1.55 !important; }
h1, h2, h3, h4 { color: #dde4f8 !important; }
.gr-accordion { border: 1px solid #1c2040 !important;
border-radius: 10px !important; }
.name-box input { font-weight: 700 !important;
font-size: 0.95rem !important; }
"""
# ── UI ────────────────────────────────────────────────────────────────────────
with gr.Blocks(title="Discourse Compass") as demo:
# ── Header ────────────────────────────────────────────────────────────
gr.HTML("""
Define two semantic poles with example sentences, then find out where any text sits between them — with plain-language explanations.
Enter several sentences that represent each extreme. One sentence per line.
""") with gr.Row(): with gr.Column(): gr.HTML("🔵 POLE A") name_a_box = gr.Textbox(label="Name for Pole A", value="Ecologically Aligned", elem_classes=["name-box"]) pole_a = gr.Textbox(label="Sentences — one per line", lines=7, value=_ALIGNED_DEFAULT) with gr.Column(): gr.HTML("🔴 POLE B") name_b_box = gr.Textbox(label="Name for Pole B", value="Ecologically Misaligned", elem_classes=["name-box"]) pole_b = gr.Textbox(label="Sentences — one per line", lines=7, value=_MISALIGNED_DEFAULT) gr.HTML("These are the texts whose position between the poles you want to measure.
""") with gr.Row(): with gr.Column(): gr.HTML("🟢 TEXT 1") name_d1_box = gr.Textbox(label="Name for Text 1", value="Traditional Italian Tourism", elem_classes=["name-box"]) disc1 = gr.Textbox(label="Sentences — one per line", lines=5, value=_D1_DEFAULT) with gr.Column(): gr.HTML("🟡 TEXT 2") name_d2_box = gr.Textbox(label="Name for Text 2", value="Sustainable Italian Tourism", elem_classes=["name-box"]) disc2 = gr.Textbox(label="Sentences — one per line", lines=5, value=_D2_DEFAULT) # ── Run button ──────────────────────────────────────────────────────── gr.HTML("Each dot is a sentence. Diamonds (◆) mark the centre of each group. Drag to rotate · scroll to zoom · click legend items to toggle.
""") plot_out = gr.Plot(label="Semantic Map") gr.HTML("Plain-language summary of every measurement.
""") text_out = gr.Textbox(label="Results", lines=42, interactive=False, elem_classes=["output-text"]) # ── Wire up events ──────────────────────────────────────────────────── run_btn.click( fn=run_analysis, inputs=[pole_a, pole_b, disc1, disc2, name_a_box, name_b_box, name_d1_box, name_d2_box], outputs=[text_out, plot_out], ) gr.HTML(f"""
All measurements use the full {MODEL_DIM}-dimensional meaning space of
{MODEL_NAME}.
The 3D map is a simplified view (PCA) for orientation only.