File size: 29,543 Bytes
7e2fd25
 
754db10
7e2fd25
 
 
 
 
 
 
 
 
 
 
 
edd7257
7e2fd25
 
754db10
f5f5452
 
 
 
 
754db10
323c1ce
 
 
 
 
 
754db10
 
 
 
 
 
323c1ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754db10
 
 
 
 
 
 
 
 
7e2fd25
edd7257
ca240a9
7e2fd25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca240a9
 
 
 
 
 
 
 
 
 
7e2fd25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5f5452
 
 
 
 
 
 
 
 
7e2fd25
 
 
 
f5f5452
 
7e2fd25
f5f5452
 
 
 
 
 
 
 
7e2fd25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca240a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edd7257
ca240a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e2fd25
 
 
 
 
 
649c859
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615e81d
 
 
 
 
edd7257
 
ca240a9
615e81d
 
 
 
edd7257
615e81d
8d566f3
615e81d
 
 
 
 
 
edd7257
615e81d
8d566f3
edd7257
 
615e81d
 
ca240a9
 
7e2fd25
f5f5452
 
 
 
 
 
 
 
 
 
 
 
 
 
7e2fd25
 
 
 
 
edd7257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5f5452
7e2fd25
f5f5452
ca240a9
edd7257
ca240a9
615e81d
edd7257
 
7e2fd25
 
 
 
 
 
 
 
 
 
 
 
 
 
649c859
 
 
 
 
 
 
f5f5452
 
 
 
7e2fd25
 
 
 
754db10
7e2fd25
 
 
8d566f3
 
 
 
 
 
 
 
edd7257
8d566f3
 
 
 
 
 
7e2fd25
8d566f3
7e2fd25
 
 
 
edd7257
754db10
7e2fd25
323c1ce
 
 
 
 
 
 
 
 
 
7e2fd25
 
 
f5f5452
7e2fd25
 
 
 
 
 
649c859
7e2fd25
649c859
 
 
edd7257
615e81d
 
edd7257
615e81d
edd7257
8d566f3
 
615e81d
edd7257
 
 
 
 
 
 
7e2fd25
 
 
 
754db10
7e2fd25
edd7257
 
 
 
7e2fd25
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
"""DiscourseGeometry: three-axis profile of a single text.

Based on Stibbe (2019) and Vallego (2026); full references in REFERENCES below.
"""

import textwrap
from functools import lru_cache
from pathlib import Path

import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from sentence_transformers import SentenceTransformer

from geometry import AXES, analyse, build_space, voronoi_zones

MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"

# Relevance filter: a sentence is "on topic" if its cosine similarity to the centre of all
# pole exemplars is at least this value. Starting guess; calibrate with real texts
# (each sentence's relevance is shown when hovering over it in the first plot).
RELEVANCE_THRESHOLD = 0.30

# Links for the citations. Paste the URLs here; an empty string shows the citation without a link.
VALLEGO_URL = "https://papers.ssrn.com/sol3/papers.cfm?abstract_id=6387958"   # SSRN page of the framework paper
STIBBE_URL = "https://eprints.glos.ac.uk/8163/"   # open-access copy, University of Gloucestershire repository


APP_URL = "https://huggingface.co/spaces/neovalle/DiscourseGeometry"   # this app's public address
APP_DOI = ""   # e.g. a Zenodo DOI for the app's code, once archived ("10.5281/zenodo.…")


def cite(label, url):
    return f"[{label}]({url})" if url else label


def _url_or_doi(url, doi=""):
    return f"https://doi.org/{doi}" if doi else url


PAPER_TITLE = ("A Spatial-Geometric Framework for Discourse Comparison: Centroid Projection, "
               "Frobenius Norm, and Eigenanalysis in a Constructed Semantic Measurement Space")

CITE_MD = f"""
**If you use DiscourseGeometry in your work, please cite the paper and the app.**

1. Vallego, J. (2026). *{PAPER_TITLE}*. SSRN.{" " + VALLEGO_URL if VALLEGO_URL else ""}
2. Vallego, J. (2026). *DiscourseGeometry* [Computer software]. Hugging Face. {_url_or_doi(APP_URL, APP_DOI)}

The three axes draw on: Stibbe, A. (2019). Education for sustainability and the search for new stories
to live by. In J. Armon, S. Scoffham & C. Armon (Eds.), *Prioritizing Sustainability Education:
A Comprehensive Approach* (pp. 233–243). Routledge.
"""

CITE_BIBTEX = f"""@misc{{vallego2026framework,
  author       = {{Vallego, Jorge}},
  title        = {{{PAPER_TITLE}}},
  year         = {{2026}},
  howpublished = {{SSRN}}{f",{chr(10)}  url          = {{{VALLEGO_URL}}}" if VALLEGO_URL else ""}
}}

@software{{vallego2026discoursegeometry,
  author       = {{Vallego, Jorge}},
  title        = {{DiscourseGeometry}},
  year         = {{2026}},
  publisher    = {{Hugging Face}},
  url          = {{{APP_URL}}}{f",{chr(10)}  doi          = {{{APP_DOI}}}" if APP_DOI else ""}
}}

@incollection{{stibbe2019education,
  author    = {{Stibbe, Arran}},
  title     = {{Education for sustainability and the search for new stories to live by}},
  booktitle = {{Prioritizing Sustainability Education: A Comprehensive Approach}},
  editor    = {{Armon, J. and Scoffham, S. and Armon, C.}},
  publisher = {{Routledge}},
  address   = {{London; New York}},
  year      = {{2019}},
  pages     = {{233--243}}
}}"""


REFERENCES = f"""
**References**

Stibbe, A. (2019). {cite("Education for sustainability and the search for new stories to live by", STIBBE_URL)}.
In: J. Armon, S. Scoffham, and C. Armon, eds. *Prioritizing Sustainability Education: A Comprehensive Approach*.
London; New York: Routledge, pp. 233–243.

Vallego, J. (2026). {cite("A Spatial-Geometric Framework for Discourse Comparison: Centroid Projection, Frobenius Norm, and Eigenanalysis in a Constructed Semantic Measurement Space", VALLEGO_URL)}.
"""
POLES_FILE = Path(__file__).parent / "poles.tsv"
# Worldview positions (in % on each axis), read from the worldview map. Edit the file to change them.
LANDMARKS_FILE = Path(__file__).parent / "landmarks.tsv"

# One colour per axis; the low pole is drawn hollow, the high pole solid.
AXIS_COLOURS = {"eco": "#2e8b57", "change": "#3b6fd1", "outlook": "#d9822b"}

EXAMPLES = [
    "At Northfield Energy we are proud to power economic growth across the region. "
    "Our new gas field will create 2,000 jobs and secure affordable energy for decades. "
    "We are committed to sustainability: by improving efficiency and investing in carbon offsets, "
    "we will reach net zero by 2050 without compromising the comfort our customers expect. "
    "Nature is one of our region's greatest assets, attracting visitors and investment.",

    "The river is coming back to life. Since the weir was removed, salmon have returned to spawn "
    "and otters hunt again along the banks. The valley was never ours to drain; it is a community "
    "of beings, and we are only one of them. If we let go of the idea that every field must produce, "
    "the land shows us how quickly it can heal. A different way of living here is possible, "
    "and it has already begun.",

    "Another summer of fires, another report ignored. The glaciers are going, the insects are going, "
    "and the politicians keep promising targets they will never meet. Recycling and electric cars "
    "won't save us. I struggle to see how this ends well.",
]


@lru_cache(maxsize=1)
def model():
    return SentenceTransformer(MODEL_NAME, device="cpu")


def encode(texts):
    return model().encode(texts, batch_size=32, show_progress_bar=False)


@lru_cache(maxsize=1)
def space():
    poles = pd.read_csv(POLES_FILE, sep="\t")
    return build_space(poles, encode)


def wrap(s, width=60):
    return "<br>".join(textwrap.wrap(s, width))


def axis_title(ax):
    # Short name only: this label moves with the 3D scene.
    return ax["name"]


def scale_note(sp):
    # Fixed text outside the 3D scene explaining what 0% and 100% mean on each axis.
    lines = [f"<b>{ax['name']}</b>: 0% = {ax['low']} Β· 100% = {ax['high']}" for ax in sp.axes]
    return dict(text="<br>".join(lines), xref="paper", yref="paper", x=0, y=1,
                xanchor="left", yanchor="bottom", showarrow=False, align="left",
                font=dict(size=12, color="#333333"))


def make_figure(res, sp, show_exemplars=False):
    fig = go.Figure()
    names = [ax["id"] for ax in sp.axes]

    # Pole exemplar sentences (hidden by default; toggle in the legend)
    for ax in sp.axes:
        for pole in ("low", "high"):
            texts, xyz = sp.pole_points[(ax["id"], pole)]
            label = ax[pole]
            fig.add_trace(go.Scatter3d(
                x=xyz[:, 0], y=xyz[:, 1], z=xyz[:, 2], mode="markers",
                marker=dict(size=3, color=AXIS_COLOURS[ax["id"]],
                            symbol="circle-open" if pole == "low" else "circle", opacity=0.5),
                name=f"{label} exemplars",
                legendgroup=f"ex-{ax['id']}",
                hovertext=[wrap(t) for t in texts], hoverinfo="text",
                visible=True if show_exemplars else "legendonly",
            ))

    # Pole centres: where 0% and 100% are defined
    for ax in sp.axes:
        for pole in ("low", "high"):
            c = sp.pole_centroids[(ax["id"], pole)]
            fig.add_trace(go.Scatter3d(
                x=[c[0]], y=[c[1]], z=[c[2]], mode="markers+text",
                marker=dict(size=9, color=AXIS_COLOURS[ax["id"]],
                            symbol="diamond-open" if pole == "low" else "diamond",
                            line=dict(width=2, color=AXIS_COLOURS[ax["id"]])),
                text=[ax[pole]], textposition="top center",
                textfont=dict(color=AXIS_COLOURS[ax["id"]], size=12),
                name=f"{ax[pole]} pole centre",
                legendgroup="poles", showlegend=False,
                hovertemplate=f"<b>{ax[pole]} pole centre</b><extra></extra>",
            ))

    # Sentences of the text: analysed ones in grey, off-topic ones (filtered out) faded
    def sentence_hover(sents, xyz, rel):
        return [
            wrap(s) + "<br>" + "<br>".join(
                f"{a['low']}β†’{a['high']}: {v:.0f}%" for a, v in zip(sp.axes, row))
            + f"<br>Relevance to topic: {r:.2f}"
            for s, row, r in zip(sents, xyz, rel)
        ]

    sx = res["sent_xyz"]
    fig.add_trace(go.Scatter3d(
        x=sx[:, 0], y=sx[:, 1], z=sx[:, 2], mode="markers",
        marker=dict(size=4, color="#7f7f7f", opacity=0.8),
        name="Sentences analysed",
        hovertext=sentence_hover(res["sentences"], sx, res["sent_rel"]), hoverinfo="text",
    ))
    ox = res["off_xyz"]
    if len(ox):
        fig.add_trace(go.Scatter3d(
            x=ox[:, 0], y=ox[:, 1], z=ox[:, 2], mode="markers",
            marker=dict(size=3, color="#bbbbbb", opacity=0.35),
            name="Off-topic sentences (not analysed)",
            hovertext=sentence_hover(res["off_sentences"], ox, res["off_rel"]), hoverinfo="text",
        ))

    # The text as a whole (centroid of its sentences)
    t = res["text_xyz"]
    fig.add_trace(go.Scatter3d(
        x=[t[0]], y=[t[1]], z=[t[2]], mode="markers+text",
        marker=dict(size=11, color="#111111", symbol="diamond",
                    line=dict(width=2, color="#ffffff")),
        text=["Your text"], textposition="bottom center",
        textfont=dict(size=13, color="#111111"),
        name="Your text (overall)",
        hovertemplate="<b>Your text</b><br>" + "<br>".join(
            f"{a['low']}β†’{a['high']}: {v:.0f}%" for a, v in zip(sp.axes, t)) + "<extra></extra>",
    ))

    # Axis ranges: always show 0–100 with some margin, widen if points fall outside
    allpts = np.vstack([sx, t[None, :]] + [v for v in sp.pole_centroids.values()])
    lo = np.minimum(allpts.min(axis=0), 0) - 10
    hi = np.maximum(allpts.max(axis=0), 100) + 10

    def axis(k):
        return dict(title=dict(text=axis_title(sp.axes[k])), range=[lo[k], hi[k]],
                    tickvals=[0, 25, 50, 75, 100], ticksuffix="%",
                    backgroundcolor="#f7f7f7", gridcolor="#dddddd", zeroline=False)

    fig.update_layout(
        scene=dict(xaxis=axis(0), yaxis=axis(1), zaxis=axis(2), aspectmode="cube",
                   camera=dict(eye=dict(x=1.6, y=1.6, z=1.1))),
        height=720, margin=dict(l=0, r=0, t=80, b=0),
        annotations=[scale_note(sp)],
        legend=dict(orientation="h", yanchor="top", y=-0.02, x=0),
        paper_bgcolor="white",
    )
    return fig


def load_landmarks():
    # Re-read on every run so edits to the file show up without restarting the app.
    df = pd.read_csv(LANDMARKS_FILE, sep="\t")
    if "description" not in df.columns:
        df["description"] = ""
    return df.fillna({"description": ""})


def make_landmark_figure(res, sp, lm):
    fig = go.Figure()
    ids = [ax["id"] for ax in sp.axes]
    xyz = lm[ids].to_numpy(dtype=float)

    fig.add_trace(go.Scatter3d(
        x=xyz[:, 0], y=xyz[:, 1], z=xyz[:, 2], mode="markers+text",
        marker=dict(size=7, color="#5b5ea6", opacity=0.85),
        text=lm["name"].tolist(), textposition="top center",
        textfont=dict(size=11, color="#3a3c75"),
        name="Worldviews",
        hovertext=[
            f"<b>{n}</b><br>{wrap(d)}<br>" + "<br>".join(
                f"{a['low']}β†’{a['high']}: {v:.0f}%" for a, v in zip(sp.axes, row))
            for n, d, row in zip(lm["name"], lm["description"], xyz)
        ],
        hoverinfo="text",
    ))

    t = res["text_xyz"]
    fig.add_trace(go.Scatter3d(
        x=[t[0]], y=[t[1]], z=[t[2]], mode="markers+text",
        marker=dict(size=11, color="#111111", symbol="diamond",
                    line=dict(width=2, color="#ffffff")),
        text=["Your text"], textposition="bottom center",
        textfont=dict(size=13, color="#111111"),
        name="Your text (overall)",
        hovertemplate="<b>Your text</b><br>" + "<br>".join(
            f"{a['low']}β†’{a['high']}: {v:.0f}%" for a, v in zip(sp.axes, t)) + "<extra></extra>",
    ))

    allpts = np.vstack([xyz, t[None, :]])
    lo = np.minimum(allpts.min(axis=0), 0) - 10
    hi = np.maximum(allpts.max(axis=0), 100) + 10

    def axis(k):
        return dict(title=dict(text=axis_title(sp.axes[k])), range=[lo[k], hi[k]],
                    tickvals=[0, 25, 50, 75, 100], ticksuffix="%",
                    backgroundcolor="#f7f7f7", gridcolor="#dddddd", zeroline=False)

    fig.update_layout(
        scene=dict(xaxis=axis(0), yaxis=axis(1), zaxis=axis(2), aspectmode="cube",
                   camera=dict(eye=dict(x=1.6, y=1.6, z=1.1))),
        height=720, margin=dict(l=0, r=0, t=80, b=0),
        annotations=[scale_note(sp)],
        legend=dict(orientation="h", yanchor="top", y=-0.02, x=0),
        paper_bgcolor="white",
    )
    return fig


def make_spread_figure(res, sp):
    """Explains the Frobenius norm and eigenanalysis: the sentence cloud, its
    1-standard-deviation ellipsoid, and its principal directions."""
    fig = go.Figure()
    sx, t, c = res["sent_xyz"], res["text_xyz"], res["cloud"]
    centre = sx.mean(axis=0)

    fig.add_trace(go.Scatter3d(
        x=sx[:, 0], y=sx[:, 1], z=sx[:, 2], mode="markers",
        marker=dict(size=4, color="#7f7f7f", opacity=0.9),
        name="Sentences of the text",
        hovertext=[wrap(s) for s in res["sentences"]], hoverinfo="text",
    ))
    fig.add_trace(go.Scatter3d(
        x=[centre[0]], y=[centre[1]], z=[centre[2]], mode="markers",
        marker=dict(size=9, color="#111111", symbol="diamond"),
        name="Text centre", hoverinfo="skip",
    ))

    if "eigvals" in c:
        vals, vecs = c["eigvals"], c["eigvecs"]
        sd = np.sqrt(vals)
        # Ellipsoid: the spread of the sentences (its overall size is what the Frobenius norm summarises)
        u, v = np.mgrid[0:2 * np.pi:40j, 0:np.pi:20j]
        sphere = np.stack([np.cos(u) * np.sin(v), np.sin(u) * np.sin(v), np.cos(v)], axis=-1)
        ell = sphere @ (vecs * sd).T + centre
        fig.add_trace(go.Surface(
            x=ell[..., 0], y=ell[..., 1], z=ell[..., 2], opacity=0.15,
            colorscale=[[0, "#5b5ea6"], [1, "#5b5ea6"]], showscale=False,
            name="Spread (1 standard deviation)", showlegend=True, hoverinfo="skip",
        ))
        # Principal directions, drawn 1 standard deviation either side of the centre
        styles = [("#c0392b", 7), ("#e67e22", 4), ("#95a5a6", 3)]
        total = vals.sum() if vals.sum() > 0 else 1.0
        for k in range(3):
            if sd[k] <= 0:
                continue
            a, b = centre - vecs[:, k] * sd[k], centre + vecs[:, k] * sd[k]
            label = ("Main direction" if k == 0 else f"Direction {k + 1}") + f" ({100 * vals[k] / total:.0f}%)"
            fig.add_trace(go.Scatter3d(
                x=[a[0], b[0]], y=[a[1], b[1]], z=[a[2], b[2]], mode="lines+text",
                line=dict(color=styles[k][0], width=styles[k][1]),
                text=["", label if k == 0 else ""], textposition="top center",
                textfont=dict(color=styles[k][0], size=12),
                name=label, hoverinfo="skip",
            ))

    allpts = np.vstack([sx, t[None, :]])
    lo = np.minimum(allpts.min(axis=0), 0) - 10
    hi = np.maximum(allpts.max(axis=0), 100) + 10

    def axis(k):
        return dict(title=dict(text=axis_title(sp.axes[k])), range=[lo[k], hi[k]],
                    tickvals=[0, 25, 50, 75, 100], ticksuffix="%",
                    backgroundcolor="#f7f7f7", gridcolor="#dddddd", zeroline=False)

    fig.update_layout(
        scene=dict(xaxis=axis(0), yaxis=axis(1), zaxis=axis(2), aspectmode="cube",
                   camera=dict(eye=dict(x=1.6, y=1.6, z=1.1))),
        height=720, margin=dict(l=0, r=0, t=80, b=0),
        annotations=[scale_note(sp)],
        legend=dict(orientation="h", yanchor="top", y=-0.02, x=0),
        paper_bgcolor="white",
    )
    return fig


SPREAD_NOTE = (
    "Each grey dot is a sentence. The shaded shape shows how far the sentences spread around "
    "the text's centre: its overall size is what the **Frobenius norm** summarises. The red line is the "
    "**main direction** found by eigenanalysis, the direction along which the sentences differ most; "
    "the percentage is its share of the spread. Needs at least three sentences."
)


def signed(v):
    return f"{v:+.1f}".replace("-", "βˆ’")


def distance_table(res, sp, lm):
    """Distance from the text to each worldview: Euclidean overall, plus the
    per-axis difference (text minus worldview), ranked from closest."""
    ids = [ax["id"] for ax in sp.axes]
    diffs = res["text_xyz"] - lm[ids].to_numpy(dtype=float)
    dist = np.linalg.norm(diffs, axis=1)
    rows = []
    for rank, i in enumerate(np.argsort(dist), start=1):
        row = {"Rank": rank, "Worldview": lm["name"].iloc[i], "Distance": round(float(dist[i]), 1)}
        for k, ax in enumerate(sp.axes):
            row[f"Ξ” {ax['name']}"] = signed(diffs[i, k])
        rows.append(row)
    return pd.DataFrame(rows)


DISTANCE_NOTE = (
    "**Overall distance** is the straight-line (Euclidean) distance between your text and each "
    "worldview in the 3D plot: the square root of the sum of the three squared differences. It is in "
    "percentage points, the same units as the axes, and smaller means closer.\n\n"
    "The **differences** (Ξ”) show where that distance comes from, axis by axis: your text's position minus "
    "the worldview's. A positive value means your text sits further towards the 100% end of that axis "
    "(more ecocentric, more transformative, more pessimistic) than the worldview; a negative value means "
    "further towards the 0% end."
)


def summary_md(res, sp):
    n, total = len(res["sentences"]), res["n_total"]
    if res["threshold"] is None:
        first = f"**All {total} sentence(s) analysed** (topic filter off)."
    elif res["fallback"]:
        first = (f"**No sentence reached the topic threshold ({res['threshold']:.2f}), "
                 f"so all {total} were analysed.** Read the results with caution.")
    else:
        first = (f"**{n} of {total} sentence(s) are on topic and were analysed.** "
                 "Off-topic sentences are shown faded in the first plot.")
        if n < total:
            u = res["unfiltered_xyz"]
            first += (" Using all sentences instead, the positions would be "
                      + ", ".join(f"{a['name']} {v:.0f}%" for a, v in zip(sp.axes, u)) + ".")
    lines = [first,
             "0% = centre of the first pole's exemplars, 100% = centre of the second pole's. "
             "Values below 0% or above 100% lie further out than the typical exemplar."]
    return "\n\n".join(lines)


# Outlook colour scale for the worldview map: light = optimistic (0%), black = pessimistic (100%)
OUTLOOK_SCALE = [[0.0, "#f3eeb8"], [0.5, "#7a7a7a"], [1.0, "#000000"]]


def make_map_figure(res, sp, lm):
    """2D worldview map: Societal change (x) by Ecocentrism (y). Each worldview owns the zone
    of the plane closer to it than to any other worldview. Outlook is shown by marker colour."""
    ax_eco, ax_change, ax_out = sp.axes[0], sp.axes[1], sp.axes[2]
    pts = lm[["change", "eco"]].to_numpy(dtype=float)
    t = res["text_xyz"]
    tx, ty, tout = float(t[1]), float(t[0]), float(t[2])

    xmin, xmax = min(0.0, tx) - 5, max(100.0, tx) + 5
    ymin, ymax = min(0.0, ty) - 5, max(100.0, ty) + 5
    zones = voronoi_zones(pts, (xmin, xmax, ymin, ymax))
    home = int(np.argmin(((pts - [tx, ty]) ** 2).sum(axis=1)))

    fig = go.Figure()
    for i, (poly, name, desc) in enumerate(zip(zones, lm["name"], lm["description"])):
        if len(poly) < 3:
            continue
        closed = np.vstack([poly, poly[:1]])
        fig.add_trace(go.Scatter(
            x=closed[:, 0], y=closed[:, 1], mode="lines", fill="toself",
            fillcolor="#cfe3d6" if i == home else "#eef1ec",
            line=dict(color="#a9b4ad", width=1.5),
            hoveron="fills", hoverinfo="text", text=f"<b>{name}</b><br>{wrap(desc)}",
            showlegend=False,
        ))

    out = lm["outlook"].to_numpy(dtype=float)
    fig.add_trace(go.Scatter(
        x=pts[:, 0], y=pts[:, 1], mode="markers+text",
        marker=dict(size=13, color=out, coloraxis="coloraxis", line=dict(width=1.5, color="#333333")),
        text=lm["name"].tolist(), textposition="top center",
        textfont=dict(size=12, color="#1f2a24"),
        name="Worldviews",
        hovertext=[f"<b>{n}</b><br>{ax_change['name']}: {x:.0f}%<br>{ax_eco['name']}: {y:.0f}%<br>"
                   f"{ax_out['name']}: {o:.0f}%" for n, x, y, o in zip(lm["name"], pts[:, 0], pts[:, 1], out)],
        hoverinfo="text",
    ))
    fig.add_trace(go.Scatter(
        x=[tx], y=[ty], mode="markers+text",
        marker=dict(size=24, symbol="diamond", color=[tout], coloraxis="coloraxis",
                    line=dict(width=3, color="#c0392b")),
        text=["Your text"], textposition="bottom center",
        textfont=dict(size=14, color="#c0392b"),
        name="Your text",
        hovertemplate=(f"<b>Your text</b><br>{ax_change['name']}: {tx:.0f}%<br>{ax_eco['name']}: {ty:.0f}%"
                       f"<br>{ax_out['name']}: {tout:.0f}%<extra></extra>"),
    ))

    fig.update_layout(
        xaxis=dict(title=dict(text=f"{ax_change['name']}: {ax_change['low']} (0%) β†’ {ax_change['high']} (100%)"),
                   range=[xmin, xmax], tickvals=[0, 25, 50, 75, 100], ticksuffix="%",
                   showgrid=False, zeroline=False),
        yaxis=dict(title=dict(text=f"{ax_eco['name']}: {ax_eco['low']} (0%) β†’ {ax_eco['high']} (100%)"),
                   range=[ymin, ymax], tickvals=[0, 25, 50, 75, 100], ticksuffix="%",
                   showgrid=False, zeroline=False, scaleanchor="x", scaleratio=1),
        coloraxis=dict(colorscale=OUTLOOK_SCALE, cmin=0, cmax=100,
                       colorbar=dict(title=dict(text=f"{ax_out['name']}<br>(marker colour)"),
                                     tickvals=[0, 50, 100],
                                     ticktext=[f"0% {ax_out['low']}", "50%", f"100% {ax_out['high']}"])),
        height=720, margin=dict(l=10, r=10, t=30, b=10),
        plot_bgcolor="white", paper_bgcolor="white", showlegend=False,
    )
    return fig, lm["name"].iloc[home]


def map_md(res, sp, home):
    out = res["text_xyz"][2]
    ax = sp.axes[2]
    return (f"Your text falls in the **{home}** zone (highlighted). Its outlook is **{out:.0f}%**, shown by the "
            f"colour of its diamond: light yellow is {ax['low'].lower()}, black is {ax['high'].lower()}.")


MAP_NOTE = (
    "**Zones.** The map divides the plane between the worldviews: each zone is the area closer to that "
    "worldview than to any other, using only Societal change and Ecocentrism. A text falls in the zone of "
    "the nearest worldview on these two axes.\n\n"
    "**Colour.** Marker colour shows Outlook, from light yellow (optimistic, 0%) to black (pessimistic, 100%), for the "
    "worldviews and for your text, so you can compare them.\n\n"
    "The zone may differ from the top row of the distance table, because the table also counts Outlook."
)


def run(text, show_exemplars, use_filter=True):
    sp = space()
    res = analyse(text or "", sp, encode, RELEVANCE_THRESHOLD if use_filter else None)
    lm = load_landmarks()
    map_fig, home = make_map_figure(res, sp, lm)
    return (summary_md(res, sp), res["table"], make_figure(res, sp, show_exemplars),
            distance_table(res, sp, lm), make_landmark_figure(res, sp, lm),
            res["cloud_table"], make_spread_figure(res, sp),
            map_fig, map_md(res, sp, home))


ABOUT = """
### How it works

1. Each axis is defined by two **poles**, each a set of exemplar sentences (`poles.tsv`).
   The axis direction runs from the centre of one pole's exemplars to the centre of the other's.
2. The three axes overlap in meaning (see the table below), so they are **orthogonalised**:
   symmetric orthogonalisation finds the three perpendicular directions closest to the originals,
   treating all three axes equally. This lets them be drawn as the x, y and z of one 3D space.
3. The text is split into sentences. Each sentence, and the text as a whole (the centroid of its
   sentences), is placed on the three axes. Positions are expressed as percentages between the poles.
4. **Spread** is the standard deviation of sentence positions on each axis: low spread means the text
   is consistent on that dimension; high spread means it moves between positions.
5. **Frobenius norm**: the Frobenius norm of the sentences' positions around the text centre, divided by
   √(number of sentences), i.e. the average distance of a sentence from the centre across all three axes.
   *Variation captured by the axes* splits the sentences' total variation in the full embedding space
   into the part lying along the three axes and the rest (a Pythagorean decomposition of the squared
   Frobenius norm).
6. **Eigenanalysis**: the eigenvectors of the 3Γ—3 covariance of sentence positions give the directions
   along which the sentences vary; the eigenvalues give how much variation lies along each.
7. **Topic filter**: in a long text with only a few passages about the environment, off-topic sentences
   would dilute the result and pull it towards wherever unrelated text happens to fall. With the filter on,
   only sentences whose similarity to the centre of all pole exemplars reaches a threshold are analysed;
   the others are shown faded in the first plot. If no sentence reaches the threshold, all are used.

The *Before orthogonalisation* column shows each position measured on the raw, overlapping axis,
so you can see how much orthogonalisation changes the reading.

Sentence encoder: `all-mpnet-base-v2`.
"""


TABLE_CSS = """
<style>
/* Distance table: let headers wrap onto two lines instead of being cut off with "..." */
#dist-table th, #dist-table th * {
    white-space: normal !important;
    overflow: visible !important;
    text-overflow: clip !important;
}
/* Keep each worldview name on one line */
#dist-table td:nth-child(2), #dist-table td:nth-child(2) * {
    white-space: nowrap !important;
}
</style>
"""

with gr.Blocks(title="DiscourseGeometry") as demo:
    gr.HTML(TABLE_CSS)
    gr.Markdown(
        "# DiscourseGeometry\n"
        "Where does a text sit on three axes of ecological discourse: "
        "**anthropocentric ↔ ecocentric**, **conservative ↔ transformative** and "
        "**optimistic ↔ pessimistic**? "
        f"Based on {cite('Stibbe (2019)', STIBBE_URL)} and {cite('Vallego (2026)', VALLEGO_URL)}."
    )
    cite_btn = gr.Button("πŸ“‘ Cite this work", size="sm", variant="secondary")
    cite_open = gr.State(False)
    with gr.Column(visible=False) as cite_box:
        gr.Markdown(CITE_MD)
        gr.Code(CITE_BIBTEX, label="BibTeX (use the copy button)", interactive=False)

    def toggle_cite(is_open):
        return not is_open, gr.Column(visible=not is_open)

    cite_btn.click(toggle_cite, cite_open, [cite_open, cite_box])
    with gr.Row():
        with gr.Column(scale=2):
            text = gr.Textbox(label="Text to analyse", value=EXAMPLES[0], lines=9)
            use_filter = gr.Checkbox(label="Analyse only sentences about the topic", value=True)
            show_ex = gr.Checkbox(label="Show pole exemplar sentences in the plot", value=False)
            btn = gr.Button("Analyse", variant="primary")
            gr.Examples(EXAMPLES, inputs=text, label="Example texts")
        with gr.Column(scale=3):
            summary = gr.Markdown()
            table = gr.Dataframe(label="Position on each axis (%)", interactive=False, wrap=True)
            cloud_tbl = gr.Dataframe(label="Whole-text measures", interactive=False, wrap=True)
    plot = gr.Plot(label="Three-axis semantic space")
    gr.Markdown("### How the sentences spread: Frobenius norm and eigenanalysis")
    gr.Markdown(SPREAD_NOTE)
    plot3 = gr.Plot(label="Spread and main direction of variation")
    gr.Markdown("### Your text among worldviews")
    with gr.Row():
        with gr.Column(scale=3):
            plot2 = gr.Plot(label="Worldviews on the same three axes")
        with gr.Column(scale=2):
            nearest = gr.Dataframe(label="Distance from your text to each worldview",
                                   interactive=False, wrap=True, elem_id="dist-table",
                                   column_widths=["7%", "36%", "12%", "15%", "15%", "15%"])
            gr.Markdown(DISTANCE_NOTE)
    gr.Markdown("### Worldview map")
    with gr.Row():
        with gr.Column(scale=3):
            plot4 = gr.Plot(label="Worldview map: Societal change Γ— Ecocentrism, Outlook as colour")
        with gr.Column(scale=2):
            map_info = gr.Markdown()
            gr.Markdown(MAP_NOTE)
    with gr.Accordion("About the method and the axes", open=False):
        gr.Markdown(ABOUT)
        overlap = gr.Dataframe(label="Overlap between the raw axes (cosine; 0 = independent)",
                               interactive=False)
    gr.Markdown(REFERENCES)

    btn.click(run, [text, show_ex, use_filter], [summary, table, plot, nearest, plot2, cloud_tbl, plot3, plot4, map_info])
    show_ex.change(run, [text, show_ex, use_filter], [summary, table, plot, nearest, plot2, cloud_tbl, plot3, plot4, map_info])
    use_filter.change(run, [text, show_ex, use_filter], [summary, table, plot, nearest, plot2, cloud_tbl, plot3, plot4, map_info])
    demo.load(run, [text, show_ex, use_filter], [summary, table, plot, nearest, plot2, cloud_tbl, plot3, plot4, map_info])
    demo.load(lambda: space().overlap.reset_index(names=""), None, overlap)

if __name__ == "__main__":
    demo.launch()