""" 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}