dislop 0.9.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +2 -2
- package/.codex-plugin/plugin.json +7 -8
- package/.cursor-plugin/plugin.json +2 -3
- package/.pre-commit-hooks.yaml +5 -12
- package/PRODUCT.md +19 -63
- package/README.md +360 -252
- package/README.zh-CN.md +390 -240
- package/action.yml +30 -39
- package/bin/dislop-mcp.mjs +3 -4
- package/bin/dislop.mjs +4 -4594
- package/gemini-extension.json +2 -2
- package/llms-install.md +68 -0
- package/package.json +17 -63
- package/packs/common/artifact-qa/pack.json +5 -0
- package/packs/common/artifact-qa/prompts/rules.md +11 -0
- package/packs/common/artifact-qa/scripts/index.mjs +173 -0
- package/packs/common/slide-deck/pack.json +6 -0
- package/packs/common/slide-deck/prompts/rules.md +11 -0
- package/packs/common/slide-deck/scripts/index.mjs +62 -0
- package/packs/common/web-ui/pack.json +6 -0
- package/packs/common/web-ui/prompts/rules.md +11 -0
- package/packs/common/web-ui/scripts/index.mjs +80 -0
- package/packs/en/artifact-qa/pack.json +6 -0
- package/packs/en/artifact-qa/prompts/rules.md +14 -0
- package/packs/en/artifact-qa/scripts/index.mjs +90 -0
- package/packs/en/prose/pack.json +7 -0
- package/packs/en/prose/prompts/rules.md +26 -0
- package/packs/en/prose/scripts/index.mjs +290 -0
- package/packs/en/slide-deck/pack.json +7 -0
- package/packs/en/slide-deck/prompts/rules.md +17 -0
- package/packs/en/slide-deck/scripts/index.mjs +81 -0
- package/packs/en/web-ui/pack.json +7 -0
- package/packs/en/web-ui/prompts/rules.md +20 -0
- package/packs/en/web-ui/scripts/index.mjs +103 -0
- package/packs/zh/artifact-qa/pack.json +6 -0
- package/packs/zh/artifact-qa/prompts/rules.md +14 -0
- package/packs/zh/artifact-qa/scripts/index.mjs +89 -0
- package/packs/zh/prose/pack.json +7 -0
- package/packs/zh/prose/prompts/rules.md +26 -0
- package/packs/zh/prose/scripts/index.mjs +305 -0
- package/packs/zh/slide-deck/pack.json +7 -0
- package/packs/zh/slide-deck/prompts/rules.md +17 -0
- package/packs/zh/slide-deck/scripts/index.mjs +75 -0
- package/packs/zh/web-ui/pack.json +7 -0
- package/packs/zh/web-ui/prompts/rules.md +20 -0
- package/packs/zh/web-ui/scripts/index.mjs +98 -0
- package/plugin.json +5 -6
- package/server.json +2 -2
- package/skills/deslop-docs/SKILL.md +10 -8
- package/skills/deslop-slides-docx/SKILL.md +7 -8
- package/skills/deslop-verify/SKILL.md +7 -8
- package/skills/deslop-web-ui/SKILL.md +7 -8
- package/skills/dislop/SKILL.md +16 -28
- package/skills/dislop/references/essay.md +1 -1
- package/skills/dislop/references/essay.zh-CN.md +1 -1
- package/skills/dislop/references/office.md +1 -1
- package/skills/dislop/references/office.zh-CN.md +1 -1
- package/skills/dislop/references/web-ui.md +1 -1
- package/skills/dislop/references/web-ui.zh-CN.md +1 -1
- package/skills/dislop/references/work-docs.md +1 -1
- package/skills/dislop/references/work-docs.zh-CN.md +1 -1
- package/src/cli-main.mjs +210 -0
- package/src/commands/check-fix.mjs +169 -0
- package/src/commands/doctor.mjs +110 -0
- package/src/commands/init.mjs +49 -0
- package/src/commands/login.mjs +82 -0
- package/src/commands/model.mjs +130 -0
- package/src/commands/packs.mjs +44 -0
- package/src/commands/verify.mjs +133 -0
- package/src/commands/voice.mjs +84 -0
- package/src/kernel/config.mjs +232 -0
- package/src/kernel/document-model.mjs +1412 -0
- package/src/kernel/fact-gate.mjs +615 -0
- package/src/kernel/file-discovery.mjs +139 -0
- package/src/{binary-node.mjs → kernel/ooxml-binary.mjs} +532 -893
- package/src/kernel/pack-loader.mjs +715 -0
- package/src/kernel/patcher.mjs +341 -0
- package/src/kernel/pipeline.mjs +267 -0
- package/src/kernel/prompt-assembler.mjs +307 -0
- package/src/kernel/voice-profile.mjs +177 -0
- package/src/mcp/stdio-server.mjs +372 -0
- package/src/runners/auto-fix.mjs +59 -0
- package/src/runners/interactive-tty.mjs +461 -0
- package/src/runners/reporters.mjs +256 -0
- package/src/runtime/chunker.mjs +87 -0
- package/src/runtime/json-extract.mjs +144 -0
- package/src/runtime/privacy-gate.mjs +97 -0
- package/src/runtime/providers/anthropic.mjs +65 -0
- package/src/runtime/providers/cloud.mjs +136 -0
- package/src/runtime/providers/gemini.mjs +91 -0
- package/src/runtime/providers/local-model.mjs +139 -0
- package/src/runtime/providers/openai-compat.mjs +130 -0
- package/src/runtime/router.mjs +315 -0
- package/src/sdk/index.mjs +137 -0
- package/models/manifest.json +0 -90
- package/models/pocket-slop-v1.json +0 -1
- package/packs/business-brief/pack.json +0 -937
- package/packs/core/pack.json +0 -209
- package/packs/deck-and-ui/pack.json +0 -539
- package/packs/engineering-spec/pack.json +0 -144
- package/packs/executive-deck/pack.json +0 -98
- package/packs/literary-essay/pack.json +0 -344
- package/packs/regulated-comms/pack.json +0 -99
- package/patterns/ai-tic-rubric.json +0 -252
- package/patterns/banks/composite-fusion.json +0 -48
- package/patterns/banks/discourse-rhythm.json +0 -95
- package/patterns/banks/lexical-signals.json +0 -92
- package/patterns/banks/syntactic-frames.json +0 -52
- package/patterns/banks/visual-deck.json +0 -44
- package/patterns/dimensions/artifacts.json +0 -121
- package/patterns/dimensions/discourse.json +0 -438
- package/patterns/dimensions/lexical.json +0 -198
- package/patterns/dimensions/rhythm.json +0 -258
- package/patterns/dimensions/syntactic.json +0 -285
- package/patterns/dimensions/visual-and-deck.json +0 -530
- package/patterns/taxonomy.json +0 -112
- package/src/core.mjs +0 -5497
- package/src/dislop/review-picker.vim +0 -114
- package/src/local-model.mjs +0 -997
- package/src/pattern-engine.mjs +0 -1003
- package/src/pocket-model.mjs +0 -729
- package/src/review-apply.mjs +0 -151
- package/src/review-client.mjs +0 -1073
package/src/pocket-model.mjs
DELETED
|
@@ -1,729 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Zero-dependency Bundled Pocket Traditional ML Engine (`dislop.pocket-model/1`).
|
|
3
|
-
* Runs two built-in offline models (<15 KB gzipped JSON, <0.5 ms per paragraph, 0 network):
|
|
4
|
-
* 1. `pocket-slop-ensemble`: De-lexicalized INT8 N-gram Log-Odds LM + Calibrated 24-Feature
|
|
5
|
-
* Linear Attribution + 45-Tree Shallow GBDT Paragraph/Prose Slop Scorer.
|
|
6
|
-
* 2. `pocket-pack-router`: Quantized INT8 Multinomial Log-Odds 5-Domain Pack Classifier.
|
|
7
|
-
*
|
|
8
|
-
* Bit-for-bit aligned with Python `src/dislop/pocket_model.py`.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import fs from "node:fs";
|
|
12
|
-
import path from "node:path";
|
|
13
|
-
import { fileURLToPath } from "node:url";
|
|
14
|
-
|
|
15
|
-
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
-
const DEFAULT_MODEL_CANDIDATES = [
|
|
17
|
-
path.resolve(__dirname, "..", "models", "pocket-slop-v1.json"),
|
|
18
|
-
path.resolve(__dirname, "pocket-slop-v1.json"),
|
|
19
|
-
];
|
|
20
|
-
|
|
21
|
-
let _cachedBundle = null;
|
|
22
|
-
|
|
23
|
-
export function loadPocketModelBundle(customPath = null) {
|
|
24
|
-
if (!customPath && _cachedBundle) return _cachedBundle;
|
|
25
|
-
const candidates = customPath ? [customPath] : DEFAULT_MODEL_CANDIDATES;
|
|
26
|
-
for (const p of candidates) {
|
|
27
|
-
if (fs.existsSync(p)) {
|
|
28
|
-
const raw = JSON.parse(fs.readFileSync(p, "utf8"));
|
|
29
|
-
raw._enFuncSet = new Set(raw.enFuncWords || []);
|
|
30
|
-
raw._zhStructSet = new Set(Array.from(raw.zhStructChars || ""));
|
|
31
|
-
if (!customPath) _cachedBundle = raw;
|
|
32
|
-
return raw;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
throw new Error("dislop pocket model bundle (pocket-slop-v1.json) not found.");
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function cpLen(s) {
|
|
39
|
-
let n = 0;
|
|
40
|
-
for (const _ of s) n += 1;
|
|
41
|
-
return n;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function round4(v) {
|
|
45
|
-
const scaled = v * 10000.0;
|
|
46
|
-
const fl = Math.floor(scaled);
|
|
47
|
-
const rounded = scaled - fl >= 0.5 ? fl + 1 : fl;
|
|
48
|
-
const res = rounded / 10000.0;
|
|
49
|
-
return Object.is(res, -0) ? 0 : res;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function maxOf(arr) {
|
|
53
|
-
let m = -Infinity;
|
|
54
|
-
for (let i = 0; i < arr.length; i += 1) {
|
|
55
|
-
if (arr[i] > m) m = arr[i];
|
|
56
|
-
}
|
|
57
|
-
return m;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const FENCE_BLOCK_RE = /```[\s\S]*?```|~~~[\s\S]*?~~~/g;
|
|
61
|
-
const DISLOP_QUOTE_BLOCK_RE = /<!--\s*dislop-quote-start\s*-->[\s\S]*?<!--\s*dislop-quote-end\s*-->/gi;
|
|
62
|
-
const HTML_COMMENT_RE = /<!--[\s\S]*?-->/g;
|
|
63
|
-
const HTML_TAG_RE = /<\/?[A-Za-z][^>\n]{0,400}>/g;
|
|
64
|
-
|
|
65
|
-
const INLINE_CODE_RE = /`[^`\n]+`/g;
|
|
66
|
-
const MD_LINK_COUNT_RE = /\[[^\[\]\n]{1,240}\]\([^()\s\n]{1,360}\)/g;
|
|
67
|
-
const MD_LINK_REPLACE_RE = /\[([^\[\]\n]{1,240})\]\([^()\s\n]{1,360}\)/g;
|
|
68
|
-
const BARE_URL_RE = /https?:\/\/[^\s)>\]"']+/g;
|
|
69
|
-
const CITATION_AUTHOR_RE = /\([A-Z][A-Za-z-]{1,30}(?:\s+et\s+al\.)?,?\s*(?:19|20)[0-9]{2}[a-z]?(?:[;,]\s*[^()\n]{1,80})?\)/g;
|
|
70
|
-
const CITATION_BRACKET_RE = /\[[0-9]{1,4}(?:\s*[,-]\s*[0-9]{1,4}){0,20}\]/g;
|
|
71
|
-
const PAREN_QUOTE_RE = /[((]\s*[“"「『][^((”"」』\n]{6,160}[”"」』]\s*[))]/gu;
|
|
72
|
-
const EXAMPLE_QUOTE_RE = /(?:例如|比如|如|e\.g\.|such as)\s*[::,,]?\s*[“"「『][^”"」』\n]{6,160}[”"」』]/giu;
|
|
73
|
-
const TAG_STRIP_RE = /<(?:CODE|URL)>/g;
|
|
74
|
-
const CJK_RE = /[\u4e00-\u9fff]/g;
|
|
75
|
-
const EN_WORD_RE = /[A-Za-z]+/g;
|
|
76
|
-
const EN_ALNUM_RE = /[A-Za-z0-9]+/g;
|
|
77
|
-
const NUM_MASK_RE = /(?<![A-Za-z0-9])[0-9]+(?:[.,:/-][0-9]+)*%?(?![A-Za-z0-9])/g;
|
|
78
|
-
const NUM_HIT_RE = /(?<![A-Za-z0-9])[0-9]+(?:[.,:][0-9]+)?%?(?![A-Za-z0-9])/g;
|
|
79
|
-
const TOKEN_SCAN_RE = /<(?:CODE|URL|NUM)>|[A-Za-z]+|[\u4e00-\u9fff]|[,。!?;:、,.!?;:—\-]/g;
|
|
80
|
-
const LEX_TOK_RE = /[\u4e00-\u9fff]|[a-z]{2,}/g;
|
|
81
|
-
|
|
82
|
-
const EN_NUM_TIME_RE = /(?<![A-Za-z])(?:one|two|three|four|five|six|seven|eight|nine|ten|twenty|thirty|monday|tuesday|wednesday|thursday|friday|saturday|sunday|yesterday|last\s+week)(?![A-Za-z])/gi;
|
|
83
|
-
const ZH_NUM_TIME_RE = /(?:[一二三四五六七八九十两百千万]+[天月年次个张条座块斤米秒分时点]|周[一二三四五六日天]|昨天|昨晚|今早|上周|下周)/g;
|
|
84
|
-
const PATH_HIT_RE = /[./\\][A-Za-z0-9._/-]+\.[a-z]{1,6}(?![A-Za-z])/g;
|
|
85
|
-
|
|
86
|
-
const EN_ABSTRACT_RE = /(?<![A-Za-z])[A-Za-z]{4,}(?:tion|tions|sion|sions|ment|ments|ity|ities|ness|ance|ence|ization|isation)(?![A-Za-z])/gi;
|
|
87
|
-
const EN_GERUND_OPENER_RE = /(?:^|[.!?]\s+)(?:By\s+[a-z]+ing|[A-Z][a-z]+ing\s+[a-z]+)(?![A-Za-z])/g;
|
|
88
|
-
const EN_CUSHION_RE = /(?<![A-Za-z])(?:plays?\s+an?\s+(?:important|key|vital|critical|central|meaningful)\s+role|provides?\s+(?:meaningful|valuable|important|actionable)\s+(?:context|insights?|guidance)|often\s+(?:notice|require|involves?|leads?\s+to|helps?)|helps?\s+[a-z]+\s+(?:focus|maintain|reduce|build|navigate|cultivate)|supports?\s+(?:steady|long-term|sustainable|effective|productive)|contributes?\s+(?:directly\s+)?to|minimizes?\s+unexpected|enabling\s+[a-z]+\s+to|while\s+(?:maintaining|preserving|enabling|supporting|ensuring|strengthening)|greater\s+confidence|shared\s+visibility|operational\s+(?:progress|observations)|rather\s+than\s+isolated\s+assumptions|when\s+additional\s+resources\s+are\s+required|quiet\s+sense\s+of|creating\s+a\s+[a-z]+\s+rhythm\s+that)(?![A-Za-z])/gi;
|
|
89
|
-
|
|
90
|
-
const ZH_NOMINAL_FRAME_RE = /(?:在[^,。!?\n]{2,14}的(?:过程|背景|环境|节奏|框架|语境)[中里]|之[中后前下]|的(?:打磨|推进|演进|提升|构建|平衡点|割裂感|积极意义|重要前提|良好基础))/g;
|
|
91
|
-
const ZH_CUSHION_RE = /(?:往往(?:能够|需要|是|会)|能够在[^,。]{2,10}中|在很大程度上|潜移默化中|不可忽视的|恰到好处的|平稳有序|稳步提升|奠定(?:了)?(?:良好|坚实)?基础|具有[^,。]{2,8}意义|重要前提|独特气息|柔和的倒影|不知不觉中)/g;
|
|
92
|
-
const ZH_COLLOQUIAL_CONCRETE_RE = /(?:砍掉|顺手|盯|摸了摸|揣进|烫着|铁桶|三轮车|报刊亭|置顶|标红|吞成|卡点|踩的|坑|锁死|别写成)/g;
|
|
93
|
-
const EN_DIRECT_CONCRETE_RE = /(?<![A-Za-z])(?:we\s+stopped|never\s+[a-z]+|delete\s+the|way\s+more\s+than|last\s+week|yesterday|three\s+in\s+the\s+morning|hoses\s+down|burnt\s+sugar|wet\s+cardboard)(?![A-Za-z])/gi;
|
|
94
|
-
const ZH_DIRECT_PRON_RE = /[我你咱们别]/g;
|
|
95
|
-
const PUNCT_CHAR_RE = /[,。!?;:、,.!?;:—\-()()“”"']/g;
|
|
96
|
-
const EMDASH_RE = /——|—/g;
|
|
97
|
-
|
|
98
|
-
const EN_CUSHION_WORDS = new Set([
|
|
99
|
-
"often", "typically", "effectively", "seamlessly", "steadily", "proactively",
|
|
100
|
-
"ensure", "ensures", "ensuring", "enable", "enables", "enabling", "foster",
|
|
101
|
-
"fostering", "enhance", "enhancing", "streamline", "navigate", "leverage",
|
|
102
|
-
"meaningful", "actionable", "sustainable", "holistic", "comprehensive",
|
|
103
|
-
]);
|
|
104
|
-
const EN_DIRECT_WORDS = new Set([
|
|
105
|
-
"i", "we", "you", "my", "our", "your", "never", "stop", "delete", "ship", "shipped", "broke",
|
|
106
|
-
]);
|
|
107
|
-
|
|
108
|
-
const DRIVER_LABELS = {
|
|
109
|
-
ngram_llr_mean: {
|
|
110
|
-
en: "predictable structural & transition phrasing",
|
|
111
|
-
zh: "句式衔接高度顺滑可预测",
|
|
112
|
-
},
|
|
113
|
-
ngram_llr_max_sent: {
|
|
114
|
-
en: "high-template sentence skeleton",
|
|
115
|
-
zh: "单句呈高频模板化骨架",
|
|
116
|
-
},
|
|
117
|
-
concreteness: {
|
|
118
|
-
en: "low concrete anchors (few numbers, dates, files, or citations)",
|
|
119
|
-
zh: "缺少具体事实锚点(数字、时间、文件名或出处)",
|
|
120
|
-
},
|
|
121
|
-
en_abstract_noun_rate: {
|
|
122
|
-
en: "dense abstract nominalizations (-tion/-ment/-ity/-ness)",
|
|
123
|
-
zh: "抽象名词化后缀密集",
|
|
124
|
-
},
|
|
125
|
-
en_func_cushion_rate: {
|
|
126
|
-
en: "hedged corporate cushion verbs/adverbs",
|
|
127
|
-
zh: "堆叠温和缓冲动词与副词",
|
|
128
|
-
},
|
|
129
|
-
en_cushion_phrase_rate: {
|
|
130
|
-
en: "stock framing phrases (plays a role / supports steady...)",
|
|
131
|
-
zh: "套用公关过渡短语",
|
|
132
|
-
},
|
|
133
|
-
en_gerund_opener_rate: {
|
|
134
|
-
en: "participial/gerund sentence openers (By -ing / Maintaining...)",
|
|
135
|
-
zh: "分词结构机械起句",
|
|
136
|
-
},
|
|
137
|
-
zh_nominal_frame_rate: {
|
|
138
|
-
en: "nominalized wrapper frames (在…的过程中 / …的推进)",
|
|
139
|
-
zh: "套用「在……的过程中 / ……的推进」名词化外壳",
|
|
140
|
-
},
|
|
141
|
-
zh_cushion_phrase_rate: {
|
|
142
|
-
en: "soft filler cushions (往往能够 / 稳步提升 / 不可忽视)",
|
|
143
|
-
zh: "堆叠「往往能够 / 稳步提升」缓冲套话",
|
|
144
|
-
},
|
|
145
|
-
zh_de_particle_rate: {
|
|
146
|
-
en: "heavy modifier chains (的)",
|
|
147
|
-
zh: "「的」字修饰链偏密",
|
|
148
|
-
},
|
|
149
|
-
sent_cv: {
|
|
150
|
-
en: "uniform sentence lengths",
|
|
151
|
-
zh: "句长起伏偏平",
|
|
152
|
-
},
|
|
153
|
-
clause_cv: {
|
|
154
|
-
en: "metronomic comma-clause lengths",
|
|
155
|
-
zh: "逗号分句长短过于整齐",
|
|
156
|
-
},
|
|
157
|
-
pronoun_imperative_rate: {
|
|
158
|
-
en: "impersonal passive distance (no direct actor or action)",
|
|
159
|
-
zh: "缺少明确主语和直接动作",
|
|
160
|
-
},
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
function countMatches(str, re) {
|
|
164
|
-
const m = str.match(re);
|
|
165
|
-
return m ? m.length : 0;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
function stripFencedBlocksLinear(raw) {
|
|
169
|
-
const lines = String(raw || "").split("\n");
|
|
170
|
-
const out = [];
|
|
171
|
-
let fenceMarker = null;
|
|
172
|
-
for (const ln of lines) {
|
|
173
|
-
const trimmed = ln.trim();
|
|
174
|
-
if (!fenceMarker) {
|
|
175
|
-
if (trimmed.startsWith("```")) {
|
|
176
|
-
fenceMarker = "```";
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
if (trimmed.startsWith("~~~")) {
|
|
180
|
-
fenceMarker = "~~~";
|
|
181
|
-
continue;
|
|
182
|
-
}
|
|
183
|
-
if (trimmed.startsWith("|") && trimmed.endsWith("|")) continue;
|
|
184
|
-
out.push(ln);
|
|
185
|
-
} else if (trimmed.startsWith(fenceMarker)) {
|
|
186
|
-
fenceMarker = null;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
return out.join("\n");
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
export function cleanProseSurface(raw) {
|
|
193
|
-
let s = String(raw || "").replace(/^\uFEFF/, "").replace(/\uFEFF/g, " ");
|
|
194
|
-
s = s.replace(/^[ \t]*---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?=\r?\n|$)/, " ");
|
|
195
|
-
s = s.replace(DISLOP_QUOTE_BLOCK_RE, " ");
|
|
196
|
-
s = s.replace(HTML_COMMENT_RE, " ");
|
|
197
|
-
s = stripFencedBlocksLinear(s);
|
|
198
|
-
s = s.replace(HTML_TAG_RE, " ");
|
|
199
|
-
|
|
200
|
-
const inlineCodes = countMatches(s, INLINE_CODE_RE);
|
|
201
|
-
const mdLinks = countMatches(s, MD_LINK_COUNT_RE);
|
|
202
|
-
const bareUrls = countMatches(s, BARE_URL_RE);
|
|
203
|
-
const citations = countMatches(s, CITATION_AUTHOR_RE) + countMatches(s, CITATION_BRACKET_RE);
|
|
204
|
-
const techAnchors = inlineCodes + mdLinks + bareUrls + citations;
|
|
205
|
-
|
|
206
|
-
s = s.replace(PAREN_QUOTE_RE, " ");
|
|
207
|
-
s = s.replace(EXAMPLE_QUOTE_RE, " ");
|
|
208
|
-
|
|
209
|
-
s = s.replace(MD_LINK_REPLACE_RE, "$1 <URL> ");
|
|
210
|
-
s = s.replace(BARE_URL_RE, " <URL> ");
|
|
211
|
-
s = s.replace(INLINE_CODE_RE, " <CODE> ");
|
|
212
|
-
|
|
213
|
-
const proseOnly = s.replace(TAG_STRIP_RE, " ");
|
|
214
|
-
const cjkN = countMatches(proseOnly, CJK_RE);
|
|
215
|
-
const enN = countMatches(proseOnly, EN_WORD_RE);
|
|
216
|
-
const units = cjkN * 0.6 + enN;
|
|
217
|
-
const sents = proseOnly
|
|
218
|
-
.split(/[。!?.!?\n]+/)
|
|
219
|
-
.map((p) => p.trim())
|
|
220
|
-
.filter((p) => cpLen(p) >= 4);
|
|
221
|
-
const eligible = sents.length >= 2 && units >= 26.0 ? 1 : 0;
|
|
222
|
-
return { surface: s, techAnchors, eligible, units, sentCount: sents.length };
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
export function delexicalizeTokens(raw, bundle) {
|
|
226
|
-
const { surface } = cleanProseSurface(raw);
|
|
227
|
-
const s = surface.replace(NUM_MASK_RE, " <NUM> ");
|
|
228
|
-
const enFuncSet = bundle._enFuncSet;
|
|
229
|
-
const suffixes = bundle.enAbstractSuffixes || [];
|
|
230
|
-
const zhStructSet = bundle._zhStructSet;
|
|
231
|
-
const tokens = [];
|
|
232
|
-
|
|
233
|
-
const matches = s.match(TOKEN_SCAN_RE) || [];
|
|
234
|
-
for (const tok of matches) {
|
|
235
|
-
const c0 = tok[0];
|
|
236
|
-
if (c0 === "<") {
|
|
237
|
-
tokens.push(tok);
|
|
238
|
-
} else if ((c0 >= "A" && c0 <= "Z") || (c0 >= "a" && c0 <= "z")) {
|
|
239
|
-
const low = tok.toLowerCase();
|
|
240
|
-
if (enFuncSet.has(low)) {
|
|
241
|
-
tokens.push("en:" + low);
|
|
242
|
-
} else {
|
|
243
|
-
let matchedSuf = null;
|
|
244
|
-
if (low.length >= 6) {
|
|
245
|
-
for (const suf of suffixes) {
|
|
246
|
-
if (low.endsWith(suf)) {
|
|
247
|
-
matchedSuf = suf;
|
|
248
|
-
break;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
if (matchedSuf) {
|
|
253
|
-
tokens.push("suf:" + matchedSuf);
|
|
254
|
-
} else if (low.endsWith("ing") && low.length >= 6) {
|
|
255
|
-
tokens.push("suf:ing");
|
|
256
|
-
} else if (low.endsWith("ly") && low.length >= 5) {
|
|
257
|
-
tokens.push("suf:ly");
|
|
258
|
-
} else if (low.endsWith("ed") && low.length >= 5) {
|
|
259
|
-
tokens.push("suf:ed");
|
|
260
|
-
} else if (low.length <= 4) {
|
|
261
|
-
tokens.push("en:<WS>");
|
|
262
|
-
} else {
|
|
263
|
-
tokens.push("en:<WC>");
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
} else if (c0 >= "\u4e00" && c0 <= "\u9fff") {
|
|
267
|
-
tokens.push(zhStructSet.has(tok) ? "zh:" + tok : "zh:<H>");
|
|
268
|
-
} else {
|
|
269
|
-
tokens.push("p:" + tok);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
return tokens;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function extractNgrams(delexTokens) {
|
|
276
|
-
const feats = [];
|
|
277
|
-
const n = delexTokens.length;
|
|
278
|
-
for (let i = 0; i < n; i += 1) {
|
|
279
|
-
const t1 = delexTokens[i];
|
|
280
|
-
if (t1 !== "en:<WC>" && t1 !== "en:<WS>" && t1 !== "zh:<H>") {
|
|
281
|
-
feats.push(t1);
|
|
282
|
-
}
|
|
283
|
-
if (i + 1 < n) {
|
|
284
|
-
feats.push(t1 + "|" + delexTokens[i + 1]);
|
|
285
|
-
}
|
|
286
|
-
if (i + 2 < n) {
|
|
287
|
-
feats.push(t1 + "|" + delexTokens[i + 1] + "|" + delexTokens[i + 2]);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
return feats;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
function scoreLmSpan(text, bundle) {
|
|
294
|
-
const toks = delexicalizeTokens(text, bundle);
|
|
295
|
-
if (toks.length === 0) return 0.0;
|
|
296
|
-
const uniqueNgs = Array.from(new Set(extractNgrams(toks))).sort();
|
|
297
|
-
if (uniqueNgs.length === 0) return 0.0;
|
|
298
|
-
const weights = bundle.ngramLm.weightsInt8;
|
|
299
|
-
const scale = bundle.ngramLm.scale;
|
|
300
|
-
let total = 0.0;
|
|
301
|
-
for (const g of uniqueNgs) {
|
|
302
|
-
if (Object.hasOwn(weights, g)) {
|
|
303
|
-
total += weights[g] * scale;
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
return total / Math.sqrt(uniqueNgs.length + 8.0);
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
function scoreLmFeatures(text, bundle) {
|
|
310
|
-
const whole = scoreLmSpan(text, bundle);
|
|
311
|
-
const { surface } = cleanProseSurface(text);
|
|
312
|
-
const sents = surface
|
|
313
|
-
.split(/[。!?.!?\n]+/)
|
|
314
|
-
.map((s) => s.trim())
|
|
315
|
-
.filter((s) => cpLen(s) >= 4);
|
|
316
|
-
if (sents.length === 0) return [whole, whole, 0.0];
|
|
317
|
-
const sScores = sents.map((s) => scoreLmSpan(s, bundle));
|
|
318
|
-
const meanS = sScores.reduce((a, b) => a + b, 0) / sScores.length;
|
|
319
|
-
const maxS = maxOf(sScores);
|
|
320
|
-
let stdS = 0.0;
|
|
321
|
-
if (sScores.length >= 2) {
|
|
322
|
-
const variance = sScores.reduce((acc, x) => acc + (x - meanS) ** 2, 0) / sScores.length;
|
|
323
|
-
stdS = Math.sqrt(variance);
|
|
324
|
-
}
|
|
325
|
-
return [whole, maxS, stdS];
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
export function extractPocketFeatures(text, bundle) {
|
|
329
|
-
const raw = String(text || "");
|
|
330
|
-
const { surface, techAnchors, eligible } = cleanProseSurface(raw);
|
|
331
|
-
const noTags = surface.replace(TAG_STRIP_RE, " ");
|
|
332
|
-
|
|
333
|
-
const cjkChars = noTags.match(CJK_RE) || [];
|
|
334
|
-
const enWords = noTags.match(EN_WORD_RE) || [];
|
|
335
|
-
const units = Math.max(1.0, cjkChars.length * 0.6 + enWords.length);
|
|
336
|
-
|
|
337
|
-
const sents = noTags
|
|
338
|
-
.split(/[。!?.!?\n]+/)
|
|
339
|
-
.map((s) => s.trim())
|
|
340
|
-
.filter((s) => cpLen(s) >= 3);
|
|
341
|
-
const sentLens = sents
|
|
342
|
-
.map((s) => countMatches(s, CJK_RE) * 0.6 + countMatches(s, EN_ALNUM_RE))
|
|
343
|
-
.filter((x) => x > 0);
|
|
344
|
-
const nSents = sentLens.length;
|
|
345
|
-
let meanS = 0.0;
|
|
346
|
-
let sentCv = 0.38;
|
|
347
|
-
let adjDiff = 0.38;
|
|
348
|
-
if (nSents >= 2) {
|
|
349
|
-
meanS = sentLens.reduce((a, b) => a + b, 0) / nSents;
|
|
350
|
-
const stdS = Math.sqrt(sentLens.reduce((acc, x) => acc + (x - meanS) ** 2, 0) / nSents);
|
|
351
|
-
sentCv = meanS > 0 ? stdS / meanS : 0.0;
|
|
352
|
-
let diffSum = 0.0;
|
|
353
|
-
for (let i = 1; i < nSents; i += 1) {
|
|
354
|
-
diffSum += Math.abs(sentLens[i] - sentLens[i - 1]);
|
|
355
|
-
}
|
|
356
|
-
adjDiff = diffSum / ((nSents - 1) * Math.max(1.0, meanS));
|
|
357
|
-
} else if (nSents === 1) {
|
|
358
|
-
meanS = sentLens[0];
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
const clauses = noTags
|
|
362
|
-
.split(/[,,;;::。!?.!?\n]+/)
|
|
363
|
-
.map((c) => c.trim())
|
|
364
|
-
.filter((c) => cpLen(c) >= 2);
|
|
365
|
-
const clauseLens = clauses
|
|
366
|
-
.map((c) => countMatches(c, CJK_RE) * 0.6 + countMatches(c, EN_ALNUM_RE))
|
|
367
|
-
.filter((x) => x > 0);
|
|
368
|
-
let clauseCv = 0.42;
|
|
369
|
-
if (clauseLens.length >= 3) {
|
|
370
|
-
const mc = clauseLens.reduce((a, b) => a + b, 0) / clauseLens.length;
|
|
371
|
-
const sc = Math.sqrt(clauseLens.reduce((acc, x) => acc + (x - mc) ** 2, 0) / clauseLens.length);
|
|
372
|
-
clauseCv = mc > 0 ? sc / mc : 0.0;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
const lexToks = noTags.toLowerCase().match(LEX_TOK_RE) || [];
|
|
376
|
-
const nTok = lexToks.length;
|
|
377
|
-
let mattr = 0.0;
|
|
378
|
-
if (nTok > 25) {
|
|
379
|
-
let winSum = 0.0;
|
|
380
|
-
let winCount = 0;
|
|
381
|
-
for (let i = 0; i <= nTok - 25; i += 5) {
|
|
382
|
-
winSum += new Set(lexToks.slice(i, i + 25)).size / 25.0;
|
|
383
|
-
winCount += 1;
|
|
384
|
-
}
|
|
385
|
-
mattr = winSum / winCount;
|
|
386
|
-
} else {
|
|
387
|
-
mattr = new Set(lexToks).size / Math.max(1, nTok);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
let bigramRep = 0.0;
|
|
391
|
-
if (nTok >= 2) {
|
|
392
|
-
const bgs = [];
|
|
393
|
-
for (let i = 0; i < nTok - 1; i += 1) {
|
|
394
|
-
bgs.push(lexToks[i] + "_" + lexToks[i + 1]);
|
|
395
|
-
}
|
|
396
|
-
bigramRep = 1.0 - new Set(bgs).size / bgs.length;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
const numHits = countMatches(noTags, NUM_HIT_RE);
|
|
400
|
-
const enNumTime = countMatches(noTags, EN_NUM_TIME_RE);
|
|
401
|
-
const zhNumTime = countMatches(noTags, ZH_NUM_TIME_RE);
|
|
402
|
-
const pathHits = countMatches(raw, PATH_HIT_RE);
|
|
403
|
-
const concreteness = ((numHits + enNumTime + zhNumTime + pathHits + techAnchors) / units) * 100.0;
|
|
404
|
-
const codeUrlDensity = (techAnchors / units) * 100.0;
|
|
405
|
-
|
|
406
|
-
const nEn = Math.max(1, enWords.length);
|
|
407
|
-
const enAbs = enWords.length >= 5 ? (countMatches(noTags, EN_ABSTRACT_RE) / nEn) * 100.0 : 0.0;
|
|
408
|
-
const enCushWords = enWords.filter((w) => EN_CUSHION_WORDS.has(w.toLowerCase())).length;
|
|
409
|
-
const enFuncCush = enWords.length >= 5 ? (enCushWords / nEn) * 100.0 : 0.0;
|
|
410
|
-
const enGerund = enWords.length >= 5 ? countMatches(noTags, EN_GERUND_OPENER_RE) / Math.max(1, nSents) : 0.0;
|
|
411
|
-
const enCushPhrase = (countMatches(noTags, EN_CUSHION_RE) / units) * 100.0;
|
|
412
|
-
|
|
413
|
-
const nZh = Math.max(1, cjkChars.length);
|
|
414
|
-
const deCount = (noTags.match(/的/g) || []).length;
|
|
415
|
-
const zhDe = cjkChars.length >= 8 ? (deCount / nZh) * 100.0 : 0.0;
|
|
416
|
-
const zhNom = cjkChars.length >= 8 ? (countMatches(noTags, ZH_NOMINAL_FRAME_RE) / units) * 100.0 : 0.0;
|
|
417
|
-
const zhCush = cjkChars.length >= 8 ? (countMatches(noTags, ZH_CUSHION_RE) / units) * 100.0 : 0.0;
|
|
418
|
-
const zhStructRatio =
|
|
419
|
-
cjkChars.length >= 8
|
|
420
|
-
? cjkChars.filter((c) => bundle._zhStructSet.has(c)).length / nZh
|
|
421
|
-
: 0.5;
|
|
422
|
-
|
|
423
|
-
const enDirect =
|
|
424
|
-
enWords.filter((w) => EN_DIRECT_WORDS.has(w.toLowerCase())).length +
|
|
425
|
-
countMatches(noTags, EN_DIRECT_CONCRETE_RE);
|
|
426
|
-
const zhDirect = countMatches(noTags, ZH_DIRECT_PRON_RE) + countMatches(noTags, ZH_COLLOQUIAL_CONCRETE_RE);
|
|
427
|
-
const pronounImp = ((enDirect + zhDirect) / units) * 100.0;
|
|
428
|
-
|
|
429
|
-
const punctChars = noTags.match(PUNCT_CHAR_RE) || [];
|
|
430
|
-
const punctVar =
|
|
431
|
-
punctChars.length > 0 ? new Set(punctChars).size / Math.max(1.0, Math.sqrt(punctChars.length)) : 0.0;
|
|
432
|
-
const semiCount = (noTags.match(/;/g) || []).length + (noTags.match(/;/g) || []).length;
|
|
433
|
-
const semiEm = ((semiCount + countMatches(noTags, EMDASH_RE)) / units) * 100.0;
|
|
434
|
-
|
|
435
|
-
const [llrMean, llrMax, llrStd] = scoreLmFeatures(raw, bundle);
|
|
436
|
-
|
|
437
|
-
const features = [
|
|
438
|
-
Math.log1p(units),
|
|
439
|
-
nSents,
|
|
440
|
-
meanS,
|
|
441
|
-
sentCv,
|
|
442
|
-
adjDiff,
|
|
443
|
-
clauseCv,
|
|
444
|
-
mattr,
|
|
445
|
-
bigramRep,
|
|
446
|
-
concreteness,
|
|
447
|
-
codeUrlDensity,
|
|
448
|
-
enAbs,
|
|
449
|
-
enFuncCush,
|
|
450
|
-
enGerund,
|
|
451
|
-
enCushPhrase,
|
|
452
|
-
zhDe,
|
|
453
|
-
zhNom,
|
|
454
|
-
zhCush,
|
|
455
|
-
zhStructRatio,
|
|
456
|
-
pronounImp,
|
|
457
|
-
punctVar,
|
|
458
|
-
semiEm,
|
|
459
|
-
llrMean,
|
|
460
|
-
llrMax,
|
|
461
|
-
llrStd,
|
|
462
|
-
];
|
|
463
|
-
return { features, eligible };
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
function sigmoid(x) {
|
|
467
|
-
const clamped = Math.max(-30.0, Math.min(30.0, x));
|
|
468
|
-
return 1.0 / (1.0 + Math.exp(-clamped));
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
function inferGbdt(gbdtJson, feats) {
|
|
472
|
-
let raw = gbdtJson.init;
|
|
473
|
-
const lr = gbdtJson.lr;
|
|
474
|
-
for (const nodes of gbdtJson.trees) {
|
|
475
|
-
let idx = 0;
|
|
476
|
-
while (nodes[idx].v === undefined) {
|
|
477
|
-
const nd = nodes[idx];
|
|
478
|
-
idx = feats[nd.f] <= nd.t ? nd.l : nd.r;
|
|
479
|
-
}
|
|
480
|
-
raw += lr * nodes[idx].v;
|
|
481
|
-
}
|
|
482
|
-
return sigmoid(raw);
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
export function scorePocketSpan(text, customBundle = null) {
|
|
486
|
-
const bundle = customBundle || loadPocketModelBundle();
|
|
487
|
-
const { features, eligible } = extractPocketFeatures(text, bundle);
|
|
488
|
-
if (!eligible) {
|
|
489
|
-
return {
|
|
490
|
-
eligible: false,
|
|
491
|
-
slopProbability: 0,
|
|
492
|
-
linearProbability: 0,
|
|
493
|
-
gbdtProbability: 0,
|
|
494
|
-
band: "short-or-non-prose",
|
|
495
|
-
topDrivers: [],
|
|
496
|
-
};
|
|
497
|
-
}
|
|
498
|
-
const lin = bundle.linear;
|
|
499
|
-
const zVec = features.map((v, i) => (v - lin.mean[i]) / lin.scale[i]);
|
|
500
|
-
let logit = lin.intercept;
|
|
501
|
-
const contribs = [];
|
|
502
|
-
const fNames = bundle.featureNames;
|
|
503
|
-
for (let i = 0; i < zVec.length; i += 1) {
|
|
504
|
-
const c = zVec[i] * lin.coef[i];
|
|
505
|
-
logit += c;
|
|
506
|
-
const fname = fNames[i];
|
|
507
|
-
if (c > 0.08 && Object.hasOwn(DRIVER_LABELS, fname)) {
|
|
508
|
-
contribs.push({
|
|
509
|
-
feature: fname,
|
|
510
|
-
impact: round4(c),
|
|
511
|
-
reason: DRIVER_LABELS[fname],
|
|
512
|
-
});
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
contribs.sort((a, b) => b.impact - a.impact);
|
|
516
|
-
const pLin = sigmoid(logit);
|
|
517
|
-
const pGbdt = inferGbdt(bundle.gbdt, features);
|
|
518
|
-
const prob = round4(bundle.ensembleWeights.linear * pLin + bundle.ensembleWeights.gbdt * pGbdt);
|
|
519
|
-
const stealthThr = bundle.thresholds?.stealthWarning ?? 0.755;
|
|
520
|
-
const advThr = bundle.thresholds?.advisory ?? 0.62;
|
|
521
|
-
const band = prob >= stealthThr ? "high" : prob >= advThr ? "elevated" : "clean";
|
|
522
|
-
|
|
523
|
-
return {
|
|
524
|
-
eligible: true,
|
|
525
|
-
slopProbability: prob,
|
|
526
|
-
linearProbability: round4(pLin),
|
|
527
|
-
gbdtProbability: round4(pGbdt),
|
|
528
|
-
band,
|
|
529
|
-
topDrivers: contribs.slice(0, 3),
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
export function predictPackWithPocketRouter(text, customBundle = null) {
|
|
534
|
-
const bundle = customBundle || loadPocketModelBundle();
|
|
535
|
-
const router = bundle.packRouter;
|
|
536
|
-
const packs = router.packs;
|
|
537
|
-
const scores = new Array(packs.length).fill(0.0);
|
|
538
|
-
const low = String(text || "").toLowerCase();
|
|
539
|
-
const seen = new Set();
|
|
540
|
-
|
|
541
|
-
const enMatches = low.match(/[a-z][a-z0-9_-]{2,22}/g) || [];
|
|
542
|
-
for (const w of enMatches) seen.add(w);
|
|
543
|
-
const zhSegs = low.match(/[\u4e00-\u9fff]{2,}/g) || [];
|
|
544
|
-
for (const seg of zhSegs) {
|
|
545
|
-
const chars = Array.from(seg);
|
|
546
|
-
for (let i = 0; i < chars.length - 1; i += 1) {
|
|
547
|
-
seen.add(chars[i] + chars[i + 1]);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
let matchedTokens = 0;
|
|
552
|
-
const weightsMap = router.weightsInt8;
|
|
553
|
-
for (const tok of Array.from(seen).sort()) {
|
|
554
|
-
if (!Object.hasOwn(weightsMap, tok)) continue;
|
|
555
|
-
const wVec = weightsMap[tok];
|
|
556
|
-
matchedTokens += 1;
|
|
557
|
-
for (let k = 0; k < packs.length; k += 1) {
|
|
558
|
-
scores[k] += wVec[k] * router.scale;
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
if (matchedTokens === 0) {
|
|
563
|
-
return {
|
|
564
|
-
recommendedPack: "business-brief",
|
|
565
|
-
confidence: round4(1.0 / packs.length),
|
|
566
|
-
matchedSignals: 0,
|
|
567
|
-
scores: Object.fromEntries(packs.map((p) => [p, round4(1.0 / packs.length)])),
|
|
568
|
-
};
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
const normFactor = 1.0 / Math.sqrt(matchedTokens + 3.0);
|
|
572
|
-
const scaled = scores.map((s) => s * normFactor);
|
|
573
|
-
const maxLogit = maxOf(scaled);
|
|
574
|
-
const exps = scaled.map((s) => Math.exp(s - maxLogit));
|
|
575
|
-
const sumExp = exps.reduce((a, b) => a + b, 0);
|
|
576
|
-
const probs = exps.map((e) => e / sumExp);
|
|
577
|
-
|
|
578
|
-
let bestIdx = 0;
|
|
579
|
-
for (let i = 1; i < probs.length; i += 1) {
|
|
580
|
-
if (probs[i] > probs[bestIdx]) bestIdx = i;
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
return {
|
|
584
|
-
recommendedPack: packs[bestIdx],
|
|
585
|
-
confidence: round4(probs[bestIdx]),
|
|
586
|
-
matchedSignals: matchedTokens,
|
|
587
|
-
scores: Object.fromEntries(packs.map((p, i) => [p, round4(probs[i])])),
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
function maskNewlinePreserving(text) {
|
|
592
|
-
return String(text || "")
|
|
593
|
-
.replace(/^\uFEFF?[ \t]*---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?=\r?\n|$)/, (m) => m.replace(/[^\n]/g, " "))
|
|
594
|
-
.replace(DISLOP_QUOTE_BLOCK_RE, (m) => m.replace(/[^\n]/g, " "))
|
|
595
|
-
.replace(HTML_COMMENT_RE, (m) => m.replace(/[^\n]/g, " "));
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
function isUiShortLineStack(lines) {
|
|
599
|
-
if (!lines || lines.length < 3) return false;
|
|
600
|
-
const nonEmpty = lines.map((l) => l.trim()).filter(Boolean);
|
|
601
|
-
if (nonEmpty.length < 3) return false;
|
|
602
|
-
const shortCount = nonEmpty.filter((l) => cpLen(l) <= 16).length;
|
|
603
|
-
return shortCount * 2 >= nonEmpty.length;
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
function splitParagraphBlocks(raw, meta = null) {
|
|
607
|
-
const text = maskNewlinePreserving(raw);
|
|
608
|
-
const blocks = [];
|
|
609
|
-
let suppressedUiCount = 0;
|
|
610
|
-
let lineNo = 1;
|
|
611
|
-
let idx = 0;
|
|
612
|
-
const lines = text.split("\n");
|
|
613
|
-
let curLines = [];
|
|
614
|
-
let curStartOffset = 0;
|
|
615
|
-
let curStartLine = 1;
|
|
616
|
-
let fenceMarker = null;
|
|
617
|
-
|
|
618
|
-
const flush = (endOffset, endLine) => {
|
|
619
|
-
if (curLines.length === 0) return;
|
|
620
|
-
const content = curLines.join("\n");
|
|
621
|
-
const trimmed = content.trim();
|
|
622
|
-
if (isUiShortLineStack(curLines)) {
|
|
623
|
-
suppressedUiCount += 1;
|
|
624
|
-
} else if (
|
|
625
|
-
trimmed.length >= 24 &&
|
|
626
|
-
!trimmed.startsWith("#") &&
|
|
627
|
-
!trimmed.startsWith("|") &&
|
|
628
|
-
!trimmed.startsWith("```") &&
|
|
629
|
-
!trimmed.startsWith("~~~") &&
|
|
630
|
-
!trimmed.startsWith(">") &&
|
|
631
|
-
!/^(?:[-*+]|[0-9]+\.)\s/.test(trimmed)
|
|
632
|
-
) {
|
|
633
|
-
blocks.push({
|
|
634
|
-
text: content,
|
|
635
|
-
startOffset: curStartOffset,
|
|
636
|
-
endOffset,
|
|
637
|
-
startLine: curStartLine,
|
|
638
|
-
endLine,
|
|
639
|
-
});
|
|
640
|
-
}
|
|
641
|
-
curLines = [];
|
|
642
|
-
};
|
|
643
|
-
|
|
644
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
645
|
-
const ln = lines[i];
|
|
646
|
-
const trimmed = ln.trim();
|
|
647
|
-
const lnLen = cpLen(ln);
|
|
648
|
-
if (!fenceMarker && (trimmed.startsWith("```") || trimmed.startsWith("~~~"))) {
|
|
649
|
-
flush(idx, Math.max(curStartLine, lineNo - 1));
|
|
650
|
-
fenceMarker = trimmed.startsWith("```") ? "```" : "~~~";
|
|
651
|
-
idx += lnLen + 1;
|
|
652
|
-
lineNo += 1;
|
|
653
|
-
continue;
|
|
654
|
-
}
|
|
655
|
-
if (fenceMarker) {
|
|
656
|
-
if (trimmed.startsWith(fenceMarker)) fenceMarker = null;
|
|
657
|
-
idx += lnLen + 1;
|
|
658
|
-
lineNo += 1;
|
|
659
|
-
continue;
|
|
660
|
-
}
|
|
661
|
-
if (trimmed === "") {
|
|
662
|
-
flush(idx, Math.max(curStartLine, lineNo - 1));
|
|
663
|
-
} else {
|
|
664
|
-
if (curLines.length === 0) {
|
|
665
|
-
curStartOffset = idx;
|
|
666
|
-
curStartLine = lineNo;
|
|
667
|
-
}
|
|
668
|
-
curLines.push(ln);
|
|
669
|
-
}
|
|
670
|
-
idx += lnLen + 1;
|
|
671
|
-
lineNo += 1;
|
|
672
|
-
}
|
|
673
|
-
flush(cpLen(text), lines.length);
|
|
674
|
-
if (meta) meta.suppressedUiCount = suppressedUiCount;
|
|
675
|
-
return blocks;
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
export function analyzeDocumentWithPocketModels(text, { threshold = null, customBundle = null } = {}) {
|
|
679
|
-
const bundle = customBundle || loadPocketModelBundle();
|
|
680
|
-
if (threshold !== null && threshold !== undefined) {
|
|
681
|
-
if (typeof threshold !== "number" || Number.isNaN(threshold) || !Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
|
|
682
|
-
throw new Error(`Invalid pocket model threshold '${threshold}' (expected a number between 0 and 1).`);
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
const effectiveThreshold = threshold ?? bundle.thresholds?.stealthWarning ?? 0.755;
|
|
686
|
-
const whole = scorePocketSpan(text, bundle);
|
|
687
|
-
const packRouting = predictPackWithPocketRouter(text, bundle);
|
|
688
|
-
const blockMeta = { suppressedUiCount: 0 };
|
|
689
|
-
const blocks = splitParagraphBlocks(text, blockMeta);
|
|
690
|
-
|
|
691
|
-
const paragraphs = [];
|
|
692
|
-
for (const b of blocks) {
|
|
693
|
-
const res = scorePocketSpan(b.text, bundle);
|
|
694
|
-
if (!res.eligible) continue;
|
|
695
|
-
const trimmed = b.text.trim();
|
|
696
|
-
paragraphs.push({
|
|
697
|
-
startLine: b.startLine,
|
|
698
|
-
endLine: b.endLine,
|
|
699
|
-
startOffset: b.startOffset,
|
|
700
|
-
endOffset: b.endOffset,
|
|
701
|
-
excerpt: cpLen(trimmed) > 120 ? Array.from(trimmed).slice(0, 120).join("") + "…" : trimmed,
|
|
702
|
-
...res,
|
|
703
|
-
flagged: res.slopProbability >= effectiveThreshold,
|
|
704
|
-
});
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
const maxParagraphProb =
|
|
708
|
-
paragraphs.length > 0 ? maxOf(paragraphs.map((p) => p.slopProbability)) : whole.slopProbability;
|
|
709
|
-
const flaggedParagraphs = paragraphs.filter((p) => p.flagged);
|
|
710
|
-
let documentProbability = round4(Math.max(whole.slopProbability, maxParagraphProb));
|
|
711
|
-
if (
|
|
712
|
-
flaggedParagraphs.length === 0 &&
|
|
713
|
-
(paragraphs.length > 0 || blockMeta.suppressedUiCount > 0 || !whole.eligible) &&
|
|
714
|
-
documentProbability >= effectiveThreshold
|
|
715
|
-
) {
|
|
716
|
-
documentProbability = round4(Math.max(0, effectiveThreshold - 0.005));
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
return {
|
|
720
|
-
schema: bundle.schema,
|
|
721
|
-
modelVersion: bundle.version,
|
|
722
|
-
threshold: round4(effectiveThreshold),
|
|
723
|
-
documentProbability,
|
|
724
|
-
wholeTextScore: whole,
|
|
725
|
-
packRouter: packRouting,
|
|
726
|
-
paragraphs,
|
|
727
|
-
flaggedCount: flaggedParagraphs.length,
|
|
728
|
-
};
|
|
729
|
-
}
|