File size: 5,466 Bytes
99fb72f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! Deterministic, zero-dependency JSON serializer for `ForensicReport`.
//!
//! Escapes all control characters, quotes, backslashes, and `<` (`\u003c`) so emitted JSON
//! is safe across DOM, SSR, and WebAssembly memory bridges without pulling in external crates.

use std::fmt::Write as _;

use crate::model::{ForensicReport, SentenceForensic};

/// Appends a JSON-escaped string literal (including surrounding `"`) to `out`.
pub fn push_json_str(out: &mut String, value: &str) {
    out.push('"');
    for ch in value.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '<' => out.push_str("\\u003c"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

fn round3(v: f64) -> f64 {
    if v.is_finite() {
        ((v * 1000.0).round()) / 1000.0
    } else {
        0.0
    }
}

fn push_sentence_json(out: &mut String, s: &SentenceForensic) {
    let _ = write!(
        out,
        "{{\"index\":{},\"unitLen\":{},\"aiPct\":{:.1},\"gltrBand\":\"{}\",\"reason\":",
        s.index,
        s.unit_len,
        s.ai_score.as_percent(),
        s.gltr_band.slug()
    );
    push_json_str(out, s.reason_code);
    let _ = write!(out, ",\"phraseHits\":{},\"text\":", s.phrase_hits);
    push_json_str(out, &s.text);
    out.push('}');
}

/// Serializes a `ForensicReport` into a compact UTF-8 JSON document.
#[must_use]
pub fn serialize_report_json(report: &ForensicReport) -> String {
    let mut out = String::with_capacity(2048 + report.byte_len);
    let g0 = report.gltr_counts.first().copied().unwrap_or(0);
    let g1 = report.gltr_counts.get(1).copied().unwrap_or(0);
    let g2 = report.gltr_counts.get(2).copied().unwrap_or(0);
    let g3 = report.gltr_counts.get(3).copied().unwrap_or(0);

    let _ = write!(
        out,
        "{{\"modelEngine\":\"gbdt_treeshap_v2\",\"aiPct\":{:.1},\"humanPct\":{:.1},\"confidencePct\":{:.1},\"mleAlphaPct\":{:.1},\"hurstExponent\":{:.3},\"graphClustering\":{:.3},\"ppmLlrBits\":{:.3},\"nbsvmMargin\":{:.3},\"verdict\":\"{}\",\"scriptFamily\":\"{}\",\"genre\":\"{}\",\"byteLen\":{},\"charCount\":{},\"tokenCount\":{},\"sentenceCount\":{},\"meanSentenceLen\":{:.2},\"stdSentenceLen\":{:.2},\"burstinessCv\":{:.3},\"mattr50\":{:.3},\"hapaxRatio\":{:.3},\"lz77Ratio\":{:.3},\"conditionalEntropyBits\":{:.3},\"crossEntropyRatio\":{:.3},\"removableWatermarkChars\":{},",
        report.overall_ai_score.as_percent(),
        report.overall_human_score.as_percent(),
        report.confidence.as_percent(),
        report.mle_alpha_fraction.as_percent(),
        round3(report.hurst_exponent),
        round3(report.graph_clustering),
        round3(report.ppm_llr_bits),
        round3(report.nbsvm_margin),
        report.verdict.slug(),
        report.script_family.slug(),
        report.genre.slug(),
        report.byte_len,
        report.char_count,
        report.token_count,
        report.sentence_count,
        round3(report.mean_sentence_len),
        round3(report.std_sentence_len),
        round3(report.burstiness_cv),
        round3(report.mattr_50),
        round3(report.hapax_ratio),
        round3(report.lz77_ratio),
        round3(report.conditional_entropy_bits),
        round3(report.cross_entropy_ratio),
        report.removable_watermark_chars,
    );

    let sf = &report.shap_families;
    let _ = write!(
        out,
        "\"shapLogOdds\":{{\"ppm\":{:.3},\"diveye\":{:.3},\"cadence\":{:.3},\"mleGraph\":{:.3},\"nbsvm\":{:.3}}},",
        round3(sf.first().copied().unwrap_or(0.0)),
        round3(sf.get(1).copied().unwrap_or(0.0)),
        round3(sf.get(2).copied().unwrap_or(0.0)),
        round3(sf.get(3).copied().unwrap_or(0.0)),
        round3(sf.get(4).copied().unwrap_or(0.0)),
    );

    let d = &report.dimensions;
    let _ = write!(
        out,
        "\"dimensions\":{{\"compression\":{:.1},\"crossEntropy\":{:.1},\"cadence\":{:.1},\"lexical\":{:.1},\"discourse\":{:.1},\"watermarks\":{:.1}}},",
        d.compression_predictability.as_percent(),
        d.cross_entropy_curvature.as_percent(),
        d.cadence_uniformity.as_percent(),
        d.lexical_concentration.as_percent(),
        d.discourse_template_signal.as_percent(),
        d.watermark_artifact_signal.as_percent(),
    );

    let _ = write!(
        out,
        "\"gltrCounts\":{{\"green\":{g0},\"yellow\":{g1},\"red\":{g2},\"violet\":{g3}}},\"matchedPhrases\":["
    );
    for (i, phrase) in report.matched_phrases.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        push_json_str(&mut out, phrase);
    }

    out.push_str("],\"watermarkFindings\":[");
    for (i, wf) in report.watermark_findings.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str("{\"code\":");
        push_json_str(&mut out, wf.code);
        out.push_str(",\"label\":");
        push_json_str(&mut out, wf.label);
        let _ = write!(out, ",\"count\":{}}}", wf.count);
    }

    out.push_str("],\"sentences\":[");
    for (i, sent) in report.sentences.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        push_sentence_json(&mut out, sent);
    }
    out.push_str("]}");
    out
}