${title}
${tr(subtitles[page])}
':''} + ${page==='overview'?tourLinks():''} + ${tourNext()}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..c231190
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,41 @@
+name: CI
+
+on:
+ push:
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: Node ${{ matrix.node-version }} / Python 3.12
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ node-version: [22.x, 24.x]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ matrix.node-version }}
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Require packaged workbench assets
+ run: |
+ test -f dist/index.html
+ test -f dist/assets/engine.js
+ test -f dist/data/procurement-demo.json
+ test -f dist/data/demo.json
+ - name: Install Python packages
+ run: python -m pip install -r requirements-dev.txt
+ - name: Browser modules
+ run: npm test
+ - name: Python engine and API
+ run: python -m unittest discover -s tests -p 'test_*.py' -v
+ - name: Demo evaluation entry points
+ run: |
+ python -m datalens evaluate
+ python -m datalens evaluate dist/data/demo.json
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
new file mode 100644
index 0000000..7b92137
--- /dev/null
+++ b/.github/workflows/pages.yml
@@ -0,0 +1,35 @@
+name: GitHub Pages
+
+on:
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+concurrency:
+ group: pages
+ cancel-in-progress: true
+
+jobs:
+ deploy:
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Require packaged workbench
+ run: |
+ test -f dist/index.html
+ test -f dist/assets/engine.js
+ test -f dist/data/procurement-demo.json
+ - uses: actions/configure-pages@v5
+ - uses: actions/upload-pages-artifact@v3
+ with:
+ path: dist
+ - id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..cce6f54
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,8 @@
+.venv/
+__pycache__/
+*.pyc
+.pytest_cache/
+node_modules/
+dist/downloads/
+.datalens-ai/
+*.sqlite3
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..6796c74
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 plii05
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.en.md b/README.en.md
new file mode 100644
index 0000000..c3ac217
--- /dev/null
+++ b/README.en.md
@@ -0,0 +1,104 @@
+# DataLens AI
+
+[简体中文](README.md)
+
+DataLens AI is a workbench for training-data selection and delivery acceptance. In the default procurement case, the cheapest supplier has 70% of usable records already present in inventory. The workspace puts historical overlap, evaluation leakage, post-remediation net-new yield, and quotes side by side so a team can decide which batches to buy.
+
+[Open the hosted procurement demo](https://plii05.github.io/DataLens-AI/) · [Case data and acceptance criteria](docs/demo.md)
+
+> After the first merge to `main`, enable **Settings → Pages → Build and deployment → Source: GitHub Actions**. Until that Pages site is live, the previous hosted demo remains at [chatgpt.site](https://datalens-ai-workbench-k8m4.bushyolive1024.chatgpt.site).
+
+## Walk the procurement decision
+
+| Candidate | Input | Decision you can verify |
+|---|---|---|
+| Batch-A · Value Desk | $20 for 20 rows; 14 already in history; 3 hit eval prompts | After removing eval overlap and rechecking, only 3 of 17 accepted rows are net-new. |
+| Batch-B · Route Desk | $44 for 8 logistics rows; 1 contains a sample phone | Open deep QA from the overview, preview masking, save a new version. After it passes, it can fill 8 of 10 logistics gaps. |
+| Batch-C · Account Escalations | $90 for 6 account-escalation samples | The first version already passes. It can cover the remaining 6 account gaps and be compared on marginal cost with remediated A and B. |
+
+New workspaces load this case by default. Existing workspaces can append one run from **Decision overview → Open procurement case**. Switch budget or purchase goals under **Mix fill** to recompute. When every remediation passes and quotes are unchanged, the lowest total that covers all goals is **$154**.
+
+The three home-page tours open B’s tiered quote, evidence for record #1, and a budget sandbox after sample remediation. Tours use temporary demo data; return to the workspace for your own work.
+
+## From delivery quotes to a training set
+
+| Page | What you can do |
+|---|---|
+| Procurement compare | Keep a package quote and a progressive quote billed on net-new rows. Demo B is $44 packaged; the same 8 net-new rows settle at $6 for the first 5 and $5 for the last 3 ($45). |
+| Issues & recheck | Download a supplier remediation ZIP with a notice, row-numbered issue list, and masked examples. The procurement page summarizes first-delivery duplicate rate, eval overlap, and first-pass rate. |
+| Requirements / deep QA | Set per-scene floors for basic QA, multi-condition reasoning, and correction samples. Supplier difficulty labels are kept; unlabeled rows get a rule estimate for acceptance layering only. |
+| Mix fill | Drag budget, include remediated batches, compare coverage and incremental cost, sample by scene weight, and export ChatML, ShareGPT, or Alpaca train/val sets with manifests and `lineage.jsonl`. |
+| Model review | Inspect documented demo scores, or score through an OpenAI-compatible endpoint / Ollama. Keys stay in page memory. |
+| Evidence Q&A | Ask for `Batch-A #3` or eval overlap for a batch; open cited rows in the side panel. |
+
+## Where data and compute live
+
+| Mode | Storage / compute | Workflow |
+|---|---|---|
+| **Cloud Demo Mode** | Files, clean versions, and tasks stay in this browser. Precomputed support vectors ship with the site; DuckDB-Wasm loads in a worker. | Import, zero-shot scene match, filters, cleanup diffs, quotes, mix solve, synthetic-share warnings, browser scoring, calibration import, training export. |
+| **Local Full Mode** | Same UI against FastAPI + SQLite. Optional sentence embeddings, local LLMs, and streaming JSONL CLI. | Everything above, plus re-encode corpora, topics, stratified sampling, blind gold review, and draft generation for gaps. |
+
+The UI supports Chinese, English, and light/dark themes. Model and sample sources are labeled on each page.
+
+## Methods and auditable metrics
+
+| Module | Business question | Implementation |
+|---|---|---|
+| Scene labeling | How to measure coverage without reliable labels? | Prototype matching from task descriptions; cloud demo uses precomputed LSA + terms; local mode can use SentenceTransformer. [classification](docs/classification.md) |
+| Deep QA | Duplicate purchase? Eval leakage? | Normalized exact keys, MinHash/LSH near-dup, 13-gram eval overlap; streaming CLI uses SHA-256 + on-disk SQLite. [cloud](docs/cloud.md) |
+| Cleanup & recheck | What changed, and can we replay it? | Immutable snapshots with parent IDs, rule version, source line, and the same acceptance gates. |
+| Model review | Rare scenes covered? Do humans agree? | Stratified samples, four-dimension rubric, Cohen’s κ with bootstrap intervals. [models](docs/models.md) |
+| Synthetic tracking | Is one scene over-dependent on synthetic data? | Known synthetic share and unknown-origin upper bound; default threshold 20%. [provenance](docs/provenance.md) |
+| Procurement / expansion | How much new coverage for a fixed budget? | Exact subset search up to 8 lots; greedy marginal gain beyond that. [solver](docs/solver.md) |
+
+### 10k-row deep-scan benchmark
+
+With rule `quality-scan/1.1` and Node.js 24.22.3, three independent processes on the same 10,000-row (1,547,165 byte) synthetic JSONL plus 5 eval prompts took **1,372 / 752 / 1,018 ms (median 1,018)**. Reproduce with `python scripts/bench_jsonl.py sample.jsonl --rows 10000` then `node scripts/bench_deep.mjs sample.jsonl`.
+
+### Large files
+
+The streaming CLI parsed 100,000 synthetic JSONL rows in 3.03 s at 38.84 MiB peak RSS in an earlier Linux run (startup + rule gates, no model inference). See [stream](docs/stream.md).
+
+```bash
+docker build -t datalens-ai . && docker run --rm -p 127.0.0.1:8000:8000 datalens-ai
+```
+
+## Local start
+
+Python 3.10+. From the project root:
+
+```bash
+python -m venv .venv
+source .venv/bin/activate
+python -m pip install -r requirements.txt
+python -m datalens serve
+```
+
+Open http://127.0.0.1:8000. SQLite defaults to `~/.datalens-ai/workspace.sqlite3` (`DATALENS_DB` overrides). Offline evaluation needs no third-party packages beyond the stdlib path used by the engine itself when dependencies are present for the API:
+
+```bash
+python -m datalens evaluate --out report.json
+python -m datalens evaluate dist/data/demo.json --out report.json
+python -m datalens experiment
+```
+
+Pure frontend mode: `python -m http.server 8000 --directory dist`. Hosted browser state is IndexedDB-only and does not sync with the local SQLite workspace.
+
+## Import contract
+
+UTF-8 CSV, JSON arrays, JSON with `rows`/`data`, or JSONL. Limits: 12 MiB per file, 50,000 logical rows. Custom field maps supported. Multiturn `messages` keep prior turns as context and use the last user/assistant pair as instruction/response.
+
+## Repository layout
+
+| Path | Contents |
+|---|---|
+| `dist/` | Static workbench, demo data, browser decision modules |
+| `datalens/` | Python engine, FastAPI, streaming CLI |
+| `tests/` | Browser/Python parity tests |
+| `docs/` | Classification, QA, solver, provenance, model-review notes |
+
+`dist/` is part of the product, not build cache. Generated self-packaging zips go to `dist/downloads/` (gitignored).
+
+## License and topics
+
+Released under the [MIT License](LICENSE). Suggested GitHub topics: `llm`, `training-data`, `data-quality`, `procurement`, `evaluation`, `fastapi`.
diff --git a/README.md b/README.md
index 6920623..5d7f716 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,12 @@
# DataLens AI
+[English](README.en.md)
+
DataLens AI 用于训练数据选型与交付验收。默认采购案例中,最便宜的供应商有 70% 的可用记录与已有库存重复。工作台把历史重合、评测泄漏、整改后的真实增量和报价放在一起,供团队决定应该购买哪些批次。
-[打开在线采购案例](https://datalens-ai-workbench-k8m4.bushyolive1024.chatgpt.site) · [案例数据与验证口径](docs/demo.md)
+[打开 GitHub Pages 采购案例](https://plii05.github.io/DataLens-AI/) · [案例数据与验证口径](docs/demo.md)
+
+> 合并到 `main` 后,在仓库 **Settings → Pages → Build and deployment** 将 Source 设为 **GitHub Actions**,站点才会首次发布。启用前仍可使用[原托管演示](https://datalens-ai-workbench-k8m4.bushyolive1024.chatgpt.site)。建议在仓库 About 中把 Homepage 设为 Pages 地址,并添加 topics:`llm`、`training-data`、`data-quality`、`procurement`、`evaluation`、`fastapi`。
## 先跑一遍采购决策
@@ -123,3 +127,18 @@ node --test tests/*.test.mjs
```
测试需要 Node.js 22 或更高版本,包含浏览器与 Python 两套实现的全部样例指标和逐行问题对照。FastAPI 接口说明在本机服务的 `/docs`。标准化输入格式见 `dist/data/demo.json`,API 接收相同结构。项目提供浏览器模块、Python 决策引擎、FastAPI、SQLite,以及合成数据和生成脚本。
+
+## 仓库内容
+
+| 路径 | 内容 |
+|---|---|
+| `dist/` | 静态工作台、演示数据与浏览器决策模块;克隆后即可 `python -m datalens serve` 或 `python -m http.server 8000 --directory dist` |
+| `datalens/` | Python 决策引擎、FastAPI、流式 CLI |
+| `tests/` | 浏览器模块与 Python 引擎对照测试 |
+| `docs/` | 归类、质检、求解、来源与模型评审说明 |
+
+`dist/` 是可运行工作台的一部分,不是构建缓存。缺少该目录时,页面、Docker 镜像和大部分 Node 测试都无法运行。生成的自打包文件写在 `dist/downloads/`,已加入 `.gitignore`。
+
+## 许可
+
+本项目以 [MIT License](LICENSE) 发布。
diff --git a/dist/assets/app.js b/dist/assets/app.js
new file mode 100644
index 0000000..2210f0a
--- /dev/null
+++ b/dist/assets/app.js
@@ -0,0 +1,485 @@
+import {tour, tourLinks, tourNext, demoWorkspace} from './demo-tour.js';
+import {explicitRecords,supportingRecords,citationLink,recordEvidence} from './record-evidence.js';
+import {supplierFeedbackPane,downloadSupplierFeedback,supplierHistoryPane,supplierRiskNotice,supplierInput,supplierName} from './supplier.js';
+import {trainingPanel} from './training-export.js';
+import {complexityGoalFields,readComplexityGoals} from './complexity-form.js';
+import {solverPane, updateSandbox, semanticTable, decisionSummary, proposedMix} from './mix-solver.js';
+import {syntheticPanel,mixLineage,updateThreshold,synthThreshold} from './provenance.js';
+import {tr, message, language, setPreference, evidenceLabel, eventLabel} from './locale.js';
+import {qualityPage,inspectQualityBatch} from './quality-lab.js';
+import {procurementPage} from './procurement.js';
+import {modelPage} from './model-lab.js';
+import {procurementScenarioSummary} from './scenario-summary.js';
+import {parseGate} from './gates.js';
+import {contentKey,analyze,ordered,portfolio,recommend,delta,cleanRows,report,kinds,statuses,fmt,norm} from './engine.js';
+import {intentControls,classifyMapped,previewTable,intentEvidence,reviewRowsLink} from './intent-import.js';
+import {parseFile,mapRows} from './import.js';
+import {loadState,saveState,storageLabel} from './store.js';
+import {icon,esc,btn,mark,badge,pane,empty,intent,date,runName,table,td,download,csv,keyname,gapChart} from './ui.js';
+const $=s=>document.querySelector(s), root=$('#root'), modal=$('#modal');
+let state,run,ds,rs,archive=null,menu=false,busy=false,query='',statusFilter='',issueKey='',issueType='overlap',issuePage=0,mix=[],mixAt='',qa=[],qaAt='',focusRestore=null,toastTimer;
+const nav=[['overview',"决策总览",'dashboard'],['compare',"候选对比",'compare'],['issues',"问题与复检",'audit'],['mix',"组合补数",'mix'],['qa',"证据问答",'chat'],['runs',"运行档案",'history'],['quality','深度质检','audit'],['procurement','采购对比','chart'],['models','模型评估','flask']];
+const subtitles={quality:'检查原始记录,预览清洗结果并按版本复检。',procurement:'比较批次的质量、覆盖和单位成本。',models:'评估回答质量,探索语义主题,按覆盖缺口生成草稿。',overview:"查看当前任务的筛选结果、质量证据与候选决策。",compare:"在同一套标准下比较每个数据版本,查看证据和评分依据。",issues:"定位到原始记录,保留交付版本,再按原标准复检。",mix:"按选择顺序合并合格候选,计算独立贡献与剩余缺口。",qa:"根据当前运行的实测指标与记录,查询每项结论的依据。",runs:"查看历史任务、候选版本与当时使用的验收标准。"};
+const route=()=>nav.find(n=>n[0]===location.hash.slice(1))?.[0]||'overview';
+const dsBy=id=>ds.find(d=>d.id===id), rBy=id=>rs.find(r=>r.id===id);
+function toast(s){$('#toast').textContent=s;clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('#toast').textContent='',4500);}
+function dialog(title,html,drawer=false){modal.classList.toggle('evidence-drawer',drawer);if(!modal.open)focusRestore=document.activeElement;modal.innerHTML=''+esc(title)+'
'+btn('×','close','','flat',("aria-label=\""+tr("关闭")+"\""))+'
${tr(subtitles[page])}
'+tr('已设置采购需求,目前还没有待验收的数据集。')+'
')+pane(tr('等待供应商交付'),'stack',''+tr('验收标准已保存。导入第一批数据后,即可查看质检和采购结果。')+'
'+add)+supplierHistoryPane(state,run.n); + return; + } + $('#view').innerHTML=({overview,compare,issues,mix:mixView,qa:qaView,runs,quality:()=>qualityPage(ds,run,!!archive),procurement:()=>procurementPage(ds,rs,run.task.mode,run.task,state.versions)+supplierHistoryPane(state,run.n),models:()=>modelPage(ds,rs,run,mix,!!archive)}[p])();} +function candidateSummary(parts) { + const total = parts.reduce((sum, part) => sum + part.count, 0); + let offset = 0; + const arcs = parts.filter(part => part.count > 0).map(part => { + const width = 100 * part.count / total; + const start = offset; + offset += width; + return `${esc(objective)}
+${tr('本次评估的数据集')} · ${ds.slice(0,3).map(d=>esc(d.name)).join(tr('、'))}${ds.length>3?' '+esc(message('等 {count} 批',{count:ds.length})):''}
+${tr('需要覆盖的场景')} · ${esc(intents)}
+ +'+esc(txt)+'
"+tr("点击阶段可查看记录。评测重合在去重后单独判定。")+"
"); + return hero+kpi+procurementScenarioSummary(run.task,ds,rs)+'"+tr("先筛出符合验收要求的批次,再按场景覆盖得分排序。得分按各场景的达标比例和权重计算。")+"
"),'")+esc(measurementSummary(r))+'
'+gapChart(r.counts,run.task)+("")+esc(d.review||tr("尚无人工核实记录。"))+'
'+rBy(x.id).hitPrompts+tr(" 条重合指令,涉及 ")+rBy(x.id).excluded.overlap+(tr(" 条可用记录")+"
"+tr("已修复 "))+v.fixed+tr(" 项,新增 ")+v.added+tr(" 项。可用样本变化 ")+sign(v.unique)+tr(",重合记录变化 ")+sign(v.overlap)+(tr("。")+"
"+tr("各意图变化:"))+Object.entries(v.cover).map(([k,n])=>esc(intent(k))+' '+sign(n)).join(tr(","))+'
"+tr("复检沿用当前运行标准。也可以在「导入数据」中将交付文件作为候选的新版本。")+"
")); +} +const sign=n=>n>0?'+'+n:String(n); +function pager(p,n,a){return '"+tr("按加入顺序计算新增唯一内容。再次点击可移除候选。")+"
"+tr("与已选内容重复 "))+fmt(x.overlap)+(tr(" 条")+"
")+Object.entries(x.byIntent).map(([k,n])=>esc(intent(k))+' '+fmt(n)).join(' · ')+'
"+tr("组合合计 "))+fmt(p.total)+(tr(" 条唯一内容。")+"
"):empty(tr("选择一个合格候选,开始计算组合。")))+pane(tr("目标覆盖与补采缺口"),'target',gapChart(p.counts,run.task)+(""+tr("仍需补采 "))+fmt(Object.values(p.gaps).reduce((a,b)=>a+b,0))+(tr(" 条目标意图记录。")+"
"),btn(tr("导出补采 CSV"),'gapcsv','download') + (mix.length ? btn(tr('导出组合与血缘'),'merged-export','download') : ''))+''+esc(x.answer)+'
"+tr("覆盖变化:"))+Object.entries(diff.cover).map(([k,n])=>esc(intent(k))+' '+sign(n)).join(tr(","))+'
"+tr("共 "))+fmt(list.length)+(tr(" 条 · 序号为文件内的逻辑记录编号。")+"
")+(list.length?table([tr("候选"),tr("序号"),tr("原始指令"),''],list.slice(page*10,page*10+10).map(([d,i])=>td(esc(d.key),i+1,''+esc(v||tr("(空)"))+'
"+tr("固定合成评测集 · "))+x.queryCount+tr(" 个留出查询、")+n.pairs.length+(tr(" 对标注指令。可在源码中复跑。")+"
")+table([tr("检索策略"),tr("首位命中率"),tr("平均倒数排名")],Object.entries(x.ranking).map(([k,v])=>td(models[k],hit(v.top1),v.mrr)))+("'+esc(q.query)+tr(" · 目标 ")+esc(q.target)+tr(" · 首位 ")+esc(q.top||tr("无匹配"))+'
').join('')+(""+tr("字符序列相似度阈值 "))+n.threshold+tr(",精确率 ")+hit(n.precision)+tr(",召回率 ")+hit(n.recall)+(tr("。此实验仅提示人工复核。")+"
")+table([tr("句对"),tr("实测"),tr("标注")],n.pairs.filter(p=>p.predicted!==p.truth).map(p=>td(esc(p.left)+''+esc(line)+'
').join('')+''+runName(run)+' · '+esc(taskLabel(run.task))+' · '+ds.length+(tr(" 个候选。报告包含任务标准、数据版本、排序依据、证据缺口和当前组合。")+"
'+t('使用同一批 30–50 条独立人工标注和模型评分。按数据版本及行号配对,逐维计算未加权 Cohen’s κ。','Pair 30–50 independent human ratings with model ratings by version and row. Each dimension reports unweighted Cohen’s κ.')+'
'; + const files=''; + const buttons=''; + const direct=['ollama','openai'].includes(ctx.judgeMode); + const blind=ctx.calGold&&!ctx.calIllustrative&&!ctx.archived&&(direct||(ctx.local&&ctx.status?.available&&ctx.judgeMode==='backend')) ? + ''+t('仅发送引用记录的脱敏正文,不发送人工分数。','Only the masked source text is sent. Human scores stay out of the prompt.')+'
' : ''; + let output=''; + if(ctx.calResult){ + const rows=ctx.calResult.map((m,i)=>td(esc(t(...names[i])),m.n,m.missing,m.agreement==null?'—':(100*m.agreement).toFixed(1)+'%',m.kappa==null?'—':m.kappa.toFixed(3),m.interval?m.interval.map(x=>x.toFixed(3)).join(' … '):'—')); + output=''+(ctx.calIllustrative?t('构造评分示例 · 用于演示计算。','Constructed ratings for demonstration.'):t('来自已导入评分。','Computed from imported ratings.'))+'
'+table([t('维度','Dimension'),t('配对数','Pairs'),t('缺失','Missing'),t('完全一致','Exact agreement'),'Cohen’s κ','95% CI'],rows)+''+t('区间由逐行配对 bootstrap 估计(1,000 次)。分数无变化时 κ 可能无定义。区间假设各行相互独立。','Intervals use 1,000 paired row bootstrap resamples assuming independent rows. κ may be undefined for constant ratings.')+'
'; + } + return pane(t('人工金标准校准','Human gold-set calibration'),'audit',intro+files+buttons+blind+''+esc(ctx.calNotice||'')+'
'+output); +} diff --git a/dist/assets/classification.js b/dist/assets/classification.js new file mode 100644 index 0000000..e965b5f --- /dev/null +++ b/dist/assets/classification.js @@ -0,0 +1,93 @@ +export const REVIEW_INTENT = '__review__'; +const descriptions = { + refund:'refund return reimbursement money back exchange returned merchandise 退款退货', + shipping:'shipping shipment delivery tracking parcel courier lost package 物流配送', + account:'account login authentication profile password recovery sign in 账号登录', + billing:'billing invoice receipt tax charge card payment statement 账单发票' +}; +export function prototypes(goals) { + return Object.keys(goals).filter(k => k !== REVIEW_INTENT).map(label => ({ + label, text:Object.hasOwn(descriptions,label) ? descriptions[label] : label.replace(/[_-]/g,' ') + })); +} +function terms(value) { + const words=value.normalize('NFKC').toLowerCase().match(/[a-z0-9]+|[\u3400-\u9fff]+/g)||[]; + return words.flatMap(w => /[\u3400-\u9fff]/.test(w) && w.length>1 ? Array.from({length:w.length-1},(_,i)=>w.slice(i,i+2)) : [w]); +} +function represent(text,model) { + const counts=new Map(); + for (const term of terms(text)) counts.set(term,1+(counts.get(term)||0)); + const vector=new Array(model.dimensions).fill(0); + for (const [word,n] of counts) { + if (!Object.hasOwn(model.terms,word)) continue; + const [idf,...coords]=model.terms[word]; + for (let i=0;i'+ + (en()?'Set a minimum for each batch in this scenario. Blank or zero turns the requirement off.':'按批次验收这个场景,留空或填 0 表示该难度不限数量。')+ + '
'+t('内置示例评分 · 取自 Batch-B 第 1 条,展示评分口径。','Preset example ratings for Batch-B, row 1, illustrating the rubric.')+'
'+ + 'My parcel is at a locker that is out of service. Where can I collect it?'+ + table([t('维度','Criterion'),t('评分 / 5','Score / 5'),t('理由','Rationale')],names.map((name,i)=>td(name,[5,t('待核实','Unverified'),4,3][i],reasons[i]))); +} +export function judgeControls(ctx,dropdown){ + const opts=[['demo',t('内置评分示例','Preset example')],['openai',t('云端或自定义接口','Hosted or custom endpoint')],['ollama',t('本机 Ollama','Ollama on this device')]]; + if(ctx.local)opts.push(['backend',t('已配置的本机服务','Configured local service')]); + const disabled=ctx.busy?' disabled':''; + const picker=''; + if(ctx.judgeMode==='demo')return picker+fixture(); + const web=isDirect(ctx); + const form=web?'
“Ask the carrier to move the parcel to an accessible pickup point.”
'+t('请先启动 Ollama,并在 OLLAMA_ORIGINS 中允许当前站点','Start Ollama and allow this site in OLLAMA_ORIGINS')+' '+esc(location.origin)+'。
'+t('按场景和文本长度分层抽样,优先覆盖稀有样本。','Samples are stratified by intent and text length, starting with rare strata.')+'
'; + const target=ctx.pendingJudge; + let preview=''; + if(target){ + const labels=target.plan.rows.map(r=>(ctx.ds.find(d=>d.id===r.row.dataset)?.name||r.row.dataset)+' #'+r.row.line); + const excerpt=target.plan.rows.map((r,i)=>''+esc(JSON.stringify(maskedMaterial(r.source),null,2))+'
'+t('接收接口','Endpoint')+' '+esc(target.config.endpoint)+' · '+esc(target.config.model)+'
'+t('待发送记录','Rows to send')+' ('+labels.length+') · '+esc(labels.join('、'))+'
'+t('每条请求只含已遮盖常见敏感信息的指令、上下文和回答,每个字段最多 6,000 字符。若填了密钥,将随请求发给上述接口。服务商可能收取推理费用。','Each request sends the masked instruction, context and answer, up to 6,000 characters per field. Any entered key goes to the endpoint above. Provider charges may apply.')+'
'+ + ''+axes.map((k,i)=>(i+1)+' '+esc(intent(k))).join(' · ')+'
'+ + t('虚线为已有覆盖,实线为采购后覆盖。','Dashed: owned. Solid: after purchase.')+'
'+t('请输入非负预算。','Enter a nonnegative budget.')+'
'; + } + last=pickScenario(plan,modeValue,budget); + const {ds,run,archived}=sandbox; + const byId=new Map(ds.map(d=>[d.id,d])); + const names=ids=>ids.map(id=>byId.get(id)?.name||id).join(' + '); + const gaps=Object.entries(last.gaps).filter(([,v])=>v>0).map(([k,v])=>intent(k)+' '+v).join(' · '); + const currency=run.task.procurement?.currency||''; + const spend=cost=>esc(money(cost)+' '+currency); + const summary=''+esc(names(last.ids)||t('无需新增采购','No purchase selected'))+'
'+esc(gaps?t('剩余缺口','Remaining gaps')+' · '+gaps:t('全部目标已覆盖','All targets covered'))+'
'; + const steps=last.steps.length?table([t('批次','Batch'),t('净新增','Net new'),t('本批结算额','Batch cost'),t('每条新增成本','Cost / net new')], + last.steps.map(s=>td(esc(names([s.id])),String(s.added),spend(s.cost),s.added?spend(s.cost/s.added):'—'))):''; + const exclusion=[last.excluded.length?t('未通过验收、交付不完整或缺少报价','Ineligible, incomplete or unpriced')+' · '+names(last.excluded):'', + last.excludedRevisions.length?t('已排除整改批次','Rectified batches excluded')+' · '+names(last.excludedRevisions):''].filter(Boolean); + const pending=last.ids.filter(id=>plan.simulated.includes(id)); + const forecastNote=pending.length?''+t('预清洗预测,须正式整改复检后才能应用','Forecast only. Recheck deliveries before applying')+' · '+esc(names(pending))+'
':''; + return forecastNote+summary+coverageChart(run.task.goals,last.initial.gaps,last.gaps)+steps+ + ''+esc(last.exact?t('已穷举全部可选批次组合。','All eligible batch subsets evaluated.'): + t('批次较多,按每单位新增成本带来的覆盖增益近似求解。','Approximation using marginal coverage gain per added cost.'))+'
'+ + exclusion.map(s=>''+esc(s)+'
').join('')+ + (pending.length?'':sandbox.guide?'':!archived?'':''); +} +export function solverPane(ds,rs,run,mix,versions,archived,guide=false) { + const quotes=new Map(ds.map(d=>[d.id,settlementQuote(d,run.task,versions)])); + const key=JSON.stringify([...quotes]); + if(currentRun!==run || quoteKey!==key) { + cachedPlans.clear();quoteKey=key; + if(currentRun!==run) { + modeValue='budget';includeRectified=true;simulateCleaning=false;budgetValue=''; + } + currentRun=run; + } + const revisions=new Set(ds.filter(d=>isRectified(d,versions)).map(d=>d.id)); + sandbox={ds,rs,run,archived,quotes,revisions,guide}; + const plan=currentPlan(); + if(budgetValue==='') budgetValue=String(Math.max(0,...plan.candidates.map(c=>c.standalone))); + if(typeof document!=='undefined') loadSpace(); + const moneyLabel=run.task.procurement?.currency?' ('+esc(run.task.procurement.currency)+')':''; + const disabled=modeValue==='full'?'disabled':''; + const controls=''+t('报价沿用「采购对比」中的结算方式。已有数据和先前批次中的重复样本不计入净新增。','Uses the settlement terms in Procurement. Net new excludes records already owned or assigned to an earlier batch.')+'
'+t( + '每种组合先扣除库存和批次间的重复样本,再按净新增条数重算阶梯价。可选批次不超过 8 个时缓存全部组合供滑块筛选。更多批次时,每轮优先选择单位新增成本带来覆盖提升最大的方案。', + 'Each mix is deduplicated and repriced at its net-new tier rates. Up to 8 eligible batches use cached exhaustive search. Larger cases use a greedy estimate based on marginal coverage gained per additional cost.')+'
')+ + pane(t('问法覆盖扩展度','Semantic coverage expansion'),'chart',''+ + t('将独立指令与历史库和先前所选批次做向量比较。最高余弦相似度低于 0.82 计为新问法。使用客服语料 LSA,按行序等距抽查最多 256 条指令、512 条参照。零向量和空参照不计入分母。', + 'Compare unique prompts against owned history and earlier selections. Maximum cosine below 0.82 counts as expansion. Support-corpus LSA uses systematic samples of up to 256 prompts and 512 references. Empty references and zero vectors are excluded.')+'
'); +} + +// Update the output region only. Replacing the range during a drag drops pointer capture. +export function updateSandbox(input) { + const parent=input.closest('.sandbox-layout'); + if(!parent || !sandbox)return; + const slider=parent.querySelector('#solver-slider'),number=parent.querySelector('#solver-budget'); + if(input.id==='solver-mode') modeValue=input.value; + else if(input.id==='solver-preclean') simulateCleaning=input.checked; + else if(input.id==='solver-rectified') includeRectified=input.checked; + else if(input.id==='solver-slider') { + budgetValue=String(Math.round(Number(input.value)*100)/100);number.value=budgetValue; + } else if(input.id==='solver-budget') budgetValue=input.value; + else return; + const plan=currentPlan(); + slider.disabled=number.disabled=modeValue==='full'; + slider.max=String(Math.max(1,Math.ceil(plan.maxBudget),Number(budgetValue)||0)); + slider.value=budgetValue||'0'; + parent.querySelector('#solver-result').innerHTML=sandboxResult(); +} +export const proposedMix=()=>last?.ids?.slice()??null; + +export function decisionSummary(run,datasets,results,versions) { + const quotes=new Map(datasets.map(d=>[d.id,settlementQuote(d,run.task,versions)])); + const plan=solvePurchase(datasets,results,run.task,quotes,{mode:'full'}); + const names=plan.ids.map(id=>datasets.find(d=>d.id===id).name); + const returned=results.filter(r=>r.status==='block').map(r=>datasets.find(d=>d.id===r.id).name); + return [ + t('建议采购','Recommended batches')+' · '+(names.join(' + ')||'—'), + t('预计总花费','Estimated total')+' · '+money(plan.cost)+' '+(run.task.procurement?.currency||''), + t('各场景剩余缺口率','Remaining scenario gaps')+' · '+Object.entries(plan.gaps).map(([k,n])=>intent(k)+' '+percent(n/run.task.goals[k])).join(' · '), + t('需附整改退回清单','Attach remediation notices for')+' · '+(returned.join(' · ')||t('无','None')) + ]; +} diff --git a/dist/assets/model-lab.js b/dist/assets/model-lab.js new file mode 100644 index 0000000..ebc4c49 --- /dev/null +++ b/dist/assets/model-lab.js @@ -0,0 +1,243 @@ +import {changeJudge, isDirect, judgeControls, preparePlan, runPlan} from './judge-panel.js'; +import {forecastPanel} from './provenance.js'; +import {calibrationPanel,calibrate,exampleSet,validateGold} from './calibration.js'; +import {validateReport, renderReport} from './model-report.js'; +import {language} from './locale.js'; +import {portfolio} from './engine.js'; +import {download, empty, esc, intent, pane, table, td} from './ui.js'; + +const t = (zh, en) => language() === 'en' ? en : zh; +let active = null; + +function operationState(ctx) { + if (ctx.archived) return t('历史快照仅供查看。', 'This is a read-only historical snapshot.'); + if (!ctx.local) return ''; + if (ctx.status === null) return t('正在检查本机模型配置…', 'Checking local model settings…'); + if (!ctx.status.available) return t('请配置 DATALENS_MODEL_URL 为回环地址,并设置 DATALENS_MODEL 后重启本机服务。', 'Set DATALENS_MODEL_URL to a loopback chat endpoint and set DATALENS_MODEL, then restart the local service.'); + return t('当前本机模型', 'Current local model') + ' · ' + ctx.status.model; +} + +const dimensions = { + instruction_following: ['指令遵循', 'Instruction following'], + factual_accuracy: ['事实准确性', 'Factual accuracy'], + logical_coherence: ['逻辑连贯性', 'Logical coherence'], + response_depth: ['回答完整性', 'Response depth'] +}; + +function results(ctx) { + if (!ctx.result) return ''; + if (ctx.op === 'judge') { + const records = ctx.result.records.map(({row, ratings, raw_scores, stratum, verbosity}) => { + const dataset = ctx.ds.find(d => d.id === row.dataset); + const detail = Object.entries(dimensions).map(([key, labels]) => td( + esc(t(...labels)), esc(raw_scores?.[key] ?? '—'), esc(ratings[key].score ?? t('待核实', 'Unverified')), esc(ratings[key].reason) + )); + return ''+esc(stratum?.intent)+' · '+esc(stratum?.token_bin)+' tokens · '+t('冗余扣分','Redundancy deduction')+' '+esc(verbosity?.deduction)+'
'+table([t('评审维度', 'Criterion'), t('原始分','Raw'),t('校正分 / 5', 'Adjusted / 5'), t('模型理由', 'Model rationale')], detail); + }).join(''); + return pane(t('抽样评审结果', 'Sample reviews'), 'file', records ? ''+records : empty(t('没有可评审记录。', 'No records to review.'))); + } + const items = ctx.result.drafts.map(row => td(esc(intent(row.intent)), esc(row.instruction), esc(row.response))); + return pane(t('待人工复核的合成草稿', 'Synthetic drafts for review'), 'file', items.length ? + forecastPanel(ctx,ctx.result.drafts) + table([t('意图', 'Intent'), t('指令', 'Instruction'), t('回答', 'Response')], items) + + '' : + empty(t('本次没有生成新草稿。', 'No new drafts were generated.'))); +} + +function content(ctx) { + const gaps = Object.entries(ctx.gaps).filter(([, count]) => count > 0); + const canRun = ctx.local && !ctx.archived && ctx.status?.available && !ctx.busy; + const dropdown = ctx.ds.map(d => '').join(''); + const setup = ctx.judgeMode==='backend' ? '' + esc(operationState(ctx)) + '
' : ''; + const preview = judgeControls(ctx,dropdown); + const draftInfo = '' + t('从当前组合中选择合格记录作为示例,按实际缺口生成最多 3 条草稿。发送内容包括目标意图、语言及脱敏后的示例文本。','Use eligible records in the current mix as examples and generate up to three drafts for actual gaps. The local model receives the target intent, language and masked examples.') + '
' + + esc(gaps.map(([key,n]) => intent(key)+' '+n).join(' · ') || t('各意图已达标。', 'All coverage goals are met.')) + '
' + + '' + (!ctx.local?''+t('生成草稿需连接本机工作台的合成服务。','Generating drafts requires the local workbench synthesis service.')+'
':'') + + (ctx.ids.length ? forecastPanel(ctx) : ''+t('请先在「组合补数」选入合格批次。','Select an eligible batch in Dataset mix first.')+'
'); + const local = ''+t('导出本次运行的标准项目 JSON,在本机运行语义近邻、评测题近邻和主题聚类。命令与模型配置见项目源码中的 docs/models.md。','Export this run as a project JSON file for semantic neighbors, benchmark matching and topic clustering. See docs/models.md in the source package for commands and model settings.')+'
' + + 'python -m datalens.models semantic project.json --out neighbors.json\npython -m datalens.models topics project.json --out topics.json --plot topics.png' + + ''; + return setup + pane(t('大模型抽样评审','Model sample review'),'audit',preview) + + '
'+t('合成样例 · 字符级 LSA、PCA 与 HDBSCAN','Synthetic demo · character LSA, PCA and HDBSCAN')+'
' : ''; + if (!ctx.report) return controls+demo+''+esc(ctx.reportNotice || '')+'
'; + const report=ctx.report; + const byId=new Map((ctx.demoDatasets || ctx.ds).map(d=>[d.id,d])); + const snippet=text => esc(maskText(String(text)).slice(0,180)); + const source = ref => { + const d=byId.get(ref.dataset); + return esc(d.name)+' · v'+esc(d.version)+' · #'+ref.line+''+t('余弦相似度阈值','Cosine threshold')+' '+report.threshold+'
'; + heads=[t('原始记录','Source record'),t('最近邻','Nearest match'),t('相似度','Cosine similarity')]; + rows=report.matches.slice(first,first+pageSize).map(p=>td(source(p.row),p.neighbor?source(p.neighbor): + t('评测题','Benchmark')+' #'+p.benchmark+''+t('所有报价使用同一币种。议价时,整包方案按可用样本计算每条成本,按增量结算的方案按净新增样本计算。','Use one currency. For the unit cost ceiling, divide the package price by usable records, or the incremental payment by net-new records.')+'
'; +} + +export function procurementPage(ds, rs, mode, task={}, versions={}) { + purchaseTask=task; purchaseVersions=versions; + datasets = ds; + results = rs; + if (reference!==EMPTY_REFERENCE && !ds.some(d=>d.id===reference) && reference!==task.procurement?.history?.id) reference=task.procurement?.history?.id||''; + const byId = new Map(rs.map(r=>[r.id,r])); + addedCounts = additionalCounts(); + const headings = [t('批次 / 来源','Batch / source'),tr('决策'),t('有效 / 交付','Usable / delivered'),t('报价与结算方式','Quote and terms'),t('整包单价(按交付量)','Package price / delivered'),t('净新增条数','Net-new records'),t('预计结算金额','Estimated payment'),t('每条可用成本','Cost / usable'),t('每条净新增成本','Cost / net-new record'),t('采购建议','Advice')]; + const currency=task.procurement?.currency; + if(currency) headings[6]+=' ('+currency+')'; + const rows = ds.map((d,index) => { + const r=byId.get(d.id), values=decisionResults(d,r,addedCounts?.get(d.id)); + const output=k=>''+esc(values[k])+''; + return td(''+esc(d.name)+' · v'+Number(d.version)+''+t('净新增只统计与所选对照批次不重复的可用记录。按增量结算时,各档单价只用于该档内的新增记录,零新增的应付金额为零。这里按单个批次试算;组合采购会再扣除所选批次之间的重复。完整交付后可试算,验收通过后才可纳入采购组合。报价保存在当前浏览器。','Net-new records exclude matches against the selected reference. Each tier charges only the records in that band. Zero net-new means zero incremental payment. This table estimates each batch independently; a mix also deducts overlaps across selected batches. Full deliveries can be estimated; only accepted deliveries are purchasable. Quotes are saved in this browser.')+'
')+ + pane(t('质量雷达图','Quality profiles'),'chart',''+t('从顶部顺时针依次为完整率、语言符合率、有效率和覆盖得分。各轴均为 0–100%。','Clockwise from the top: completeness, language match, usable yield, and coverage score. Each axis ranges from 0 to 100%.')+'
'+ + t('按历史库与当前组合去重后的唯一记录统计。比例分母含来源未知的记录,因此显示值是已知下界。阈值用于人工复核。','Counts cover distinct records in the baseline and selected batches. Unknown origins remain in the denominator, so the displayed share is a lower bound. The threshold triggers human review.')+ + '
'+t('选择批次后显示占比。','Select a batch to see the breakdown.')+'
')); +} + +export function forecastPanel(ctx, generated) { + const {records} = mixLineage(ctx.ds,ctx.rs,ctx.ids,ctx.run.task); + let bins = originShares(records); + if (generated) bins = originShares(records,generated).filter(b => b.added); + else { + const affected = []; + let remaining=3; + for (const [scene,gap] of Object.entries(ctx.gaps)) { + if (!remaining) break; + const added = Math.min(gap,remaining); + if (!added) continue; + const base = bins.find(b => b.scene===scene) || {scene, total:0, synthetic:0,unknown:0}; + affected.push({...base,added,total:base.total+added,synthetic:base.synthetic+added}); + remaining-=added; + } + bins=affected; + } + if (!bins.length) return ''; + const title = generated ? t('若接收本次去重草稿','If these distinct drafts are accepted') : + t('若按当前缺口顺序接收最多三条新草稿','If up to three new drafts are accepted in gap order'); + const limit = synthThreshold(); + const warning = bins.some(b => warningStatus(b,limit)==='above') ? ''+t('接收这些草稿可能使部分场景的合成占比超过阈值。','Accepting these drafts could push some intents above the synthetic-share limit.')+'
':''; + return warning+''+t('在独立样例中核对问题和整改结果。当前工作区的数据可在上方选择。','Explore seeded issues and try cleanup here. Select a workspace batch above to inspect your own data.')+'
':'')); +} +function metrics() { + const s=scan.stats, flagged=scan.rows.filter(r=>r.kinds.length).length; + const metrics=[[t('记录数','Records'),scan.rows.length],[t('需检查的记录','Flagged records'),flagged],[t('估算长度 P95','Est. length P95'),s.p95],['Distinct-1',pct(s.distinct1)],['Distinct-2',pct(s.distinct2)]]; + const max=Math.max(1,...s.bins.map(b=>b.count)); + return pane(t('长度分布与词汇多样性','Length and lexical diversity'),'chart', + ''+t('横条按指令、上下文和回答的估算 token 总数分组。Distinct-1/2 是回答中独立一元词和二元词组的占比。','Bars group rows by estimated tokens across prompt, context and response. Distinct-1/2 measure unique response unigrams and bigrams as a share of their totals.')+'
'); +} +const difficultyReasons = { + label:['文件自带标签','Supplied label'], + exception:['题目或上下文含异常处理线索','Exception cue in the prompt or context'], + dialogue:['保留了之前的用户发言','Prior customer turn in context'], + conditions:['命中两类及以上条件线索','At least two types of condition cues'], + default:['未发现多条件或异常处理线索','No multi-condition or exception cue'] +}; +function difficultySummary(){ + const minimums=(selection===demoId?demoTask:run.task).complexityMin||{}; + const scenes=[...new Set([...Object.keys(counts),...Object.keys(minimums)])]; + const lines=scenes.map(scene=>td(esc(intent(scene)),...tiers.map(tier=>{ + const n=counts[scene]?.[tier]||0, minimum=minimums[scene]?.[tier]||0; + return minimum ? ''+n+' / '+minimum+'' : String(n); + }))); + return pane(t('各场景的样本难度','Sample difficulty by scenario'),'chart', + table([t('场景','Scenario'),...tiers.map(tier=>t(...tierNames[tier]))],lines)+ + ''+t('仅统计字段完整、语言符合且去重的样本;排除与评测题完全重合的记录,以及启用敏感信息检查时命中的记录。设有要求的格子显示“实有 / 最少”。优先采用交付文件中的难度标签,其余按题目和上下文估算,可在下方核对。', + 'Counts include complete, language-matched, unique samples and exclude exact benchmark matches and rows flagged by an enabled privacy check. Configured cells show observed / minimum. Supplied labels take priority; other rows are estimated from prompt and context. Inspect the evidence below.')+'
'); +} +function rowText(row) { + return [row?.instruction,row?.context,row?.response].filter(Boolean).join('\n'); +} +function rowEvidence(e) { + const row=source.rows[e.line-1], flags=e.kinds.map(label).join(' · ') || t('无规则命中','No rule hit'); + const match=e.nearLine?term(t('对照行','Matched row'),'#'+e.nearLine+' · '+pct(e.similarity)+''+esc(scan.ruleVersion)+' · '+(query&&!criteria.tags.length?t('未识别筛选条件。可组合意图、回答字符数、重复或隐私。','No filters recognized. Combine an intent, response length, duplicates or PII.'):([kind&&label(kind),...criteria.tags].filter(Boolean).map(esc).join(' + ') || t('全部记录','All records')))+' · '+(filterPending?t('查询中…','Filtering…'):entries.length+' '+t('条','matches')+(filterEngine?' · '+esc(filterEngine):''))+'
'+ + entries.slice(page*pageSize,(page+1)*pageSize).map(rowEvidence).join('')+ + ''+t('清洗前','Before')+' '+source.rows.length+' · '+t('清洗后','After')+' '+preview.rows.length+' · '+t('变更','Changed')+' '+preview.changes.length+'
'+ + cleanupDiff(source.rows,preview)+ + ''+t('上次复检','Previous cleanup')+' · '+safe(prev.ruleVersion)+' · '+(prev.changes?.length||0)+' '+t('处变更','changes')+'
'+button('lineage',t('导出上次整改记录','Export previous cleanup log')):'')); +} +function paint(){ + const el=root();if(!el)return; + const status=scanError?''+esc(scanError)+'
'+button('retry',t('重试','Retry')):''+t('正在分析记录…','Scanning records…')+'
'; + el.innerHTML=controls()+(scan&&!scanError?metrics()+difficultySummary()+evidence()+cleanup():status); +} +function saveJSON(name,value){download(name,JSON.stringify(value,null,2),'application/json');} +document.addEventListener('change',event=>{ + const input=event.target;if(!input.closest('#quality-lab'))return; + if(input.dataset.qfield==='source')changeSource(input.value); + else if(input.dataset.qfield==='limit'){ + if(input.reportValidity()){limit=Number(input.value);selectSource();} + } else if(input.dataset.qfield==='kind'){kind=input.value;requestFilter();} + else if(input.dataset.qfield==='difficulty'){difficulty=input.value;page=0;paint();} + else if(input.dataset.qoption){settings[input.dataset.qoption]=input.checked;preview=null;paint();} +}); +function filter(){query=root().querySelector('[data-qfield="query"]').value.trim();requestFilter();} +document.addEventListener('keydown',e=>{if(e.key==='Enter' && e.target.closest('#quality-lab [data-qfield="query"]')){e.preventDefault();filter();}}); +document.addEventListener('click',e=>{ + const b=e.target.closest('#quality-lab [data-ql]');if(!b)return; + switch(b.dataset.ql){ + case 'retry': changeSource(selection);break; + case 'reset-demo': demo=null;demoRevision=0;changeSource(demoId);break; + case 'filter':filter();break; + case 'prev':page--;paint();break; + case 'next':page++;paint();break; + case 'preview':cleaning=true;preview=null;worker.postMessage({type:'clean',options:{...settings},settingsKey:JSON.stringify(settings)});paint();break; + case 'export':saveJSON('quality-evidence.json',{dataset:source.id,version:source.version,limit,...scan});break; + case 'changes':saveJSON('cleanup-preview.json',{parent:source.id,ruleVersion:preview.ruleVersion,changes:preview.changes});break; + case 'lineage':saveJSON('quality-lineage.json',source.lineage);break; + case 'apply':{ + if(!preview?.changes.length)return; + if(selection===demoId){ + demoRevision++; + demo={...demo,id:'quality-demo-v'+(demoRevision+1),version:demoRevision+1,rows:preview.rows,lineage:{parent:demo.id,ruleVersion:preview.ruleVersion,changes:preview.changes}}; + selectSource(); + }else if(!archived){ + document.dispatchEvent(new CustomEvent('quality-clean',{detail:{id:source.id,runNumber:run.n,...preview}})); + } + break; + } + } +}); + +export function inspectQualityBatch(id) { + selection = id; + kind = ''; difficulty = ''; query = ''; page = 0; +} diff --git a/dist/assets/quality-worker.js b/dist/assets/quality-worker.js new file mode 100644 index 0000000..69124fc --- /dev/null +++ b/dist/assets/quality-worker.js @@ -0,0 +1,29 @@ +import {scanRows,cleanRows} from './deep-scan.js'; +import {filterColumns,matchesFilter,openFilterDatabase} from './quality-filter.js'; + +let rows, scan, index, connection; +self.onmessage = async ({data}) => { + try { + if (data.type === 'scan') { + rows = data.rows; + scan = scanRows(rows, data.benchmarks, {maxTokens:data.limit}); + self.postMessage({type:'scan', scan}); + } else if (data.type === 'filter') { + index ??= scan.rows.map((entry,i)=>filterColumns(rows[i],entry)); + connection ??= openFilterDatabase(index).catch(()=>null); + const filter = await connection; + if (filter) { + try { + self.postMessage({type:'filtered', engine:'DuckDB-Wasm', serial:data.serial, lines:filter(data.spec)}); + return; + } catch { connection=Promise.resolve(null); } + } + const lines=index.filter(record=>matchesFilter(record,data.spec)).map(r=>r.line); + self.postMessage({type:'filtered',engine:'JavaScript',serial:data.serial,lines}); + } else if (data.type === 'clean') { + self.postMessage({type:'clean',settingsKey:data.settingsKey,result:cleanRows(rows, scan, data.options)}); + } + } catch (error) { + self.postMessage({type:'error', message:String(error.message || error)}); + } +}; diff --git a/dist/assets/record-evidence.js b/dist/assets/record-evidence.js new file mode 100644 index 0000000..f68086e --- /dev/null +++ b/dist/assets/record-evidence.js @@ -0,0 +1,75 @@ +import {contentKey, kinds, norm} from './engine.js'; +import {language, tr} from './locale.js'; +import {maskText} from './pii.js'; +import {btn, esc, intent} from './ui.js'; + +const label = (zh,en) => language()==='en' ? en : zh; +const safe = value => esc(maskText(value)); +const escapedPattern = value => String(value).replace(/[.*+?^${}()|[\]\\]/g,'\\$&'); + +export function explicitRecords(question, datasets) { + const citations = []; + for (const d of datasets) { + const pattern = new RegExp('(?:^|[^a-z0-9])(?:batch[\\s-]*)?'+escapedPattern(d.key)+'\\s*(?:批次)?\\s*(?:#|#|第)\\s*(\\d+)', 'gi'); + for (const match of question.matchAll(pattern)) { + const line = Number(match[1]); + if (!citations.some(ref=>ref.id===d.id && ref.line===line)) + citations.push({id:d.id,line,available:line>=1 && line<=d.rows.length}); + } + } + return citations; +} + +export function supportingRecords(results, question) { + const wanted = /隐私|敏感|手机|pii|phone|privacy/i.test(question) ? 'pii' + : /评测|泄漏|benchmark|leak/i.test(question) ? 'overlap' + : /重复|duplicate/i.test(question) ? 'duplicate' : ''; + const citations = []; + for (const result of results) { + const lines = new Set(result.issues.filter(i=>!wanted||i.kind===wanted).map(i=>i.line)); + if (!lines.size && !wanted && result.valid.length) lines.add(result.valid[0]+1); + for (const line of Array.from(lines).slice(0,4)) citations.push({id:result.id,line}); + } + return citations; +} + +export function citationLink(d, line) { + return btn(d.key+' · v'+d.version+' #'+line,'record-evidence','file','chip', + 'data-id="'+esc(d.id)+'" data-line="'+Number(line)+'"'); +} + +function recordBlock(row) { + return [[label('指令','Instruction'),row.instruction],[label('上下文','Context'),row.context], + [label('回答','Response'),row.response]].filter(([,v])=>v).map(([k,v])=> + ''+safe(v)+'
'+safe(prompt)+'
'); + } + if(matches.some(i=>i.kind==='duplicate')){ + const key=contentKey(row); + const index=d.rows.findIndex((r,i)=>i'+safe(d.name)+' · v'+d.version+' · '+safe(intent(row.intent))+'
'+ + ''+label('行号从 1 开始,按该版本的文件顺序排列。敏感字段在此处以占位符显示。','Row numbers start at 1 in this version. Detected sensitive values are masked in this view.')+'
'; +} diff --git a/dist/assets/scenario-summary.js b/dist/assets/scenario-summary.js new file mode 100644 index 0000000..68769cf --- /dev/null +++ b/dist/assets/scenario-summary.js @@ -0,0 +1,61 @@ +import {contentKey, norm} from './engine.js'; +import {language} from './locale.js'; +import {btn, esc, intent, pane, table, td} from './ui.js'; + +const t = (zh,en) => language()==='en' ? en : zh; + +export function scenarioEvidence(task,datasets,results) { + const history = task.procurement?.history?.rows; + if (!Array.isArray(history)) return []; + const owned = new Set(); + const covered = new Map(); + for (const row of history) { + const key = contentKey(row); + if (owned.has(key)) continue; + owned.add(key); + const scene = norm(row.intent); + covered.set(scene,(covered.get(scene) || 0)+1); + } + const lookup = new Map(results.map(r=>[r.id,r])); + return datasets.map(d=>{ + const result = lookup.get(d.id); + const increments = new Map(); + let overlap = 0; + for (const index of result.valid) { + const row = d.rows[index]; + if (owned.has(contentKey(row))) overlap++; + else { + const scene = norm(row.intent); + increments.set(scene,(increments.get(scene)||0)+1); + } + } + const targets = Object.entries(task.goals).map(([scene,goal])=>{ + const gap = Math.max(0,goal-(covered.get(scene)||0)); + return {scene, gap, adds:Math.min(gap,increments.get(scene)||0)}; + }).filter(g=>g.adds>0).sort((a,b)=>b.adds-a.adds); + return {dataset:d, result, overlap, total:result.valid.length, target:targets[0]}; + }); +} + +export function procurementScenarioSummary(task,datasets,results) { + const evidence = scenarioEvidence(task,datasets,results); + if (!evidence.length) return ''; + const headings = [t('批次','Batch'), t('与历史库重复','Already owned'), + t('评测与隐私命中','Screening flags'), t('可补的主要缺口','Largest potential contribution'),t('证据','Evidence')]; + const rows = evidence.map(({dataset,result,overlap,total,target}) => { + const flags = []; + if (result.excluded.overlap) flags.push(t('评测重合 ','Benchmark overlaps ')+result.excluded.overlap); + if (result.excluded.pii) flags.push(t('隐私信息 ','PII rows ')+result.excluded.pii); + return td(esc(dataset.name)+' · v'+esc(dataset.version), + total ? overlap+' / '+total+' ('+Math.round(100*overlap/total)+'%)' : '—', + esc(flags.join(' · ') || t('无命中','None detected')), + target ? esc(intent(target.scene))+' · '+target.adds+' / '+target.gap+ + ' ('+Math.round(100*target.adds/target.gap)+'%)' : '—', + btn(t('深度质检','Inspect batch'),'inspect-quality','','link','data-id="'+esc(dataset.id)+'"')); + }); + const note = t('历史重合率以批内去重后的可用记录为分母。缺口贡献按单批独立估算,未通过验收的批次须先整改。', + 'Owned share uses usable, internally deduplicated records. Contributions are estimated separately for each batch. Flagged batches must pass recheck before purchase.'); + return pane(t('采购批次与已有库存','Available batches and existing inventory'),'compare', + table(headings,rows)+''+esc(note)+'
', + ''+t('求解采购组合','Compare purchase plans')+''); +} diff --git a/dist/assets/store.js b/dist/assets/store.js new file mode 100644 index 0000000..fb8641e --- /dev/null +++ b/dist/assets/store.js @@ -0,0 +1,17 @@ +import {tr} from './locale.js'; +const localServer=document.querySelector('meta[name=datalens-runtime]').content==='local'; +export const storageLabel=localServer?'本机 SQLite':'浏览器本地'; +let database=null; +function asPromise(request){return new Promise((ok,fail)=>{request.onsuccess=()=>ok(request.result);request.onerror=()=>fail(request.error);});} +export async function loadState(){ + if(localServer){const res=await fetch('./api/workspace');if(!res.ok)throw Error(tr("无法连接本机工作台"));return (await res.json()).workspace;} + const open=indexedDB.open('datalens-workbench-v1',1);open.onupgradeneeded=()=>open.result.createObjectStore('workspace'); + database=await asPromise(open);return asPromise(database.transaction('workspace').objectStore('workspace').get('current')); +} +export async function saveState(state,expected){ + if(localServer){const res=await fetch('./api/workspace',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({expected,workspace:state})}); + if(!res.ok)throw Error(res.status===409?tr("另一窗口已保存更新,请刷新后重试"):tr("本机保存失败,请检查数据目录空间"));return;} + return new Promise((ok,fail)=>{const tx=database.transaction('workspace','readwrite');const store=tx.objectStore('workspace');let failure; + const read=store.get('current');read.onsuccess=()=>{if((read.result?.revision||0)!==expected){failure=tr("另一窗口已保存更新,请刷新后重试");tx.abort();}else store.put(state,'current');}; + tx.oncomplete=ok;tx.onabort=()=>fail(Error(failure||tr("本地存储失败,请检查可用空间")));tx.onerror=()=>fail(tx.error);}); +} diff --git a/dist/assets/style.css b/dist/assets/style.css new file mode 100644 index 0000000..c713c05 --- /dev/null +++ b/dist/assets/style.css @@ -0,0 +1,178 @@ +:root { + color-scheme: light; + --mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Consolas, monospace; + --ink: #172235; + --muted: #526176; + --panel: #ffffff; + --line: #dce4ee; + --divider: #e7ecf3; + --canvas: #f9fbfe; + --soft: #f4f7fb; + --hover: #eaf0fa; + --primary: #255bc6; + --primary-hover: #1e49a1; + --primary-ink: #ffffff; + --accent-text: #244f9b; + --accent-wash: #eff4ff; + --accent-line: #bfceed; + --focus: #2b61c4; + --ok-bg: #e2edff; + --ok-fg: #244f97; + --warn-bg: #fff0df; + --warn-fg: #884511; + --neutral-bg: #eaf0f7; + --neutral-fg: #4a5e76; + --violet-bg: #f5ebf1; + --violet-fg: #81596d; + --danger: #a0332d; + --funnel-1: #b7cff0; + --funnel-2: #83ace3; + --funnel-3: #5387ce; + --funnel-4: #3264ac; + --chart-pass: #386dc4; + --chart-block: #ae7435; + --chart-review: #8d9bb1; + font: 16px/1.5 Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; + color: var(--ink); + background: var(--canvas); + --nav-surface: #fbfcff; + --nav-active: #e3edff; + --task-surface: #eef3fc; +} +:root[data-theme="dark"] { + color-scheme: dark; + --ink: #edf1f8; + --muted: #aebbcf; + --panel: #10151e; + --line: #2a3444; + --divider: #202a37; + --canvas: #070a10; + --soft: #151c28; + --hover: #1c293c; + --primary: #93b8ff; + --primary-hover: #aecaff; + --primary-ink: #102348; + --accent-text: #a6c5ff; + --accent-wash: #17253a; + --accent-line: #344d71; + --focus: #a1c5ff; + --ok-bg: #192e50; + --ok-fg: #aacaff; + --warn-bg: #493421; + --warn-fg: #ffca92; + --neutral-bg: #293445; + --neutral-fg: #c5d2e5; + --violet-bg: #41333c; + --violet-fg: #e6bdd0; + --danger: #ffaaa6; + --funnel-1: #405a82; + --funnel-2: #5276a9; + --funnel-3: #7399cd; + --funnel-4: #97baf0; + --nav-surface: #0a0e16; + --nav-active: #192c49; + --task-surface: #111b2a; + --chart-pass: #8eb6fa; + --chart-block: #dcad75; + --chart-review: #8798af; +} +*{box-sizing:border-box}body{margin:0}a{color:inherit}button,input,select,textarea{font:inherit;color:inherit}button,a,select{touch-action:manipulation}button,.btn{border:1px solid var(--line);background:var(--panel);color:var(--ink);border-radius:8px;padding:.6rem .85rem;min-height:38px;font-weight:600;cursor:pointer;display:inline-flex;gap:8px;align-items:center;justify-content:center;font-size:.875rem;text-decoration:none}button:hover,.btn:hover{background:var(--hover)}button:disabled{opacity:.46;cursor:not-allowed}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid var(--focus);outline-offset:2px}button.primary,.btn.primary{background:var(--primary);color:var(--primary-ink);border-color:var(--primary)}button.primary:hover{background:var(--primary-hover)}.flat{background:transparent;border-color:transparent}.link{color:var(--accent-text);border:0;background:none;padding:2px 0;min-height:30px}.ico{width:19px;height:19px;flex:0 0 auto;stroke:currentColor;fill:none;stroke-width:1.65;stroke-linecap:round;stroke-linejoin:round}.app{display:grid;grid-template-columns:224px minmax(0,1fr);min-height:100vh}.side{color:var(--ink);background:var(--nav-surface);display:flex;flex-direction:column;padding:27px 15px 17px;position:sticky;top:0;height:100dvh;z-index:5}.brand{display:flex;gap:11px;align-items:center;text-decoration:none;font-family:Inter,system-ui,sans-serif;font-size:24px;letter-spacing:-1.1px;font-weight:700;padding:0 9px}.brand img{width:34px;height:34px}.brand b{font-family:var(--mono);font-size:12px;letter-spacing:0;color:var(--accent-text);border:1px solid var(--accent-line);border-radius:5px;padding:2px 4px;vertical-align:middle}.side-title{font-size:12px;font-weight:650;color:var(--muted);margin:37px 12px 11px;letter-spacing:.09em}.side nav{display:grid;gap:4px}.side nav a{display:flex;align-items:center;gap:13px;color:var(--muted);padding:12px 14px;text-decoration:none;border-radius:8px;font-size:.925rem}.side nav a:hover{background:var(--hover)}.side nav a.active{background:var(--nav-active);color:var(--accent-text);font-weight:700}.side nav a small{margin-left:auto;font:12px var(--mono);padding:2px 6px;background:var(--soft);border-radius:4px;color:var(--muted)}.side nav a.active small{background:var(--panel);color:var(--accent-text)}.side-foot{margin-top:auto;padding-top:24px}.side-foot a{border-top:1px solid var(--divider);display:flex;align-items:center;gap:10px;color:var(--muted);text-decoration:none;font-size:.875rem;padding:18px 11px 3px}.body{min-width:0}.top{height:61px;display:flex;align-items:center;justify-content:space-between;padding:0 clamp(20px,3.1vw,52px);background:var(--panel);border-bottom:1px solid var(--line)}.crumb,.topright,.actions,.tags,.hstack,.inline,.legend{display:flex;align-items:center;gap:10px}.crumb,.topright{font-size:.82rem;color:var(--muted)}.crumb strong{color:var(--ink)}.slash{color:var(--muted)}.topright .ico{width:16px}.avatar{display:grid;place-items:center;width:31px;height:31px;border-radius:50%;background:var(--accent-wash);color:var(--accent-text);letter-spacing:-.05em;font:600 12px var(--mono);margin-left:8px}.mobile{display:none}.main{max-width:1550px;margin:auto;padding:clamp(22px,2.5vw,40px) clamp(20px,3.1vw,52px) 48px}.pagehead{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:22px}h1,h2,h3,p{margin:0}h1{font-size:clamp(1.65rem,2.45vw,2.4rem);letter-spacing:-.055em;line-height:1.25;color:var(--ink)}h2{font-size:1.08rem;letter-spacing:-.035em}h3{font-size:1rem}p{line-height:1.65}.desc{color:var(--muted);font-size:.9rem;margin-top:7px}.actions,.tags,.hstack,.legend{flex-wrap:wrap}.hero{position:relative;isolation:isolate;background:var(--task-surface);color:var(--ink);border:1px solid var(--line);border-radius:15px;overflow:hidden;padding:27px 30px;display:flex;align-items:center;justify-content:space-between;gap:26px;margin-bottom:18px}.hero h2{font-size:clamp(1.5rem,2.25vw,2.1rem);letter-spacing:-.055em;margin:9px 0 9px;color:var(--ink)}.hero .eyebrow{color:var(--accent-text)}.eyebrow{font-size:.785rem;font-weight:650;display:flex;align-items:center;gap:7px;letter-spacing:.05em}.eyebrow .ico{width:16px;height:16px}.hero p{color:var(--muted);font-size:.875rem}.hero .tags{margin-top:15px}.hero .tags span{font-size:.75rem;background:var(--panel);color:var(--muted);border:1px solid var(--line);border-radius:5px;padding:4px 8px}.hero-side{min-width:220px;min-height:112px;display:flex;align-items:center;justify-content:center;gap:17px;padding-right:8px}.ring{width:104px;height:104px;border-radius:100%;display:grid;place-items:center;position:relative}.ring>div{border-radius:50%;width:81px;height:81px;display:grid;align-content:center;justify-items:center;z-index:1}.ring svg{position:absolute;inset:0;width:100%;height:100%;transform:rotate(-90deg)}.ring b{font:600 26px var(--mono);color:var(--ink)}.ring small{font-size:11px;color:var(--muted)}.hero-key{display:grid;gap:8px;min-width:83px}.hero-key div{display:flex;align-items:center;gap:6px;font-size:.75rem;color:var(--ink)}.hero-key b{margin-left:auto;font:600 13px var(--mono)}.swatch{width:8px;height:8px;background:var(--sw);border-radius:3px;display:inline-block;flex-shrink:0}.kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:13px;margin-bottom:18px}.panel,.kpi{border:1px solid var(--line);background:var(--panel);border-radius:15px}.kpi{padding:16px 17px;position:relative}.kpi .ico-box{position:absolute;right:13px;top:13px;display:grid;place-items:center;background:var(--accent-wash);color:var(--accent-text);padding:7px;border-radius:8px}.kpi .ico-box .ico{height:16px;width:16px}.kpi:nth-child(3) .ico-box{background:var(--warn-bg);color:var(--warn-fg)}.kpi:nth-child(4) .ico-box{background:var(--neutral-bg);color:var(--neutral-fg)}.kpi .label{font-weight:600;font-size:.84rem;color:var(--muted)}.kpi b,.mono{font-family:var(--mono);font-variant-numeric:tabular-nums}.kpi b{display:block;font-size:clamp(1.7rem,2.3vw,2.25rem);font-weight:560;letter-spacing:-.075em;line-height:1.22;margin:9px 0 4px}.kpi small,.sub,small{font-size:.78rem;color:var(--muted)}.grid2{display:grid;grid-template-columns:minmax(0,1.12fr) minmax(0,1fr);gap:16px;margin-bottom:18px}.panel{padding:20px;min-width:0;margin-bottom:17px}.grid2>.panel{margin:0}.panel-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:16px}.eyeline{display:flex;align-items:center;gap:9px}.eyeline .ico{color:var(--accent-text)}.runid{font:12px var(--mono);color:var(--muted);border:1px solid var(--divider);border-radius:5px;background:var(--soft);padding:4px 7px}.funnel{display:grid;gap:7px}.funnel button{display:grid;grid-template-columns:83px minmax(0,1fr) 55px;width:100%;border:0;background:none;padding:5px 0;min-height:25px;text-align:left;gap:6px;font-size:.81rem;font-weight:500}.track{height:12px;position:relative;background:var(--soft);border-radius:3px;overflow:hidden}.track i{height:100%;display:block;border-radius:3px;background:var(--bar,var(--funnel-4))}.funnel .mono{text-align:right}.note{border-top:1px solid var(--divider);margin-top:14px;padding-top:12px;color:var(--muted);font-size:.79rem}.dec-row{display:flex;gap:12px;align-items:center;padding:10px 0;border-top:1px solid var(--divider)}.dec-row:first-of-type{border:0}.dec-row div{flex:1;min-width:0}.dec-row b{font-size:.875rem;display:block}.dec-row p{font-size:.79rem;color:var(--muted);margin-top:2px}.mark{width:33px;height:33px;border-radius:9px;display:grid;place-items:center;flex-shrink:0;font-weight:700;font-family:var(--mono);font-size:14px}.mark.a,.tone-pass{background:var(--ok-bg);color:var(--ok-fg)}.mark.b,.tone-block{background:var(--warn-bg);color:var(--warn-fg)}.mark.c,.tone-review{background:var(--neutral-bg);color:var(--neutral-fg)}.mark.d{background:var(--violet-bg);color:var(--violet-fg)}.badge{display:inline-flex;align-items:center;gap:5px;padding:4px 8px;font-size:.75rem;border-radius:6px;white-space:nowrap;font-weight:650}.badge .ico{width:13px;height:13px}.scroller{overflow:auto}.gridtable{width:100%;border-collapse:collapse;font-size:.875rem;text-align:left}.gridtable th,.gridtable td{padding:12px 10px;border-bottom:1px solid var(--divider);vertical-align:middle}.gridtable th{background:var(--soft);color:var(--muted);font-size:.76rem;font-weight:600;white-space:nowrap}.gridtable tr:last-child td{border-bottom:0}.gridtable .name{display:flex;align-items:center;gap:10px;white-space:nowrap}.name b{font-size:.875rem}.name small{display:block;margin-top:2px}.filters{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:16px}.field{display:grid;gap:6px;align-content:start;min-width:0;font-size:.86rem;font-weight:600}.field small{font-weight:400}.field input,.field select,.field textarea,.filters input,.filters select,.select{border:1px solid var(--line);background:var(--panel);border-radius:7px;padding:9px 11px;min-width:0;width:100%;font-size:.9rem}.filters input,.filters select{width:auto;max-width:100%}input[type=checkbox]{accent-color:var(--primary)}select{appearance:none;padding-right:30px!important;background-image:url("data:image/svg+xml,%3Csvg width='16' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m4 4 4 4 4-4' fill='none' stroke='%23556b88' stroke-width='1.5'/%3E%3C/svg%3E")!important;background-repeat:no-repeat!important;background-position:right 8px center!important}.twocol{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.form{display:grid;gap:14px}.chips{display:flex;gap:7px;flex-wrap:wrap}.chip,.toggle{border:1px solid var(--line);border-radius:7px;background:var(--soft);font-size:.82rem;padding:6px 10px}.toggle.on{background:var(--hover);border-color:var(--accent-line);color:var(--accent-text)}.pager{display:flex;align-items:center;justify-content:flex-end;gap:12px;margin-top:13px}.pager button{padding:4px 10px;min-height:32px}.empty{padding:20px;background:var(--soft);color:var(--muted);border-radius:8px;font-size:.9rem}.break{overflow-wrap:anywhere;white-space:pre-wrap}.code{font:13px/1.6 var(--mono);white-space:pre-wrap;word-break:break-word}.lineentry{padding:13px 0;border-bottom:1px solid var(--divider)}.lineentry:last-child{border:0}.lineentry h3{margin-bottom:5px}.flow{display:grid;gap:10px}.flow .dec-row{border:1px solid var(--line);border-radius:9px;padding:12px}.callout{border:1px solid var(--accent-line);background:var(--accent-wash);border-radius:9px;padding:13px 15px;color:var(--accent-text);font-size:.89rem;line-height:1.6}.danger{color:var(--warn-fg)}.err{color:var(--danger);font-size:.875rem;line-height:1.5}.checks{display:flex;align-items:center;gap:8px;font-size:.875rem}.gaprow{display:grid;grid-template-columns:77px 1fr 104px;align-items:center;gap:9px;margin:14px 0;font-size:.86rem}.gaprow .mono{text-align:right}.footnote{font-size:.78rem;color:var(--muted);margin-top:10px}.qa{background:var(--accent-wash);border:1px solid var(--accent-line);border-radius:9px;padding:15px;margin:14px 0}.qa h3{margin-bottom:6px}.qa p{font-size:.9rem}.qa input{width:100%}dialog{width:min(690px,calc(100% - 24px));padding:0;border:1px solid var(--line);border-radius:15px;max-height:86dvh;color:var(--ink);}dialog::backdrop{background:#081225a6}dialog header{position:sticky;top:0;background:var(--panel);z-index:2;padding:17px 20px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--line)}dialog header button{min-height:30px;padding:3px 8px;font-size:1.25rem}dialog .modalbody{padding:20px}dialog .end{border-top:1px solid var(--line);padding-top:12px;display:flex;justify-content:flex-end;gap:8px}.upload{display:grid;place-items:center;gap:8px;padding:22px 15px;border:1.5px dashed var(--accent-line);border-radius:10px;background:var(--accent-wash);text-align:center}.upload input{max-width:100%;font-size:.86rem}.skip{position:absolute;left:-9999px}.skip:focus{left:8px;top:8px;background:var(--panel);padding:8px;z-index:20}.boot{padding:36px}.hidden,[hidden]{display:none!important}#toast{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);color:var(--primary-ink);background:var(--primary);border-radius:8px;padding:10px 16px;z-index:20;font-size:.875rem;max-width:90vw}#toast:empty{display:none}.longtext{max-width:370px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.wrap{overflow-wrap:anywhere}.reviewnote{padding:10px 0;color:var(--muted);font-size:.84rem}.form h3{margin-top:6px}.kv{margin:0;display:grid;grid-template-columns:100px 1fr;gap:8px;font-size:.875rem}.kv dt{color:var(--muted)}.kv dd{margin:0;overflow-wrap:anywhere}.layout-main{min-height:66vh} +@media(min-width:1600px){.app{grid-template-columns:245px minmax(0,1fr)}.kpi{padding:20px 23px}.hero{padding:31px 36px}.panel{padding:24px}} +@media(max-width:1200px){.app{grid-template-columns:188px minmax(0,1fr)}.side{padding-left:10px;padding-right:10px}.main{padding-left:22px;padding-right:22px}.kpi .ico-box{padding:5px}.grid2{grid-template-columns:1fr 1fr}.hero-side{min-width:185px}} +@media(max-width:980px){.app{grid-template-columns:160px minmax(0,1fr)}.brand{font-size:19px;padding:0 3px}.brand img{width:28px;height:28px}.side nav a{padding:10px;gap:8px}.grid2{grid-template-columns:1fr}.kpi .ico-box{display:none}.hero-side{min-width:110px}.hero-key{display:none}.pagehead{align-items:flex-start}.hero{padding:22px}.actions{justify-content:flex-end}.actions button{padding:8px 10px}.top{padding:0 22px}} +@media(max-width:730px){.app{display:block}.side{display:none}.side.open{display:flex;position:fixed;inset:55px auto 0 0;width:230px;height:calc(100dvh - 55px);}.mobile{display:inline-flex;padding:4px;min-height:32px}.top{height:55px;padding:0 14px}.main{padding:18px 14px 36px}.topright .sync-text{display:none}.pagehead{flex-wrap:wrap;gap:12px;margin-bottom:15px}.actions{justify-content:flex-start}.hero{padding:19px 17px;gap:7px;margin-bottom:12px}.hero-side{min-width:auto;padding:0}.ring{width:74px;height:74px}.ring>div{width:58px;height:58px}.ring b{font-size:20px}.ring small{font-size:9px}.hero p{font-size:.8rem}.hero h2{font-size:1.35rem}.hero .tags{gap:5px;margin-top:9px}.hero .tags span{padding:3px 5px}.kpis{grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;margin-bottom:12px}.kpi{padding:12px}.kpi b{margin:5px 0}.kpi .ico-box{display:grid;top:10px;right:10px}.grid2{gap:12px;margin-bottom:12px}.panel{padding:15px;margin-bottom:12px}.panel-head{align-items:flex-start}.twocol{grid-template-columns:1fr}.gridtable th,.gridtable td{padding:9px 7px}.topright{gap:4px}.funnel button{grid-template-columns:84px minmax(0,1fr) 50px}.kv{grid-template-columns:76px 1fr}.gaprow{grid-template-columns:70px 1fr 95px}.longtext{max-width:200px}} +.brand{gap:8px}.brand>span{display:inline-flex;align-items:center;gap:6px;white-space:nowrap}.brand b{line-height:1.1}.goal-row{display:grid;grid-template-columns:1.2fr 1fr 1fr auto;gap:8px;align-items:end}.goal-row .field{font-size:.8rem}.goal-row button{padding:6px}.workspace-note{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:.8rem}.mix-footer{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:15px}@media(max-width:730px){.goal-row{grid-template-columns:minmax(0,1.2fr) minmax(0,1fr) minmax(0,.8fr) auto}.goal-row input{padding:8px 5px}} + +/* Flat surfaces and solid chart marks share the same theme colors. */ +body { background: var(--canvas); } + +html[lang="en"] .skip [lang="zh-CN"], html[lang="en"] .boot [lang="zh-CN"], +html[lang="zh-CN"] .skip [lang="en"], html[lang="zh-CN"] .boot [lang="en"] { display:none; } +.side { border-right: 1px solid var(--line); } + +.side nav a { min-height:44px; } +.side nav a span { line-height:1.35; } +.brand img { width:36px;height:36px;border-radius:11px; } +.side-title { letter-spacing:.055em; } +.top { min-height:65px;height:auto;gap:12px;padding-block:10px;background:var(--panel); } +.crumb-root,.sync-text { display:inline-flex; align-items:center; gap:7px; } +.crumb { min-width:0; } +.crumb strong { overflow:hidden;text-overflow:ellipsis;white-space:nowrap; } +.topright { flex-shrink:0;gap:8px; } +.sync-text { margin-right:9px;font-size:.78rem; } +.language-picker { display:inline-flex;align-items:center;gap:2px;background:var(--soft);border:1px solid var(--line);border-radius:10px;padding:3px; } +.language-picker button { min-height:30px;min-width:36px;padding:3px 8px;background:none;border:0;border-radius:7px;color:var(--muted);font-size:.81rem;line-height:1.2; } +.language-picker [aria-pressed="true"] { color:var(--accent-text);background:var(--panel); } +.language-picker button:hover,.theme-control:hover { background:var(--accent-wash); } +.theme-control { height:38px;padding:5px 10px;border-radius:10px;min-width:40px;gap:6px; } +.theme-control .ico { color:var(--accent-text); } +.hero { padding:28px 32px; } + + + +.hero .eyebrow { letter-spacing:.07em;font-size:.8rem; } + +.hero-key { min-width:98px; } +.hero-side { gap:18px; } +.hero .ring {width:108px;height:108px;} +.ring>div { width:84px;height:84px; } +.eyeline>.ico { width:18px;height:18px; } +.panel-head h2,.pagehead h1 { line-height:1.25; } +.kpi .label {display:block;padding-right:30px;} +.kpi:nth-child(2) .ico-box {background:var(--ok-bg);color:var(--ok-fg);} +.kpi:nth-child(4) .ico-box {background:var(--violet-bg);color:var(--violet-fg);} +.track {border-radius:5px;} +.track i {border-radius:5px;} +.gridtable tr:hover td {background:var(--soft);} +.gridtable th {padding-block:10px;} +input,textarea { caret-color:var(--primary); } +input::placeholder,textarea::placeholder { color:var(--muted);opacity:.85; } +dialog header { border-radius:15px 15px 0 0; } +dialog { background:var(--panel); } +dialog::backdrop { background-color:#081225a6; } +select { background-image:url("data:image/svg+xml,%3Csvg width='16' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m4 4 4 4 4-4' fill='none' stroke='%23556b88' stroke-width='1.6'/%3E%3C/svg%3E")!important; } +:root[data-theme="dark"] select { background-image:url("data:image/svg+xml,%3Csvg width='16' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='m4 4 4 4 4-4' fill='none' stroke='%23adbed8' stroke-width='1.6'/%3E%3C/svg%3E")!important; } +html[lang="en"] .funnel button { grid-template-columns:106px minmax(0,1fr) 56px; } +html[lang="en"] .gaprow { grid-template-columns:minmax(90px,1fr) minmax(30px,2fr) auto; } +html[lang="en"] .badge { font-size:.74rem; } +@media(max-width:1120px){.sync-text{display:none;} .hero{padding:24px;}} +@media(max-width:980px){.kpi .label{padding-right:0;} .side nav a{font-size:.86rem;}.hero .ring{width:90px;height:90px;}.ring>div{width:70px;height:70px;}} +@media(max-width:730px){ + .top{min-height:55px;padding:7px 12px;}.topright{gap:5px;}.crumb{gap:6px;}.crumb-root,.crumb .slash{display:none;} + .side.open{top:55px;}.language-picker button{min-width:34px;}.theme-control span{display:none;} + .hero{padding:18px;gap:12px;}.hero .ring{width:70px;height:70px;}.ring>div{width:54px;height:54px;} + .hero-side{min-height:85px;}.hero>div:first-child{min-width:0;}.hero h2{overflow-wrap:anywhere;}.kpi .label{padding-right:23px;} + .pagehead .actions button{min-height:40px;}.gridtable .name{white-space:normal;}.gridtable th{white-space:normal;} + html[lang="en"] .panel-head{flex-wrap:wrap;} .hero .tags{gap:4px;} .hero .tags span{font-size:.68rem;} +} +@media(max-width:390px){.kpis{gap:7px;}.kpi .ico-box{display:none;}.kpi .label{padding-right:0;}.hero .ring{width:59px;height:59px;}.ring>div{width:45px;height:45px;}.theme-control{padding:4px;min-width:32px;}.crumb strong{max-width:112px;}} + +.side { overflow-y:auto; } +.side-foot { flex-shrink:0; } + +#modal.evidence-drawer { + position: fixed; + inset: 0 0 0 auto; + margin: 0; + width: min(39rem, 100%); + max-width: 100vw; + height: 100dvh; + max-height: 100dvh; + border-radius: 0; + border: 0; + border-left: 1px solid var(--line); +} +#modal.evidence-drawer[open] { display: flex; flex-direction: column; } +#modal.evidence-drawer header { flex-shrink: 0; border-radius: 0; } +#modal.evidence-drawer .modalbody { overflow-y: auto; max-height: none; } +.evidence-body details { padding: 0.8rem; border: 1px solid var(--line); border-radius: 0.5rem; } +.evidence-body summary { cursor: pointer; font-weight: 600; } +.qa .chips { margin-top: 0.6rem; } + +.demo-links {display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin:0 0 1rem;} +.demo-links strong {margin-inline-end:.4rem;color:var(--ink);font-size:.9rem;} +.demo-links .btn {background:var(--accent-wash);border-color:var(--accent-line);color:var(--accent-text);} +.demo-links .btn:hover {background:var(--panel);} +.tour-highlight {outline:3px solid var(--accent-text);outline-offset:3px;border-radius:.45rem;scroll-margin-block:5rem;} +.hero p strong {font-weight:600;} +.tour-next {position:sticky;bottom:0;padding:.65rem 0;margin-top:1rem;background:var(--panel);border-top:1px solid var(--line);z-index:2;text-align:right;} diff --git a/dist/assets/supplier.js b/dist/assets/supplier.js new file mode 100644 index 0000000..43c2b82 --- /dev/null +++ b/dist/assets/supplier.js @@ -0,0 +1,195 @@ +import {analyze, contentKey, norm} from './engine.js'; +import {scanRows, ruleVersion} from './deep-scan.js'; +import {language, evidenceLabel} from './locale.js'; +import {maskText, sensitiveFields} from './pii.js'; +import {btn, csv, download, empty, esc, pane, runName, table, td} from './ui.js'; +import {zipTextFiles} from './training-zip.js'; + +const t = (zh,en) => language()==='en' ? en : zh; +const percent = n => n==null ? '—' : (100*n).toFixed(1)+'%'; +const demoVendors = new Map([['Batch-A · Value Desk','Value Desk'],['Batch-B · Route Desk','Route Desk'],['Batch-C · Account Escalations','Account Escalations']]); +function authoredFixture(d) { + return d.source==='DataLens · 项目编写 / Authored fixture' && demoVendors.has(d.name); +} + +export function supplierName(d) { + if (!d) return ''; + if (String(d.supplier||'').trim()) return String(d.supplier).trim(); + if (authoredFixture(d)) return demoVendors.get(d.name); + return ''; +} + +export function supplierInput(d) { + return ''; +} + +const profileCache = new WeakMap(); +export function supplierHistory(state, through=Infinity) { + let cache=profileCache.get(state); + if (!cache) { cache=new Map(); profileCache.set(state,cache); } + if (cache.has(through)) return cache.get(through); + const profiles=new Map(), deliveries=new Set(); + for (const run of state.runs) { + if (run.n>through) break; + let owned; + for (const id of run.ids) { + const d=state.versions[id]; + if (!d || d.parent) continue; + // Opening the built-in case again creates new snapshot IDs for the same fictional delivery. + const key=authoredFixture(d) ? 'fixture:'+d.name : 'delivery:'+d.id; + if (deliveries.has(key)) continue; + deliveries.add(key); + const supplier=supplierName(d); + if (!supplier) continue; + owned ??= new Set((run.task.procurement?.history?.rows||[]).map(contentKey)); + const r=analyze(d,run.task); + const duplicateRows=r.excluded.duplicate+r.valid.filter(i=>owned.has(contentKey(d.rows[i]))).length; + const eligible=r.stages[2]; + const supplierKey=norm(supplier); + let profile=profiles.get(supplierKey); + if (!profile) { + profile={supplier,deliveries:0,passed:0,leakedDeliveries:0,leakedRows:0, + duplicateRateSum:0,measuredDeliveries:0,latest:run.at,latestBatch:d.name}; + profiles.set(supplierKey,profile); + } + profile.deliveries++; + if (r.status==='pass') profile.passed++; + if (r.excluded.overlap) profile.leakedDeliveries++; + profile.leakedRows+=r.excluded.overlap; + if (eligible) { + profile.duplicateRateSum+=duplicateRows/eligible; + profile.measuredDeliveries++; + } + profile.latest=run.at; + profile.latestBatch=d.name; + } + } + const result=[...profiles.values()].map(p=>({...p,firstPassRate:p.passed/p.deliveries, + meanDuplicateRate:p.measuredDeliveries ? p.duplicateRateSum/p.measuredDeliveries : null})); + cache.set(through,result); + return result; +} + +export function supplierHistoryPane(state, through) { + const profiles=supplierHistory(state,through); + return pane(t('供应商历史表现','Supplier track record'),'history', + (profiles.length ? table([t('供应商','Supplier'),t('首次交付批次','First deliveries'),t('平均重复率','Mean duplicate rate'), + t('评测题重合','Benchmark overlap'),t('一次通过率','First-pass rate')], + profiles.map(p=>td(esc(p.supplier),p.deliveries,percent(p.meanDuplicateRate), + p.leakedRows+t(' 条,涉及 ',' rows across ')+p.leakedDeliveries+t(' 批',' deliveries'), + percent(p.firstPassRate)+' ('+p.passed+'/'+p.deliveries+')'))) : empty(t('导入时填写供应商名称,即可积累该供应商的验收记录。','Name a supplier when importing a delivery to start its track record.'))) + + ''+t('每批按首次交付时的标准统计一次。重复率按批取平均,分母是字段完整且语言符合要求的行数,重复包括批内和历史库精确重复。评测题重合统计去重后与完整评测题一致的样本。','Each delivery is assessed once under its original requirements. Duplicate rates include exact in-batch and inventory matches among complete, language-matching rows, averaged across measurable batches. Benchmark counts refer to distinct usable rows matching complete prompts.')+'
'); +} + +export function supplierRiskNotice(state, through) { + const profiles=supplierHistory(state,through); + const risks=profiles.filter(p=>p.passed'+esc(p.supplier)+' · '+t('首次验收通过 ','Passed on first delivery ')+p.passed+'/'+p.deliveries+ + (p.leakedRows?' · '+t('评测题重合 ','Benchmark overlaps ')+p.leakedRows:'')+ + (p.meanDuplicateRate>=0.5?' · '+t('平均重复率 ','Mean duplicate rate ')+percent(p.meanDuplicateRate):'')+'
').join('')+''+t('按批次下载通知单、逐行问题清单和脱敏示例,供供应商核对后重新交付。','Download a notice, row-by-row findings and masked examples for a supplier to review and resubmit.')+'
'+ + ds.map(d=>''+t('按历史库与所选批次去重。导出占比高于需求占比至少 15 个百分点时提示复核。','Counts include deduplicated history and selected batches. A warning appears at 15 percentage points above the goal share.')+'
'+ + ''+t('回复平均长度(字符)','Mean reply length (characters)')+' · '+t('历史库','History')+' '+(h===null?'—':h.toFixed(1))+' (n='+history.n+') · '+t('新增','New')+' '+(a===null?'—':a.toFixed(1))+' (n='+added.n+')'+ + (drift?' · '+t('新增回复均长达到历史库的 ','New replies average ')+(a/h).toFixed(1)+t(' 倍,请复核训练风格。','× the baseline; review the style shift.')+'':'')+'
'+ + ''+t('验证集仅包含明确标注为真实的样本。含合成或来源未知样本的问题组只能进入训练集。','Validation uses explicitly real rows only. Prompt groups with synthetic or unknown rows stay in training.')+'
'+ + pressure.map(([scene,ratio])=>''+esc(intent(scene))+' · '+t('若保持原总量,目标配比需平均使用每条样本 ','Maintaining the original size would require average reuse of ')+ratio.toFixed(2)+'×。'+t('当前按无放回采样缩减总量,每条最多使用一次。',' Actual sampling shrinks the export and uses each row at most once.')+'
').join('')+ + ''+t('训练集','Train')+' '+split.train.length+' · '+t('验证集','Validation')+' '+split.val.length+' · '+t('唯一问题','Distinct prompts')+' '+split.groups+'
'+ + (split.groups===1&&options.validationPercent>0?''+t('只有一组问题,全部保留在训练集。','A single prompt group stays in training.')+'
':'')+ + ''+t('导出前按当前设置额外排除 ','Additional rows excluded by the export settings: ')+excluded+t(' 条。',' rows.')+'
'+ + ''; +} + +export function trainingPanel(ds,rs,mix,run) { + const key=JSON.stringify([run.n,run.at]); + if (key!==settingsKey) {settingsKey=key;options={format:'ChatML',validationPercent:10,seed:42,filterFlagged:true,weights:Object.create(null)};} + const entries=mixLineage(ds,rs,mix,run.task).records; + return renderPanel(entries,run,mix); +} + +function renderPanel(entries,run,mix) { + const pool=trainingPool(entries,run.task,options.filterFlagged); + current={pool,run,entries,selection:[...mix]}; + const controls=[...pool.counts].map(([scene,n])=>'').join(''); + return pane(t('训练配比与导出','Training mix and export'),'download',''+t('默认保留全部样本。权重 2:1 表示希望两种场景按 2:1 分布。系统按现有数量向下取整,不重复抽取;填 0 可排除该场景。同一问题的不同回复始终划入同一集合。','Default weights retain all rows. A 2:1 ratio requests twice as many samples from one scene. Available counts cap the sample, rounded down without replacement. Zero omits a scene. Replies to the same normalized question always stay together.')+ + '
| '+esc(x)+' | ').join('')+'
|---|
正在载入数据工作台…Loading workspace…
{if((t.scaleMode!=0||t.canvasResolutionScaleMode!=0)&&JSEvents_resizeCanvasForFullscreen(e,t),e.requestFullscreen)e.requestFullscreen();else if(e.webkitRequestFullscreen)e.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);else return JSEvents.fullscreenEnabled()?-3:-1;return currentFullscreenStrategy=t,t.canvasResizedCallback&&getWasmTableEntry(t.canvasResizedCallback)(37,0,t.canvasResizedCallbackUserData),0},hideEverythingExceptGivenElement=e=>{for(var t=e,r=t.parentNode,n=[];t!=document.body;){for(var a=r.children,o=0;o p*_&&(l=_*p/m|0),f=(c-_)/2|0),n&&(setCanvasElementSize(u,l,_),u.GLctxObject&&u.GLctxObject.GLctx.viewport(0,0,l,_)),t&&(f/=e,l/=e,_/=e,l=Math.round(l*1e4)/1e4,_=Math.round(_*1e4)/1e4,f=Math.round(f*1e4)/1e4),a){var g=(innerHeight-jstoi_q(u.style.height))/2,h=(innerWidth-jstoi_q(u.style.width))/2;setLetterbox(u,g,h)}else{u.style.width=l+"px",u.style.height=_+"px";var h=(innerWidth-l)/2;setLetterbox(u,f,h)}!a&¤tFullscreenStrategy.canvasResizedCallback&&getWasmTableEntry(currentFullscreenStrategy.canvasResizedCallback)(37,0,currentFullscreenStrategy.canvasResizedCallbackUserData)},doRequestFullscreen=(e,t)=>JSEvents.fullscreenEnabled()?(e=findEventTarget(e),e?!e.requestFullscreen&&!e.webkitRequestFullscreen?-3:JSEvents.canPerformEventHandlerRequests()?JSEvents_requestFullscreen(e,t):t.deferUntilInEventHandler?(JSEvents.deferCall(JSEvents_requestFullscreen,1,[e,t]),1):-2:-4):-1;function _emscripten_request_fullscreen(e,t){e>>>=0;var r={scaleMode:0,canvasResolutionScaleMode:0,filteringMode:0,deferUntilInEventHandler:t,canvasResizedCallbackTargetThread:2};return doRequestFullscreen(e,r)}_emscripten_request_fullscreen.sig="ipi";function _emscripten_request_fullscreen_strategy(e,t,r){e>>>=0,r>>>=0;var n={scaleMode:HEAP32[r>>>2>>>0],canvasResolutionScaleMode:HEAP32[r+4>>>2>>>0],filteringMode:HEAP32[r+8>>>2>>>0],deferUntilInEventHandler:t,canvasResizedCallback:HEAP32[r+12>>>2>>>0],canvasResizedCallbackUserData:HEAP32[r+16>>>2>>>0]};return doRequestFullscreen(e,n)}_emscripten_request_fullscreen_strategy.sig="ipip";function _emscripten_enter_soft_fullscreen(e,t){if(e>>>=0,t>>>=0,e=findEventTarget(e),!e)return-4;var r={scaleMode:HEAP32[t>>>2>>>0],canvasResolutionScaleMode:HEAP32[t+4>>>2>>>0],filteringMode:HEAP32[t+8>>>2>>>0],canvasResizedCallback:HEAP32[t+12>>>2>>>0],canvasResizedCallbackUserData:HEAP32[t+16>>>2>>>0],target:e,softFullscreen:!0},n=JSEvents_resizeCanvasForFullscreen(e,r);document.documentElement.style.overflow="hidden",document.body.scroll="no",document.body.style.margin="0px";var a=hideEverythingExceptGivenElement(e);function o(){n(),restoreHiddenElements(a),removeEventListener("resize",softFullscreenResizeWebGLRenderTarget),r.canvasResizedCallback&&getWasmTableEntry(r.canvasResizedCallback)(37,0,r.canvasResizedCallbackUserData),currentFullscreenStrategy=0}return restoreOldWindowedStyle=o,currentFullscreenStrategy=r,addEventListener("resize",softFullscreenResizeWebGLRenderTarget),r.canvasResizedCallback&&getWasmTableEntry(r.canvasResizedCallback)(37,0,r.canvasResizedCallbackUserData),0}_emscripten_enter_soft_fullscreen.sig="ipp";var _emscripten_exit_soft_fullscreen=()=>(restoreOldWindowedStyle?.(),restoreOldWindowedStyle=null,0);_emscripten_exit_soft_fullscreen.sig="i";var _emscripten_exit_fullscreen=()=>{if(!JSEvents.fullscreenEnabled())return-1;JSEvents.removeDeferredCalls(JSEvents_requestFullscreen);var e=specialHTMLTargets[1];if(e.exitFullscreen)e.fullscreenElement&&e.exitFullscreen();else if(e.webkitExitFullscreen)e.webkitFullscreenElement&&e.webkitExitFullscreen();else return-1;return 0};_emscripten_exit_fullscreen.sig="i";var fillPointerlockChangeEventData=e=>{var t=document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement||document.msPointerLockElement,r=!!t;HEAP8[e>>>0]=r;var n=JSEvents.getNodeNameForTarget(t),a=t?.id||"";stringToUTF8(n,e+1,128),stringToUTF8(a,e+129,128)},registerPointerlockChangeEventCallback=(e,t,r,n,a,o,c)=>{JSEvents.pointerlockChangeEvent||(JSEvents.pointerlockChangeEvent=_malloc(257));var l=(u=event)=>{var d=JSEvents.pointerlockChangeEvent;fillPointerlockChangeEventData(d),getWasmTableEntry(n)(a,d,t)&&u.preventDefault()},_={target:e,eventTypeString:o,callbackfunc:n,handlerFunc:l,useCapture:r};return JSEvents.registerOrRemoveHandler(_)};function _emscripten_set_pointerlockchange_callback_on_thread(e,t,r,n,a){return e>>>=0,t>>>=0,n>>>=0,a>>>=0,!document||!document.body||!document.body.requestPointerLock&&!document.body.mozRequestPointerLock&&!document.body.webkitRequestPointerLock&&!document.body.msRequestPointerLock?-1:(e=findEventTarget(e),e?(registerPointerlockChangeEventCallback(e,t,r,n,20,"mozpointerlockchange",a),registerPointerlockChangeEventCallback(e,t,r,n,20,"webkitpointerlockchange",a),registerPointerlockChangeEventCallback(e,t,r,n,20,"mspointerlockchange",a),registerPointerlockChangeEventCallback(e,t,r,n,20,"pointerlockchange",a)):-4)}_emscripten_set_pointerlockchange_callback_on_thread.sig="ippipp";var registerPointerlockErrorEventCallback=(e,t,r,n,a,o,c)=>{var l=(u=event)=>{getWasmTableEntry(n)(a,0,t)&&u.preventDefault()},_={target:e,eventTypeString:o,callbackfunc:n,handlerFunc:l,useCapture:r};return JSEvents.registerOrRemoveHandler(_)};function _emscripten_set_pointerlockerror_callback_on_thread(e,t,r,n,a){return e>>>=0,t>>>=0,n>>>=0,a>>>=0,!document||!document.body.requestPointerLock&&!document.body.mozRequestPointerLock&&!document.body.webkitRequestPointerLock&&!document.body.msRequestPointerLock?-1:(e=findEventTarget(e),e?(registerPointerlockErrorEventCallback(e,t,r,n,38,"mozpointerlockerror",a),registerPointerlockErrorEventCallback(e,t,r,n,38,"webkitpointerlockerror",a),registerPointerlockErrorEventCallback(e,t,r,n,38,"mspointerlockerror",a),registerPointerlockErrorEventCallback(e,t,r,n,38,"pointerlockerror",a)):-4)}_emscripten_set_pointerlockerror_callback_on_thread.sig="ippipp";function _emscripten_get_pointerlock_status(e){return e>>>=0,e&&fillPointerlockChangeEventData(e),!document.body||!document.body.requestPointerLock&&!document.body.mozRequestPointerLock&&!document.body.webkitRequestPointerLock&&!document.body.msRequestPointerLock?-1:0}_emscripten_get_pointerlock_status.sig="ip";var requestPointerLock=e=>{if(e.requestPointerLock)e.requestPointerLock();else return document.body.requestPointerLock?-3:-1;return 0};function _emscripten_request_pointerlock(e,t){return e>>>=0,e=findEventTarget(e),e?e.requestPointerLock?JSEvents.canPerformEventHandlerRequests()?requestPointerLock(e):t?(JSEvents.deferCall(requestPointerLock,2,[e]),1):-2:-1:-4}_emscripten_request_pointerlock.sig="ipi";var _emscripten_exit_pointerlock=()=>{if(JSEvents.removeDeferredCalls(requestPointerLock),document.exitPointerLock)document.exitPointerLock();else return-1;return 0};_emscripten_exit_pointerlock.sig="i";var _emscripten_vibrate=e=>navigator.vibrate?(navigator.vibrate(e),0):-1;_emscripten_vibrate.sig="ii";function _emscripten_vibrate_pattern(e,t){if(e>>>=0,!navigator.vibrate)return-1;for(var r=[],n=0;n