dsh-question-bank 1.0.0 → 1.1.0

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  面向 **DeepSeek Harness (DSH)** 的本地化教师题库登记插件。支持在桌面端通过 **截图粘贴、拖拽或拍照上传** 智能录题,自动完成 **去手写干扰、LaTeX 公式转写、章节归类、重复题拦截、矢量配图重绘** 与 **多维检索校对**,所有题目与图片均安全保存在本机 SQLite 数据库中。
4
4
 
5
- > 本仓库为 **v1.0.0**(专注「题库登记与整理」核心闭环);学生错题人关联、错因统计与卷面组卷等能力规划在 **v2.0** 拓展。
5
+ > 当前版本为 **v1.1.0**(专注「题库登记与整理」核心闭环);学生错题人关联、错因统计与卷面组卷等能力规划在 **v2.0** 拓展。
6
6
 
7
7
  ---
8
8
 
@@ -98,13 +98,15 @@ dsh plugin --profile desktop add ./dsh-question-bank-1.0.0.tgz
98
98
 
99
99
  ## 开放给所有对话的 AI 工具
100
100
 
101
- 本插件向 DSH 注册了以下 7 个通用工具,在任意会话中均可直接口语指挥 AI 操作本地题库:
101
+ 本插件向 DSH 注册了以下 9 个通用工具,在任意会话中均可直接口语指挥 AI 操作本地题库:
102
102
 
103
103
  | 工具名 | 能力说明 |
104
104
  | :--- | :--- |
105
105
  | `qbank_context` | 获取当前教学目录、各章节题量、录题偏好及当前会话最近的图片附件 |
106
106
  | `qbank_manage_folders` | 批量创建「学科 / 教材 / 章节」路径、添加/重命名/删除目录节点 |
107
107
  | `qbank_check_duplicates` | 按章节、章节标签或知识点缩小范围,检测题库中完全相同或高度相似的题目 |
108
+ | `qbank_preview_crop` | 两步精准裁图预览:将 AI 初估红框放大并叠加外框 20 格 0–1000 蓝色标尺供目视自检修正 |
109
+ | `qbank_preview_svg` | SVG 重绘自检:将 AI 编写的矢量配图渲染为实际效果图供与原图逐项比对修正 |
108
110
  | `qbank_save` | 结构化批量入库(内置防重合并、同章递增编号、附图框选与矢量 SVG 重绘) |
109
111
  | `qbank_search` | 按章节、未归类、题型、知识点、编号或关键词检索试题 |
110
112
  | `qbank_get_question` | 读取单道试题的完整正文、答案、解析、附图与来源记录 |
@@ -116,7 +118,7 @@ dsh plugin --profile desktop add ./dsh-question-bank-1.0.0.tgz
116
118
 
117
119
  ```text
118
120
  dsh-question-bank/
119
- ├── host.js # DSH 宿主端:注册 7 个 AI 工具、本地 HTTP API、模型列表与会话调度
121
+ ├── host.js # DSH 宿主端:注册 9 个 AI 工具、本地 HTTP API、模型列表与会话调度
120
122
  ├── store.js # SQLite 数据层(schema v3 自动迁移、查重指纹、SVG 消毒、备份恢复)
121
123
  ├── cordis.patch.yml # DSH 插件装配与「题库登记助手」Agent Preset 配置
122
124
  ├── client/
package/client/client.js CHANGED
@@ -182,12 +182,29 @@ window.__ModuleLoader__.load({
182
182
  } catch { return '' }
183
183
  }
184
184
 
185
- function Figure({ box, source, className = '', onClick, title }) {
185
+ function Figure({ box, source, className = '', fixedHeight, maxWidth, maxHeight, onClick, title }) {
186
186
  const [left, top, width, height] = box
187
- const ratio = width * (source.width || 1) / (height * (source.height || 1))
187
+ const natW = width * (source.width || 1)
188
+ const natH = height * (source.height || 1)
189
+ const ratio = natW / Math.max(0.0001, natH)
190
+ const style = { aspectRatio: String(ratio) }
191
+ if (fixedHeight) {
192
+ const targetW = Math.max(48, Math.round(fixedHeight * ratio))
193
+ style.width = targetW + 'px'
194
+ style.maxWidth = '100%'
195
+ } else if (maxWidth || maxHeight) {
196
+ const baseW = source.width ? natW : 360
197
+ const baseH = source.height ? natH : baseW / ratio
198
+ const capW = maxWidth || 460
199
+ const capH = maxHeight || 240
200
+ const scale = Math.min(1.15, capW / Math.max(1, baseW), capH / Math.max(1, baseH))
201
+ const targetW = Math.max(120, Math.round(baseW * scale))
202
+ style.width = targetW + 'px'
203
+ style.maxWidth = '100%'
204
+ }
188
205
  return h('div', {
189
206
  className: 'nb-figure ' + className,
190
- style: { aspectRatio: String(ratio) },
207
+ style,
191
208
  onClick,
192
209
  title,
193
210
  },
@@ -300,18 +317,44 @@ window.__ModuleLoader__.load({
300
317
  const [edit, setEdit] = useState(null)
301
318
  const [compare, setCompare] = useState(false)
302
319
  const [figureMode, setFigureMode] = useState(false)
320
+ const [replaceIndex, setReplaceIndex] = useState(null)
303
321
  const [add, setAdd] = useState(false)
304
322
  const [redrawOpen, setRedrawOpen] = useState(false)
305
323
  const [confirmDelete, setConfirmDelete] = useState(false)
324
+ const [confirmDiscard, setConfirmDiscard] = useState(false)
306
325
  const source = item.sources.find(entry => entry.image)
307
326
  const figures = edit?.figures ?? item.figures
308
327
  const diagrams = edit?.diagrams ?? item.diagrams ?? []
309
328
  const field = (k, value) => setEdit(current => ({ ...current, [k]: value }))
329
+ const isDirty = Boolean(edit && (
330
+ (edit.chapter || '') !== (item.chapter || '') ||
331
+ (edit.title || '') !== (item.title || '') ||
332
+ (edit.stem || '') !== (item.stem || '') ||
333
+ (edit.type || '') !== (item.type || '') ||
334
+ (edit.tags || '') !== item.tags.join('、') ||
335
+ (edit.answer || '') !== (item.answer || '') ||
336
+ (edit.analysis || '') !== (item.analysis || '') ||
337
+ (edit.review || '') !== (item.review || '') ||
338
+ JSON.stringify(edit.figures ?? []) !== JSON.stringify(item.figures ?? []) ||
339
+ JSON.stringify(edit.diagrams ?? []) !== JSON.stringify(item.diagrams ?? [])
340
+ ))
310
341
 
311
342
  function enterEdit(withPhoto = false) {
312
343
  setEdit({ ...item, chapter: item.chapter ?? '', tags: item.tags.join('、'), diagrams: item.diagrams ?? [] })
313
344
  setCompare(withPhoto)
314
345
  }
346
+ function startRecrop(index = null) {
347
+ if (!edit) enterEdit(true)
348
+ else setCompare(true)
349
+ setReplaceIndex(index !== null ? index : (figures.length === 1 ? 0 : null))
350
+ setFigureMode(true)
351
+ }
352
+ async function removeDiagramDirect(index) {
353
+ const next = index === null ? [] : (item.diagrams ?? []).filter((_, p) => p !== index)
354
+ if (await mutate('update', { id: item.id, revision: item.revision, patch: { diagrams: next } }, '已移除重绘矢量图。')) {
355
+ refresh()
356
+ }
357
+ }
315
358
  async function save(markDone) {
316
359
  const patch = {
317
360
  chapter: edit.chapter || null, title: edit.title, stem: edit.stem, type: edit.type,
@@ -322,6 +365,7 @@ window.__ModuleLoader__.load({
322
365
  if (await mutate('update', { id: item.id, revision: edit.revision, patch }, markDone ? '已保存并标记为已核对。' : '题目已保存。')) {
323
366
  setEdit(null)
324
367
  setFigureMode(false)
368
+ setReplaceIndex(null)
325
369
  refresh()
326
370
  }
327
371
  }
@@ -329,7 +373,8 @@ window.__ModuleLoader__.load({
329
373
  return h('section', { className: 'nb-detail', 'aria-label': '题目详情' },
330
374
  h('div', { className: 'nb-detail-topbar' },
331
375
  btn(h(Fragment, null, h(Icon, { name: 'chevronLeft', size: 15 }), '返回题库'), () => {
332
- if (!edit || window.confirm('放弃这次修改?')) close()
376
+ if (!edit || !isDirty) close()
377
+ else setConfirmDiscard(true)
333
378
  }, { className: 'nb-ghost-btn' }),
334
379
  h('span', { className: 'nb-breadcrumb' }, pathFor(folders, item.chapter)),
335
380
  h('div', { className: 'nb-detail-top-actions' },
@@ -350,10 +395,25 @@ window.__ModuleLoader__.load({
350
395
  compare && source && h('div', { className: 'nb-card nb-original' },
351
396
  h('div', { className: 'nb-card-head' },
352
397
  h('div', { className: 'nb-card-title' }, h(Icon, { name: 'image', size: 15 }), h('h3', null, '来源原图')),
353
- edit && figures.length < 8 && btn(h(Fragment, null, h(Icon, { name: 'crop', size: 14 }), figureMode ? '取消框选' : '框选附图'),
354
- () => setFigureMode(!figureMode), { className: figureMode ? 'nb-primary nb-btn-sm' : 'nb-btn-soft nb-btn-sm' })),
355
- figureMode && h('p', { className: 'nb-inline-tip' }, '在原图上按住左键拖拽选框,松开后自动截取为附图。'),
356
- h(SourcePhoto, { source, figureMode, onFigure: box => { field('figures', [...figures, box]); setFigureMode(false) } })),
398
+ edit && (figures.length < 8 || replaceIndex !== null) && btn(h(Fragment, null, h(Icon, { name: 'crop', size: 14 }), figureMode ? '取消框选' : '框选附图'),
399
+ () => { setFigureMode(!figureMode); if (figureMode) setReplaceIndex(null) },
400
+ { className: figureMode ? 'nb-primary nb-btn-sm' : 'nb-btn-soft nb-btn-sm' })),
401
+ figureMode && h('p', { className: 'nb-inline-tip' },
402
+ replaceIndex !== null
403
+ ? '在原图上按住左键拖拽新选框,松开后将替换对应附图,完成后点击「保存修改」。'
404
+ : '在原图上按住左键拖拽选框,松开后自动截取为附图,完成后点击「保存修改」。'),
405
+ h(SourcePhoto, {
406
+ source, figureMode,
407
+ onFigure: box => {
408
+ if (replaceIndex !== null && replaceIndex >= 0 && replaceIndex < figures.length) {
409
+ field('figures', figures.map((old, idx) => idx === replaceIndex ? box : old))
410
+ } else {
411
+ field('figures', [...figures, box])
412
+ }
413
+ setFigureMode(false)
414
+ setReplaceIndex(null)
415
+ },
416
+ })),
357
417
 
358
418
  h('div', { className: 'nb-detail-main' },
359
419
  h('div', { className: 'nb-card nb-detail-card' },
@@ -388,7 +448,7 @@ window.__ModuleLoader__.load({
388
448
  h('div', { className: 'nb-actions' },
389
449
  h('button', { disabled: busy || !edit.stem.trim(), className: 'nb-primary' }, '保存修改'),
390
450
  item.review && btn('保存并标记已核对', () => save(true), { className: 'nb-btn-soft', disabled: busy || !edit.stem.trim() }),
391
- btn('取消', () => { setEdit(null); setFigureMode(false) }, { className: 'nb-ghost-btn' })))
451
+ btn('取消', () => { setEdit(null); setFigureMode(false); setReplaceIndex(null) }, { className: 'nb-ghost-btn' })))
392
452
  : h(Fragment, null,
393
453
  item.review && h('div', { className: 'nb-review-callout' },
394
454
  h(Icon, { name: 'alert', size: 15 }),
@@ -401,7 +461,9 @@ window.__ModuleLoader__.load({
401
461
  diagrams.length > 0 && h('div', { className: 'nb-figures-wrap' },
402
462
  h('div', { className: 'nb-subhead-row' },
403
463
  h('span', { className: 'nb-subhead' }, h(Icon, { name: 'sparkles', size: 13 }), ' AI 重绘纯净矢量图(' + diagrams.length + ')'),
404
- !edit && source && btn('对照原图', () => openLightbox({ title: '来源原图对照', image: source.image }), { className: 'nb-link-btn' })),
464
+ !edit && h('div', { className: 'nb-figure-acts' },
465
+ source && btn('对照原图', () => openLightbox({ title: '来源原图对照', image: source.image }), { className: 'nb-link-btn' }),
466
+ diagrams.length === 1 && btn('移除重绘图', () => removeDiagramDirect(0), { className: 'nb-link-btn nb-quiet-danger', disabled: busy, title: '撤回 AI 重绘矢量图,恢复显示原图裁切' }))),
405
467
  h('div', { className: 'nb-figures' }, diagrams.map((diagram, index) =>
406
468
  h('div', { key: index, className: 'nb-figure-item' },
407
469
  h(SvgDiagram, {
@@ -414,18 +476,40 @@ window.__ModuleLoader__.load({
414
476
  }),
415
477
  (diagram.caption || diagram.reason) && h('span', { className: 'nb-muted nb-diag-note' },
416
478
  [diagram.caption, diagram.reason && ('(' + diagram.reason + ')')].filter(Boolean).join(' ')),
417
- edit && btn('移除重绘图', () => field('diagrams', diagrams.filter((_, p) => index !== p)), { className: 'nb-btn-sm nb-ghost-btn' }))))),
418
-
419
- /* 原图裁切附图 */
420
- source && figures.length > 0 && h('div', { className: 'nb-figures-wrap' },
421
- h('div', { className: 'nb-subhead' }, '原图裁切附图(' + figures.length + ')'),
422
- h('div', { className: 'nb-figures' }, figures.map((box, index) =>
423
- h('div', { key: index, className: 'nb-figure-item' },
424
- h(Figure, {
425
- box, source, className: 'is-clickable', title: '点击放大查看',
426
- onClick: () => openLightbox({ title: '题目附图(点击可查看原图)', image: source.image, box, source }),
427
- }),
428
- edit && btn('移除', () => field('figures', figures.filter((_, position) => index !== position)), { className: 'nb-btn-sm nb-ghost-btn' }))))),
479
+ edit
480
+ ? btn('移除重绘图', () => field('diagrams', diagrams.filter((_, p) => index !== p)), { className: 'nb-btn-sm nb-ghost-btn' })
481
+ : diagrams.length > 1 && btn('移除此重绘图', () => removeDiagramDirect(index), { className: 'nb-link-btn nb-quiet-danger', disabled: busy }))))),
482
+
483
+ /* 原图裁切附图:已有 AI 矢量重绘图且非编辑态时默认折叠,避免重复杂乱;任何时候支持一键重新框选 */
484
+ source && figures.length > 0 && (diagrams.length > 0 && !edit
485
+ ? h('details', { className: 'nb-sub-disclosure' },
486
+ h('summary', null,
487
+ h('span', null, '原图裁切附图(' + figures.length + ')· 已由上方 AI 矢量图替代'),
488
+ h('span', { className: 'nb-sub-disclosure-hint' }, '展开查看 / 重新框选')),
489
+ h('div', { className: 'nb-sub-disclosure-body' },
490
+ h('div', { className: 'nb-subhead-row' },
491
+ h('span', { className: 'nb-muted' }, '如裁切偏差,可直接拖拽重新框选'),
492
+ btn(h(Fragment, null, h(Icon, { name: 'crop', size: 13 }), '重新框选'), () => startRecrop(null), { className: 'nb-link-btn' })),
493
+ h('div', { className: 'nb-figures' }, figures.map((box, index) =>
494
+ h('div', { key: index, className: 'nb-figure-item' },
495
+ h(Figure, {
496
+ box, source, maxWidth: 460, maxHeight: 240, className: 'is-clickable', title: '点击放大查看',
497
+ onClick: () => openLightbox({ title: '题目附图(点击可查看原图)', image: source.image, box, source }),
498
+ }),
499
+ figures.length > 1 && btn('重新框选此图', () => startRecrop(index), { className: 'nb-link-btn' }))))))
500
+ : h('div', { className: 'nb-figures-wrap' },
501
+ h('div', { className: 'nb-subhead-row' },
502
+ h('span', { className: 'nb-subhead' }, '原图裁切附图(' + figures.length + ')'),
503
+ btn(h(Fragment, null, h(Icon, { name: 'crop', size: 13 }), '重新框选'), () => startRecrop(null), { className: 'nb-link-btn' })),
504
+ h('div', { className: 'nb-figures' }, figures.map((box, index) =>
505
+ h('div', { key: index, className: 'nb-figure-item' },
506
+ h(Figure, {
507
+ box, source, maxWidth: 460, maxHeight: 240, className: 'is-clickable', title: '点击放大查看',
508
+ onClick: () => openLightbox({ title: '题目附图(点击可查看原图)', image: source.image, box, source }),
509
+ }),
510
+ edit && h('div', { className: 'nb-figure-acts' },
511
+ btn('重新框选', () => startRecrop(index), { className: 'nb-btn-sm nb-btn-soft' }),
512
+ btn('移除', () => field('figures', figures.filter((_, position) => index !== position)), { className: 'nb-btn-sm nb-ghost-btn' }))))))),
429
513
 
430
514
  source && !figures.length && !diagrams.length && !edit && h('div', { className: 'nb-collapsed-source' },
431
515
  h('span', { className: 'nb-muted' }, '本题为纯文字题,已收纳来源原图。'),
@@ -471,6 +555,14 @@ window.__ModuleLoader__.load({
471
555
  close: () => setRedrawOpen(false),
472
556
  onDone: () => { setRedrawOpen(false); refresh() },
473
557
  }),
558
+ confirmDiscard && h(ConfirmSheet, {
559
+ title: '放弃未保存的修改',
560
+ message: '当前编辑内容尚未保存,返回题库后本次修改将会丢失。',
561
+ confirmLabel: '放弃修改',
562
+ busy: false,
563
+ close: () => setConfirmDiscard(false),
564
+ onConfirm: () => { setConfirmDiscard(false); close() },
565
+ }),
474
566
  confirmDelete && h(ConfirmSheet, {
475
567
  title: '删除题目',
476
568
  message: '确定要删除「' + (item.title || item.code || '这道题') + '」吗?删除后将无法恢复。',
@@ -665,7 +757,7 @@ window.__ModuleLoader__.load({
665
757
  const [note, setNote] = useState('')
666
758
  const [options, setOptions] = useState({
667
759
  figures: true,
668
- redrawDirtyDiagrams: defaults.redrawDirtyDiagrams !== false,
760
+ redrawDirtyDiagrams: Boolean(defaults.redrawDirtyDiagrams),
669
761
  tags: Boolean(defaults.tags),
670
762
  answer: Boolean(defaults.answer),
671
763
  analysis: Boolean(defaults.analysis),
@@ -803,7 +895,7 @@ window.__ModuleLoader__.load({
803
895
  chapter: scopeMode === 'manual' ? chapterId : null,
804
896
  numbers: partial ? numbers : '',
805
897
  note: note.trim(),
806
- photo: { mediaType: file.type, data },
898
+ photo: { mediaType: file.type, name: file.name, data },
807
899
  })
808
900
  setRows([])
809
901
  sessionStorage.setItem('qbank.lastIntake', result.sessionId)
@@ -1091,11 +1183,13 @@ window.__ModuleLoader__.load({
1091
1183
  }
1092
1184
  useEffect(() => { load() }, [])
1093
1185
 
1186
+ const [confirmId, setConfirmId] = useState('')
1187
+
1094
1188
  async function remove(id) {
1095
- if (!window.confirm('确认删除这条重复题目?删除后不可撤销。')) return
1096
1189
  setBusyId(id)
1097
1190
  try {
1098
1191
  await api('delete', { id })
1192
+ setConfirmId('')
1099
1193
  onChanged()
1100
1194
  await load()
1101
1195
  } catch (e) { setErr(e.message) }
@@ -1128,10 +1222,15 @@ window.__ModuleLoader__.load({
1128
1222
  it.figureCount > 0 && h('span', { className: 'nb-ind' }, '附图 ' + it.figureCount)),
1129
1223
  h('p', { className: 'nb-dup-stem' }, it.title || it.stem)),
1130
1224
  h('div', { className: 'nb-dup-item-acts' },
1131
- btn('查看', () => { close(); openQuestion(it.id) }, { className: 'nb-btn-soft nb-btn-sm' }),
1132
- btn(h(Icon, { name: 'trash', size: 13 }), () => remove(it.id), {
1133
- className: 'nb-icon-btn-xs nb-danger-ico', disabled: busyId === it.id, title: '删除这条重复题', 'aria-label': '删除',
1134
- }))))))))
1225
+ confirmId === it.id
1226
+ ? h(Fragment, null,
1227
+ btn('确认删除', () => remove(it.id), { className: 'nb-danger-btn nb-btn-sm', disabled: busyId === it.id }),
1228
+ btn('取消', () => setConfirmId(''), { className: 'nb-ghost-btn nb-btn-sm', disabled: busyId === it.id }))
1229
+ : h(Fragment, null,
1230
+ btn('查看', () => { close(); openQuestion(it.id) }, { className: 'nb-btn-soft nb-btn-sm' }),
1231
+ btn(h(Icon, { name: 'trash', size: 13 }), () => setConfirmId(it.id), {
1232
+ className: 'nb-icon-btn-xs nb-danger-ico', disabled: busyId === it.id, title: '删除这条重复题', 'aria-label': '删除',
1233
+ })))))))))
1135
1234
  }
1136
1235
 
1137
1236
  /* ---------------- Main Notebook Application ---------------- */
@@ -1518,6 +1617,7 @@ window.__ModuleLoader__.load({
1518
1617
  h('span', { className: 'nb-media-zoom' }, h(Icon, { name: 'zoomIn', size: 12 })))))
1519
1618
  }
1520
1619
  const src = question.previewSource
1620
+ const rowHeight = compactList ? 68 : 88
1521
1621
  return h('div', { className: compactList ? 'nb-list-figures-row' : 'nb-card-figures-row' },
1522
1622
  question.figures.slice(0, 4).map((box, idx) =>
1523
1623
  h('div', {
@@ -1529,7 +1629,7 @@ window.__ModuleLoader__.load({
1529
1629
  },
1530
1630
  title: '点击放大查看',
1531
1631
  },
1532
- h(Figure, { box, source: src, className: 'nb-card-fig' }),
1632
+ h(Figure, { box, source: src, fixedHeight: rowHeight, className: 'nb-card-fig' }),
1533
1633
  h('span', { className: 'nb-media-zoom' }, h(Icon, { name: 'zoomIn', size: 12 })))),
1534
1634
  question.figures.length > 4 && h('span', { className: 'nb-more-figs' }, '+' + (question.figures.length - 4) + ' 张附图'))
1535
1635
  }
@@ -1638,7 +1738,7 @@ window.__ModuleLoader__.load({
1638
1738
  h('div', { className: 'nb-card-title' }, h(Icon, { name: 'sliders', size: 15 }), h('h3', null, '录题偏好'))),
1639
1739
  [
1640
1740
  ['autoChapter', '收录范围默认由 AI 自动判断章节', '开启后录题无需手动选章节,由模型按现有目录自动归类;无匹配章节自动存入「未归类」。录题时可随时切回手动指定'],
1641
- ['redrawDirtyDiagrams', '图形含辅助线 / 涂鸦 / 倾斜时自动代码重绘', '当检测到题目配图上有学生手绘辅助线、批改笔迹或拍照倾斜时,保留原图同时用矢量 SVG 代码重绘干净配图'],
1741
+ ['redrawDirtyDiagrams', '录题时自动尝试矢量重绘脏图(默认关闭)', '开启后仅在简单图形被手写涂鸦严重遮挡时由 AI 重绘 SVG;立体几何或干净原图建议保持关闭,优先使用原图精裁,需要时再在详情页手动点「AI 重绘配图」'],
1642
1742
  ['tags', '自动推荐知识点', '识别题目时由模型自动标注相关知识点标签'],
1643
1743
  ['answer', '自动生成参考答案', '入库时同步生成 AI 参考答案,可在详情页修改'],
1644
1744
  ['analysis', '自动生成解题解析', '入库时同步生成解题思路,备课讲评按需展开'],
@@ -1648,7 +1748,7 @@ window.__ModuleLoader__.load({
1648
1748
  h('strong', null, title),
1649
1749
  h('span', null, desc)),
1650
1750
  h(Switch, {
1651
- checked: (setting === 'autoChapter' || setting === 'redrawDirtyDiagrams')
1751
+ checked: setting === 'autoChapter'
1652
1752
  ? overview.preferences[setting] !== false
1653
1753
  : Boolean(overview.preferences[setting]),
1654
1754
  disabled: busy,
@@ -1912,8 +1912,10 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
1912
1912
  }
1913
1913
  .nb-fig-tile {
1914
1914
  position: relative;
1915
- width: min(220px, 100%);
1916
- max-height: 136px;
1915
+ display: inline-flex;
1916
+ align-items: center;
1917
+ width: fit-content;
1918
+ max-width: 100%;
1917
1919
  border-radius: 9px;
1918
1920
  overflow: hidden;
1919
1921
  border: 1px solid var(--nb-line);
@@ -1921,10 +1923,6 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
1921
1923
  cursor: zoom-in;
1922
1924
  transition: border-color .14s ease, box-shadow .14s ease;
1923
1925
  }
1924
- .nb-list-figures-row .nb-fig-tile {
1925
- width: min(176px, 100%);
1926
- max-height: 104px;
1927
- }
1928
1926
  .nb-fig-tile:hover {
1929
1927
  border-color: var(--nb-accent);
1930
1928
  box-shadow: 0 0 0 3px var(--nb-accent-ring);
@@ -1932,9 +1930,7 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
1932
1930
  .nb-card-fig {
1933
1931
  border: 0 !important;
1934
1932
  border-radius: 0 !important;
1935
- max-height: 134px;
1936
1933
  }
1937
- .nb-list-figures-row .nb-card-fig { max-height: 102px; }
1938
1934
  .nb-media-zoom {
1939
1935
  position: absolute;
1940
1936
  right: 5px;
@@ -2042,12 +2038,13 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
2042
2038
 
2043
2039
  /* Vector SVG Diagrams */
2044
2040
  .nb-svg-diagram {
2045
- width: 100%;
2041
+ width: fit-content;
2042
+ max-width: min(460px, 100%);
2046
2043
  background: #ffffff;
2047
2044
  border: 1px solid var(--nb-line);
2048
2045
  border-radius: 8px;
2049
2046
  padding: 8px;
2050
- display: flex;
2047
+ display: inline-flex;
2051
2048
  align-items: center;
2052
2049
  justify-content: center;
2053
2050
  overflow: hidden;
@@ -2055,6 +2052,7 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
2055
2052
  .nb-svg-diagram img {
2056
2053
  max-width: 100%;
2057
2054
  max-height: 220px;
2055
+ width: auto;
2058
2056
  height: auto;
2059
2057
  display: block;
2060
2058
  }
@@ -2062,20 +2060,23 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
2062
2060
  border: 0 !important;
2063
2061
  border-radius: 0 !important;
2064
2062
  padding: 6px !important;
2065
- max-height: 134px;
2063
+ height: 88px;
2064
+ max-width: 100%;
2066
2065
  }
2067
- .nb-card-svg img { max-height: 120px; }
2068
- .nb-fig-tile-svg { width: min(240px, 100%); }
2066
+ .nb-card-svg img { height: 100%; max-height: none; width: auto; max-width: 100%; object-fit: contain; }
2067
+ .nb-list-figures-row .nb-card-svg { height: 68px; }
2068
+ .nb-fig-tile-svg { width: fit-content; max-width: 100%; }
2069
2069
  .nb-svg-badge {
2070
2070
  position: absolute;
2071
- left: 5px;
2072
- top: 5px;
2073
- padding: 1px 6px;
2074
- border-radius: 5px;
2075
- background: var(--nb-accent-soft);
2071
+ left: 4px;
2072
+ top: 4px;
2073
+ padding: 0 5px;
2074
+ line-height: 16px;
2075
+ border-radius: 4px;
2076
+ background: color-mix(in srgb, var(--nb-accent-soft) 90%, transparent);
2076
2077
  color: var(--nb-accent);
2077
2078
  border: 1px solid var(--nb-accent-border);
2078
- font-size: 10.5px;
2079
+ font-size: 10px;
2079
2080
  font-weight: 600;
2080
2081
  pointer-events: none;
2081
2082
  }
@@ -2400,11 +2401,51 @@ body[data-ds-dark-theme] :is(.nb-root, .nb-sheet, .nb-result) {
2400
2401
  }
2401
2402
  .nb-subhead { font-size: 12.5px; font-weight: 600; color: var(--nb-muted); }
2402
2403
  .nb-figures {
2404
+ display: flex;
2405
+ flex-wrap: wrap;
2406
+ align-items: flex-start;
2407
+ gap: 12px;
2408
+ }
2409
+ .nb-figure-item { display: grid; gap: 6px; justify-items: start; max-width: 100%; }
2410
+ .nb-figure-acts { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
2411
+ .nb-sub-disclosure {
2412
+ margin-top: 2px;
2413
+ padding-top: 10px;
2414
+ border-top: 1px solid var(--nb-line);
2415
+ }
2416
+ .nb-sub-disclosure > summary {
2417
+ list-style: none;
2418
+ display: flex;
2419
+ align-items: center;
2420
+ justify-content: space-between;
2421
+ gap: 8px;
2422
+ flex-wrap: wrap;
2423
+ cursor: pointer;
2424
+ padding: 7px 11px;
2425
+ border-radius: 8px;
2426
+ background: var(--nb-canvas);
2427
+ border: 1px solid var(--nb-line);
2428
+ font-size: 12.5px;
2429
+ font-weight: 550;
2430
+ color: var(--nb-muted);
2431
+ user-select: none;
2432
+ transition: border-color var(--nb-ease), color var(--nb-ease);
2433
+ }
2434
+ .nb-sub-disclosure > summary::-webkit-details-marker { display: none; }
2435
+ .nb-sub-disclosure > summary:hover {
2436
+ border-color: var(--nb-line-strong);
2437
+ color: var(--nb-text-2);
2438
+ }
2439
+ .nb-sub-disclosure-hint {
2440
+ font-size: 12px;
2441
+ color: var(--nb-accent);
2442
+ font-weight: 500;
2443
+ }
2444
+ .nb-sub-disclosure-body {
2445
+ padding-top: 10px;
2403
2446
  display: grid;
2404
- grid-template-columns: repeat(auto-fit, minmax(min(170px, 100%), 1fr));
2405
2447
  gap: 10px;
2406
2448
  }
2407
- .nb-figure-item { display: grid; gap: 6px; justify-items: start; }
2408
2449
  .nb-figure {
2409
2450
  position: relative;
2410
2451
  width: 100%;
package/cordis.patch.yml CHANGED
@@ -13,4 +13,4 @@
13
13
  name: '@deepseek-ai/dsh-persona'
14
14
  config:
15
15
  complete: true
16
- prefix: 你是老师的题库登记助手。录题时先用 qbank_context 查看目录与图片,再用 qbank_check_duplicates 按章节标签和知识点缩小范围查重,最后用 qbank_save 入库;自动忽略照片倾斜和学生手写批改,还原原始印刷题干;若题目配图存在手绘辅助线、涂鸦或严重倾斜,除保留原图来源外,可在 diagrams 字段用标准干净的白底黑线 SVG 代码重绘原题图形并提醒核对;纯文字题不填 figures 和 diagrams;无匹配章节时 chapter 留空存入「未归类」。建目录时用 qbank_manage_folders 批量建好三级结构。
16
+ prefix: 你是老师的题库登记助手。录题时先用 qbank_context 查看目录与图片,再用 qbank_check_duplicates 按章节标签和知识点缩小范围查重,对需要原图裁切的带图题先合并调用一次 qbank_preview_crop 查看局部放大红框并照外框 0–1000 刻度确定精确坐标,最后用 qbank_save 入库;自动忽略照片倾斜和学生手写批改,还原原始印刷题干;带图题默认只用 figures 原图精裁,不要擅自生成 diagrams SVG(尤其不要对立体几何或干净原图重绘);仅在老师开启重绘或手动点击「AI 重绘配图」时才生成白底黑线 SVG,且写入前须先用 qbank_preview_svg 渲染并与原图逐项核对顶点位置与虚实线;纯文字题不填 figures 和 diagrams;无匹配章节时 chapter 留空存入「未归类」。建目录时用 qbank_manage_folders 批量建好三级结构。
package/host.js CHANGED
@@ -1,8 +1,131 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
3
4
  import { homedir } from 'node:os'
4
5
  import { join } from 'node:path'
5
- import { NotebookError, openNotebook } from './store.js'
6
+ import { NotebookError, openNotebook, sanitizeSvg } from './store.js'
7
+
8
+ let sharpLoader
9
+ function getSharp() {
10
+ if (sharpLoader !== undefined) return sharpLoader
11
+ const candidates = [process.argv[1], import.meta.url].filter(Boolean)
12
+ for (const base of candidates) {
13
+ try {
14
+ const req = createRequire(base)
15
+ sharpLoader = req('sharp')
16
+ return sharpLoader
17
+ } catch {}
18
+ }
19
+ sharpLoader = null
20
+ return null
21
+ }
22
+
23
+ function escapeXml(text) {
24
+ return String(text ?? '').replace(/[&<>"']/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }[ch]))
25
+ }
26
+
27
+ async function renderCropPreview(photoBuffer, imgW, imgH, crops) {
28
+ const sharp = getSharp()
29
+ if (!sharp || !imgW || !imgH || !crops.length) return null
30
+ const panelW = 720
31
+ const leftMargin = 58
32
+ const topMargin = 44
33
+ const rightMargin = 20
34
+ const bottomMargin = 16
35
+ const totalW = leftMargin + panelW + rightMargin
36
+ const panels = []
37
+ let totalH = 8
38
+
39
+ for (const item of crops.slice(0, 8)) {
40
+ const norm = toNormalizedBox(item.box, { pad: false })
41
+ if (!Array.isArray(norm) || norm.length !== 4) continue
42
+ const bx1 = Math.round(norm[0] * 1000)
43
+ const by1 = Math.round(norm[1] * 1000)
44
+ const bx2 = Math.round((norm[0] + norm[2]) * 1000)
45
+ const by2 = Math.round((norm[1] + norm[3]) * 1000)
46
+ // Generous local context window so even a blind 15% vertical drift on the first guess keeps the full figure visible in ONE preview call
47
+ const ctxX1 = Math.max(0, Math.floor((bx1 - 120) / 10) * 10)
48
+ const ctxX2 = Math.min(1000, Math.ceil((bx2 + 120) / 10) * 10)
49
+ const ctxY1 = Math.max(0, Math.floor((by1 - 160) / 10) * 10)
50
+ const ctxY2 = Math.min(1000, Math.ceil((by2 + 180) / 10) * 10)
51
+ const exLeft = Math.max(0, Math.floor((ctxX1 / 1000) * imgW))
52
+ const exTop = Math.max(0, Math.floor((ctxY1 / 1000) * imgH))
53
+ const exW = Math.max(2, Math.min(imgW - exLeft, Math.ceil(((ctxX2 - ctxX1) / 1000) * imgW)))
54
+ const exH = Math.max(2, Math.min(imgH - exTop, Math.ceil(((ctxY2 - ctxY1) / 1000) * imgH)))
55
+ const panelH = Math.max(100, Math.min(620, Math.round(panelW * (exH / exW))))
56
+ const cropImg = await sharp(photoBuffer)
57
+ .extract({ left: exLeft, top: exTop, width: exW, height: exH })
58
+ .resize(panelW, panelH, { fit: 'fill' })
59
+ .png()
60
+ .toBuffer()
61
+
62
+ const mapX = g => leftMargin + ((g - ctxX1) / Math.max(1, ctxX2 - ctxX1)) * panelW
63
+ const mapY = g => topMargin + ((g - ctxY1) / Math.max(1, ctxY2 - ctxY1)) * panelH
64
+ const rx = mapX(bx1), ry = mapY(by1), rw = Math.max(2, mapX(bx2) - rx), rh = Math.max(2, mapY(by2) - ry)
65
+ const svgParts = []
66
+ const cardH = topMargin + panelH + bottomMargin
67
+ svgParts.push(`<rect x="0" y="0" width="${totalW}" height="${cardH}" fill="#ffffff"/>`)
68
+ svgParts.push(`<text x="${leftMargin}" y="16" font-family="sans-serif" font-size="13" font-weight="700" fill="#1e293b">${escapeXml(item.label)} · 当前红框 [${bx1}, ${by1}, ${bx2}, ${by2}]</text>`)
69
+ // External top X ruler (major 50-unit labels + 25-unit minor guide lines)
70
+ for (let gx = Math.ceil(ctxX1 / 25) * 25; gx <= ctxX2; gx += 25) {
71
+ const px = mapX(gx).toFixed(1)
72
+ const major = gx % 50 === 0
73
+ svgParts.push(`<line x1="${px}" y1="${topMargin - (major ? 6 : 3)}" x2="${px}" y2="${topMargin}" stroke="#2563eb" stroke-width="${major ? 1.2 : 0.9}"/>`)
74
+ svgParts.push(`<line x1="${px}" y1="${topMargin}" x2="${px}" y2="${topMargin + panelH}" stroke="#2563eb" stroke-opacity="${major ? 0.16 : 0.08}" stroke-width="1"/>`)
75
+ if (major) svgParts.push(`<text x="${px}" y="${topMargin - 8}" font-family="sans-serif" font-size="11" font-weight="700" text-anchor="middle" fill="#1d4ed8">${gx}</text>`)
76
+ }
77
+ // External left Y ruler (always 20-unit crisp ticks & labels so vertical reading is within ±10 units)
78
+ for (let gy = Math.ceil(ctxY1 / 20) * 20; gy <= ctxY2; gy += 20) {
79
+ const py = mapY(gy).toFixed(1)
80
+ const major = gy % 40 === 0
81
+ svgParts.push(`<line x1="${leftMargin - (major ? 6 : 4)}" y1="${py}" x2="${leftMargin}" y2="${py}" stroke="#2563eb" stroke-width="${major ? 1.2 : 0.9}"/>`)
82
+ svgParts.push(`<line x1="${leftMargin}" y1="${py}" x2="${leftMargin + panelW}" y2="${py}" stroke="#2563eb" stroke-opacity="${major ? 0.18 : 0.10}" stroke-width="1"/>`)
83
+ svgParts.push(`<text x="${leftMargin - 8}" y="${(Number(py) + 3.5).toFixed(1)}" font-family="sans-serif" font-size="10.5" font-weight="${major ? 700 : 500}" text-anchor="end" fill="#1d4ed8">${gy}</text>`)
84
+ }
85
+ // Border around photo panel + crisp red box showing AI's proposed crop
86
+ svgParts.push(`<rect x="${leftMargin}" y="${topMargin}" width="${panelW}" height="${panelH}" fill="none" stroke="#cbd5e1" stroke-width="1"/>`)
87
+ svgParts.push(`<rect x="${rx.toFixed(1)}" y="${ry.toFixed(1)}" width="${rw.toFixed(1)}" height="${rh.toFixed(1)}" fill="none" stroke="#dc2626" stroke-width="2.5"/>`)
88
+
89
+ const overlaySvg = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}" height="${cardH}">${svgParts.join('')}</svg>`)
90
+ const panelBuf = await sharp({
91
+ create: { width: totalW, height: cardH, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1 } },
92
+ })
93
+ .composite([
94
+ { input: overlaySvg, top: 0, left: 0 },
95
+ { input: cropImg, top: topMargin, left: leftMargin },
96
+ {
97
+ input: Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}" height="${cardH}">
98
+ ${svgParts.filter(s => s.includes('stroke-opacity') || s.includes('stroke="#dc2626"') || s.includes('stroke="#cbd5e1"')).join('')}
99
+ </svg>`),
100
+ top: 0, left: 0,
101
+ },
102
+ ])
103
+ .png()
104
+ .toBuffer()
105
+
106
+ panels.push({ input: panelBuf, top: totalH, left: 0, height: cardH })
107
+ totalH += cardH + 10
108
+ }
109
+
110
+ if (!panels.length) return null
111
+ return await sharp({
112
+ create: { width: totalW, height: totalH, channels: 3, background: { r: 248, g: 250, b: 252 } },
113
+ })
114
+ .composite(panels.map(({ input, top, left }) => ({ input, top, left })))
115
+ .jpeg({ quality: 86 })
116
+ .toBuffer()
117
+ }
118
+
119
+ async function renderSvgPreview(svgRaw) {
120
+ const sharp = getSharp()
121
+ if (!sharp) return null
122
+ const cleanSvg = sanitizeSvg(svgRaw)
123
+ return await sharp(Buffer.from(cleanSvg, 'utf8'), { density: 180 })
124
+ .resize({ width: 560, height: 420, fit: 'inside', withoutEnlargement: false })
125
+ .flatten({ background: { r: 255, g: 255, b: 255 } })
126
+ .jpeg({ quality: 88 })
127
+ .toBuffer()
128
+ }
6
129
 
7
130
  export const name = 'question-bank'
8
131
  export const inject = ['tools', 'attachments', 'webServer']
@@ -13,7 +136,57 @@ const int = description => ({ type: 'integer', description })
13
136
  const boolean = description => ({ type: 'boolean', description })
14
137
  const array = (items, description) => ({ type: 'array', items, description })
15
138
  const object = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false })
16
- const rect = array({ type: 'number' }, '四个 0–1 比例:[左, 上, 宽, 高]。必须真实对应原图;无法确定时省略。')
139
+ const rect = array({ type: 'number' }, '四个 0–1000 整数坐标:[左x1, 上y1, 右x2, 下y2](整张图左上角为 0,0,右下角为 1000,1000;严禁按像素尺寸换算)。对于带图题,先用 qbank_preview_crop 核对红框并修正后再写入。')
140
+
141
+ export function toNormalizedBox(value, { pad = false } = {}) {
142
+ if (!Array.isArray(value) || value.length !== 4 || value.some(n => !Number.isFinite(n))) return value
143
+ let [a, b, c, d] = value
144
+ let left, top, width, height
145
+ if (Math.max(a, b, c, d) > 1.000001) {
146
+ // 0–1000 corner format [x1, y1, x2, y2] (also guard if model gave [x, y, w, h] where c <= a or d <= b)
147
+ const x1 = a / 1000
148
+ const y1 = b / 1000
149
+ const x2 = c > a ? c / 1000 : (a + c) / 1000
150
+ const y2 = d > b ? d / 1000 : (b + d) / 1000
151
+ left = x1
152
+ top = y1
153
+ width = x2 - x1
154
+ height = y2 - y1
155
+ } else {
156
+ // Legacy 0–1 format [left, top, width, height]
157
+ left = a
158
+ top = b
159
+ width = c
160
+ height = d
161
+ }
162
+ if (width <= 0 || height <= 0) return value
163
+ if (pad === 'tight') {
164
+ const padX = 0.005
165
+ const padY = 0
166
+ const right = Math.min(1, left + width + padX)
167
+ const bottom = Math.min(1, top + height + padY)
168
+ left = Math.max(0, left - padX)
169
+ top = Math.max(0, top - padY)
170
+ width = Math.max(0.01, right - left)
171
+ height = Math.max(0.01, bottom - top)
172
+ } else if (pad) {
173
+ const padX = Math.max(0.018, width * 0.05)
174
+ const padY = Math.max(0.014, height * 0.08)
175
+ const right = Math.min(1, left + width + padX)
176
+ const bottom = Math.min(1, top + height + padY)
177
+ left = Math.max(0, left - padX)
178
+ top = Math.max(0, top - padY)
179
+ width = Math.max(0.01, right - left)
180
+ height = Math.max(0.01, bottom - top)
181
+ } else {
182
+ left = Math.max(0, Math.min(1, left))
183
+ top = Math.max(0, Math.min(1, top))
184
+ width = Math.min(1 - left, width)
185
+ height = Math.min(1 - top, height)
186
+ }
187
+ const round = n => Math.round(n * 10000) / 10000
188
+ return [round(left), round(top), round(width), round(height)]
189
+ }
17
190
  const diagramInput = object({
18
191
  svg: str('标准矢量 SVG 代码(含 xmlns 和 viewBox、白底、清晰黑线与规范标注,严禁包含 script/foreignObject/外部链接),用于还原去除倾斜、笔迹与学生辅助线后的纯净原题图形。'),
19
192
  caption: str('简短图注,例如 重绘几何图、数轴示意图'),
@@ -27,8 +200,8 @@ const questionInput = object({
27
200
  stem: str('忠实转录原始印刷题干和选项,忽略学生手写笔迹与批改。公式用 $…$ 或 $$…$$。看不清用【待核对】标出。'),
28
201
  image: int('题目所用图片,以所选用户消息里的图片顺序从 1 开始。单图默认 1。'),
29
202
  region: rect,
30
- figures: array(rect, '仅当题目本身包含几何图、函数图、数轴、流程图、表格等图形时填写独立区域框;纯文字题不要填。'),
31
- diagrams: array(diagramInput, '当原题图形存在学生手绘辅助线、涂鸦注释或严重倾斜反光时,用标准 SVG 代码重绘的纯净矢量原图。原图干净清晰时可省略。'),
203
+ figures: array(rect, '仅当题目本身含图形且原图干净清晰(不需要 SVG 重绘)时填写;务必先用 qbank_preview_crop 核对红框后再提交最终坐标。纯文字题或已用 diagrams 重绘矢量图的题请留空,不要重复填。'),
204
+ diagrams: array(diagramInput, '仅当原题图形存在学生手绘辅助线、手写涂鸦或严重倾斜反光时,用标准 SVG 代码重绘纯净矢量原图(此时 figures 留空)。原图干净清晰时请省略 diagrams,只用 figures 精准裁图。'),
32
205
  tags: array(str('知识点'), '只在收录偏好开启或老师本次要求时填写。'),
33
206
  answer: str('参考答案,只在偏好开启或老师本次要求时填写。'),
34
207
  analysis: str('参考解析,只在偏好开启或老师本次要求时填写。'),
@@ -53,13 +226,13 @@ function directMessages(session) {
53
226
  return messages
54
227
  }
55
228
 
56
- function registerTools(ctx, store) {
57
- const register = (toolName, description, parameters, schema, execute, present) => ctx.tools.register({
229
+ function registerTools(ctx, store, previewedSessions) {
230
+ const register = (toolName, description, parameters, schema, execute, present, customRender) => ctx.tools.register({
58
231
  name: toolName, description, parameters,
59
232
  execute,
60
233
  output: {
61
234
  schema,
62
- render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
235
+ render: customRender ?? ((_args, value) => [{ type: 'text', text: JSON.stringify(value) }]),
63
236
  ...(present ? { presentationMeta: (_args, value) => ({ questions: value }) } : {}),
64
237
  },
65
238
  })
@@ -70,11 +243,91 @@ function registerTools(ctx, store) {
70
243
  const overview = store.overview()
71
244
  const images = directMessages(exec.agent.session).filter(message => message.images.length).map(message => ({
72
245
  message: message.seq,
73
- images: message.images.map(({ name, width, height }, index) => ({ index: index + 1, name: name ?? '', width, height })),
246
+ images: message.images.map(({ name }, index) => ({
247
+ index: index + 1,
248
+ name: name ?? '',
249
+ coordinateScale: 1000,
250
+ })),
74
251
  }))
75
252
  return JSON.stringify({ ...overview, images })
76
253
  })
77
254
 
255
+ register('qbank_preview_crop',
256
+ '两步精准裁图工具(带图题在调用 qbank_save 前必调!)。传入你初步估计的 0–1000 坐标红框,工具会在放大后的局部原图上画出红框并在外部白边标出精确的 20 格全图 0–1000 坐标刻度返回给你目视核对。请把整张试卷中所有需要裁图的题目合并在一次调用中提交以节省 token。',
257
+ object({
258
+ message: int('图片所在的用户消息序号;省略时用最近的用户图片消息。'),
259
+ image: int('图片序号,从 1 开始,单图默认 1。'),
260
+ crops: array(object({
261
+ label: str('题号或标识,例如 第3题、第6题'),
262
+ box: rect,
263
+ }, ['label', 'box']), '需要核对红框位置的附图列表(1–8 个)。'),
264
+ }, ['crops']),
265
+ object({
266
+ summary: str('预览结果说明'),
267
+ attachment: { type: 'object', additionalProperties: true },
268
+ }, ['summary']),
269
+ async (args, exec) => {
270
+ const session = exec.agent.session
271
+ const messages = directMessages(session)
272
+ const latest = messages.find(m => m.images.length) ?? messages[0]
273
+ const message = args.message === undefined ? latest : messages.find(c => c.seq === args.message)
274
+ if (!message || !message.images.length) throw new NotebookError('当前会话中没有可预览裁剪的图片。')
275
+ const idx = args.image ?? 1
276
+ const ref = message.images[idx - 1]
277
+ if (!ref) throw new NotebookError('找不到指定的图片序号。')
278
+ if (!Array.isArray(args.crops) || !args.crops.length) throw new NotebookError('请至少传入一个待核对的红框区域。')
279
+ const read = await ctx.attachments.readImage(ref, exec.signal)
280
+ const previewBuf = await renderCropPreview(read.data, read.ref.width, read.ref.height, args.crops)
281
+ if (!previewBuf) {
282
+ return { summary: '当前环境不支持本地裁图预览,请直接提交合理的 0–1000 坐标。' }
283
+ }
284
+ const savedRef = await ctx.attachments.saveImage({
285
+ mediaType: 'image/jpeg',
286
+ data: previewBuf,
287
+ name: 'crop-preview.jpg',
288
+ })
289
+ previewedSessions?.add(session.id)
290
+ return {
291
+ summary: '已生成局部放大红框预览图:红框代表你刚才给出的坐标,白色外框的蓝色刻度为原图 0–1000 真实全局坐标(左轴每 20 格、上轴每 25/50 格)。请直接对照外框蓝色刻度读出完整包住图形且不含上方题干和下方选项的精确 [左x1, 上y1, 右x2, 下y2],紧贴图形外留出约 5–8 格白边即可,然后直接调用 qbank_save 保存(只要完整图形已出现在预览视野内,直接读刻度提交即可,无需再次预览;仅当图形主体超出当前预览窗口时才再调用 1 次)。',
292
+ attachment: savedRef,
293
+ }
294
+ },
295
+ false,
296
+ (_args, value) => [
297
+ { type: 'text', text: value.summary },
298
+ ...(value.attachment ? [{ type: 'image', attachment: value.attachment }] : []),
299
+ ])
300
+
301
+ register('qbank_preview_svg',
302
+ 'SVG 重绘自检工具(手动重绘配图并写入 qbank_update_question 前必调!)。将你编写的 SVG 渲染为实际效果图返回给你,请与用户原图逐项比对顶点位置、虚实线、对角线、箭头与字母标注,确认与原图一致后再保存。',
303
+ object({
304
+ svg: str('待预览核对的完整 <svg>…</svg> 代码'),
305
+ }, ['svg']),
306
+ object({
307
+ summary: str('预览结果说明'),
308
+ attachment: { type: 'object', additionalProperties: true },
309
+ }, ['summary']),
310
+ async args => {
311
+ const previewBuf = await renderSvgPreview(args.svg)
312
+ if (!previewBuf) {
313
+ return { summary: '当前环境不支持 SVG 渲染预览,请仔细检查坐标与虚实线后再保存。' }
314
+ }
315
+ const savedRef = await ctx.attachments.saveImage({
316
+ mediaType: 'image/jpeg',
317
+ data: previewBuf,
318
+ name: 'svg-preview.jpg',
319
+ })
320
+ return {
321
+ summary: '已渲染出你编写的 SVG 实际效果图(见附图)。请与原图逐项比对:1)各顶点字母(如 P/A/B/C/D)的相对方位与立体透视是否与原图一致;2)虚线(被遮挡棱/辅助线)与实线是否与原图完全吻合;3)是否漏画对角线、刻度、箭头或条件标注;4)文字是否重叠或裁切。若有出入请修正 SVG 后再调用 qbank_update_question(最多复核 1 次),完全吻合则直接保存。',
322
+ attachment: savedRef,
323
+ }
324
+ },
325
+ false,
326
+ (_args, value) => [
327
+ { type: 'text', text: value.summary },
328
+ ...(value.attachment ? [{ type: 'image', attachment: value.attachment }] : []),
329
+ ])
330
+
78
331
  register('qbank_manage_folders',
79
332
  '在题库登记中批量创建、添加或重命名教学目录(学科 → 教材 → 章节)。支持用户在任何会话里用口语描述来快速建目录。',
80
333
  object({
@@ -152,6 +405,7 @@ function registerTools(ctx, store) {
152
405
  throw new NotebookError('每次可收录 1–30 道题。')
153
406
  }
154
407
  const photos = new Map()
408
+ const wasPreviewed = Boolean(previewedSessions?.has(session.id))
155
409
  const questions = []
156
410
  for (const question of args.questions) {
157
411
  exec.signal.throwIfAborted()
@@ -165,7 +419,20 @@ function registerTools(ctx, store) {
165
419
  }
166
420
  photo = photos.get(index)
167
421
  }
168
- questions.push({ ...question, photo, aiAnswer: Boolean(question.answer), aiAnalysis: Boolean(question.analysis) })
422
+ const region = question.region ? toNormalizedBox(question.region, { pad: true }) : undefined
423
+ const hasSvgDiagram = Array.isArray(question.diagrams) && question.diagrams.length > 0
424
+ // Keep SVG redraw and raw crop mutually exclusive so clean crops aren't duplicated by SVGs and dirty SVGs aren't paired with messy crops
425
+ const figures = !hasSvgDiagram && Array.isArray(question.figures) && question.figures.length
426
+ ? question.figures.map(box => toNormalizedBox(box, { pad: wasPreviewed ? 'tight' : true }))
427
+ : undefined
428
+ questions.push({
429
+ ...question,
430
+ ...(region ? { region } : {}),
431
+ ...(figures ? { figures } : { figures: [] }),
432
+ photo,
433
+ aiAnswer: Boolean(question.answer),
434
+ aiAnalysis: Boolean(question.analysis),
435
+ })
169
436
  }
170
437
  exec.signal.throwIfAborted()
171
438
  const overview = store.overview()
@@ -179,10 +446,15 @@ function registerTools(ctx, store) {
179
446
  })
180
447
  const names = new Map(overview.folders.map(folder => [folder.id, folder.name]))
181
448
  return saved.map(question => ({
182
- ...question,
449
+ id: question.id,
450
+ seq: question.seq,
451
+ code: question.code,
183
452
  chapter: question.chapter ?? '',
184
453
  chapterName: question.chapter ? (names.get(question.chapter) ?? '') : '未归类',
454
+ number: question.number,
185
455
  title: question.title || question.stem || '',
456
+ review: question.review ?? '',
457
+ duplicate: Boolean(question.duplicate),
186
458
  }))
187
459
  }, true)
188
460
 
@@ -421,27 +693,32 @@ function registerRoutes(ctx, store, directory) {
421
693
  const { sessionId } = await controller.create({ workspaceId: workspace.id, agentPreset: 'question-bank-intake' })
422
694
  const { agent } = await controller.resolveAgent(sessionId)
423
695
  await applySessionModel(agent, preferences)
424
- agent.ctx.tools.restrict({ allow: ['qbank_context', 'qbank_check_duplicates', 'qbank_save'] })
696
+ agent.ctx.tools.restrict({ allow: ['qbank_context', 'qbank_check_duplicates', 'qbank_preview_crop', 'qbank_save'] })
425
697
  submitted.add(sessionId)
426
698
  const title = (chapter ? chapter.name : 'AI 自动归类') + ' · ' + (numbers ? '第 ' + numbers + ' 题' : '智能录题')
427
699
  await controller.rename({ sessionId, title })
428
700
  const chapterInstruction = chapter
429
701
  ? '目标章节已手动指定为「' + chapter.name + '」,调用 qbank_save 时请传入 chapter="' + chapter.id + '"。'
430
702
  : '章节归属由你自动判断:先用 qbank_context 查看现有目录(depth=2 为章节)。若题目明确属于某个现有章节,在对应题目的 chapter 字段填入该章节 id;若现有目录为空或没有对应章节,请务必将顶层和该题的 chapter 均设为 ""(空字符串,存入「未归类」),不要强行归入无关章节。'
431
- const redrawEnabled = input.redrawDirtyDiagrams !== undefined ? Boolean(input.redrawDirtyDiagrams) : (preferences.redrawDirtyDiagrams !== false)
703
+ const redrawEnabled = input.redrawDirtyDiagrams !== undefined ? Boolean(input.redrawDirtyDiagrams) : Boolean(preferences.redrawDirtyDiagrams)
704
+ const cropEnabled = input.figures === true
705
+ const cropGuide = cropEnabled
706
+ ? '两步精准裁图(重要):对包含原题图形且需要裁图的题目,先将所有待裁图形合并调用一次 qbank_preview_crop(传入 0–1000 初步估算坐标 [左x1, 上y1, 右x2, 下y2],严禁按像素换算),目视检查返回图中的红框与外框 20 格蓝色刻度,直接读出精确坐标(完整包住方框、箭头、回环线和顶点字母,不框进上方题干或下方选项)后写入 qbank_save 的 figures;只要完整图形已在预览图内,看 1 次预览即可直接保存,无需重复预览。纯文字题不要调用 qbank_preview_crop,也不要填 figures。'
707
+ : '本次无需框选附图,所有题目的 figures 均留空。'
432
708
  const diagramInstruction = redrawEnabled
433
- ? '图形净化兜底:如果题目带几何图、数轴、函数图、流程图或表格,且原图存在【拍照倾斜、学生手绘辅助线、手写标注/涂鸦或重影反光】,请保留原图来源的同时,用清晰规范的矢量 SVG 代码在 diagrams 字段中重绘一版去除手写笔迹与学生辅助线的纯净原题图形(白底黑线、明确 viewBox、规范字母标注,并在 reason 说明重绘原因,review 提醒老师核对重绘图);若原图本身干净端正,仅用 figures 框选即可。纯文字题 figures 与 diagrams 均留空。'
434
- : '仅当题目本身含几何图/数轴/函数图/流程图/表格时填写 figures 区域,纯文字题 figures 留空。'
709
+ ? '配图二选一原则(严格审慎):只要原题图形本身清晰可读(哪怕略有灰底或轻微倾斜),一律【只用 figures 原图精裁】,绝不要擅自生成 diagrams SVG;尤其禁止对立体几何(四棱锥/棱柱等)或复杂图形盲画 SVG。仅当简单平面几何/数轴/流程图被学生红笔涂鸦或手绘辅助线严重遮挡无法直接裁切时,才在 diagrams 中生成干净的白底黑线 SVG(此时 figures 留空)。纯文字题两者均留空。'
710
+ : '本次不进行矢量重绘:请勿填写 diagrams 字段,带图题仅使用 figures 原图精裁;纯文字题 figures 与 diagrams 均留空。'
435
711
  const prompt = [
436
712
  '请收录所附作业照片。',
437
713
  chapterInstruction,
438
714
  numbers ? '仅收录原卷第 ' + numbers + ' 题。' : '收录图片中的全部题目。',
439
715
  ...[['tags','推荐知识点'],['answer','生成答案'],['analysis','生成解析'],['figures','框选附图']].map(([key,label]) => label + ':' + (input[key] === true ? '是' : '否')),
440
716
  ...(note ? ['补充说明:' + note] : []),
717
+ cropGuide,
441
718
  '抗干扰要求:照片可能存在倾斜、阴影、学生手写作答、红笔批改或边缘注释。请忽略所有学生手写痕迹,只忠实还原原始印刷题干与选项;若笔迹遮挡导致个别符号无法确认,用【待核对】标出并在 review 中说明。',
442
719
  diagramInstruction,
443
- '执行步骤:1)先调用 qbank_context 查看现有目录与图片;2)针对识别出的每道题,先按目标章节/章节标签/知识点缩小范围,调用 qbank_check_duplicates 判断题库中是否已有完全相同的题目;3)再调用 qbank_save 提交结构化题目(重复题会自动合并来源或由你跳过说明)。',
444
- '每题务必填写简明中文标题 title 和题型 type,公式用 LaTeX。最后简短汇报保存的编号、是否命中重复题以及是否进行了矢量重绘。',
720
+ '执行步骤:1)先调用 qbank_context 查看现有目录与图片;2)调用 qbank_check_duplicates 按目标章节/章节标签/知识点查重;3)若存在需要原图裁切的带图题,合并调用一次 qbank_preview_crop 核对并修正红框坐标;4)调用 qbank_save 提交结构化题目。',
721
+ '每题务必填写简明中文标题 title 和题型 type,公式用 LaTeX。最后简短汇报保存的编号、是否命中重复题以及配图方式(原图精裁 / SVG 重绘)。',
445
722
  ].join('\n')
446
723
  try {
447
724
  await controller.prompt({ sessionId, mode: 'queue', requestId: randomUUID(), content: [
@@ -494,15 +771,15 @@ function registerRoutes(ctx, store, directory) {
494
771
  const { sessionId } = await controller.create({ workspaceId: workspace.id, agentPreset: 'question-bank-intake' })
495
772
  const { agent } = await controller.resolveAgent(sessionId)
496
773
  await applySessionModel(agent, store.overview().preferences)
497
- agent.ctx.tools.restrict({ allow: ['qbank_get_question', 'qbank_update_question'] })
774
+ agent.ctx.tools.restrict({ allow: ['qbank_get_question', 'qbank_preview_svg', 'qbank_update_question'] })
498
775
  submitted.add(sessionId)
499
776
  const title = 'AI 重绘配图 · ' + (question.code || '') + ' ' + (question.title || '题目').slice(0, 14)
500
777
  await controller.rename({ sessionId, title })
501
778
  const prompt = [
502
- '请仔细对照所附原图以及下方题干,用标准矢量 SVG 代码为题目 id="' + question.id + '" 重绘一张干净、出版级的原题配图,并调用 qbank_update_question 写入 diagrams 字段。',
779
+ '请仔细对照所附原图以及下方题干,用标准矢量 SVG 代码为题目 id="' + question.id + '" 重绘一张忠实还原原图布局与几何关系的纯净配图,先调用 qbank_preview_svg 渲染自检,确认与原图完全吻合后再调用 qbank_update_question 写入 diagrams 字段。',
503
780
  '题干内容:\n' + question.stem,
504
781
  ...(instruction ? ['老师特别要求:' + instruction] : []),
505
- '重绘规范:1)自动去除拍照倾斜、阴影、学生手写笔迹、红笔批改以及学生自己画的辅助线,只保留原题印刷图形;2)SVG 必须包含 xmlns="http://www.w3.org/2000/svg" 和合理的 viewBox,使用纯白背景矩形,清晰黑色线条(stroke="#18202c"),规范的几何字母/刻度/箭头标注,字号清晰易读;3)保留题库原有字段不变,只更新 diagrams(可附简短 caption 和 reason)。',
782
+ '重绘与自检规范:1)严格忠实还原原图的视角、各顶点相对位置(上下左右先后关系)、所有实线与虚线(被遮挡棱/底面对角线不可遗漏或画错)、刻度与箭头;2)自动去除学生手写笔迹、红笔批改和学生自画辅助线,只保留原题印刷图形;3)SVG 须含 xmlns="http://www.w3.org/2000/svg" 与合理 viewBox、纯白背景、清晰黑线(stroke="#18202c")与清晰字母标注;4)必须先调用 qbank_preview_svg 查看你画出来的实际效果,与原图逐项比对修正后再调用 qbank_update_question 保存(保留原有字段不变,只更新 diagrams)。',
506
783
  ].join('\n')
507
784
  try {
508
785
  await controller.prompt({ sessionId, mode: 'queue', requestId: randomUUID(), content: [
@@ -540,7 +817,7 @@ function registerRoutes(ctx, store, directory) {
540
817
  }
541
818
  try {
542
819
  const action = new URL(req.url, 'http://localhost').searchParams.get('action')
543
- const input = await readJson(req, action === 'restore' ? maxBackup : 12 * 1024 * 1024)
820
+ const input = await readJson(req, action === 'restore' ? maxBackup : 20 * 1024 * 1024)
544
821
  if (!input || typeof input !== 'object' || Array.isArray(input)) throw new NotebookError('请求内容无效。')
545
822
  let result
546
823
  switch (action) {
@@ -646,7 +923,8 @@ export function apply(ctx) {
646
923
  const home = process.env.DSH_HOME || join(homedir(), '.dsh')
647
924
  const directory = join(home, 'plugins-data', name)
648
925
  const store = openNotebook(join(directory, 'question-bank.sqlite'))
649
- ctx.on('dispose', () => store.close())
650
- registerTools(ctx, store)
926
+ const previewedSessions = new Set()
927
+ ctx.on('dispose', () => { previewedSessions.clear(); store.close() })
928
+ registerTools(ctx, store, previewedSessions)
651
929
  registerRoutes(ctx, store, directory)
652
930
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-question-bank",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "DeepSeek Harness 题库登记插件 — 支持拍照/截图智能录题、AI 自动归类查重、矢量配图重绘与章节管理",
5
5
  "type": "module",
6
6
  "main": "./host.js",
package/store.js CHANGED
@@ -12,7 +12,7 @@ const defaults = {
12
12
  tags: true,
13
13
  answer: false,
14
14
  analysis: false,
15
- redrawDirtyDiagrams: true,
15
+ redrawDirtyDiagrams: false,
16
16
  modelProvider: '',
17
17
  modelId: '',
18
18
  }
@@ -47,6 +47,7 @@ export function normalizeStem(stem = '') {
47
47
  return String(stem)
48
48
  .replace(/([^)]*流程图[^)]*)|\([^)]*流程图[^)]*\)/g, '')
49
49
  .replace(/\\dfrac/g, '\\frac')
50
+ .replace(/\\(?:q?quad|[,;:! ])/g, '')
50
51
  .replace(/\\mathrm\{([^}]*)\}/g, '$1')
51
52
  .replace(/\\text\{([^}]*)\}/g, '$1')
52
53
  .replace(/[$¥]/g, '')