Text Classification
Transformers
ONNX
Safetensors
ai-detection
machine-generated-text
knowledge-distillation
modernbert
mmbert
webgpu
webassembly
lightgbm
treeshap
Run this model with HF Jobs
Run ElderRyan/proseguard on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ElderRyan/proseguard. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ElderRyan/proseguard on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ElderRyan/proseguard with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ElderRyan/proseguard with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="ElderRyan/proseguard")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("ElderRyan/proseguard", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 27,064 Bytes
1ddf025 | 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 | //! Dual-Proxy Corpus Language Model & Modern RLHF Syntactic Log-Odds Scorer (`lm_proxy`).
//!
//! Inspired by Ghostbuster (NAACL) and GPTZero's multi-indicator architecture:
//! 1. Scores token/character transitions against embedded RLHF-vs-Human log-odds lexicons across
//! English, Simplified/Traditional Chinese, and Japanese (covering GPT-4o, Claude, DeepSeek, Qwen).
//! 2. Evaluates structural negative parallelisms ("not just X, but Y", "不是…而是…", "単なる…ではなく"),
//! participial clause tails (", ensuring...", ", making it..."), conceptual scare-quotes ("“XX”"),
//! and nominalization/glue smoothness.
//! 3. Computes per-sentence proxy surprisal & cross-sentence surprisal burstiness, catching clean,
//! cliché-free LLM articles via flat predictability pacing.
use crate::model::{ScriptFamily, UnitScore};
/// High-log-odds English RLHF vocabulary stems (GPT-4o / Claude / Llama / DeepSeek).
const EN_RLHF_WORDS: &[(&str, f64)] = &[
("delve", 2.4),
("delves", 2.4),
("delving", 2.4),
("tapestry", 2.5),
("testament", 2.0),
("pivotal", 2.1),
("crucial", 1.1),
("vital", 0.9),
("multifaceted", 2.3),
("nuanced", 1.7),
("nuances", 1.6),
("underscore", 2.0),
("underscores", 2.2),
("underscoring", 2.2),
("foster", 1.7),
("fostering", 2.0),
("fosters", 1.8),
("realm", 1.7),
("beacon", 1.9),
("interplay", 2.1),
("synergy", 1.8),
("holistic", 1.9),
("seamless", 1.6),
("seamlessly", 1.9),
("leverage", 1.3),
("leveraging", 1.7),
("harness", 1.6),
("harnessing", 1.9),
("empower", 1.6),
("empowering", 1.8),
("empowers", 1.7),
("elevate", 1.5),
("elevating", 1.7),
("streamline", 1.6),
("streamlining", 1.8),
("transformative", 1.9),
("paradigm", 1.9),
("ecosystem", 1.2),
("stakeholders", 1.6),
("actionable", 1.7),
("overarching", 0.9),
("intricate", 1.7),
("intricacies", 2.0),
("meticulous", 1.8),
("meticulously", 2.0),
("commendable", 1.9),
("indispensable", 1.6),
("catalyst", 1.6),
("cornerstone", 1.7),
("navigating", 1.8),
("embark", 1.8),
("poised", 1.6),
("unprecedented", 1.3),
("burgeoning", 2.0),
("resonate", 1.5),
("resonates", 1.7),
("alignment", 1.3),
("reimagine", 1.9),
("demystify", 2.0),
("illuminate", 1.6),
("illuminates", 1.8),
("spearhead", 1.8),
("bolster", 1.5),
("cultivate", 1.5),
("cultivating", 1.7),
("landscape", 1.4),
("moreover", 1.6),
("furthermore", 1.7),
("additionally", 1.2),
("consequently", 1.1),
("ultimately", 1.0),
("notably", 1.1),
("undeniably", 1.6),
];
/// Modern English syntactic & rhetorical frames favored by GPT-4o, Claude, and DeepSeek.
const EN_RLHF_FRAMES: &[(&str, f64)] = &[
("not just ", 1.5),
("not merely ", 1.8),
("more than just ", 1.7),
("isn't just ", 1.6),
("aren't just ", 1.6),
("it's not about ", 1.8),
("it is not about ", 1.8),
("isn't about ", 1.8),
("not because ", 1.3),
("more often than not", 1.7),
("at its core", 1.9),
("in essence,", 1.7),
("the reality is", 1.4),
("here's why", 1.4),
("here's what", 1.5),
("here's the ", 1.3),
("that's why ", 1.2),
("think about what happens", 1.6),
("moves the needle", 1.7),
("nice-to-have", 1.5),
("first-class", 1.2),
("narrative coherence", 2.0),
("peculiar comfort", 1.8),
("this is where ", 1.3),
("that's where ", 1.3),
("whether you're ", 1.5),
("whether it's ", 1.5),
("it is important to note", 2.4),
("it's important to note", 2.4),
("it is worth noting", 2.1),
("it's worth noting", 2.0),
("in conclusion,", 2.0),
("in summary,", 1.9),
("on one hand", 1.4),
("on the other hand", 1.3),
("at the same time,", 1.1),
("by doing so,", 1.6),
("in other words,", 1.1),
("with that in mind", 1.7),
("moving forward", 1.4),
("looking ahead", 1.4),
("plays a pivotal role", 2.5),
("plays a crucial role", 2.2),
("plays a vital role", 2.1),
("rapidly evolving", 2.2),
("ever-evolving", 2.3),
("rich tapestry", 2.6),
("a testament to", 2.1),
(", making it ", 1.3),
(", allowing ", 1.2),
(", enabling ", 1.4),
(", ensuring ", 1.5),
(", creating ", 1.2),
(", fostering ", 2.0),
(", highlighting ", 1.6),
(", underscoring ", 2.1),
(", reflecting ", 1.3),
(", offering ", 1.3),
(", paving the way", 2.0),
];
/// Chinese RLHF vocabulary, abstract nominalizations & syntactic markers (GPT-4o / Claude / DeepSeek / Qwen).
const ZH_RLHF_MARKERS: &[(&str, f64)] = &[
("值得注意的是", 2.3),
("值得一提的是", 1.9),
("需要指出的是", 2.1),
("不可否认", 1.7),
("毫无疑问", 1.5),
("显而易见", 1.5),
("不难发现", 1.8),
("不难看出", 1.7),
("这意味着", 1.5),
("这也意味着", 1.7),
("换句话说", 1.4),
("换言之", 1.4),
("某种程度上", 1.5),
("从某种意义上", 1.7),
("从本质上讲", 1.9),
("本质上", 1.2),
("归根结底", 1.6),
("事实上,", 1.2),
("在此背景下", 1.9),
("正因如此", 1.5),
("由此可见", 1.6),
("更重要的是", 1.2),
("尤为重要的是", 1.8),
("与此同时", 1.4),
("不仅如此", 1.5),
("除此之外", 1.2),
("总而言之", 2.2),
("综上所述", 2.2),
("总的来看", 1.7),
("展望未来", 1.8),
("赋能", 2.1),
("闭环", 2.0),
("抓手", 2.0),
("底座", 1.7),
("范式", 1.8),
("颗粒度", 1.9),
("心智", 1.6),
("势能", 1.8),
("场域", 1.9),
("底层逻辑", 1.9),
("顶层设计", 1.8),
("全链路", 1.9),
("护城河", 1.5),
("方法论", 1.5),
("差异化", 1.4),
("规模化", 1.3),
("精细化", 1.4),
("常态化", 1.4),
("多元化", 1.3),
("系统性", 1.2),
("结构性", 1.3),
("确定性", 1.4),
("可持续", 1.3),
("多维度", 1.9),
("全方位", 1.7),
("深层次", 1.5),
("核心竞争力", 1.7),
("不可或缺", 1.6),
("至关重要", 1.8),
("息息相关", 1.5),
("相辅相成", 1.6),
("潜移默化", 1.4),
("双刃剑", 1.8),
("重塑", 1.5),
("重构", 1.3),
("洞察", 1.4),
("锚定", 1.8),
("拆解", 1.3),
("沉淀", 1.5),
("演进", 1.3),
("深耕", 1.6),
("注入了", 1.6),
("展现出", 1.3),
("呈现出", 1.3),
("折射出", 1.6),
("扮演着", 1.8),
("发挥着", 1.6),
("在当今", 2.0),
("随着科技", 1.9),
("悄然", 1.6),
("支离破碎", 1.6),
("延迟满足", 1.7),
("情绪内耗", 1.8),
("课题分离", 1.8),
("生活质感", 1.9),
("庸常瞬间", 2.0),
("或许所谓的", 2.1),
("温和抵抗", 1.9),
("精神锚点", 2.0),
("说到底,", 1.3),
("很多人以为", 1.5),
("總而言之", 2.2),
("綜上所述", 2.2),
("扮演著", 1.8),
("發揮著", 1.6),
("至關重要", 1.8),
("不可或缺", 1.6),
("多維度", 1.9),
("生態閉環", 2.2),
("底層邏輯", 1.9),
("這意味著", 1.5),
("換句話說", 1.4),
("在此背景下", 1.9),
("與此同時", 1.4),
];
/// Japanese RLHF markers (GPT-4o / Claude / DeepSeek Japanese prose).
const JA_RLHF_MARKERS: &[(&str, f64)] = &[
("重要な点として", 2.2),
("特筆すべき", 2.0),
("結論として", 2.0),
("総じて言えば", 2.1),
("言い換えれば", 1.5),
("すなわち、", 1.3),
("このように、", 1.3),
("その一方で", 1.3),
("にとどまらず", 1.7),
("重要な役割を果たし", 2.1),
("不可欠な要素", 1.9),
("多面的な視点", 2.1),
("包括的な", 1.7),
("持続可能な", 1.5),
("急速に進化", 2.0),
("パラダイム", 1.8),
("浮き彫りに", 1.6),
("再定義", 1.6),
("枠組み", 1.3),
];
/// Output of the proxy language model & RLHF syntactic scorer.
#[derive(Debug, Clone)]
pub struct ProxyLmAnalysis {
/// Document-level RLHF lexical & syntactic log-odds AI score (`[0.0, 1.0]`).
pub rlhf_discourse_score: UnitScore,
/// Proxy language model predictability & cross-sentence surprisal flatness (`[0.0, 1.0]`).
pub perplexity_flatness_score: UnitScore,
/// Per-sentence proxy AI likelihood (`len == all_sentences.len()`).
pub sentence_lm_scores: Vec<f64>,
/// Per-sentence hit counts of RLHF frames/stems.
pub sentence_hit_counts: Vec<usize>,
/// Mean sentence proxy surprisal (`bits/token` equivalent).
pub mean_surprisal_bits: f64,
/// Cross-sentence surprisal coefficient of variation (low = flat AI perplexity).
pub surprisal_cv: f64,
/// Top matched RLHF phrases / syntactic frames for explainability UI.
pub matched_signals: Vec<String>,
}
fn push_unique_signal(out: &mut Vec<String>, label: &str) {
if out.len() < 12 && !out.iter().any(|s| s == label) {
out.push(label.to_string());
}
}
/// Detects paired contrastive / negative-parallelism constructions inside a sentence.
#[must_use]
pub fn count_paired_contrast_frames(sent_lower: &str) -> (usize, Option<&'static str>) {
const PAIRS: &[(&str, &str, &str)] = &[
("不是", "而是", "不是…而是…"),
("并非", "而是", "并非…而是…"),
("不再是", "而", "不再是…而…"),
("从来不", "而", "从来不…而…"),
("从来不在", "藏在", "从来不在…就藏在…"),
("不在于", "而在于", "不在于…而在于…"),
("不只是", "更是", "不只是…更是…"),
("不仅仅是", "更是", "不仅仅是…更是…"),
("不仅是", "更是", "不仅是…更是…"),
("不仅", "而且", "不仅…而且…"),
("与其说", "不如说", "与其说…不如说…"),
("一方面", "另一方面", "一方面…另一方面…"),
("无论是", "还是", "无论是…还是…"),
("既要", "又要", "既要…又要…"),
("not only ", " but also ", "not only ... but also"),
("not just ", " but ", "not just ... but"),
("not merely ", " but ", "not merely ... but"),
(
"not because ",
" but because ",
"not because ... but because",
),
("isn't ", "; it's ", "isn't X; it's Y"),
("isn't ", "—it's ", "isn't X—it's Y"),
("rather than ", ", ", "rather than ... contrast"),
("until ", ", they remain ", "until X, they remain Y"),
("単なる", "ではなく", "単なる…ではなく"),
("だけでなく", "もまた", "だけでなく…もまた"),
];
let mut hits = 0usize;
let mut first_label = None;
for &(left, right, label) in PAIRS {
if let Some(pos) = sent_lower.find(left) {
let after = pos.saturating_add(left.len());
if let Some(rest) = sent_lower.get(after..) {
if rest.contains(right) {
hits = hits.saturating_add(1);
if first_label.is_none() {
first_label = Some(label);
}
}
}
}
}
(hits, first_label)
}
/// Counts short conceptual scare-quotes (`“XX”` or `「XX」` wrapping 2–6 chars).
#[must_use]
fn count_conceptual_scare_quotes(text: &str) -> usize {
let mut count = 0usize;
for (open_q, close_q) in [('“', '”'), ('「', '」')] {
let mut rest = text;
while let Some(start) = rest.find(open_q) {
let after_open = start.saturating_add(open_q.len_utf8());
let Some(tail) = rest.get(after_open..) else {
break;
};
let Some(end) = tail.find(close_q) else {
break;
};
if let Some(inner) = tail.get(..end) {
let char_len = inner.chars().count();
let has_punct = inner
.chars()
.any(|c| matches!(c, ',' | '。' | '!' | '?' | ',' | '.' | ':'));
if (2..=6).contains(&char_len) && !has_punct {
count = count.saturating_add(1);
}
}
let next_start = end.saturating_add(close_q.len_utf8());
rest = tail.get(next_start..).unwrap_or("");
}
}
count
}
fn cjk_clause_surprisal(sentence: &str) -> f64 {
const CJK_ABSTRACT: &[char] = &[
'化', '性', '度', '体', '系', '机', '制', '模', '式', '赋', '维', '环', '态', '域', '层',
'构', '筑', '塑',
];
const CJK_SPOKEN_STANCE: &[&str] = &[
"我觉得",
"我覺得",
"我喜欢",
"我喜歡",
"我不在乎",
"我是",
"我们做",
"我們做",
"咱们",
"咱們",
"说不定",
"說不定",
"实话说",
"實話說",
"可惜",
"私",
"僕",
"思います",
"信じています",
"可愛い",
"んです",
"わけです",
];
let chars: Vec<char> = sentence.chars().filter(|c| !c.is_whitespace()).collect();
let total = chars.len().max(1);
let abs_cnt = chars.iter().filter(|c| CJK_ABSTRACT.contains(c)).count();
let abs_ratio = (abs_cnt as f64) / (total as f64);
let mut delta = 0.0f64;
if abs_ratio >= 0.07 {
delta -= (abs_ratio * 5.0).min(0.68);
}
if CJK_SPOKEN_STANCE.iter().any(|&s| sentence.contains(s)) {
delta += 0.54;
} else if sentence.contains('我') || sentence.contains('你') {
delta += 0.28;
}
let clauses: Vec<usize> = sentence
.split([',', ',', '、', ';'])
.map(|cl| cl.chars().filter(|c| !c.is_whitespace()).count())
.filter(|&len| len > 0)
.collect();
if clauses.len() >= 3 {
let mean_cl = (clauses.iter().sum::<usize>() as f64) / (clauses.len() as f64);
if clauses.iter().all(|&c| (8..=22).contains(&c)) && (10.5..=18.5).contains(&mean_cl) {
delta -= 0.42;
}
}
delta
}
fn alpha_clause_surprisal(sentence: &str) -> f64 {
const FIRST_PERSON: &[&str] = &[
"i", "i'm", "i've", "i'd", "i'll", "my", "me", "we", "we're", "we've", "our", "us", "you",
"you're", "your",
];
const RLHF_GERUNDS: &[&str] = &[
"fostering",
"navigating",
"leveraging",
"streamlining",
"reshaping",
"embracing",
"cultivating",
"empowering",
"underscoring",
"prioritizing",
"optimizing",
"unlocking",
"bridging",
"harnessing",
];
let raw_words: Vec<&str> = sentence
.split(|c: char| !c.is_alphabetic() && c != '\'')
.filter(|w| !w.is_empty())
.collect();
let total = raw_words.len().max(1);
let words: Vec<String> = raw_words.iter().map(|w| w.to_lowercase()).collect();
let nom_cnt = words
.iter()
.filter(|w| {
RLHF_GERUNDS.contains(&w.as_str())
|| (w.len() >= 8
&& (w.ends_with("tion")
|| w.ends_with("tions")
|| w.ends_with("ment")
|| w.ends_with("ments")
|| w.ends_with("ity")
|| w.ends_with("ities")
|| w.ends_with("ness")))
})
.count();
let has_stance = words.iter().any(|w| FIRST_PERSON.contains(&w.as_str()));
let proper_nouns = raw_words
.iter()
.skip(1)
.filter(|w| w.len() >= 3 && w.chars().next().map(char::is_uppercase).unwrap_or(false))
.count();
let nom_ratio = (nom_cnt as f64) / (total as f64);
let mut delta = 0.0f64;
if nom_ratio >= 0.10 {
delta -= (nom_ratio * 3.4).min(0.68);
}
if total >= 13 && !has_stance && proper_nouns == 0 {
delta -= 0.34;
}
if has_stance {
delta += 0.36;
}
if proper_nouns >= 1 {
delta += (proper_nouns as f64 * 0.18).min(0.42);
}
if sentence.contains('(') || sentence.contains("...") || sentence.contains(';') {
delta += 0.24;
}
delta
}
/// Estimates proxy surprisal (in bits per token equivalent) for a single prose sentence.
#[must_use]
pub fn estimate_sentence_surprisal_bits(sentence: &str, script: ScriptFamily) -> f64 {
const HUMAN_COLLOQUIAL: &[&str] = &[
"wait",
"honestly",
"literally",
"weird",
"crazy",
"damn",
"ugh",
"btw",
"imo",
"tbh",
"gonna",
"wanna",
"kinda",
"sorta",
"heck",
"nope",
"yep",
"folks",
"居然",
"简直",
"离谱",
"吐槽",
"折腾",
"压根",
"说白了",
"算了",
"哈哈",
"偏偏",
"硬是",
"真绝",
"干脆",
"莫名其妙",
"说实话",
"毛病",
"狂刷",
"搞明白",
"抽风",
"老头儿",
"泥巴",
"嘎嘣",
"老婆",
"笑话",
"哪有",
"钟头",
"鐘頭",
"離譜",
"古怪",
"遣散",
"訴苦",
"发呆",
"發呆",
"没边儿",
"愣半天",
"turns out",
"sure—",
"barely",
"declined to",
"pretend",
"fool ",
"まさか",
"ぶっちゃけ",
"なんか",
"やばい",
"しかめ面",
"タクシードライバー",
];
let mut surprisal = 4.60f64;
surprisal += if script.uses_ideographic_cadence() {
cjk_clause_surprisal(sentence)
} else {
alpha_clause_surprisal(sentence)
};
let digit_groups = sentence
.split(|c: char| !c.is_ascii_digit())
.filter(|s| !s.is_empty())
.count();
if digit_groups >= 2 {
surprisal += 0.46;
} else if digit_groups == 1 {
surprisal += 0.18;
}
if sentence
.chars()
.any(|c| matches!(c, '?' | '!' | '?' | '!' | '`' | '/'))
{
surprisal += 0.44;
}
let lower = sentence.to_lowercase();
if HUMAN_COLLOQUIAL.iter().any(|&kw| lower.contains(kw)) {
surprisal += 0.88;
}
surprisal.clamp(2.4, 8.2)
}
fn accumulate_english_odds(lower_full: &str, signals: &mut Vec<String>) -> f64 {
let mut odds = 0.0f64;
for word in lower_full.split(|c: char| !c.is_alphabetic()) {
if word.is_empty() {
continue;
}
for &(stem, w) in EN_RLHF_WORDS {
if word == stem {
odds += w;
push_unique_signal(signals, stem);
break;
}
}
}
for &(frame, w) in EN_RLHF_FRAMES {
let cnt = lower_full.matches(frame).count();
if cnt > 0 {
odds += w * (cnt as f64).min(4.0);
push_unique_signal(signals, frame.trim_matches(|c: char| c == ',' || c == ' '));
}
}
odds
}
fn accumulate_cjk_odds(full_text: &str, signals: &mut Vec<String>) -> f64 {
let mut odds = 0.0f64;
for &(marker, w) in ZH_RLHF_MARKERS.iter().chain(JA_RLHF_MARKERS.iter()) {
let cnt = full_text.matches(marker).count();
if cnt > 0 {
odds += w * (cnt as f64).min(4.0);
push_unique_signal(signals, marker);
}
}
let scare_quotes = count_conceptual_scare_quotes(full_text);
let char_k = (full_text.chars().count().max(120) as f64) / 1000.0;
let sq_per_k = (scare_quotes as f64) / char_k;
if scare_quotes >= 3 && sq_per_k >= 4.0 {
odds += ((sq_per_k - 3.0) * 0.45).min(4.5);
push_unique_signal(signals, "“概念双引号”高频修饰");
}
odds
}
fn accumulate_markdown_odds(full_text: &str, signals: &mut Vec<String>) -> f64 {
let mut headings = 0usize;
let mut bold_bullets = 0usize;
let mut plain_bullets = 0usize;
for line in full_text.lines() {
let t = line.trim_start();
if t.starts_with("# ") || t.starts_with("## ") || t.starts_with("### ") {
headings = headings.saturating_add(1);
} else if t.starts_with("- ")
|| t.starts_with("* ")
|| t.starts_with("1. ")
|| t.starts_with("2. ")
|| t.starts_with("3. ")
|| t.starts_with("4. ")
{
plain_bullets = plain_bullets.saturating_add(1);
if t.contains("**:") || t.contains("**:") || t.contains("** —") || t.contains("** -")
{
bold_bullets = bold_bullets.saturating_add(1);
}
}
}
if bold_bullets >= 2 {
push_unique_signal(signals, "Markdown **Bold**: List");
2.6 + ((bold_bullets as f64) * 0.75).min(3.6)
} else if headings >= 2 && plain_bullets >= 3 {
1.9
} else if headings >= 3 {
1.1
} else {
0.0
}
}
fn score_single_sentence(sent: &str, script: ScriptFamily) -> (f64, usize) {
let s_low = sent.to_lowercase();
let (mut s_hits, _) = count_paired_contrast_frames(&s_low);
if !matches!(script, ScriptFamily::Cjk) {
s_hits = s_hits.saturating_add(
EN_RLHF_FRAMES
.iter()
.filter(|&&(f, _)| s_low.contains(f))
.count(),
);
s_hits = s_hits.saturating_add(
s_low
.split(|c: char| !c.is_alphabetic())
.filter(|w| EN_RLHF_WORDS.iter().any(|&(st, _)| &st == w))
.count(),
);
}
if script.uses_ideographic_cadence() {
s_hits = s_hits.saturating_add(
ZH_RLHF_MARKERS
.iter()
.chain(JA_RLHF_MARKERS.iter())
.filter(|&&(m, _)| sent.contains(m))
.count(),
);
}
let s_bits = estimate_sentence_surprisal_bits(sent, script);
let prob = (0.54 + (4.58 - s_bits) * 0.42 + (s_hits as f64) * 0.17).clamp(0.03, 0.98);
(prob, s_hits)
}
fn accumulate_rhetorical_cadence_odds(
lower_full: &str,
prose_sentences: &[String],
script: ScriptFamily,
signals: &mut Vec<String>,
) -> f64 {
let mut odds = 0.0f64;
let mut consec_short_decl = 0usize;
let mut max_consec_short = 0usize;
let mut consec_questions = 0usize;
let mut max_consec_q = 0usize;
for s in prose_sentences {
let trimmed = s.trim();
let wc = trimmed
.split(|c: char| !c.is_alphanumeric())
.filter(|w| !w.is_empty())
.count();
if trimmed.ends_with('.') && (2..=4).contains(&wc) && !script.uses_ideographic_cadence() {
consec_short_decl = consec_short_decl.saturating_add(1);
max_consec_short = max_consec_short.max(consec_short_decl);
} else {
consec_short_decl = 0;
}
if trimmed.ends_with('?') || trimmed.ends_with('?') {
consec_questions = consec_questions.saturating_add(1);
max_consec_q = max_consec_q.max(consec_questions);
} else {
consec_questions = 0;
}
}
if max_consec_short >= 2 {
odds += 2.9;
push_unique_signal(signals, "Staccato Triplet Rhythm");
}
if max_consec_q >= 2 {
odds += 2.2;
push_unique_signal(signals, "Rhetorical Question Series");
}
if lower_full.contains("everyone talks about") && lower_full.contains("nobody talks about") {
odds += 2.6;
push_unique_signal(signals, "everyone talks / nobody talks");
}
odds
}
/// Evaluates full document and sentence-level proxy LM & RLHF stylometric signals.
#[must_use]
pub fn evaluate_proxy_lm(
full_text: &str,
prose_sentences: &[String],
all_sentences: &[String],
script: ScriptFamily,
inspect_markdown: bool,
) -> ProxyLmAnalysis {
let lower_full = full_text.to_lowercase();
let mut matched_signals: Vec<String> = Vec::new();
let mut total_log_odds = 0.0f64;
if !matches!(script, ScriptFamily::Cjk) {
total_log_odds += accumulate_english_odds(&lower_full, &mut matched_signals);
}
if script.uses_ideographic_cadence() {
total_log_odds += accumulate_cjk_odds(full_text, &mut matched_signals);
}
for sent in all_sentences {
let (cnt, lbl) = count_paired_contrast_frames(&sent.to_lowercase());
if cnt > 0 {
total_log_odds += (cnt as f64) * 1.95;
if let Some(label_str) = lbl {
push_unique_signal(&mut matched_signals, label_str);
}
}
}
total_log_odds += accumulate_rhetorical_cadence_odds(
&lower_full,
prose_sentences,
script,
&mut matched_signals,
);
if inspect_markdown {
total_log_odds += accumulate_markdown_odds(full_text, &mut matched_signals);
}
let eff_sents = ((prose_sentences.len().max(2)) as f64).powf(0.76);
let odds_density = total_log_odds / eff_sents;
let rlhf_discourse_score =
UnitScore::clamped(1.0 / (1.0 + (-1.45 * (odds_density - 0.78)).exp()));
let eval_pool = if prose_sentences.is_empty() {
all_sentences
} else {
prose_sentences
};
let surprisals: Vec<f64> = eval_pool
.iter()
.map(|s| estimate_sentence_surprisal_bits(s, script))
.collect();
let mean_surprisal_bits = if surprisals.is_empty() {
4.5
} else {
surprisals.iter().sum::<f64>() / (surprisals.len() as f64)
};
let surprisal_cv = if surprisals.len() >= 2 {
let var = surprisals
.iter()
.map(|&x| (x - mean_surprisal_bits).powi(2))
.sum::<f64>()
/ (surprisals.len() as f64);
var.sqrt() / mean_surprisal_bits.max(1.0)
} else {
0.10
};
let low_ppl_signal = (4.58 - mean_surprisal_bits).clamp(-1.2, 1.2) * 0.46;
let flat_cv_signal = (0.12 - surprisal_cv).clamp(-0.12, 0.10) * 2.8;
let perplexity_flatness_score = UnitScore::clamped(0.52 + low_ppl_signal + flat_cv_signal);
let mut sentence_lm_scores = Vec::with_capacity(all_sentences.len());
let mut sentence_hit_counts = Vec::with_capacity(all_sentences.len());
for sent in all_sentences {
let (p, h) = score_single_sentence(sent, script);
sentence_lm_scores.push(p);
sentence_hit_counts.push(h);
}
ProxyLmAnalysis {
rlhf_discourse_score,
perplexity_flatness_score,
sentence_lm_scores,
sentence_hit_counts,
mean_surprisal_bits,
surprisal_cv,
matched_signals,
}
}
|