File size: 14,888 Bytes
06f2ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Generate Plotly figure data for the StoryScope web app.
Three key visualizations:
  1. Narrative Space scatter plot (Figure 2 reproduction)
  2. Feature radar chart (human vs AI vs input)
  3. Feature importance bar chart
  4. Per-source rarity violin (Figure 5 reproduction)
"""
import json
import math
import hashlib
from .features import CORE_FEATURES, SOURCE_CENTROIDS

# Reproducible pseudo-random scatter using deterministic seed
def _pseudorand(seed_str: str, n: int, scale: float = 1.0, offset: float = 0.0) -> list:
    """Generate n deterministic pseudo-random values from seed."""
    vals = []
    for i in range(n):
        h = int(hashlib.md5(f"{seed_str}_{i}".encode()).hexdigest(), 16)
        # Box-Muller for normal distribution approximation
        u1 = ((h >> 16) & 0xFFFF) / 65535.0 + 1e-9
        u2 = (h & 0xFFFF) / 65535.0 + 1e-9
        z = math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
        vals.append(z * scale + offset)
    return vals


def _background_traces() -> list:
    """Shared synthetic scatter + centroid traces for all narrative space plots."""
    traces = []
    N_POINTS = 200
    for source, cfg in SOURCE_CENTROIDS.items():
        xs = _pseudorand(f"{source}_ld1", N_POINTS, cfg["spread_ld1"], cfg["ld1"])
        ys = _pseudorand(f"{source}_ld2", N_POINTS, cfg["spread_ld2"], cfg["ld2"])
        if source == "Human":
            xs = [x * 1.22 for x in xs]
            ys = [y * 1.22 for y in ys]
        traces.append({
            "type": "scatter", "x": xs, "y": ys, "mode": "markers", "name": source,
            "marker": {"color": cfg["color"], "size": 5, "opacity": 0.45},
            "legendgroup": source, "showlegend": True,
        })
        traces.append({
            "type": "scatter", "x": [cfg["ld1"]], "y": [cfg["ld2"]],
            "mode": "markers", "name": f"{source} centroid",
            "marker": {"color": cfg["color"], "size": 14, "symbol": "diamond",
                       "opacity": 1.0, "line": {"color": "white", "width": 1.5}},
            "legendgroup": source, "showlegend": False,
        })
    return traces


def _space_layout(title: str, annotations: list = None) -> dict:
    return {
        "paper_bgcolor": "#1a1a2e", "plot_bgcolor": "#16213e",
        "font": {"color": "#e0e0e0", "family": "Inter, sans-serif"},
        "title": {"text": title, "font": {"size": 15}, "x": 0.5},
        "xaxis": {"title": "LD1 (Human ← β†’ AI)", "gridcolor": "#2a2a4a",
                  "zeroline": True, "zerolinecolor": "#4a4a6a", "range": [-9, 6]},
        "yaxis": {"title": "LD2 (Between-model variation)", "gridcolor": "#2a2a4a",
                  "zeroline": True, "zerolinecolor": "#4a4a6a", "range": [-5, 5]},
        "legend": {"bgcolor": "#1a1a2e", "bordercolor": "#444", "borderwidth": 1},
        "annotations": (annotations or []) + [
            {"x": -5.5, "y": 4.2, "text": "← Human region", "showarrow": False,
             "font": {"color": "#8B6655", "size": 11}},
            {"x": 3.0, "y": 4.2, "text": "AI cluster β†’", "showarrow": False,
             "font": {"color": "#aaaaaa", "size": 11}},
        ],
        "margin": {"l": 55, "r": 20, "t": 50, "b": 50},
    }


def narrative_space_plot(ld1: float, ld2: float, predicted_source: str) -> dict:
    """Reproduce Figure 2 from the paper. Input text shown as a star."""
    traces = _background_traces()
    input_color = SOURCE_CENTROIDS.get(predicted_source, {}).get("color", "#FF0000")
    traces.append({
        "type": "scatter", "x": [ld1], "y": [ld2],
        "mode": "markers+text", "name": "Your Text",
        "text": ["β–Ά Your Text"], "textposition": "top right",
        "textfont": {"size": 12, "color": "white"},
        "marker": {"color": "#FFFFFF", "size": 20, "symbol": "star",
                   "opacity": 1.0, "line": {"color": input_color, "width": 3}},
        "showlegend": True,
    })
    return {"data": traces, "layout": _space_layout("Narrative Feature Space (approx. LDA projection)")}


def narrative_space_comparison_plot(
    before_ld1: float, before_ld2: float,
    after_ld1: float, after_ld2: float,
    before_source: str, after_source: str,
) -> dict:
    """Before/after humanization overlay on narrative space. Arrow shows direction of movement."""
    traces = _background_traces()

    before_color = SOURCE_CENTROIDS.get(before_source, {}).get("color", "#FF8C00")
    after_color = SOURCE_CENTROIDS.get(after_source, {}).get("color", "#FFFFFF")

    traces.append({
        "type": "scatter", "x": [before_ld1], "y": [before_ld2],
        "mode": "markers+text", "name": "Before",
        "text": ["β—€ Before"], "textposition": "bottom left",
        "textfont": {"size": 11, "color": "#FF8C00"},
        "marker": {"color": "#FF8C00", "size": 18, "symbol": "star",
                   "opacity": 0.9, "line": {"color": "white", "width": 2}},
    })
    traces.append({
        "type": "scatter", "x": [after_ld1], "y": [after_ld2],
        "mode": "markers+text", "name": "After",
        "text": ["β–Ά After"], "textposition": "top right",
        "textfont": {"size": 11, "color": "#00FF88"},
        "marker": {"color": "#00FF88", "size": 18, "symbol": "star",
                   "opacity": 1.0, "line": {"color": "white", "width": 2}},
    })

    # Arrow annotation from before β†’ after
    arrow_annotation = {
        "x": after_ld1, "y": after_ld2,
        "ax": before_ld1, "ay": before_ld2,
        "xref": "x", "yref": "y", "axref": "x", "ayref": "y",
        "arrowhead": 3, "arrowsize": 1.5, "arrowwidth": 2,
        "arrowcolor": "#00FF88",
        "showarrow": True,
    }

    return {
        "data": traces,
        "layout": _space_layout(
            "Narrative Space: Before vs After Humanization",
            annotations=[arrow_annotation],
        ),
    }


def feature_radar_chart(per_feature_scores: dict) -> dict:
    """
    Radar chart comparing input text to human/AI means across key features.
    Shows ~15 most discriminative features (by |gap|).
    """
    # Pick top features by weight (most discriminative)
    features_sorted = sorted(
        [f for f in CORE_FEATURES if f.get("gap") is not None],
        key=lambda f: abs(f["gap"]),
        reverse=True
    )[:16]

    labels = [f["name"].replace(" & ", " &\n").replace(" → ", "\n→ ") for f in features_sorted]

    # Normalize values to [0, 1] for display
    human_vals = []
    ai_vals = []
    input_vals = []

    for feat in features_sorted:
        fid = feat["id"]
        human_mean = feat["human_mean"]
        ai_mean = feat["ai_mean"]

        # Only scale/ordinal features have numeric options and scalar means
        numeric_opts = [o for o in (feat.get("values") or []) if isinstance(o, (int, float))]
        if numeric_opts and human_mean is not None and ai_mean is not None:
            scale_max = max(numeric_opts)
            scale_min = min(numeric_opts)
            span = (scale_max - scale_min) or 1
            human_norm = (human_mean - scale_min) / span
            ai_norm = (ai_mean - scale_min) / span
        else:
            # Binary/categorical: use humanness score directly
            human_norm = 0.7
            ai_norm = 0.3
            span = 1
            scale_min = 0

        human_vals.append(round(human_norm, 3))
        ai_vals.append(round(ai_norm, 3))

        score_info = per_feature_scores.get(fid, {})
        raw_val = score_info.get("value")
        h_score = score_info.get("humanness")

        if numeric_opts and raw_val is not None:
            try:
                input_norm = (float(raw_val) - scale_min) / span
                input_vals.append(round(max(0, min(1, input_norm)), 3))
            except (TypeError, ValueError):
                input_vals.append(h_score if h_score is not None else round((human_norm + ai_norm) / 2, 3))
        elif h_score is not None:
            input_vals.append(round(h_score, 3))
        else:
            input_vals.append(round((human_norm + ai_norm) / 2, 3))

    # Close the polygon
    labels_closed = labels + [labels[0]]
    human_closed = human_vals + [human_vals[0]]
    ai_closed = ai_vals + [ai_vals[0]]
    input_closed = input_vals + [input_vals[0]]

    traces = [
        {
            "type": "scatterpolar",
            "r": human_closed,
            "theta": labels_closed,
            "fill": "toself",
            "fillcolor": "rgba(139,102,85,0.15)",
            "line": {"color": "#8B6655", "width": 2},
            "name": "Human (mean)",
        },
        {
            "type": "scatterpolar",
            "r": ai_closed,
            "theta": labels_closed,
            "fill": "toself",
            "fillcolor": "rgba(100,100,200,0.15)",
            "line": {"color": "#6464c8", "width": 2},
            "name": "AI (mean)",
        },
        {
            "type": "scatterpolar",
            "r": input_closed,
            "theta": labels_closed,
            "fill": "toself",
            "fillcolor": "rgba(255,255,255,0.1)",
            "line": {"color": "#ffffff", "width": 2.5, "dash": "dot"},
            "name": "Your Text",
        },
    ]

    layout = {
        "paper_bgcolor": "#1a1a2e",
        "polar": {
            "bgcolor": "#16213e",
            "radialaxis": {
                "visible": True,
                "range": [0, 1],
                "gridcolor": "#2a2a4a",
                "tickfont": {"color": "#777"},
            },
            "angularaxis": {
                "gridcolor": "#2a2a4a",
                "tickfont": {"color": "#ccc", "size": 9},
            },
        },
        "font": {"color": "#e0e0e0", "family": "Inter, sans-serif"},
        "title": {
            "text": "Feature Profile (normalized 0–1)",
            "font": {"size": 14},
            "x": 0.5,
        },
        "legend": {"bgcolor": "#1a1a2e", "font": {"size": 11}},
        "margin": {"l": 60, "r": 60, "t": 50, "b": 50},
    }

    return {"data": traces, "layout": layout}


def feature_bar_chart(ranked_features: list) -> dict:
    """
    Horizontal bar chart: per-feature humanness score.
    Green = human-like, red = AI-like.
    """
    # Show top 15 most discriminative (by weight)
    items = sorted(ranked_features, key=lambda x: x.get("weight", 0), reverse=True)[:20]
    # Sort by humanness for display
    items.sort(key=lambda x: x.get("humanness", 0.5))

    labels = [x["name"] for x in items]
    scores = [round(x.get("humanness", 0.5), 3) for x in items]
    colors = []
    for s in scores:
        if s < 0.4:
            colors.append("#e74c3c")  # red = AI-like
        elif s > 0.6:
            colors.append("#2ecc71")  # green = human-like
        else:
            colors.append("#f39c12")  # yellow = neutral

    traces = [{
        "type": "bar",
        "x": scores,
        "y": labels,
        "orientation": "h",
        "marker": {"color": colors},
        "text": [f"{s:.0%}" for s in scores],
        "textposition": "outside",
        "textfont": {"size": 10, "color": "#ccc"},
    }]

    layout = {
        "paper_bgcolor": "#1a1a2e",
        "plot_bgcolor": "#16213e",
        "font": {"color": "#e0e0e0", "family": "Inter, sans-serif"},
        "title": {
            "text": "Per-Feature Humanness Score",
            "font": {"size": 14},
            "x": 0.5,
        },
        "xaxis": {
            "title": "Humanness (0=AI, 1=Human)",
            "range": [0, 1.15],
            "gridcolor": "#2a2a4a",
            "tickformat": ".0%",
        },
        "yaxis": {
            "tickfont": {"size": 10},
            "automargin": True,
        },
        "shapes": [
            {
                "type": "line",
                "x0": 0.5, "x1": 0.5,
                "y0": -0.5, "y1": len(items) - 0.5,
                "line": {"color": "#888", "width": 1, "dash": "dash"},
            }
        ],
        "annotations": [
            {"x": 0.25, "y": len(items) - 0.3, "text": "← AI-like", "showarrow": False,
             "font": {"color": "#e74c3c", "size": 10}},
            {"x": 0.75, "y": len(items) - 0.3, "text": "Human-like β†’", "showarrow": False,
             "font": {"color": "#2ecc71", "size": 10}},
        ],
        "margin": {"l": 220, "r": 80, "t": 50, "b": 50},
        "height": max(400, len(items) * 28 + 100),
    }

    return {"data": traces, "layout": layout}


def rarity_violin(overall_humanness: float) -> dict:
    """
    Violin plot of per-source narrative rarity (Figure 5 reproduction).
    Shows where the input text falls.
    """
    # Approximate rarity distributions (from paper Figure 5 + Table 12 stats)
    # Human: mean rarity percentile 0.71, std ~0.23
    # AI: mean rarity percentile 0.49, std ~0.27 (pooled)
    source_params = {
        "Human":    {"mean": 0.71, "std": 0.23, "color": "#8B6655"},
        "GPT":      {"mean": 0.50, "std": 0.27, "color": "#2CA02C"},
        "Claude":   {"mean": 0.46, "std": 0.25, "color": "#E6634A"},
        "DeepSeek": {"mean": 0.50, "std": 0.28, "color": "#9467BD"},
        "Kimi":     {"mean": 0.48, "std": 0.27, "color": "#FF7F0E"},
        "Gemini":   {"mean": 0.47, "std": 0.26, "color": "#1F77B4"},
    }

    traces = []
    source_order = ["Human", "GPT", "Claude", "DeepSeek", "Kimi", "Gemini"]

    for src in source_order:
        p = source_params[src]
        # Generate violin y data
        ys = _pseudorand(f"violin_{src}", 300, p["std"], p["mean"])
        ys = [max(0.0, min(1.0, y)) for y in ys]
        traces.append({
            "type": "violin",
            "y": ys,
            "name": src,
            "box": {"visible": True},
            "meanline": {"visible": True, "color": "white", "width": 2},
            "line": {"color": p["color"]},
            "fillcolor": p["color"],
            "opacity": 0.6,
            "points": False,
        })

    # Estimate rarity: human stories are rarer, so rarity β‰ˆ humanness
    estimated_rarity = 0.35 + overall_humanness * 0.45

    # Add input text as horizontal line
    traces.append({
        "type": "scatter",
        "x": source_order,
        "y": [estimated_rarity] * len(source_order),
        "mode": "lines",
        "name": "Your Text (est.)",
        "line": {"color": "white", "width": 2, "dash": "dash"},
    })

    layout = {
        "paper_bgcolor": "#1a1a2e",
        "plot_bgcolor": "#16213e",
        "font": {"color": "#e0e0e0", "family": "Inter, sans-serif"},
        "title": {
            "text": "Narrative Rarity Distribution (estimated)",
            "font": {"size": 14},
            "x": 0.5,
        },
        "yaxis": {
            "title": "Rarity Percentile",
            "range": [0, 1],
            "tickformat": ".0%",
            "gridcolor": "#2a2a4a",
        },
        "xaxis": {"gridcolor": "#2a2a4a"},
        "legend": {"bgcolor": "#1a1a2e"},
        "margin": {"l": 55, "r": 20, "t": 50, "b": 50},
    }

    return {"data": traces, "layout": layout}