File size: 36,984 Bytes
01003a4
91e0e03
01003a4
91e0e03
 
 
 
01003a4
 
765a9fe
 
 
01003a4
 
e8fdf77
01003a4
 
91e0e03
01003a4
 
e8fdf77
91e0e03
01003a4
 
 
 
 
 
 
 
91e0e03
01003a4
 
 
 
 
 
 
 
 
 
 
91e0e03
01003a4
 
91e0e03
01003a4
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5be592
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5be592
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8fdf77
f5be592
91e0e03
 
 
 
 
 
 
 
f5be592
91e0e03
e8fdf77
f5be592
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5be592
91e0e03
f5be592
9d334e5
91e0e03
 
9d334e5
 
 
91e0e03
9d334e5
 
 
 
91e0e03
9d334e5
 
 
 
91e0e03
9d334e5
91e0e03
 
 
 
 
 
9d334e5
91e0e03
 
9d334e5
91e0e03
9d334e5
91e0e03
9d334e5
91e0e03
9d334e5
91e0e03
9d334e5
91e0e03
9d334e5
91e0e03
9d334e5
91e0e03
 
 
 
9d334e5
91e0e03
 
9d334e5
 
 
91e0e03
9d334e5
 
 
91e0e03
9d334e5
 
 
91e0e03
9d334e5
 
 
91e0e03
9d334e5
 
 
91e0e03
9d334e5
 
91e0e03
 
 
9d334e5
 
91e0e03
9d334e5
 
91e0e03
9d334e5
 
91e0e03
9d334e5
 
f5be592
9d334e5
 
 
 
f5be592
9d334e5
 
91e0e03
9d334e5
 
91e0e03
9d334e5
 
 
91e0e03
9d334e5
 
 
 
f5be592
9d334e5
 
f5be592
9d334e5
91e0e03
 
 
9d334e5
 
 
f5be592
9d334e5
 
 
 
f5be592
9d334e5
f5be592
9d334e5
 
 
 
 
 
 
91e0e03
f5be592
91e0e03
 
 
 
 
 
9d334e5
 
 
91e0e03
 
9d334e5
91e0e03
9d334e5
 
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d334e5
 
91e0e03
 
9d334e5
91e0e03
9d334e5
 
 
 
 
91e0e03
9d334e5
 
91e0e03
9d334e5
 
 
91e0e03
 
9d334e5
91e0e03
9d334e5
 
 
 
91e0e03
9d334e5
 
 
 
 
91e0e03
f5be592
e8fdf77
f5be592
91e0e03
 
9d334e5
91e0e03
 
f5be592
91e0e03
 
f5be592
91e0e03
 
 
 
f5be592
91e0e03
 
9d334e5
 
 
91e0e03
f5be592
91e0e03
e8fdf77
91e0e03
e8fdf77
f5be592
765a9fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21a965d
765a9fe
 
21a965d
 
 
 
765a9fe
21a965d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765a9fe
 
 
 
 
 
 
 
 
 
 
 
 
 
f5be592
21a965d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8fdf77
21a965d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01003a4
91e0e03
 
 
01003a4
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01003a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91e0e03
01003a4
 
 
 
 
91e0e03
01003a4
91e0e03
 
 
 
01003a4
 
 
 
4589a2b
01003a4
91e0e03
01003a4
91e0e03
 
 
01003a4
 
91e0e03
 
 
01003a4
 
 
91e0e03
 
 
 
 
 
 
 
 
 
 
01003a4
 
 
91e0e03
 
21a965d
91e0e03
 
765a9fe
01003a4
91e0e03
 
21a965d
91e0e03
 
765a9fe
91e0e03
 
 
 
 
 
 
 
 
01003a4
 
 
91e0e03
 
2ce0748
91e0e03
 
21a965d
01003a4
91e0e03
 
2ce0748
91e0e03
 
21a965d
91e0e03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01003a4
91e0e03
 
 
 
 
 
 
 
 
 
01003a4
 
91e0e03
 
 
01003a4
 
91e0e03
 
 
 
 
 
01003a4
 
 
4589a2b
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
"""
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<br>(%{{x:.3f}}, %{{y:.3f}}, %{{z:.3f}})<extra></extra>",
        ))

    # ── Centroids (diamonds) ──────────────────────────────────────────────
    for c3, key, name in [
        (c_a, "A", name_a),
        (c_b, "B", name_b),
        (c_d1, "D1", name_d1),
        (c_d2, "D2", name_d2),
    ]:
        fig.add_trace(go.Scatter3d(
            x=[c3[0]], y=[c3[1]], z=[c3[2]],
            mode="markers+text",
            marker=dict(size=10, color=COLORS[key], symbol="diamond",
                        line=dict(width=2, color="white")),
            text=[f"β—† {name}"],
            textposition="top center",
            textfont=dict(color=COLORS[key], size=11),
            name=f"β—† Centre of {name}",
            legendgroup=key,
            showlegend=True,
            hovertemplate=f"Centre of {name}<br>(%{{x:.3f}}, %{{y:.3f}}, %{{z:.3f}})<extra></extra>",
        ))

    # ── Pole axis (dashed line A↔B) ───────────────────────────────────────
    fig.add_trace(go.Scatter3d(
        x=[c_a[0], c_b[0]], y=[c_a[1], c_b[1]], z=[c_a[2], c_b[2]],
        mode="lines",
        line=dict(color="white", width=3, dash="dash"),
        name=f"Spectrum: {name_a} ↔ {name_b}",
        opacity=0.5,
        hoverinfo="skip",
    ))

    # ── Spokes: discourse centres β†’ pole centres ──────────────────────────
    for c_disc, key, dname in [(c_d1, "D1", name_d1), (c_d2, "D2", name_d2)]:
        for pole_pt, pname in [(c_a, name_a), (c_b, name_b)]:
            fig.add_trace(go.Scatter3d(
                x=[c_disc[0], pole_pt[0]],
                y=[c_disc[1], pole_pt[1]],
                z=[c_disc[2], pole_pt[2]],
                mode="lines",
                line=dict(color=COLORS[key], width=1.5, dash="dot"),
                opacity=0.4,
                showlegend=False,
                hoverinfo="skip",
            ))

    # ── Principal direction arrows ────────────────────────────────────────
    scale = 0.15
    for c3, ev3, key, name in [
        (c_a, ev_a, "A", name_a),
        (c_b, ev_b, "B", name_b),
        (c_d1, ev_d1, "D1", name_d1),
        (c_d2, ev_d2, "D2", name_d2),
    ]:
        tip = c3 + ev3 * scale
        tail = c3 - ev3 * scale
        fig.add_trace(go.Scatter3d(
            x=[tail[0], tip[0]], y=[tail[1], tip[1]], z=[tail[2], tip[2]],
            mode="lines",
            line=dict(color=COLORS[key], width=6),
            showlegend=False,
            hovertemplate=f"Direction of variation β€” {name}<extra></extra>",
        ))
        # arrowhead
        fig.add_trace(go.Scatter3d(
            x=[tip[0]], y=[tip[1]], z=[tip[2]],
            mode="markers",
            marker=dict(size=5, color=COLORS[key], symbol="diamond"),
            showlegend=False,
            hoverinfo="skip",
        ))

    # ── Layout ────────────────────────────────────────────────────────────
    axis_template = dict(
        backgroundcolor=BG_COLOR,
        gridcolor=GRID_COLOR,
        showbackground=True,
        color=TEXT_COLOR,
        tickfont=dict(size=9, color=TEXT_COLOR),
    )

    fig.update_layout(
        scene=dict(
            xaxis=dict(title=f"Meaning Axis 1 ({pca_ev[0]:.0%})", **axis_template),
            yaxis=dict(title=f"Meaning Axis 2 ({pca_ev[1]:.0%})", **axis_template),
            zaxis=dict(title=f"Meaning Axis 3 ({pca_ev[2]:.0%})", **axis_template),
        ),
        paper_bgcolor=BG_COLOR,
        plot_bgcolor=BG_COLOR,
        font=dict(color=TEXT_COLOR),
        title=dict(
            text=(
                f"Discourse Compass β€” {name_a} vs {name_b}<br>"
                f"<span style='font-size:12px;color:#5a6488;'>"
                f"Drag to rotate Β· Scroll to zoom Β· {sum(pca_ev):.0%} of meaning variation shown</span>"
            ),
            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("""
    <div style="padding: 8px 0 20px 0;">
      <h1 style="color:#dde4f8; font-size:2rem; font-weight:900;
                 margin-bottom:6px; letter-spacing:-0.5px;">
        🧭 Discourse Compass
      </h1>
      <p style="color:#5a6488; font-size:0.92rem; margin:0; max-width:700px;">
        Define two semantic poles with example sentences, then find out where
        any text sits between them β€” with plain-language explanations.
      </p>
    </div>""")

    with gr.Accordion("πŸ’‘  How does this work?  (click to read)", open=False):
        gr.Markdown(EXPLAINER_HOW)

    gr.HTML("<hr style='border-color:#1c2040; margin: 8px 0 20px 0;'>")

    # ── Step 1: Poles ─────────────────────────────────────────────────────
    gr.HTML("""
    <h3 style="color:#dde4f8; margin-bottom:4px;">Step 1 β€” Define your two poles</h3>
    <p style="color:#5a6488; font-size:0.86rem; margin:0 0 14px 0;">
      Enter several sentences that represent each extreme. One sentence per line.
    </p>""")

    with gr.Row():
        with gr.Column():
            gr.HTML("<span style='color:#5aa8ff;font-weight:700;'>πŸ”΅ POLE A</span>")
            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("<span style='color:#ff6b6b;font-weight:700;'>πŸ”΄ POLE B</span>")
            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("<hr style='border-color:#1c2040; margin: 20px 0;'>")

    # ── Step 2: Discourses ────────────────────────────────────────────────
    gr.HTML("""
    <h3 style="color:#dde4f8; margin-bottom:4px;">Step 2 β€” Enter the texts to analyse</h3>
    <p style="color:#5a6488; font-size:0.86rem; margin:0 0 14px 0;">
      These are the texts whose position between the poles you want to measure.
    </p>""")

    with gr.Row():
        with gr.Column():
            gr.HTML("<span style='color:#3dd6a3;font-weight:700;'>🟒 TEXT 1</span>")
            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("<span style='color:#ffcc55;font-weight:700;'>🟑 TEXT 2</span>")
            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("<div style='margin: 24px 0 8px 0;'>")
    run_btn = gr.Button("⚑  Run Analysis", variant="primary",
                        size="lg", elem_classes=["run-btn"])
    gr.HTML("</div>")

    gr.HTML("<hr style='border-color:#1c2040; margin: 24px 0 16px 0;'>")

    # ── Results ───────────────────────────────────────────────────────────
    gr.HTML("""
    <h3 style="color:#dde4f8; margin: 0 0 4px 0;">πŸ“Š Interactive Semantic Map</h3>
    <p style="color:#5a6488; font-size:0.84rem; margin:0 0 12px 0;">
      Each dot is a sentence. Diamonds (β—†) mark the centre of each group.
      <strong>Drag to rotate Β· scroll to zoom Β· click legend items to toggle.</strong>
    </p>""")

    plot_out = gr.Plot(label="Semantic Map")

    gr.HTML("<hr style='border-color:#1c2040; margin: 24px 0 16px 0;'>")

    gr.HTML("""
    <h3 style="color:#dde4f8; margin: 0 0 4px 0;">πŸ“‹ Results Report</h3>
    <p style="color:#5a6488; font-size:0.84rem; margin:0 0 10px 0;">
      Plain-language summary of every measurement.
    </p>""")

    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"""
    <p style="color:#1e2440; font-size:0.74rem; text-align:center;
              margin-top:28px; padding-bottom:12px;">
      All measurements use the full {MODEL_DIM}-dimensional meaning space of
      <code>{MODEL_NAME}</code>.
      The 3D map is a simplified view (PCA) for orientation only.
    </p>""")

if __name__ == "__main__":
    demo.launch(share=True, css=CSS)