From ab01fa00ee57d08cc3d7e21711e7baf14f51d03c Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Fri, 27 Nov 2026 16:33:58 +0800 Subject: [PATCH 01/15] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=9C=A8?= =?UTF-8?q?=E5=8E=9F=E7=BA=B8=E4=B8=8A=E7=AD=89=E6=AF=94=E6=8E=92=E5=AD=97?= =?UTF-8?q?=E5=B9=B6=E5=AF=B9=E7=85=A7=E5=AD=97=E4=BD=93=E5=92=8C=E5=9B=BE?= =?UTF-8?q?=E6=96=87=E7=AC=94=E8=BF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:照片作业逐行拉满目标框会改变相邻文字的比例,嵌入图使用固定深色,白底选字与整页预览很难看出交付时的差异。 解决手段:提供按纸面基线等比摆字和只读原纸字体小样,让新作业的插图继承正文墨效,并在复查中给出跨行尺度、图文亮度与原尺寸裁区。 收益:可以在真实纸张上选定可读的字体,保护旧稿的既有位置,复算字宽和墨色差异,并在导出前检查同页笔迹。 --- crates/handwriting-core/src/fine_edit.rs | 15 +- crates/handwriting-core/src/parameters.rs | 4 + crates/handwriting-core/src/render.rs | 16 +- crates/handwriting-core/src/render/fine.rs | 1 + .../src/render/illustration.rs | 1 + crates/handwriting-core/tests/behavior.rs | 26 + crates/panache-mcp/README.md | 14 +- crates/panache-mcp/src/controls.json | 1 + crates/panache-mcp/src/controls.rs | 1 + crates/panache-mcp/src/drafts.rs | 7 + crates/panache-mcp/src/engine.rs | 142 +++-- crates/panache-mcp/src/engine/adjustments.rs | 39 +- crates/panache-mcp/src/engine/font_samples.rs | 169 ++++++ crates/panache-mcp/src/inputs.rs | 38 +- crates/panache-mcp/src/main.rs | 54 +- crates/panache-mcp/src/placement.rs | 257 +++++++- crates/panache-mcp/src/preview.rs | 22 +- crates/panache-mcp/src/review.rs | 58 +- crates/panache-mcp/src/review/consistency.rs | 547 ++++++++++++++++++ crates/panache-mcp/src/save.rs | 22 + crates/panache-mcp/tests/coursework_form.py | 51 ++ crates/panache-mcp/tests/font_samples.py | 90 +++ .../tests/illustration_ink_check.py | 69 ++- crates/panache-mcp/tests/illustration_pen.py | 44 ++ crates/panache-mcp/tests/smoke.py | 6 + crates/panache-mcp/tool-design.md | 2 +- 26 files changed, 1520 insertions(+), 176 deletions(-) create mode 100644 crates/panache-mcp/src/engine/font_samples.rs create mode 100644 crates/panache-mcp/src/review/consistency.rs create mode 100644 crates/panache-mcp/tests/font_samples.py create mode 100644 crates/panache-mcp/tests/illustration_pen.py diff --git a/crates/handwriting-core/src/fine_edit.rs b/crates/handwriting-core/src/fine_edit.rs index fc7b9381..5cf410ed 100644 --- a/crates/handwriting-core/src/fine_edit.rs +++ b/crates/handwriting-core/src/fine_edit.rs @@ -37,6 +37,8 @@ pub struct Adjustments { pub struct GlyphBounds { #[serde(skip)] pub is_text: bool, + #[serde(skip)] + pub is_native_diagram: bool, pub illustration: Option, pub id: u32, pub bounds: [i32; 4], @@ -64,6 +66,7 @@ pub fn inspect_page( .map(|t| GlyphBounds { id: t.id, is_text: t.is_text, + is_native_diagram: t.is_native_diagram, illustration: t.illustration, bounds: [t.x, t.y, t.mask.width() as i32, t.mask.height() as i32], source_utf16: t.source, @@ -131,6 +134,7 @@ pub(crate) fn document_key(text: &str, p: &Parameters) -> String { pub(crate) struct Tile { pub is_text: bool, + pub is_native_diagram: bool, pub illustration: Option, pub id: u32, pub x: i32, @@ -293,11 +297,12 @@ pub(crate) fn paint( edit: Option<&Adjustment>, cancel: &Cancellation, ) -> Result<()> { - let (base_thickness, base_softness, base_fill, base_opacity) = if tile.illustration.is_some() { - (0., 0., [20, 20, 25, 255], 100) - } else { - (p.ink_thickness, p.ink_softness, p.fill, p.ink_opacity) - }; + let (base_thickness, base_softness, base_fill, base_opacity) = + if tile.illustration.is_some() && !p.illustration_uses_pen { + (0., 0., [20, 20, 25, 255], 100) + } else { + (p.ink_thickness, p.ink_softness, p.fill, p.ink_opacity) + }; let thickness = (base_thickness + edit.map_or(0., |v| f64::from(v.thickness) / 10.)).clamp(-2., 2.); let softness = (base_softness + edit.map_or(0., |v| f64::from(v.softness) / 10.)).clamp(0., 2.); diff --git a/crates/handwriting-core/src/parameters.rs b/crates/handwriting-core/src/parameters.rs index a3ed0d6b..1fce3335 100644 --- a/crates/handwriting-core/src/parameters.rs +++ b/crates/handwriting-core/src/parameters.rs @@ -82,6 +82,8 @@ pub struct Parameters { pub ink_depth_sigma: f32, pub ink_layers: bool, #[serde(default)] + pub illustration_uses_pen: bool, + #[serde(default)] pub transparent_background: bool, #[serde(default)] pub fine_edit: bool, @@ -133,6 +135,7 @@ impl Default for Parameters { strikethrough_width: 8., ink_depth_sigma: 30., ink_layers: false, + illustration_uses_pen: false, transparent_background: false, fine_edit: false, fine_edits: None, @@ -235,6 +238,7 @@ impl Parameters { p.full_preview = boolean(f, "full_preview", true)?; p.pdf_save = boolean(f, "pdf_save", false)?; p.ink_layers = boolean(f, "ink_layers", false)?; + p.illustration_uses_pen = boolean(f, "illustration_uses_pen", false)?; p.transparent_background = boolean(f, "transparent_background", false)?; p.fine_edit = boolean(f, "fine_edit", false)?; if p.fine_edit { diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index 50fba85b..a6b15b41 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -48,6 +48,7 @@ use units::{fixed_cell, keeps_grid_cell, layout_units}; // 2026-10-15:先缓存整行,知道最高根式/最低分母后再统一落笔,避免后出现的公式撞进上一行。 struct LineUnit { is_text: bool, + is_native_diagram: bool, glyph: Glyph, rigid: bool, align_to_rulings: bool, @@ -478,7 +479,7 @@ fn render_planes( (h as f32 - p.top_margin - p.bottom_margin).max(1.) as u32, imaging::scale(alt), ); - let image = imaging::handdrawn( + let mut image = imaging::handdrawn( &image::DynamicImage::ImageRgba8(fitted), p.seed.wrapping_add(i as u64), cancel, @@ -512,6 +513,17 @@ fn render_planes( pages.push_tile(tile)?; } } else { + if p.illustration_uses_pen { + let mask = GrayImage::from_fn(image.width(), image.height(), |x, y| { + image::Luma([image[(x, y)][3]]) + }); + image = ink_effects::composite( + RgbaImage::new(image.width(), image.height()), + mask, + &r.params, + cancel, + )?; + } image::imageops::overlay(&mut pages.canvas, &image, x as i64, top as i64); } pages.dirty = true; @@ -557,6 +569,7 @@ fn render_planes( let advance = g.step(unit, p, extra, compound); pages.x = x + advance; pages.line.push(LineUnit { + is_native_diagram: matches!(node, Node::Circuit(_)), is_text: unit.iter().all(|node| matches!(node, Node::Char(_))), glyph: g, rigid: compound || cell.is_some(), @@ -588,6 +601,7 @@ mod ruled_tests { fn sample_line() -> Vec { vec![LineUnit { is_text: true, + is_native_diagram: false, glyph: Glyph { mask: GrayImage::from_pixel(8, 40, Luma([255])), advance: 8., diff --git a/crates/handwriting-core/src/render/fine.rs b/crates/handwriting-core/src/render/fine.rs index 63a223ef..6294dbb9 100644 --- a/crates/handwriting-core/src/render/fine.rs +++ b/crates/handwriting-core/src/render/fine.rs @@ -178,6 +178,7 @@ fn capture_one( ink::paste_mask(&mut mask, &crop, pad as i32, pad as i32); Ok(Some(fine_edit::Tile { is_text: unit.is_text, + is_native_diagram: unit.is_native_diagram, id: unit.id, illustration: None, x: origin.0 + left as i32 - radius as i32 - pad as i32, diff --git a/crates/handwriting-core/src/render/illustration.rs b/crates/handwriting-core/src/render/illustration.rs index 435c655b..2433dd24 100644 --- a/crates/handwriting-core/src/render/illustration.rs +++ b/crates/handwriting-core/src/render/illustration.rs @@ -150,6 +150,7 @@ pub(super) fn tiles( imageops::replace(&mut padded, &mask, PAD.into(), PAD.into()); Tile { is_text: false, + is_native_diagram: false, id: part, illustration: Some(id), x: x + dx as i32 - PAD as i32, diff --git a/crates/handwriting-core/tests/behavior.rs b/crates/handwriting-core/tests/behavior.rs index 31d63cf7..7d443497 100644 --- a/crates/handwriting-core/tests/behavior.rs +++ b/crates/handwriting-core/tests/behavior.rs @@ -245,6 +245,32 @@ fn full_page_illustration_paginates_and_half_scale_leaves_room_for_text() { assert_eq!(pages(&full).len(), 2); assert_eq!(pages(&half).len(), 1); } +#[test] +fn illustration_keeps_selected_pen_when_text_is_rendered_as_an_ink_layer() { + use base64::{Engine, engine::general_purpose::STANDARD}; + let image = RgbaImage::from_fn(80, 40, |x, y| { + if (10..65).contains(&x) && (15..20).contains(&y) { + Rgba([0, 0, 0, 255]) + } else { + Rgba([255; 4]) + } + }); + let data = STANDARD.encode(export::png(&image).unwrap()); + let mut r = request(&format!("![diagram](data:image/png;base64,{data})")); + r.params.ink_layers = true; + r.params.fill = [150, 20, 40, 255]; + r.params.ink_opacity = 75; + r.params.illustration_uses_pen = true; + for fine in [false, true] { + r.params.fine_edit = fine; + assert!( + pages(&r)[0] + .pixels() + .any(|p| p[0].saturating_sub(p[1]) > 40) + ); + } +} + fn docx_bytes(xml: &str) -> Vec { let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); zip.start_file( diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 9c91becf..2bc48d44 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -70,7 +70,7 @@ cargo build --locked --release -p panache-mcp | 工具 | 用法 | | --- | --- | -| `list_fonts` | 按名称、文件名或来源(`bundled`、`user`、`system`)检索字体。默认 20 项,使用 `next_offset` 翻页。为作业、实验报告选笔迹时,指导模型展示中英数混排小样,按用户偏好定稿。 | +| `list_fonts` | 按名称、文件名或来源(`bundled`、`user`、`system`)检索字体。默认 20 项,使用 `next_offset` 翻页。传入 `sample` 可在稿件的纸张上比较当前字体和一至两个候选字体。 | | `save_section` | 用 `markdown` 新建稿件。首次可传标题、字体、字号、纸样、墨色、种子和作业排版模式。返回 `draft_id`、版本号和节号。 | | `list_drafts` | 找回本地稿件和最新版本。每批 20 条,可传 `offset`。 | | `read_section` | `summary` 取版本、长度和样式;默认 `excerpt` 隐去正文中已识别的内嵌图片数据;`source` 读取精确 Markdown。后两种视图按字符分页,默认 1000 字,单次最多 4000 字。 | @@ -88,6 +88,14 @@ cargo build --locked --release -p panache-mcp 例如用 `list_fonts(query="楷", source="system", limit=8)` 检索系统字体。把 `entries[].id` 用于建稿的 `style.font` 或调稿的 `changes.font`。随包字体继续接受原文件名。个人和系统字体会随稿保存,删除源文件后仍可预览历史版本。TTF、OTF 和 TTC/OTC 中带轮廓、单个字面大小不超过 32 MiB 的字体可供选择。 +给照片作业选字时,先用正文中的一行试排,例如“基本块 B1(1~2),if i > 10”。在精修位置前调用 `list_fonts`: + +```json +{"sample":{"draft_id":"稿件 ID","revision":1,"fonts":["华阳手写体.ttf","李国夫手写体.ttf"],"crop":[200,300,580,160]}} +``` + +`crop` 是原图的左、上、宽、高。请替换为稿件实际文字所在位置;省略时比较整页。客户端会收到标有字体的图片。选中候选后使用其 `tune_arguments`。图中标签若由外部程序绘制,应在绘制时采用选定字体。新作业的嵌入图沿用正文笔色、透明度、粗细和柔化;已有稿件可用 `tune_handwriting(changes={"illustration_uses_pen":true}, preserve_local_adjustments=true)` 启用。 + 桌面与 MCP 共享“我的字体”目录,`list_fonts` 的 `user_dir` 给出绝对路径。Windows 使用 `%LOCALAPPDATA%/Panache/fonts`,macOS 使用 `~/Library/Application Support/Panache/fonts`,Linux 使用 `$XDG_DATA_HOME/Panache/fonts`(默认 `~/.local/share/Panache/fonts`)。可通过 `PANACHE_USER_FONT_DIR` 指定绝对路径。把字体放入后调用 `list_fonts(source="user", refresh=true)`。 面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。 @@ -137,7 +145,7 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ 1. 表格、无横线纸和画作均可排字。用户已指定位置或委托选位时,直接按意图排版。落字区有歧义时,简短问“要写在哪个栏,哪些地方留白?”若必填区域在画外,或失焦、遮挡、透视已使它无法定位,建稿前指出具体缺哪一块,请用户补拍该区域或确认只填可见部分。已明确要求只写正文时,直接填写可定位的正文区。 2. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。整页复查图长边最多 900 像素,像素坐标以返回的 `photo_size` 为准。检查有字区域的横线、页眉、页边和需要保留的图案。 3. 调用 `tune_handwriting(draft_id, expected_revision, paper_guides, note)` 在原照片上重排全文。至少给两条参考线,每条提供行号与左右端点。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 -4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和这次布局返回的版本交给 `adjust_glyphs`。用户点名要改哪几个字时,按 `ids` 的顺序传 `expected_texts`,例如 `ids=[4,6], expected_texts=["春","雨"]`。任一编号对应的文字不符,整批都不保存;版本冲突时重新查布局并定位。相同的字出现多次时,用上下文或位置区分。纯位置选区和旧客户端可以省略文字核对。`place_center` 将一组字移到指定照片位置;`target_quad` 按左上、右上、右下、左下四角放置所选字块,替换该组已有几何调整。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 +4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和这次布局返回的版本交给 `adjust_glyphs`。用户点名要改哪几个字时,按 `ids` 的顺序传 `expected_texts`,例如 `ids=[4,6], expected_texts=["春","雨"]`。任一编号对应的文字不符,整批都不保存;版本冲突时重新查布局并定位。相同的字出现多次时,用上下文或位置区分。纯位置选区和旧客户端可以省略文字核对。同一原始行的文字用 `natural_line={"start":[x0,y0],"end":[x1,y1]}` 沿照片上的书写基线定位。默认保留原字号和字宽,短行留白;超长时可换行或扩大可用范围。多行需要统一缩放时使用相同的 `scale_percent`。`place_center` 平移字块;明确需要铺满四角时用 `target_quad`,回执给出纸面字形中心的最大主次轴伸缩比。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 5. 用 `read_section(view="trajectory")` 回看该稿的近期操作、简短调整理由和按页记录的复盘指标。有下一页时,把 `next_cursor` 作为下一次调用的 `cursor`。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) @@ -146,6 +154,8 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ 客户端已知目标值时,可在 `tune_handwriting` 中同时传 `changes={"perturb_theta_sigma":0.07}` 和 `readback_variation=["perturb_theta_sigma"]`。成功回执的 `effective_changes` 给出写入前后的有效值,用于直接核对本次写入,省去事后再读一次。最多点名本次提交的两个 `variation` 控件。提交 `null` 时读回继承值,有效值相同的键会省略。若要根据旧值决定改多少,仍应先用 `describe_controls` 读取该稿当前版本的值。 +同页复盘在有可比样本时给出 `adjacent_row_check` 和 `illustration_ink_check`。复用其 `preview_arguments`,或逐项调用 `separate_preview_arguments`,在原图尺度看邻行字宽和图线附近的正文。`evidence.adjacent_rows` 分别记录两行的横纵伸缩比和照片投影前的垂直缩放,能区分字被拉宽和整行等比放大,`evidence.illustration_contrast` 记录采样区相对底纸的亮度下降及像素数。应结合实际裁图判断书写效果。 + 如果字像贴在照片上,先分清是墨迹边缘过锐,还是纸面光照、阴影或墨色对比造成的观感。例如,纸面右侧有阴影,但用户认为笔画已经合适,就保留原样。如果用户明确指出笔画边缘过锐,或原尺寸成品裁图中的笔画边缘确实比附近可比的实拍印字或横线更锐,可以小幅柔化试一版。比如用户说“只改第一行,第二行保留”,用 `preview_handwriting(view=layout)` 找到第一行对应的字,再用 `adjust_glyphs` 的 `softness` 只调这些字。只有用户要调整整份稿子时,才用 `tune_handwriting` 的 `ink_softness`。用户要求保留墨迹时,直接沿用原版。 需要核对时,照片整页复盘的 `photo_appearance.preview_arguments` 可直接交给 `preview_handwriting`。有页内文字基线样本时,会返回字迹附近的原尺寸底纸和成品裁图,也可以自己圈选。试调后在新版本沿用原选区,用 `compare_revision` 指向旧版本,对照底纸、改前和改后三张实际裁图:底纸用来看原有阴影和印记,两张成品用来看细笔是否糊掉、对比度是否下降。如果用户点名第二行要保留,也对照第二行的改前和改后。效果变差或拿不准就保留原版。只有文字回执时,把用户观察到的情况说清楚,例如“你觉得边缘已经合适”;还需要目视判断时,请用户看裁图。字号与可写空间是否相称可另查 `layout` 或 `typography` 组。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比;只改墨迹组参数会保留已有的单字移位和透视调整。更换字体、字号或参考线后,应在新版本重新检查选区。 diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index 7ff757f5..7eed2221 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -29,6 +29,7 @@ "latin_digits": {"type":"boolean","default":false,"description":"Leave unset on new drafts. False keeps 0–9 at the main font and size. True applies the Latin size and any selected Latin font to digits."} }, "ink": { + "illustration_uses_pen": {"type":"boolean","description":"Render embedded diagram strokes and labels using the manuscript ink color, opacity, thickness and softness. The shapes and lettering in the source image stay as drawn."}, "transparent_background": {"type":"boolean","description":"Ink-only PNG preview and ZIP. PDF retains the paper."}, "ink": {"type":"color"}, "ink_alpha": {"type":"integer","min":0,"max":255,"description":"Alpha channel of the selected RGBA pen color, before ink opacity."}, diff --git a/crates/panache-mcp/src/controls.rs b/crates/panache-mcp/src/controls.rs index 52b3c07b..78a156b3 100644 --- a/crates/panache-mcp/src/controls.rs +++ b/crates/panache-mcp/src/controls.rs @@ -97,6 +97,7 @@ pub fn parameters(draft: &Snapshot<'_>, section: u32, changes: &Changes) -> Resu top_margin: 62., bottom_margin: 55., fill: style.ink_rgba()?, + illustration_uses_pen: style.illustration_uses_pen.unwrap_or(false), strikethrough_probability: 0., perturb_x_sigma: 1., perturb_y_sigma: 1., diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 9ffa06a9..8a80527f 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -84,6 +84,13 @@ pub struct Snapshot<'a> { } impl Snapshot<'_> { + pub fn font_name(&self) -> &str { + self.controls + .get("font") + .and_then(Value::as_str) + .unwrap_or(&self.style.font) + } + pub fn review_section(&self, requested: Option) -> Result { if let Some(section) = requested { ensure!(section > 0, "section starts at 1"); diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index 796614c3..9c4cc589 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -1,4 +1,5 @@ mod adjustments; +pub(crate) mod font_samples; use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use handwriting_core::{Cancellation, FontBook, Limits, RenderRequest, export}; @@ -119,17 +120,16 @@ impl Engine { background: Option>, edits: Option, ) -> Result { - let font_name = draft - .controls - .get("font") - .and_then(serde_json::Value::as_str) - .unwrap_or(&draft.style.font); + let primary = self.draft_font(draft, draft.font_name())?; + self.request_with_font(draft, section, background, edits, primary) + } + fn draft_font(&mut self, draft: &Snapshot<'_>, font_name: &str) -> Result> { ensure!( font_name.starts_with("upload:") || self.names.iter().any(|f| f == font_name), "Font no longer available: {}", font_name ); - let primary = if font_name.starts_with("upload:") { + Ok(if font_name.starts_with("upload:") { let key = format!("{}:{}", draft.id, font_name); if let Some(font) = self.fonts.get(&key) { font.clone() @@ -140,7 +140,16 @@ impl Engine { } } else { self.font(font_name)? - }; + }) + } + fn request_with_font( + &mut self, + draft: &Snapshot<'_>, + section: Section, + background: Option>, + edits: Option, + primary: Arc, + ) -> Result { let fonts = FontBook::with_text_fallbacks(primary, §ion.text, |name| { if self.names.iter().any(|n| n == name) { self.font(name).map(Some) @@ -206,23 +215,8 @@ impl Engine { let camera = draft.camera(background.as_deref())?; let photo = Self::photo(draft, &mut background)?; let request = self.request(draft, section, background, edits)?; - let mut image = None; - let pages = - Self::render_pages(&request, photo.as_ref(), cancel, page_number, |i, page| { - if i + 1 == page_number { - image = Some(STANDARD.encode(camera.png(&page)?)); - } - Ok(()) - })?; - let png = image.ok_or_else(|| { - draft.page_error( - n, - handwriting_core::Error::new( - "invalid_page", - format!("Section has {pages} pages; requested {page_number}"), - ), - ) - })?; + let image = Self::render_page(draft, n, &request, photo.as_ref(), cancel, page_number)?; + let png = STANDARD.encode(camera.png(&image)?); let preview = RenderedPreview { png, fine_edit: request.params.fine_edit, @@ -276,6 +270,31 @@ impl Engine { None => handwriting_core::render::render_until_page(request, cancel, stop, emit), } } + fn render_page( + draft: &Snapshot<'_>, + section: u32, + request: &RenderRequest, + photo: Option<&(&handwriting_core::photo::PaperProjection, image::RgbaImage)>, + cancel: &Cancellation, + page_number: usize, + ) -> Result { + let mut image = None; + let pages = Self::render_pages(request, photo, cancel, page_number, |i, page| { + if i + 1 == page_number { + image = Some(page); + } + Ok(()) + })?; + image.ok_or_else(|| { + draft.page_error( + section, + handwriting_core::Error::new( + "invalid_page", + format!("Section has {pages} pages; requested {page_number}"), + ), + ) + }) + } pub fn page_count( &mut self, draft: &Snapshot<'_>, @@ -353,47 +372,42 @@ impl Engine { ) }) .collect(); - // Use edited geometry on this page. Raster details belong to the parent illustration. - let illustration_and_text = glyphs - .iter() - .find(|g| g.illustration == Some(g.id)) - .and_then(|g| { - let position = |g: &fine_edit::GlyphBounds, offset| { - crate::review::photo_point( - draft, - glyph_point(g, edits.get(&g.id).copied(), offset), - ) - }; - let hw = f64::from(g.bounds[2]) / 2.; - let hh = f64::from(g.bounds[3]) / 2.; - let corners = - [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]].map(|uv| position(g, uv)); - let bounds = |axis: usize| { - corners - .iter() - .map(|p| p[axis]) - .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), x| { - (lo.min(x), hi.max(x)) - }) - }; - let (left, right) = bounds(0); - let (top, bottom) = bounds(1); - let candidates = glyphs - .iter() - .filter(|v| v.is_text && edits.get(&v.id).is_none_or(|edit| edit.opacity > 0)); - let near = candidates.map(|v| position(v, [0., 0.])).min_by(|a, b| { - let distance = |p: &[f32; 2]| { - (p[0] - p[0].clamp(left, right)).hypot(p[1] - p[1].clamp(top, bottom)) - }; - distance(a).total_cmp(&distance(b)) - })?; - Some([ - [left.min(near[0]), top.min(near[1])], - [right.max(near[0]), bottom.max(near[1])], - ]) - }); + let mut text = Vec::new(); + let mut drawing = None; + for g in &glyphs { + let edit = edits.get(&g.id).copied(); + let is_drawing = g.illustration == Some(g.id) || g.is_native_diagram; + if !(g.is_text || is_drawing && drawing.is_none()) + || edit.is_some_and(|v| v.opacity == 0) + { + continue; + } + let hw = f64::from(g.bounds[2]) / 2.; + let hh = f64::from(g.bounds[3]) / 2.; + let corners = [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]] + .map(|uv| crate::review::photo_point(draft, glyph_point(g, edit, uv))); + let bounds = crate::review::Bounds::from_corners(corners); + if is_drawing { + drawing = Some(bounds); + } else { + let edge = |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).hypot(a[1] - b[1]); + let width = edge(corners[0], corners[1]) + edge(corners[3], corners[2]); + let height = edge(corners[0], corners[3]) + edge(corners[1], corners[2]); + let dy = f64::from(g.baseline - g.bounds[1]) - hh; + let baseline = glyph_point(g, edit, [0., dy])[1]; + let top = glyph_point(g, edit, [0., -hh]); + let bottom = glyph_point(g, edit, [0., hh]); + text.push(crate::review::TextSample { + bounds, + baseline, + paper_vertical_scale: edge(top, bottom) / g.bounds[3] as f32, + stretch: (width / height) / (hw / hh) as f32, + }); + } + } Ok(crate::review::PageSample { - illustration_and_text, + text, + drawing, baselines, content_sha256: format!("{:x}", membership.finalize()), }) diff --git a/crates/panache-mcp/src/engine/adjustments.rs b/crates/panache-mcp/src/engine/adjustments.rs index b224adab..0612c2b4 100644 --- a/crates/panache-mcp/src/engine/adjustments.rs +++ b/crates/panache-mcp/src/engine/adjustments.rs @@ -2,7 +2,7 @@ use super::{Engine, glyph_point, glyph_source}; use crate::{ Nudge, Shape, Style, drafts::{Section, Snapshot}, - placement::Placement, + placement::{Placement, PlacementReport}, }; use anyhow::{Context, Result, ensure}; use handwriting_core::{ @@ -19,7 +19,7 @@ impl Engine { section: Section, input: &crate::Nudge, cancel: &Cancellation, - ) -> Result { + ) -> Result<(u32, Option)> { let changes = GlyphChanges::parse(input, &draft.style)?; let version = section.version; let mut req = self.fine_request(draft, section)?; @@ -72,15 +72,20 @@ impl Engine { } ensure!(edits.len() <= 10000, "Section glyph edit limit reached"); cancel.check()?; - draft.store_edits( + let placement = match geometry { + Geometry::Placement(_, report) => Some(report), + _ => None, + }; + let next = draft.store_edits( input.section, version, &Adjustments { key, glyphs: edits.into_values().collect(), }, - &json!({"page":input.page,"ids":input.ids,"place_center":input.place_center,"target_quad":input.target_quad,"dx":input.dx,"dy":input.dy,"scale":input.scale,"angle":input.angle,"shape":input.shape,"opacity":input.opacity,"thickness":input.thickness,"softness":input.softness,"color":input.color,"note":input.note}), - ) + &json!({"page":input.page,"ids":input.ids,"place_center":input.place_center,"natural_line":input.natural_line,"target_quad":input.target_quad,"placement":placement,"dx":input.dx,"dy":input.dy,"scale":input.scale,"angle":input.angle,"shape":input.shape,"opacity":input.opacity,"thickness":input.thickness,"softness":input.softness,"color":input.color,"note":input.note}), + )?; + Ok((next, placement)) } } @@ -107,6 +112,7 @@ impl<'a> GlyphChanges<'a> { } ensure!( input.target_quad.is_some() + || input.natural_line.is_some() || input.place_center.is_some() || input.dx.is_some() || input.dy.is_some() @@ -167,7 +173,7 @@ impl<'a> GlyphChanges<'a> { fn apply(&self, geometry: &Geometry, glyph: &GlyphBounds, e: &mut Adjustment) -> Result<()> { let input = self.input; - if let Geometry::Quadrilateral(map) = geometry { + if let Geometry::Placement(map, _) = geometry { map.apply(e, glyph.bounds)?; } if let Some(shape) = &input.shape { @@ -223,7 +229,7 @@ fn shape_warp(shape: &Shape, height: i32) -> Option<[f64; 8]> { enum Geometry { Unchanged, - Quadrilateral(Placement), + Placement(Placement, PlacementReport), Translation([i32; 2]), } @@ -240,7 +246,14 @@ impl Geometry { .as_ref() .map(|p| p.photo_size.unwrap_or([p.width, p.height])) .unwrap_or([params.width.unwrap_or(0), params.height.unwrap_or(0)]); - if let Some(quad) = input.target_quad { + let projection = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); + let placement = match (&input.natural_line, input.target_quad) { + (Some(_), Some(_)) => anyhow::bail!("Use natural_line or target_quad separately"), + (Some(line), None) => Some(Placement::natural_line(projection, [w, h], bounds, line)?), + (None, Some(quad)) => Some(Placement::target_quad(projection, [w, h], bounds, quad)?), + (None, None) => None, + }; + if let Some((map, report)) = placement { ensure!( input.place_center.is_none() && input.dx.is_none() @@ -248,14 +261,9 @@ impl Geometry { && input.angle.is_none() && input.scale.is_none() && input.shape.is_none(), - "Use target_quad separately from other geometry fields" + "Use natural_line or target_quad separately from other geometry fields" ); - return Ok(Self::Quadrilateral(Placement::new( - draft, - [w, h], - bounds, - quad, - )?)); + return Ok(Self::Placement(map, report)); } if let Some(target) = input.place_center { ensure!( @@ -263,7 +271,6 @@ impl Geometry { "Use place_center separately from dx/dy/shape" ); ensure!(target[0] < w && target[1] < h, "Target outside the page"); - let projection = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); let dest = target.map(|v| v as f32); let dest = projection.map_or(dest, |p| p.paper_point(dest)); let mut mean = [0., 0.]; diff --git a/crates/panache-mcp/src/engine/font_samples.rs b/crates/panache-mcp/src/engine/font_samples.rs new file mode 100644 index 00000000..f7524458 --- /dev/null +++ b/crates/panache-mcp/src/engine/font_samples.rs @@ -0,0 +1,169 @@ +use super::Engine; +use crate::{FontSample, State, reply}; +use anyhow::{Context, Result, ensure}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use handwriting_core::{Cancellation, FontBook, Limits, export}; +use image::{GenericImageView, RgbaImage, imageops}; +use rmcp::model::{CallToolResult, ContentBlock}; +use serde_json::json; + +const MAX_EDGE: u32 = 640; + +fn crop_image(image: &RgbaImage, crop: Option<[u32; 4]>) -> Result { + let [x, y, w, h] = crop.unwrap_or([0, 0, image.width(), image.height()]); + ensure!( + w > 0 + && h > 0 + && x.checked_add(w).is_some_and(|r| r <= image.width()) + && y.checked_add(h).is_some_and(|b| b <= image.height()), + "crop must be a nonempty rectangle within the {} × {} output", + image.width(), + image.height() + ); + let view = image.view(x, y, w, h); + let longest = w.max(h); + if longest <= MAX_EDGE { + return Ok(view.to_image()); + } + let size = |n| ((u64::from(n) * u64::from(MAX_EDGE)) / u64::from(longest)).max(1) as u32; + Ok(imageops::thumbnail(&*view, size(w), size(h))) +} + +pub(crate) fn compare( + state: &State, + engine: &mut Engine, + sample: FontSample, + cancel: &Cancellation, +) -> Result { + ensure!( + (1..=2).contains(&sample.fonts.len()), + "Supply one or two candidate font IDs" + ); + let draft = state.drafts.snapshot(&sample.draft_id, sample.revision)?; + let current = draft.font_name(); + let section_number = sample.section.unwrap_or(1); + let page = sample.page.unwrap_or(1); + ensure!( + (1..=Limits::default().max_pages).contains(&page), + "Invalid page number" + ); + let section = state + .drafts + .sections(draft.id, draft.revision, Some(section_number))? + .pop() + .context("Unknown section")?; + let (_, edits) = draft.edits(§ion)?; + let mut background = draft.background()?; + let photo = Engine::photo(&draft, &mut background)?; + let mut choices = vec![current]; + for id in &sample.fonts { + if !choices.contains(&id.as_str()) { + choices.push(id); + } + } + let mut data = json!({ + "draft_id":draft.id, "revision":draft.revision, "section":section_number, "page":page, + "crop":sample.crop, "current_font":current + }); + if choices.len() > 1 { + data["content_note"] = json!(if sample.crop.is_some() { + "各图取自同一页码和同一纸面位置。换字可能改变换行和分页,请核对裁区内的文字是否仍是同一句。" + } else { + "各图取相同页码。换字可能改变换行和分页,请按实际出现的文字比较。" + }); + if edits.is_some() { + data["placement_note"] = json!( + "当前样张保留本节手摆位置和其他局部调整。备选样张按新字体重新排版,采纳参数会保护已有调整。" + ); + } + } + let mut rows = Vec::new(); + let mut unavailable = Vec::new(); + let mut blocks = Vec::new(); + for id in choices { + cancel.check()?; + let (name, primary) = if id.starts_with("upload:") || engine.names.iter().any(|f| f == id) { + (id.to_owned(), engine.draft_font(&draft, id)?) + } else { + let (entry, bytes) = state.local_fonts.read(id)?; + (entry.name, FontBook::load(&bytes)?) + }; + // Font changes reset local glyph placements in tune_handwriting. + let local_edits = if id == current { edits.clone() } else { None }; + let mut request = engine.request_with_font( + &draft, + section.clone(), + background.clone(), + local_edits, + primary, + )?; + if request.params.transparent_background { + request.params.transparent_background = false; + data["background_note"] = json!( + "本稿已开启透明 PNG。这里临时显示底纸以比较字体,稿件的 PNG 预览和导出仍使用透明背景。" + ); + } + let rendered = Engine::render_page( + &draft, + section_number, + &request, + photo.as_ref(), + cancel, + page, + ); + let image = match rendered { + Err(error) + if id != current + && error + .downcast_ref::() + .is_some_and(|error| error.code == "invalid_page") => + { + let note = + format!("备选字体 {name} 重新分页后,第 {section_number} 节没有第 {page} 页。"); + unavailable.push(json!({"font":id, "name":name, "section":section_number, + "page":page, "reason":"page_missing_after_reflow", "message":note})); + blocks.push(ContentBlock::text(note)); + continue; + } + other => other + .with_context(|| format!("字体 {name} · 第 {section_number} 节第 {page} 页"))?, + }; + let crop = crop_image(&image, sample.crop)?; + data["native_size"] = json!([image.width(), image.height()]); + data["sample_size"] = json!([crop.width(), crop.height()]); + let mut row = json!({"font":id,"name":name}); + let label = if id == current { + format!("当前字体 · {name}") + } else { + row["tune_arguments"] = json!({ + "draft_id":draft.id, "expected_revision":draft.revision, + "changes":{"font":id}, "preserve_local_adjustments":true + }); + format!("备选字体 · {name}") + }; + blocks.push(ContentBlock::text(label)); + blocks.push(ContentBlock::image( + STANDARD.encode(export::png(&crop)?), + "image/png", + )); + rows.push(row); + } + data["samples"] = json!(rows); + if !unavailable.is_empty() { + data["unavailable_samples"] = json!(unavailable); + } + let notes = ["content_note", "placement_note", "background_note"] + .into_iter() + .filter_map(|key| data[key].as_str()) + .collect::>() + .join("\n"); + let mut result = reply( + format!( + "第 {} 版 · 第 {section_number} 节第 {page} 页。第一张为当前字体。请比较字形、粗细,以及英文和数字是否清楚。若保留当前字体,无需改稿。\n{notes}\n{data}", + draft.revision + ), + data, + ); + result.content.extend(blocks); + Ok(result) +} diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index a80af171..8bff7c31 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -17,6 +17,23 @@ pub struct FontList { pub refresh: bool, /// Set false only to look up an already approved font or its ID when no new style choice is needed. Omit or set true for samples and style choices, even with an exact-name query. pub include_sample_guidance: Option, + /// Instead of searching, render the same saved page in its current font and up to two alternatives. + pub sample: Option, +} + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FontSample { + pub draft_id: String, + /// Omit for latest. + pub revision: Option, + /// One-based section and page (both default to 1). + pub section: Option, + pub page: Option, + /// One or two candidate IDs from list_fonts. The current font is shown automatically. + pub fonts: Vec, + /// Optional common crop [x,y,width,height] in native output pixels. Frame real mixed text at writing size. + pub crop: Option<[u32; 4]>, } #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)] @@ -53,6 +70,10 @@ pub struct Style { /// Slightly vary letter size and tilt. Defaults on for new homework. Use false for the usual, steadier variation. #[serde(skip_serializing_if = "Option::is_none")] pub relaxed_handwriting: Option, + /// Use the manuscript pen color, opacity, thickness and softness for embedded illustrations. + /// New homework enables this by default. Existing labels inside the image keep their drawn shapes. + #[serde(skip_serializing_if = "Option::is_none")] + pub illustration_uses_pen: Option, /// Keep this value to reproduce handwriting variations. #[schemars(transform = remove_schema_default)] pub seed: u32, @@ -70,6 +91,7 @@ impl Default for Style { font_size: 34, homework: false, relaxed_handwriting: None, + illustration_uses_pen: None, seed: u32::from_le_bytes(Uuid::new_v4().as_bytes()[..4].try_into().unwrap()), } } @@ -127,6 +149,7 @@ impl CreationStyle { if style.homework { // Resolve only on creation: older saved styles keep their original rendering. style.relaxed_handwriting.get_or_insert(true); + style.illustration_uses_pen.get_or_insert(true); } style } @@ -295,6 +318,17 @@ pub struct Shape { pub top_width_percent: u8, } +#[derive(Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct NaturalLine { + /// Start of the writing baseline in original preview pixels, at the selection's left edge. + pub start: [u32; 2], + /// End of the available baseline, in writing direction. Extra space stays blank. + pub end: [u32; 2], + /// Uniform size relative to the source layout, 50..200 (default 100). Reuse the same value on adjacent rows. + pub scale_percent: Option, +} + #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Nudge { @@ -311,7 +345,9 @@ pub struct Nudge { pub expected_texts: Option>, /// Move this selection as a group so its mean glyph center lands at [x,y] on the preview. Use separately from dx, dy and shape. pub place_center: Option<[u32; 2]>, - /// Image destinations of the original block's TL,TR,BR,BL corners, in that order (for a 90° counterclockwise sidebar: BL,TL,TR,BR of the field). Replaces prior geometry; use separately from other geometry changes. + /// Place one source line along a worksheet baseline, preserving letter proportions, spacing, and baseline offsets in paper space. Use separately from other geometry changes. + pub natural_line: Option, + /// Exact stretch to the original block's TL,TR,BR,BL image destinations (for a 90° counterclockwise sidebar: BL,TL,TR,BR of the field). Use only for intentional four-corner warping. Replaces prior geometry. pub target_quad: Option<[[u32; 2]; 4]>, /// Absolute offsets in pixels from the original glyph position. Omitted fields retain their values. pub dx: Option, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 7717399e..2c61e53f 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -279,7 +279,7 @@ impl ServerHandler for Panache { "If a required area of a photo is outside the frame, or blur, occlusion or perspective prevents locating it, identify that area before drafting. ", "Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ", "For a school assignment, even text alone, set style.homework=true on creation; omit font unless the user specifies one. For further variation (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ", - "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. When the user wants to compare fonts, see list_fonts for sample guidance. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ", + "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. For a font comparison, show the labeled images from list_fonts(sample=...) on the actual draft paper and mixed text. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ", "For print-and-report, export once and report review.unreviewed_pages. Look up existing receipts with read_section(view=review); full-page preview_handwriting(view=review) files a check. Last-page lookups use current pagination and cannot confirm the historical last page. Follow photo_appearance.preview_arguments for a native detail crop. ", "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", "Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ", @@ -332,13 +332,7 @@ impl Panache { let mut effective = serde_json::Map::new(); for k in data["controls"].as_object().unwrap().keys() { let val = match k.as_str() { - "font" => json!( - draft - .controls - .get(k) - .and_then(|v| v.as_str()) - .unwrap_or(&draft.style.font) - ), + "font" => json!(draft.font_name()), "paper" => draft .controls .get(k) @@ -389,9 +383,29 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "Search bundled, personal and system fonts by name/source. Results are paged. Use an entry ID in save_section style.font or tune_handwriting changes.font; user and system faces are saved with the draft." + description = "Search bundled, personal and system fonts. To compare fonts on the saved paper, pass sample with draft_id, one or two candidate IDs and an optional native-pixel crop. The current image retains local edits. Candidates reflow, so check which words occupy the same region. Samples show the paper even for transparent PNG drafts. Returns labeled images and tune_handwriting arguments without editing the draft." )] - async fn list_fonts(&self, Parameters(input): Parameters) -> CallToolResult { + async fn list_fonts( + &self, + Parameters(input): Parameters, + ctx: RequestContext, + ) -> CallToolResult { + if let Some(sample) = input.sample { + return tool_result( + self.render(ctx, move |state, engine, cancel| { + ensure!( + input.query.is_empty() + && input.source.is_none() + && input.offset == 0 + && input.limit.is_none() + && !input.refresh, + "Use catalog search fields separately from sample" + ); + engine::font_samples::compare(state, engine, sample, cancel) + }) + .await, + ); + } let include_sample_guidance = input.include_sample_guidance.unwrap_or(true); let query = FontSearch { query: input.query, @@ -407,9 +421,9 @@ impl Panache { let guidance = concat!( "Select only the main font for a new draft. Its letters and digits are the default, including for homework and lab reports. ", "For a hurried pen style, try 李国夫手写体.ttf if listed. Use a short line from the task with Chinese, an English term and a number or unit. ", - "Preview it at the intended size on the intended paper. Compare stroke weight, slant, relative size and digit legibility. ", + "Save the actual paper, settings and task text first. Call list_fonts(sample={draft_id,fonts:[candidate_id]}) for labeled images of the same page, optionally adding crop:[x,y,width,height] around a mixed line. Compare stroke weight, slant, relative size and digit legibility. ", "If the style is undecided, show the sample, recommend a font based on what is visible, and ask if it fits before laying out the full page. ", - "Keep an approved font. For a less regular hand inspect describe_controls(group=variation) and preview a small change. If the user wants occasional corrections, inspect group=strike. Only consider separate settings for letters or digits when the user specifically requests them or expresses dissatisfaction with their appearance; then inspect describe_controls(group=typography)." + "Keep an approved font, or apply the chosen candidate's tune_arguments once. Render diagram labels with that same draft font. For a less regular hand inspect describe_controls(group=variation) and preview a small change. If the user wants occasional corrections, inspect group=strike. Only consider separate settings for letters or digits when the user specifically requests them or expresses dissatisfaction with their appearance; then inspect describe_controls(group=typography)." ); let mut data = json!({ "entries": page.fonts, "total": page.total, @@ -562,7 +576,7 @@ impl Panache { } #[tool( - description = "Adjust selected glyphs in one section/page by IDs from its layout view. Use the same revision. Offsets and shape are in paper space before sheet projection. Use place_center for a group move; target_quad maps the entire selected text block into four corners on the image. Shape adjusts each glyph individually. An ID is local to the exact layout revision, section and page that returned it. After an intervening edit, read the latest layout and resolve the intended glyph again; do not reuse old IDs by changing only expected_revision." + description = "Adjust selected glyphs by IDs from this section/page's layout at the same revision. For worksheet lettering use natural_line with two image points on the writing baseline. It preserves original letter proportions and spacing in paper space, replaces prior warps, and leaves unused row width blank. Use one uniform size across related rows. Use place_center for a group move. Use target_quad only for an intentional exact four-corner warp. Offsets and per-glyph shape are in paper space. After an intervening edit, read the latest layout and locate the intended glyph again; do not reuse old IDs by changing only expected_revision." )] async fn adjust_glyphs( &self, @@ -583,11 +597,15 @@ impl Panache { input.note.as_ref().is_none_or(|s| s.chars().count() <= 320), "Note exceeds 320 characters" ); - let next = engine.adjust(&draft, section, &input, cancel)?; - Ok(reply( - format!("Saved revision {next}."), - json!({"draft_id":draft.id,"revision":next,"count":input.ids.len()}), - )) + let (next, placement) = engine.adjust(&draft, section, &input, cancel)?; + let mut message = format!("Saved revision {next}."); + let mut data = json!({"draft_id":draft.id,"revision":next,"count":input.ids.len()}); + if let Some(report) = placement { + message.push(' '); + message.push_str(&report.summary()); + data["placement"] = json!(report); + } + Ok(reply(message, data)) }) .await, ) diff --git a/crates/panache-mcp/src/placement.rs b/crates/panache-mcp/src/placement.rs index 9b69a221..deb2eab4 100644 --- a/crates/panache-mcp/src/placement.rs +++ b/crates/panache-mcp/src/placement.rs @@ -1,30 +1,145 @@ -//! Place a selection's original layout rectangle into four corners on the photograph. -use crate::drafts::Snapshot; +//! Map the original paper-space layout to a baseline or to exact corners on the photograph. +use crate::NaturalLine; use anyhow::{Result, ensure}; use handwriting_core::fine_edit::{Adjustment, GlyphBounds}; +use handwriting_core::photo::PaperProjection; +use serde::Serialize; + +#[derive(Serialize)] +#[serde(tag = "mode", rename_all = "snake_case")] +pub enum PlacementReport { + NaturalLine { + scale_percent: u8, + used_paper_px: f64, + available_paper_px: f64, + }, + TargetQuad { + max_glyph_center_axis_ratio: f64, + }, +} + +impl PlacementReport { + pub fn summary(&self) -> String { + match self { + Self::NaturalLine { + scale_percent, + used_paper_px, + available_paper_px, + } => format!( + "Natural line at {scale_percent}% uniform size uses {used_paper_px:.1} of {available_paper_px:.1} paper pixels." + ), + Self::TargetQuad { + max_glyph_center_axis_ratio: ratio, + } => { + let advice = if *ratio >= 1.15 { + " For proportional lettering along a worksheet row, use natural_line." + } else { + "" + }; + format!( + "Exact four-corner warp. The largest local major/minor scale ratio sampled at glyph centers is {ratio:.2}× in paper space.{advice}" + ) + } + } + } +} + +fn paper_points( + projection: Option<&PaperProjection>, + size: [u32; 2], + points: [[u32; 2]; N], +) -> Result<[[f64; 2]; N]> { + let mut result = [[0.; 2]; N]; + for (dst, src) in result.iter_mut().zip(points) { + ensure!( + src[0] < size[0] && src[1] < size[1], + "Target point outside the image" + ); + let pt = src.map(|v| v as f32); + *dst = projection.map_or(pt, |m| m.paper_point(pt)).map(f64::from); + ensure!( + dst.iter().all(|v| v.is_finite()), + "Invalid paper coordinates" + ); + } + Ok(result) +} + +fn selection_bounds(glyphs: &[GlyphBounds]) -> Result<[f64; 4]> { + let mut left = f64::INFINITY; + let mut top = f64::INFINITY; + let mut right = f64::NEG_INFINITY; + let mut bottom = f64::NEG_INFINITY; + for glyph in glyphs { + let [x, y, w, h] = glyph.bounds.map(f64::from); + left = left.min(x); + top = top.min(y); + right = right.max(x + w); + bottom = bottom.max(y + h); + } + ensure!(right > left && bottom > top, "Empty selection"); + Ok([left, top, right - left, bottom - top]) +} pub struct Placement { - // Paper-space homography normalized at the selection's top left. + // Paper-space homography normalized at the source origin. matrix: [f64; 8], origin: [f64; 2], } impl Placement { - pub fn new( - draft: &Snapshot<'_>, + pub fn natural_line( + projection: Option<&PaperProjection>, + size: [u32; 2], + glyphs: &[GlyphBounds], + line: &NaturalLine, + ) -> Result<(Self, PlacementReport)> { + let [start, end] = paper_points(projection, size, [line.start, line.end])?; + let [left, _, width, _] = selection_bounds(glyphs)?; + let baseline = glyphs[0].baseline; + ensure!( + glyphs.iter().all(|g| g.baseline == baseline + && g.illustration.is_none() + && !g.is_native_diagram), + "Select text on one original layout baseline for natural_line; place each source line separately" + ); + let scale_percent = line.scale_percent.unwrap_or(100); + ensure!( + (50..=200).contains(&scale_percent), + "natural_line scale_percent must be 50..200" + ); + let scale = f64::from(scale_percent) / 100.; + let (dx, dy) = (end[0] - start[0], end[1] - start[1]); + let available = dx.hypot(dy); + ensure!( + available > 0., + "Supply two distinct natural_line baseline points" + ); + let used = width * scale; + ensure!( + used <= available, + "Selection needs {used:.1} paper pixels at {scale_percent}%; only {available:.1} are available. Split the line, extend the baseline, or choose a smaller uniform scale_percent for the worksheet." + ); + let (a, b) = (scale * dx / available, scale * dy / available); + Ok(( + Self { + matrix: [a, -b, start[0], b, a, start[1], 0., 0.], + origin: [left, f64::from(baseline)], + }, + PlacementReport::NaturalLine { + scale_percent, + used_paper_px: used, + available_paper_px: available, + }, + )) + } + + pub fn target_quad( + projection: Option<&PaperProjection>, size: [u32; 2], glyphs: &[GlyphBounds], quad: [[u32; 2]; 4], - ) -> Result { - let mut corners = [[0.; 2]; 4]; - let map = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); - for (dst, src) in corners.iter_mut().zip(quad) { - ensure!( - src[0] < size[0] && src[1] < size[1], - "Target corner outside the image" - ); - let pt = src.map(|v| v as f32); - *dst = map.map_or(pt, |m| m.paper_point(pt)).map(f64::from); - } + ) -> Result<(Self, PlacementReport)> { + let corners = paper_points(projection, size, quad)?; for i in 0..4 { let [a, b, c] = [corners[i], corners[(i + 1) % 4], corners[(i + 2) % 4]]; ensure!( @@ -32,19 +147,7 @@ impl Placement { "Supply a convex TL, TR, BR, BL quadrilateral" ); } - let mut left = f64::INFINITY; - let mut top = f64::INFINITY; - let mut right = f64::NEG_INFINITY; - let mut bottom = f64::NEG_INFINITY; - for g in glyphs { - let [x, y, w, h] = g.bounds.map(f64::from); - left = left.min(x); - top = top.min(y); - right = right.max(x + w); - bottom = bottom.max(y + h); - } - let (w, h) = (right - left, bottom - top); - ensure!(w > 0. && h > 0., "Empty selection"); + let [left, top, w, h] = selection_bounds(glyphs)?; let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = corners; let (ax, ay) = (x1 - x2, y1 - y2); let (bx, by) = (x3 - x2, y3 - y2); @@ -53,7 +156,7 @@ impl Placement { let det = ax * by - ay * bx; let g = (dx * by - dy * bx) / det; let k = (ax * dy - ay * dx) / det; - Ok(Self { + let placement = Self { origin: [left, top], matrix: [ (x1 * (1. + g) - x0) / w, @@ -65,7 +168,31 @@ impl Placement { g / w, k / h, ], - }) + }; + let mut max_ratio: f64 = 1.; + for glyph in glyphs { + let [x, y, w, h] = glyph.bounds.map(f64::from); + let ratio = placement.axis_ratio_at(x + w / 2. - left, y + h / 2. - top); + ensure!(ratio.is_finite(), "Degenerate perspective at glyph center"); + max_ratio = max_ratio.max(ratio); + } + Ok(( + placement, + PlacementReport::TargetQuad { + max_glyph_center_axis_ratio: max_ratio, + }, + )) + } + + // Singular-value ratio of the local Jacobian. Its common scale cancels. + fn axis_ratio_at(&self, u: f64, v: f64) -> f64 { + let [a, b, c, d, e, f, g, k] = self.matrix; + let z = 1. + g * u + k * v; + let x = (a * u + b * v + c) / z; + let y = (d * u + e * v + f) / z; + let [a, b, d, e] = [a - x * g, b - x * k, d - y * g, e - y * k]; + let major = ((a + e).hypot(d - b) + (a - e).hypot(d + b)) / 2.; + major * major / (a * e - b * d).abs() } pub fn apply(&self, edit: &mut Adjustment, bounds: [i32; 4]) -> Result<()> { @@ -111,3 +238,71 @@ impl Placement { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn glyph(bounds: [i32; 4], id: u32) -> GlyphBounds { + GlyphBounds { + bounds, + id, + baseline: 80, + is_text: true, + is_native_diagram: false, + source_utf16: None, + illustration: None, + } + } + + #[test] + fn natural_line_respects_photo_direction_and_original_baseline_for_inline_math() { + let projection = PaperProjection::Rotated { + angle: std::f32::consts::FRAC_PI_2, + layout_center: [150., 150.], + photo_center: [150., 150.], + }; + let mut glyphs = [glyph([10, 50, 20, 25], 0), glyph([50, 45, 15, 28], 1)]; + glyphs[1].is_text = false; // A formula shares the text baseline. + let line = NaturalLine { + start: [130, 100], + end: [130, 200], + scale_percent: Some(125), + }; + let (placement, report) = + Placement::natural_line(Some(&projection), [300, 300], &glyphs, &line).unwrap(); + assert!( + matches!(report, PlacementReport::NaturalLine { used_paper_px, available_paper_px, .. } + if (used_paper_px - 68.75).abs() < 1e-6 && (available_paper_px - 100.).abs() < 1e-4) + ); + let [a, b, x0, d, e, y0, _, _] = placement.matrix; + for (x, y) in [(10., 80.), (65., 80.), (50., 45.)] { + let (u, v) = (x - placement.origin[0], y - placement.origin[1]); + let [photo_x, photo_y] = + projection.photo_point((a * u + b * v + x0) as f32, (d * u + e * v + y0) as f32); + assert!((f64::from(photo_x) - (130. - 1.25 * (y - 80.))).abs() < 1e-4); + assert!((f64::from(photo_y) - (100. + 1.25 * (x - 10.))).abs() < 1e-4); + } + glyphs[1].illustration = Some(1); + assert!(Placement::natural_line(Some(&projection), [300, 300], &glyphs, &line).is_err()); + } + + #[test] + fn exact_quad_keeps_illustrations_and_measures_shear_even_with_equal_edge_lengths() { + let mut glyph = glyph([0, 0, 10, 10], 0); + glyph.is_text = false; + glyph.illustration = Some(0); + // Both destination axes have length 5 but their angle is no longer 90°. + let (_, report) = Placement::target_quad( + None, + [30, 30], + &[glyph], + [[10, 10], [15, 10], [18, 14], [13, 14]], + ) + .unwrap(); + assert!( + matches!(report, PlacementReport::TargetQuad { max_glyph_center_axis_ratio } + if (max_glyph_center_axis_ratio - 2.).abs() < 1e-10) + ); + } +} diff --git a/crates/panache-mcp/src/preview.rs b/crates/panache-mcp/src/preview.rs index 3ef171be..7e24852e 100644 --- a/crates/panache-mcp/src/preview.rs +++ b/crates/panache-mcp/src/preview.rs @@ -138,7 +138,15 @@ fn render( input.offset.is_none() && input.limit.is_none(), "offset and limit require view=layout" ); - image(engine, &draft, section, page, input.fresh, cancel) + image( + engine, + &draft, + section, + page, + input.fresh, + !state.preserve_reviews, + cancel, + ) } fn paper(draft: &Snapshot<'_>) -> Result { @@ -163,19 +171,27 @@ fn image( section: Section, page: usize, fresh: bool, + review_allowed: bool, cancel: &Cancellation, ) -> Result { let number = section.number; - let contains_inline_image = section.text.contains("](data:image/"); + let contains_drawing = + section.text.contains("](data:image/") || section.text.contains("\\begin{circuitikz}"); let (preview, cached) = engine.preview_with_refresh(draft, section, page, fresh, cancel)?; let mut message = format!("第 {number} 节 · 第 {page} 页 · 版本 {}", draft.revision); let mut data = json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page_in_section":page,"cached":cached}); - if contains_inline_image { + if contains_drawing { let hint = "如果当前页既有手绘图又有文字,在判断笔迹一致前,用 view=review 加 region 框住一段图线和旁边的字,同倍率比较粗细和墨色。同页看图与字只传当前版,省略 compare_revision。看不清时说明还不能判断。"; message.push('\n'); message.push_str(hint); data["illustration_inspection"] = json!(hint); } + if draft.paper.is_some() && review_allowed { + let hint = "检查照片作业是否可以交付时,用 view=review 查看同页相邻行。按 adjacent_row_check 提供的区域以原尺寸查看字形宽窄和字高;有图时也对照图线与附近正文。"; + message.push('\n'); + message.push_str(hint); + data["photo_review_arguments"] = json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page":page,"view":"review"}); + } let mut result = reply(message, data); result .content diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index 9651257d..b55cb42d 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -1,4 +1,6 @@ +mod consistency; pub mod local; +pub(crate) use consistency::{Bounds, TextSample}; use crate::{controls, drafts::Snapshot, reply}; use anyhow::{Result, ensure}; @@ -82,7 +84,8 @@ fn ruling_offset(paper: &RgbaImage, point: [f32; 2], radius: i32) -> Option pub struct PageSample { pub baselines: Vec<[f32; 2]>, pub content_sha256: String, - pub illustration_and_text: Option<[[f32; 2]; 2]>, + pub text: Vec, + pub drawing: Option, } // Suggest a crop around a sampled text line at native resolution, including neighboring paper. @@ -279,7 +282,7 @@ pub fn page( json!({"sampled":total,"supported_samples":v.len(),"median_abs_dy_px":v.get(v.len()/2)}) }) .collect::>(); - let evidence = json!({ + let mut evidence = json!({ "visibility":status, "photo_size":[w,h], "global_ink":{"rgba":params.fill,"opacity":params.ink_opacity,"thickness":params.ink_thickness,"softness":params.ink_softness,"depth_sigma":params.ink_depth_sigma}, @@ -292,10 +295,24 @@ pub fn page( "changed_pixels_outside_reference":outside, "transparent_png":params.transparent_background, }); + let checks = consistency::checks( + sample, + &paper, + &finished, + ¶ms, + draft.paper.is_some(), + cancel, + )?; + if let Some(rows) = &checks.rows { + evidence["adjacent_rows"] = rows.metrics.clone(); + } + if let Some(ink) = &checks.ink { + evidence["illustration_contrast"] = ink.metrics.clone(); + } let observation = draft.record_review( section, page, - "paper-review/1", + "paper-review/2", &pixel_digest, &sample.content_sha256, &evidence, @@ -312,33 +329,14 @@ pub fn page( metadata["photo_size"] = json!([w, h]); metadata["thumbnail_size"] = json!([result.width(), result.height()]); metadata["next_step"] = json!(next); - if let Some([[x0, y0], [x1, y1]]) = sample.illustration_and_text { - let padding = params.font_size.ceil(); - let x = |v: f32| v.clamp(0., w as f32) as u32; - let y = |v: f32| v.clamp(0., h as f32) as u32; - let (l, t, r, b) = ( - x(x0 - padding), - y(y0 - padding), - x(x1 + padding), - y(y1 + padding), - ); - let mut check = json!({"inspect":"Compare an actual diagram stroke or arrow and adjacent handwriting at the same zoom. Use the supplied preview_arguments as given for one revision; omit compare_revision. Check thickness and darkness. If the diagram alone looks heavy, revise the illustration source and preview again; preserve the surrounding writing. Describe what you can see. If the crop is unavailable or inconclusive, ask for visual confirmation."}); - if l < r - && t < b - && r - l <= REVIEW_MAX_EDGE - && b - t <= REVIEW_MAX_EDGE - && x0 >= 0. - && y0 >= 0. - && x1 <= w as f32 - && y1 <= h as f32 - { - check["preview_arguments"] = json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page,"view":"review","region":[[l,t],[r,t],[r,b],[l,b]]}); - } else { - check["region_guidance"] = json!( - "Choose a small visible portion of the drawing and nearby writing from the finished page; use view=review with region for each at native scale." - ); - } - metadata["illustration_ink_check"] = check; + let arguments = |region| json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page,"view":"review","region":region}); + if let Some(rows) = checks.rows { + metadata["adjacent_row_check"] = rows.guidance(&arguments, + "Inspect these neighboring text rows at native size. The horizontal-to-vertical stretch describes letter proportions on the photo; paper vertical scale describes the change in letter height before photo projection. Compare both rows’ median values and inspect the crop. Check whether the difference suits the writing before making a local edit."); + } + if let Some(ink) = checks.ink { + metadata["illustration_ink_check"] = ink.guidance(&arguments, + "Compare an actual diagram stroke or arrow and nearby writing at native size. The regions measure darkening against the saved paper. Different coverage, overlapping marks, color and paper lighting can affect the readings. Inspect thickness and darkness in the crops. If only the diagram needs changing, adjust its source or pen settings. Use each preview call as given for one revision; omit compare_revision."); } if draft.paper.is_some() { let mut appearance = json!({ diff --git a/crates/panache-mcp/src/review/consistency.rs b/crates/panache-mcp/src/review/consistency.rs new file mode 100644 index 00000000..26eaf867 --- /dev/null +++ b/crates/panache-mcp/src/review/consistency.rs @@ -0,0 +1,547 @@ +//! Same-page review in native output pixels. +use super::{PageSample, REVIEW_MAX_EDGE}; +use anyhow::Result; +use handwriting_core::{Cancellation, Parameters}; +use image::{Pixel, Rgba, RgbaImage}; +use serde_json::{Value, json}; + +type Region = [[u32; 2]; 4]; + +#[derive(Clone, Copy)] +pub(crate) struct Bounds { + left: f32, + top: f32, + right: f32, + bottom: f32, +} + +impl Bounds { + pub fn from_corners(corners: [[f32; 2]; 4]) -> Self { + let [x, y] = corners[0]; + let mut b = Self { + left: x, + top: y, + right: x, + bottom: y, + }; + for [x, y] in corners { + b.left = b.left.min(x); + b.top = b.top.min(y); + b.right = b.right.max(x); + b.bottom = b.bottom.max(y); + } + b + } + + fn union(self, b: Self) -> Self { + Self { + left: self.left.min(b.left), + top: self.top.min(b.top), + right: self.right.max(b.right), + bottom: self.bottom.max(b.bottom), + } + } + + fn center(self) -> [f32; 2] { + [(self.left + self.right) / 2., (self.top + self.bottom) / 2.] + } + + fn gap(self, other: Self) -> f32 { + let x = (self.left.max(other.left) - self.right.min(other.right)).max(0.); + let y = (self.top.max(other.top) - self.bottom.min(other.bottom)).max(0.); + x.hypot(y) + } + + fn intersects(self, other: Self) -> bool { + self.left < other.right + && self.right > other.left + && self.top < other.bottom + && self.bottom > other.top + } + + fn width(self) -> f32 { + self.right - self.left + } + + fn height(self) -> f32 { + self.bottom - self.top + } + + fn on_page(self, (w, h): (u32, u32)) -> bool { + self.width() > 0. + && self.height() > 0. + && self.left >= 0. + && self.top >= 0. + && self.right <= w as f32 + && self.bottom <= h as f32 + } + + fn region(self, padding: f32, (w, h): (u32, u32)) -> Option { + let l = (self.left - padding).floor().clamp(0., w as f32) as u32; + let t = (self.top - padding).floor().clamp(0., h as f32) as u32; + let r = (self.right + padding).ceil().clamp(0., w as f32) as u32; + let b = (self.bottom + padding).ceil().clamp(0., h as f32) as u32; + (l < r && t < b).then_some([[l, t], [r, t], [r, b], [l, b]]) + } +} + +pub(crate) struct TextSample { + pub bounds: Bounds, + pub baseline: f32, + // Ratio of the two projected tile edge lengths normalized to the original tile aspect. + pub stretch: f32, + // Edited vertical centerline length in paper space, relative to the original tile height. + pub paper_vertical_scale: f32, +} + +pub(super) struct Check { + pub metrics: Value, + regions: Vec, +} + +impl Check { + pub fn guidance(&self, arguments: &impl Fn(Region) -> Value, inspect: &str) -> Value { + let mut check = json!({"inspect":inspect}); + if let [region] = self.regions.as_slice() { + check["preview_arguments"] = arguments(*region); + } else { + check["separate_preview_arguments"] = json!( + self.regions + .iter() + .copied() + .map(arguments) + .collect::>() + ); + } + check + } +} + +fn crops(pair: [Bounds; 2], anchors: [[f32; 2]; 2], size: (u32, u32), padding: f32) -> Vec { + if let Some(r) = pair[0].union(pair[1]).region(padding, size) + && r[2][0] - r[0][0] <= REVIEW_MAX_EDGE + && r[2][1] - r[0][1] <= REVIEW_MAX_EDGE + { + return vec![r]; + } + // At a distance, keep both samples at native resolution, centered on visible ink when available. + anchors + .iter() + .filter_map(|&p| Bounds::from_corners([p; 4]).region(padding.clamp(64., 240.), size)) + .collect() +} + +fn median(numbers: &mut [f32]) -> f32 { + numbers.sort_unstable_by(f32::total_cmp); + (numbers[numbers.len() / 2] + numbers[(numbers.len() - 1) / 2]) / 2. +} + +fn adjacent_rows(text: &[&TextSample], size: (u32, u32), params: &Parameters) -> Option { + let mut sorted = text.to_vec(); + sorted.sort_unstable_by(|a, b| a.baseline.total_cmp(&b.baseline)); + let spacing = params.line_spacing.max(1.); + let mut rows: Vec> = Vec::new(); + for glyph in sorted { + if let Some(row) = rows.last_mut() + && glyph.baseline - row[0].baseline <= spacing * 0.35 + { + row.push(glyph); + } else { + rows.push(vec![glyph]); + } + } + // Fields on the same baseline can belong to separate columns. Compare contiguous runs only. + let rows: Vec<_> = rows + .into_iter() + .map(|mut row| { + row.sort_unstable_by(|a, b| a.bounds.left.total_cmp(&b.bounds.left)); + let mut spans: Vec> = Vec::new(); + let mut right = f32::NEG_INFINITY; + for g in row { + if g.bounds.left - right > 2.5 * g.bounds.height().max(g.bounds.width()) { + spans.push(Vec::new()); + right = g.bounds.right; + } + right = right.max(g.bounds.right); + spans.last_mut().unwrap().push(g); + } + spans + }) + .collect(); + let mut best = None; + for pair in rows.windows(2) { + for upper in &pair[0] { + for lower in &pair[1] { + if lower[0].baseline - upper[0].baseline <= spacing * 2.5 + && let Some((factor, check)) = + compare_spans(upper, lower, size, params.font_size) + && best.as_ref().is_none_or(|(prior, _)| factor > *prior) + { + best = Some((factor, check)); + } + } + } + } + best.map(|(_, check)| check) +} + +fn compare_spans( + upper: &[&TextSample], + lower: &[&TextSample], + size: (u32, u32), + font_size: f32, +) -> Option<(f32, Check)> { + let extents = |row: &[&TextSample]| row.iter().map(|s| s.bounds).reduce(Bounds::union).unwrap(); + let a = extents(upper); + let b = extents(lower); + let left = a.left.max(b.left); + let right = a.right.min(b.right); + if left >= right { + return None; + } + let mid = (left + right) / 2.; + let radius = (font_size * 7.).clamp(80., 320.); + let measure = |row: &[&TextSample]| { + let samples = row.iter().filter(|g| { + let x = g.bounds.center()[0]; + x >= left.max(mid - radius) && x <= right.min(mid + radius) + }); + let mut stretches: Vec<_> = samples.clone().map(|g| g.stretch).collect(); + if stretches.len() < 3 { + return None; + } + let mut scales: Vec<_> = samples.clone().map(|g| g.paper_vertical_scale).collect(); + let bounds = samples.map(|g| g.bounds).reduce(Bounds::union)?; + Some(( + bounds, + median(&mut stretches), + median(&mut scales), + stretches.len(), + )) + }; + let (first, a, upper_scale, n) = measure(upper)?; + let (second, b, lower_scale, m) = measure(lower)?; + if first.center()[1] >= second.center()[1] { + return None; + } + let aspect_ratio = (a / b).max(b / a); + let scale_ratio = (upper_scale / lower_scale).max(lower_scale / upper_scale); + Some(( + aspect_ratio.max(scale_ratio), + Check { + metrics: json!({"sampled_glyphs":[n,m],"median_horizontal_to_vertical_stretch":[a,b], + "larger_to_smaller_ratio":aspect_ratio,"median_paper_vertical_scale":[upper_scale,lower_scale], + "larger_to_smaller_scale_ratio":scale_ratio,"photo_regions":[first.region(0.,size),second.region(0.,size)], + "selection":"Largest change in median aspect or median vertical scale between adjacent text rows in a shared horizontal span, at least three glyphs per row. Stretch includes photo projection. Vertical scale measures the edited height in paper space relative to each tile’s own original height."}), + regions: crops( + [first, second], + [first.center(), second.center()], + size, + font_size * 0.6, + ), + }, + )) +} + +fn light(pixel: Rgba) -> u8 { + let y = u16::from(pixel.to_luma()[0]); + (255 - ((255 - y) * u16::from(pixel[3])).div_ceil(255)) as u8 +} + +fn darkness( + region: Region, + paper: &RgbaImage, + finished: &RgbaImage, + toward: [f32; 2], + exclusions: &[Bounds], + cancel: &Cancellation, +) -> Result<(Value, [f32; 2])> { + let [l, t] = region[0]; + let [r, b] = region[2]; + let mut hist = [0u32; 256]; + let mut nearest = [(r + l) as f32 / 2., (b + t) as f32 / 2.]; + let mut min_distance = f32::INFINITY; + // Only boxes crossing this scan line can obscure ownership. Merge by marking the row spans. + let mut excluded = vec![false; (r - l) as usize]; + let mut excluded_pixels = 0u32; + for y in t..b { + excluded.fill(false); + for other in exclusions + .iter() + .filter(|g| (y as f32 + 0.5) >= g.top && (y as f32 + 0.5) < g.bottom) + { + let start = ((other.left - 0.5).ceil() as u32).clamp(l, r) - l; + let end = ((other.right - 0.5).ceil() as u32).clamp(l, r) - l; + excluded[start as usize..end as usize].fill(true); + } + cancel.check()?; + for x in l..r { + if excluded[(x - l) as usize] { + excluded_pixels += 1; + continue; + } + let delta = light(paper[(x, y)]).saturating_sub(light(finished[(x, y)])); + if delta >= 8 { + hist[usize::from(delta)] += 1; + let dx = x as f32 - toward[0]; + let dy = y as f32 - toward[1]; + let distance = dx * dx + dy * dy; + if distance < min_distance { + min_distance = distance; + nearest = [x as f32, y as f32]; + } + } + } + } + let count = hist.iter().sum::(); + let percentile = |percent: u64| { + let rank = (u64::from(count) * percent).div_ceil(100) as u32; + let mut total = 0; + hist.iter().position(|&n| { + total += n; + rank > 0 && total >= rank + }) + }; + Ok(( + json!({"region":region, "darkened_pixels":count, "overlap_pixels_excluded":excluded_pixels, "median_luma_drop":percentile(50),"p90_luma_drop":percentile(90)}), + nearest, + )) +} + +pub(super) struct Checks { + pub rows: Option, + pub ink: Option, +} + +pub(super) fn checks( + sample: &PageSample, + paper: &RgbaImage, + finished: &RgbaImage, + params: &Parameters, + photo: bool, + cancel: &Cancellation, +) -> Result { + let size = paper.dimensions(); + let text: Vec<_> = sample + .text + .iter() + .filter(|g| { + g.bounds.on_page(size) + && g.stretch.is_finite() + && g.stretch > 0. + && g.paper_vertical_scale.is_finite() + && g.paper_vertical_scale > 0. + }) + .collect(); + let rows = if photo { + adjacent_rows(&text, size, params) + } else { + None + }; + let mut ink = None; + if let Some(drawing) = sample.drawing + && let Some(diagram_region) = drawing.region(0., size) + && let Some(nearest) = text.iter().min_by(|a, b| { + // A short line beside the diagram is usually a closer body-writing reference than a title above it. + // Use simple geometric priorities and retain the actual separation in the receipt. + let rank = |g: &TextSample| { + let b = g.bounds; + let side = (drawing.top..=drawing.bottom).contains(&b.center()[1]) + && drawing.gap(b) <= b.height().max(16.) * 4.; + (drawing.intersects(b), !side) + }; + rank(a) + .cmp(&rank(b)) + .then_with(|| drawing.gap(a.bounds).total_cmp(&drawing.gap(b.bounds))) + }) + { + let mut neighbors: Vec<_> = text + .iter() + .filter(|g| { + let on_same_side = (g.bounds.center()[0] < drawing.center()[0]) + == (nearest.bounds.center()[0] < drawing.center()[0]); + on_same_side + && (g.baseline - nearest.baseline).abs() <= params.line_spacing * 0.25 + && g.bounds.gap(nearest.bounds) <= nearest.bounds.height().max(16.) * 3. + && !drawing.intersects(g.bounds) + }) + .collect(); + neighbors.sort_unstable_by(|a, b| { + a.bounds + .gap(nearest.bounds) + .total_cmp(&b.bounds.gap(nearest.bounds)) + }); + let writing_box = neighbors + .into_iter() + .take(4) + .fold(nearest.bounds, |b, g| b.union(g.bounds)); + let text_region = writing_box.region(0., size).unwrap(); + let overlaps: Vec<_> = text + .iter() + .map(|g| g.bounds) + .filter(|b| b.intersects(drawing)) + .collect(); + let (diagram, stroke) = darkness( + diagram_region, + paper, + finished, + nearest.bounds.center(), + &overlaps, + cancel, + )?; + let (writing, letter) = darkness(text_region, paper, finished, stroke, &[drawing], cancel)?; + let gap = drawing.gap(writing_box); + ink = Some(Check { + metrics: json!({"illustration":diagram,"nearby_text":writing,"minimum_luma_drop":8,"region_gap_px":gap, "distant_reference":gap > nearest.bounds.height().max(16.) * 6., + "sampling":"Saved-paper luma minus output luma (0–255) among darkened pixels in each layout box. Text boxes overlapping the diagram are masked from its sample, and diagram pixels are excluded from the writing sample. A distant reference or too little sampled ink needs visual confirmation."}), + regions: crops( + [drawing, writing_box], + [stroke, letter], + size, + params.font_size, + ), + }); + } + Ok(Checks { rows, ink }) +} + +#[cfg(test)] +mod tests { + use super::*; + use image::Rgba; + + fn bounds(left: f32, top: f32, right: f32, bottom: f32) -> Bounds { + Bounds::from_corners([[left, top], [right, top], [right, bottom], [left, bottom]]) + } + + #[test] + fn shared_pixels_do_not_count_as_diagram_or_body_ink() { + let paper = RgbaImage::from_pixel(80, 60, Rgba([255; 4])); + let mut finished = paper.clone(); + for y in 15..20 { + for x in 15..20 { + finished[(x, y)] = Rgba([0, 0, 0, 255]); + } + } + let sample = PageSample { + baselines: vec![], + content_sha256: String::new(), + drawing: Some(bounds(5., 5., 40., 40.)), + text: vec![TextSample { + bounds: bounds(15., 15., 20., 20.), + baseline: 22., + stretch: 1., + paper_vertical_scale: 1., + }], + }; + let check = checks( + &sample, + &paper, + &finished, + &Parameters::default(), + true, + &Cancellation::default(), + ) + .unwrap() + .ink + .unwrap(); + for name in ["illustration", "nearby_text"] { + let m = &check.metrics[name]; + assert_eq!(m["overlap_pixels_excluded"], 25); + assert_eq!(m["darkened_pixels"], 0); + assert!(m["p90_luma_drop"].is_null()); + } + } + + #[test] + fn distant_chart_and_writing_have_two_native_crops() { + let paper = RgbaImage::from_pixel(1300, 100, Rgba([255; 4])); + let mut finished = paper.clone(); + finished[(5, 5)] = Rgba([0, 0, 0, 255]); + finished[(1105, 5)] = Rgba([127, 127, 127, 255]); + let sample = PageSample { + baselines: vec![], + content_sha256: String::new(), + drawing: Some(bounds(0., 0., 100., 80.)), + text: vec![TextSample { + bounds: bounds(1100., 0., 1150., 40.), + baseline: 40., + stretch: 1., + paper_vertical_scale: 1., + }], + }; + let check = checks( + &sample, + &paper, + &finished, + &Parameters::default(), + true, + &Cancellation::default(), + ) + .unwrap() + .ink + .unwrap(); + assert_eq!(check.metrics["distant_reference"], true); + assert_eq!(check.metrics["illustration"]["p90_luma_drop"], 255); + assert_eq!(check.metrics["nearby_text"]["median_luma_drop"], 128); + assert_eq!(check.regions.len(), 2); + for (x, r) in [5, 1105].into_iter().zip(check.regions) { + assert!(r[0][0] <= x && x < r[2][0]); + assert!(r[2][0] - r[0][0] <= REVIEW_MAX_EDGE); + } + } + + #[test] + fn larger_size_jump_is_selected_even_with_equal_letter_proportions() { + let text: Vec<_> = [(28., 1.1, 1.), (58., 1., 1.), (88., 1., 1.5)] + .into_iter() + .flat_map(|(baseline, stretch, paper_vertical_scale)| { + (0..5).map(move |i| { + let x = 20. + i as f32 * 18.; + TextSample { + bounds: bounds(x, baseline - 16. * paper_vertical_scale, x + 14., baseline), + baseline, + stretch, + paper_vertical_scale, + } + }) + }) + .collect(); + let refs: Vec<_> = text.iter().collect(); + let check = adjacent_rows( + &refs, + (160, 120), + &Parameters { + line_spacing: 30., + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(check.metrics["larger_to_smaller_ratio"], 1.); + assert_eq!( + check.metrics["median_paper_vertical_scale"], + json!([1., 1.5]) + ); + assert_eq!(check.metrics["larger_to_smaller_scale_ratio"], 1.5); + } + + #[test] + fn separate_columns_do_not_form_a_comparable_row_pair() { + let text: Vec<_> = [(0., 20., 1.), (200., 20., 1.), (80., 60., 2.)] + .into_iter() + .flat_map(|(x, y, stretch)| { + (0..4).map(move |i| { + let l = x + i as f32 * 12.; + TextSample { + bounds: bounds(l, y - 15., l + 10., y), + baseline: y, + stretch, + paper_vertical_scale: 1., + } + }) + }) + .collect(); + let refs: Vec<_> = text.iter().collect(); + assert!(adjacent_rows(&refs, (400, 200), &Parameters::default()).is_none()); + } +} diff --git a/crates/panache-mcp/src/save.rs b/crates/panache-mcp/src/save.rs index 565c81e2..60bb43ed 100644 --- a/crates/panache-mcp/src/save.rs +++ b/crates/panache-mcp/src/save.rs @@ -131,6 +131,28 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn illustration_pen_default_is_pinned_when_homework_is_created() -> Result<()> { + for (args, enabled) in [ + (json!({}), false), + (json!({"homework":true}), true), + ( + json!({"homework":true,"illustration_uses_pen":false}), + false, + ), + (json!({"illustration_uses_pen":true}), true), + ] { + let style: crate::CreationStyle = serde_json::from_value(args)?; + assert_eq!( + style.resolve(&[]).illustration_uses_pen.unwrap_or(false), + enabled + ); + } + let archived: Style = serde_json::from_value(json!({"homework":true}))?; + assert!(!archived.illustration_uses_pen.unwrap_or(false)); + Ok(()) + } + #[test] fn homework_variation_is_saved_on_creation_and_respects_overrides() -> Result<()> { use crate::{controls, drafts::Drafts}; diff --git a/crates/panache-mcp/tests/coursework_form.py b/crates/panache-mcp/tests/coursework_form.py index 93393963..ddfbfe11 100644 --- a/crates/panache-mcp/tests/coursework_form.py +++ b/crates/panache-mcp/tests/coursework_form.py @@ -112,3 +112,54 @@ async def place(text, quad): review = (await call(client, "preview_handwriting", **key, revision=revision, view="review")).structuredContent assert review["evidence"]["changed_pixels_outside_reference"] > 0 + + # Recreate a twice-wide worksheet row and restore its original letters with one edit. + async def layout_glyphs(): + layout = (await call(client, "preview_handwriting", **key, revision=revision, + view="layout", limit=32)).structuredContent + return {g["text"]: g for g in layout["glyphs"]} + + glyphs = await layout_glyphs() + line = [glyphs[c] for c in body[0]] + xs, ys = zip(*(p for glyph in line for p in glyph["photo_quad"])) + wide = corners((min(xs), min(ys), min(xs) + 2 * (max(xs) - min(xs)), max(ys))) + targets = dict(ids=[g["id"] for g in line], expected_texts=list(body[0])) + stretched = await call(client, "adjust_glyphs", **key, expected_revision=revision, + **targets, target_quad=wide) + revision = stretched.structuredContent["revision"] + report = stretched.structuredContent["placement"] + assert report["mode"] == "target_quad" and 1.9 < report["max_glyph_center_axis_ratio"] < 2.1 + assert "natural_line" in stretched.content[0].text + distorted = finished_image(await call(client, "preview_handwriting", **key, revision=revision)) + row = (78, 118, 383, 159) + original_ink = ink.crop(row) + wide_ink = ink_mask(paper.crop(row), distorted.crop(row)) + assert wide_ink.getbbox()[2] - wide_ink.getbbox()[0] > 1.8 * ( + original_ink.getbbox()[2] - original_ink.getbbox()[0]) + + glyphs = await layout_glyphs() + targets["ids"] = [glyphs[c]["id"] for c in body[0]] + start = min((glyphs[c]["photo_baseline"][0] for c in body[0]), key=lambda p: p[0]) + baseline = {"start": start, "end": [383, start[1]]} + for args, reason in [ + ({"natural_line": {**baseline, "end": [start[0] + 5, start[1]]}}, "Split the line"), + ({"natural_line": baseline, "target_quad": wide}, "separately"), + ({"natural_line": baseline, "ids": [line[0]["id"], glyphs[body[1][0]]["id"]], + "expected_texts": [body[0][0], body[1][0]]}, "one original layout baseline"), + ]: + rejected = await client.call_tool("adjust_glyphs", { + **key, "expected_revision": revision, **targets, **args, + }) + assert rejected.isError and reason in rejected.content[0].text + + restored = await call(client, "adjust_glyphs", **key, expected_revision=revision, + **targets, natural_line=baseline) + revision = restored.structuredContent["revision"] + report = restored.structuredContent["placement"] + assert report["mode"] == "natural_line" and report["scale_percent"] == 100 + assert report["available_paper_px"] > 2 * report["used_paper_px"] + result = finished_image(await call(client, "preview_handwriting", **key, revision=revision)) + aligned = ink_mask(paper.crop(row), result.crop(row)) + intersection = ImageChops.darker(original_ink, aligned).histogram()[255] + union = ImageChops.lighter(original_ink, aligned).histogram()[255] + assert intersection / union > 0.85, (intersection, union) diff --git a/crates/panache-mcp/tests/font_samples.py b/crates/panache-mcp/tests/font_samples.py new file mode 100644 index 00000000..f7c729ad --- /dev/null +++ b/crates/panache-mcp/tests/font_samples.py @@ -0,0 +1,90 @@ +"""Compare MCP font sample pixels to the same photo before and after adopting a face.""" + +import base64 +import io +from pathlib import Path + +from PIL import Image + +from mcp_client import call + + +def images(result): + return [ + Image.open(io.BytesIO(base64.b64decode(block.data, validate=True))).convert("RGBA") + for block in result.content if block.type == "image" + ] + + +async def check(client, local_font): + paper = Path(__file__).resolve().parent / "fixtures" / "ruled.png" + current = "志莽行书.ttf" + draft = (await call( + client, "save_section", markdown="溶液 NaCl 25 mL", paper_path=str(paper), + style={"font": current, "homework": True, "seed": 79}, + )).structuredContent + key = {"draft_id": draft["draft_id"]} + sample = {**key, "revision": 1, "fonts": [local_font], "crop": [12, 10, 376, 210]} + before = images(await call(client, "preview_handwriting", **key))[0] + result = await call(client, "list_fonts", sample=sample) + meta = result.structuredContent + assert meta["current_font"] == current and meta["native_size"] == [400, 500] + assert "同一句" in meta["content_note"] and meta["content_note"] in result.content[0].text + assert "placement_note" not in meta and "background_note" not in meta + assert meta["sample_size"] == [376, 210] + assert [row["font"] for row in meta["samples"]] == [current, local_font] + assert [b.type for b in result.content] == ["text", "text", "image", "text", "image"] + actual, candidate = images(result) + bounds = (12, 10, 388, 220) + assert actual.tobytes() == before.crop(bounds).tobytes() + assert candidate.tobytes() != actual.tobytes() + for invalid in [{"fonts": [current] * 3}, {"crop": [395, 0, 6, 1]}]: + assert (await client.call_tool("list_fonts", {"sample": {**sample, **invalid}})).isError + pinned = await call(client, "preview_handwriting", **key) + assert pinned.structuredContent["revision"] == 1 and pinned.structuredContent["cached"] + assert images(pinned)[0].tobytes() == before.tobytes() + assert "tune_arguments" not in meta["samples"][0] + applied = await call(client, "tune_handwriting", **meta["samples"][1]["tune_arguments"]) + assert applied.structuredContent["revision"] == 2 + after = images(await call(client, "preview_handwriting", **key))[0] + assert after.crop(bounds).tobytes() == candidate.tobytes() + + layout = (await call(client, "preview_handwriting", **key, view="layout", limit=1)).structuredContent + gid = layout["glyphs"][0]["id"] + await call(client, "adjust_glyphs", **key, expected_revision=2, section=1, page=1, ids=[gid], dx=11) + placed = images(await call(client, "preview_handwriting", **key))[0].crop(bounds) + assert placed.tobytes() != candidate.tobytes() + await call(client, "tune_handwriting", **key, expected_revision=3, changes={"transparent_background": True}) + resampled = await call(client, "list_fonts", sample={**sample, "revision": 4, "fonts": [current]}) + meta = resampled.structuredContent + for note in ("placement_note", "background_note"): + assert meta[note] in resampled.content[0].text + sampled_current, alternate = images(resampled) + assert sampled_current.tobytes() == placed.tobytes() + assert alternate.tobytes() == actual.tobytes() + protected = await client.call_tool("tune_handwriting", meta["samples"][1]["tune_arguments"]) + assert protected.isError and "local glyph adjustments" in protected.content[0].text + regular = await call(client, "preview_handwriting", **key) + assert regular.structuredContent["revision"] == 4 + assert images(regular)[0].getchannel("A").getextrema()[0] == 0 + + await check_missing_candidate_page(client) + + +async def check_missing_candidate_page(client): + draft = (await call( + client, "save_section", markdown=" ".join(["WWW"] * 75), style={"font": "青叶手写体.ttf", "seed": 79}, + )).structuredContent + key = {"draft_id": draft["draft_id"]} + await call(client, "tune_handwriting", **key, expected_revision=1, changes={ + "width": 330, "height": 320, "top_margin": 20, "bottom_margin": 22, "left_margin": 20, "right_margin": 20, + }) + missing, present = "李国夫手写体.ttf", "霞鹜文楷.ttf" + result = await call(client, "list_fonts", sample={**key, "page": 7, "fonts": [missing, present]}) + meta = result.structuredContent + assert len(images(result)) == 2 + assert [row["font"] for row in meta["samples"]] == ["青叶手写体.ttf", present] + skipped, = meta["unavailable_samples"] + assert (skipped["font"], skipped["section"], skipped["page"]) == (missing, 1, 7) + assert skipped["reason"] == "page_missing_after_reflow" + assert skipped["message"] in [b.text for b in result.content if b.type == "text"] diff --git a/crates/panache-mcp/tests/illustration_ink_check.py b/crates/panache-mcp/tests/illustration_ink_check.py index 09e777e0..e07ed210 100644 --- a/crates/panache-mcp/tests/illustration_ink_check.py +++ b/crates/panache-mcp/tests/illustration_ink_check.py @@ -13,6 +13,51 @@ from review_comparison import slanted_sheet +async def moved_rows(client, paper, guides): + # Both groups start on a single source baseline; each will occupy a different photo row. + saved = await call(client, "save_section", markdown="春夏秋冬东南西北天地山水", + paper_path=str(paper), paper_guides=guides, style={"font_size": 20, "seed": 27}) + key = {"draft_id": saved.structuredContent["draft_id"], "section": 1, "page": 1} + for rev, (word, width, top) in enumerate([("春夏秋冬东南", 220, 125), ("西北天地山水", 140, 165)], 1): + layout = (await call(client, "preview_handwriting", **key, revision=rev, + view="layout", limit=32)).structuredContent["glyphs"] + if rev == 1: + # The guides slope 16 px over 320 px. Compare original baselines at a common x. + levels = [y + x * 16 / 320 for g in layout for x, y in g["photo_baseline"][:1]] + assert max(levels) - min(levels) < 2, levels + selected = [g for g in layout if g["text"] in word] + assert len(selected) == len(word) + await call(client, "adjust_glyphs", **key, expected_revision=rev, + ids=[g["id"] for g in selected], + target_quad=[[65, top], [65 + width, top], [65 + width, top + 28], [65, top + 28]]) + full = (await call(client, "preview_handwriting", **key, revision=3, view="review")).structuredContent + metrics = full["evidence"]["adjacent_rows"] + assert min(metrics["sampled_glyphs"]) >= 3 + a, b = metrics["median_horizontal_to_vertical_stretch"] + assert a / b > 1.3, metrics + args = full["adjacent_row_check"]["preview_arguments"] + assert args["revision"] == 3 and "compare_revision" not in args + local = (await call(client, "preview_handwriting", **args)).structuredContent + assert local["crop_bounds"][2:] == local["crop_image_size"] + for region in metrics["photo_regions"]: + assert all(args["region"][0][0] <= x <= args["region"][2][0] and + args["region"][0][1] <= y <= args["region"][2][1] for x, y in region) + # Reset both placements with proportional lettering. Only the lower row grows. + for rev, (word, scale, y) in enumerate([("春夏秋冬东南", 100, 130), ("西北天地山水", 150, 175)], 3): + layout = (await call(client, "preview_handwriting", **key, revision=rev, + view="layout", limit=32)).structuredContent["glyphs"] + ids = [g["id"] for g in layout if g["text"] in word] + await call(client, "adjust_glyphs", **key, expected_revision=rev, ids=ids, + natural_line={"start": [60, y], "end": [350, y], "scale_percent": scale}) + resized = (await call(client, "preview_handwriting", **key, revision=5, view="review")).structuredContent + scale_check = resized["evidence"]["adjacent_rows"] + upper, lower = scale_check["median_paper_vertical_scale"] + assert abs(upper - 1) < 0.01 and abs(lower - 1.5) < 0.01, scale_check + assert 1.49 < scale_check["larger_to_smaller_scale_ratio"] < 1.51 + assert scale_check["larger_to_smaller_ratio"] < 1.02, scale_check + return metrics["larger_to_smaller_ratio"], scale_check["larger_to_smaller_scale_ratio"] + + async def verify(client, home): paper = home / "ruled.png" guides = slanted_sheet(paper) @@ -28,21 +73,33 @@ async def verify(client, home): cases = [ ("drawings_only", drawings, False), ("drawings_then_text", drawings + "\n\n字", True), + ("native", arrow + "\n\n字", True), ("mixed", "循环 i = 10\n" + diagram, True), ("text", "循环 i = 10", False), ("image", diagram, False), ] result = {} + with open_db(home) as db: + initial = db.execute("SELECT count(*) FROM review_observations").fetchone()[0] for name, markdown, expect_crop in cases: saved = await call(client, "save_section", markdown=markdown, paper_path=str(paper), - paper_guides=guides, style={"seed": 27}) + paper_guides=guides, style={"seed": 27, "illustration_uses_pen": False}) key = {"draft_id": saved.structuredContent["draft_id"], "revision": 1} image = await call(client, "preview_handwriting", **key, view="image") - assert ("illustration_inspection" in image.structuredContent) == (name != "text") + assert ("illustration_inspection" in image.structuredContent) == (diagram in markdown or arrow in markdown) + if name == "mixed": + await call(client, "tune_handwriting", draft_id=key["draft_id"], expected_revision=1, + changes={"ink_opacity": 20}) + key["revision"] = 2 full = await call(client, "preview_handwriting", **key, view="review") check = full.structuredContent.get("illustration_ink_check") assert bool(check) == expect_crop, name if check: + evidence = full.structuredContent["evidence"]["illustration_contrast"] + chart, text = evidence["illustration"], evidence["nearby_text"] + assert min(chart["darkened_pixels"], text["darkened_pixels"]) > 0 + if name == "mixed": + assert chart["p90_luma_drop"] > text["p90_luma_drop"] + 30, evidence args = check["preview_arguments"] assert all(args[k] == v for k, v in key.items()) local = await call(client, "preview_handwriting", **args) @@ -50,7 +107,10 @@ async def verify(client, home): assert meta["crop_bounds"][2:] == meta["crop_image_size"] layout = await call(client, "preview_handwriting", **{**args, "view": "layout"}, limit=32) items = layout.structuredContent["glyphs"] - assert any(i.get("kind") == "illustration" for i in items) + if name != "native": + assert any(i.get("kind") == "illustration" for i in items) + else: + assert len(items) >= 2 assert any("kind" not in i for i in items) if name == "drawings_then_text": page = await call(client, "preview_handwriting", **key, view="layout", limit=32) @@ -61,8 +121,9 @@ async def verify(client, home): assert len([p for p in local.content if p.type == "image"]) == 2 result[name + "_crop_size"] = meta["crop_image_size"] result[name] = bool(check) + result["moved_row_ratio"], result["uniform_scale_ratio"] = await moved_rows(client, paper, guides) with open_db(home) as db: - assert db.execute("SELECT count(*) FROM review_observations").fetchone()[0] == len(cases) + assert db.execute("SELECT count(*) FROM review_observations").fetchone()[0] == initial + len(cases) + 2 return result diff --git a/crates/panache-mcp/tests/illustration_pen.py b/crates/panache-mcp/tests/illustration_pen.py new file mode 100644 index 00000000..fe3da623 --- /dev/null +++ b/crates/panache-mcp/tests/illustration_pen.py @@ -0,0 +1,44 @@ +"""Verify pen inheritance against the exported diagram pixels, including old revisions.""" + +import base64 +import io +from pathlib import Path +from zipfile import ZipFile + +from PIL import Image, ImageDraw + +from mcp_client import call + + +async def verify(client): + drawing = Image.new("RGB", (110, 60), "white") + draw = ImageDraw.Draw(drawing) + draw.rectangle((6, 6, 70, 50), outline="black", width=4) + draw.line((70, 29, 105, 29), fill="black", width=3) + buffer = io.BytesIO() + drawing.save(buffer, "PNG") + markdown = "![CFG](data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode() + ")" + saved = await call(client, "save_section", markdown=markdown, + style={"homework": True, "ink": "#943020", "seed": 13}) + key = {"draft_id": saved.structuredContent["draft_id"]} + + async def preview(revision): + result = await call(client, "preview_handwriting", revision=revision, **key) + return base64.b64decode(next(item.data for item in result.content if item.type == "image")) + + original = await preview(1) + red = Image.open(io.BytesIO(original)).convert("RGB") + assert any(r > g + 35 and r > b + 35 for r, g, b in red.getdata()) + for rev, changes in [(1, {"illustration_uses_pen": False}), + (2, {"illustration_uses_pen": True, "ink_opacity": 0})]: + applied = await call(client, "tune_handwriting", expected_revision=rev, changes=changes, **key) + assert applied.structuredContent["fine_layout"] == "preserved" + legacy = Image.open(io.BytesIO(await preview(2))).convert("RGB") + assert not any(r > g + 35 for r, g, _ in legacy.getdata()) + assert min(legacy.getextrema()[0]) < 150 + clear = Image.open(io.BytesIO(await preview(3))).convert("RGB") + assert clear.getextrema() == ((255, 255),) * 3 + assert await preview(1) == original + exported = await call(client, "export_handwriting", revision=1, format="zip", **key) + with ZipFile(Path(exported.structuredContent["path"])) as archive: + assert archive.read("0.png") == original diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 9ccc5ef5..6628192f 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -18,6 +18,9 @@ from PIL import Image import coursework_form +import illustration_pen +import illustration_ink_check +import font_samples import review_comparison from mcp_client import call @@ -324,6 +327,7 @@ async def smoke(command, arguments, out): assert results["total"] == 1 and results["next_offset"] is None entry = results["entries"][0] assert entry["source"] == "user" and entry["filename"] == custom_font.name + await font_samples.check(client, entry["id"]) saved_font = (await call(client, "save_section", markdown="ABC 123", style={"font": entry["id"]})).structuredContent font_key = {"draft_id": saved_font["draft_id"]} second = (await call(client, "list_fonts", source="user", query="secondsample")).structuredContent["entries"][0] @@ -424,6 +428,8 @@ async def smoke(command, arguments, out): await placement_pixels(client) await glyph_target_text(client) await coursework_form.exercise(client, Path(temp)) + await illustration_pen.verify(client) + await illustration_ink_check.verify(client, Path(temp)) comparison_key, reviewed_id, user_quote = await review_comparison.exercise(client, Path(temp), call) # Keep the traditional eight verse lines for a single folio. poem = POEM.replace(",", ",\n") diff --git a/crates/panache-mcp/tool-design.md b/crates/panache-mcp/tool-design.md index e2c51d1a..8e51b74d 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -40,7 +40,7 @@ - **有清楚的横线,但字没贴上去。** 在同一份稿上用 `tune_handwriting(paper_guides=…)` 指出第一条和最后一条可写基线,必要时补中间几行。每条包含行号 `row` 和原图上的两个端点 `left:[x,y]`、`right:[x,y]`,首行编号为 0。两个端点沿纸纹取,即使横线在照片里向上斜,也能给模型一个明确的书写方向。传空数组可恢复建稿时的校准。 - **没有横线,或者纸上有画。** `alignment="unverified"` 表示没找到可靠横线。用户已指定右下角或委托选位时,可以在该区域试排。左右都有空白、位置会影响画面时,再问用户想写在哪、哪里要留白。若任务要求填写表头,但表头被裁掉或遮住了,先请用户补拍,或确认只写可见部分。 -- **只需调一块文字。** 在 `view="layout"` 中用原图像素圈选字形中心。投影稿的 `photo_quad` 给出原始字框的左上、右上、右下、左下四角,`photo_baseline` 给出原始基线两端,已有调整另列。要把一组字挪到图中的某点,用 `place_center`;要贴合斜栏或转向侧栏,用 `target_quad` 指定目标四角。只需相对移动时用 `dx/dy`,它们的单位是投影前的纸面像素。纸面上水平移动,在照片上可能同时改变 x 和 y。 +- **只需调一块文字。** 在 `view="layout"` 中用原图像素圈选字形中心。投影稿的 `photo_quad` 给出原始字框的左上、右上、右下、左下四角,`photo_baseline` 给出原始基线两端,已有调整另列。要把一组字挪到图中的某点,用 `place_center`;让同一原始行的文字顺着照片上的横线或斜栏书写,用 `natural_line` 指定基线两端,跨行沿用同一缩放比例。需要精确映射到四角时才用 `target_quad`,结合回执中的轴向形变和相邻行判断效果。只需相对移动时用 `dx/dy`,它们的单位是投影前的纸面像素。纸面上水平移动,在照片上可能同时改变 x 和 y。 局部 `shape` 也在纸面投影之前生效。比如 `{"shear_degrees":4,"top_width_percent":94}` 会让字底向右倾,字顶略窄;设回 0 度和 100% 就还原。字号、行距和边距同样按纸面像素指定,可以在一次修改里一起调整。 From f6e761af94bb9fe60829931ccd5cf5b8501f3b6d Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Fri, 27 Nov 2026 16:50:37 +0800 Subject: [PATCH 02/15] =?UTF-8?q?feat(crates/handwriting-core):=20?= =?UTF-8?q?=E8=AE=A9=E6=B5=81=E7=A8=8B=E5=9B=BE=E6=A0=87=E7=AD=BE=E5=92=8C?= =?UTF-8?q?=E7=BA=BF=E6=A1=86=E4=BD=BF=E7=94=A8=E6=AD=A3=E6=96=87=E5=AD=97?= =?UTF-8?q?=E4=BD=93=E4=B8=8E=E7=AC=94=E5=AE=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:位图流程图把原字体固化在像素中,统一笔色后标签、框线和正文仍有明显差异。 解决手段:新增可选的原生流程图语法,沿用正文标签渲染并按字干横截面定笔宽,让箭头止于形状边界,覆盖实际 Markdown worker 到 stdio 出图路径。 收益:节点和条件随整稿选字,箭杆与同页文字可以在自然字号下使用相称的线宽。 --- .../src/render/glyph/circuit.rs | 72 ++++- .../src/render/glyph/circuit/flowchart.rs | 305 ++++++++++++++++++ crates/handwriting-core/src/text/circuit.rs | 7 +- .../src/text/circuit/labels.rs | 1 + crates/handwriting-core/tests/circuitikz.rs | 13 + crates/panache-mcp/tests/illustration_pen.py | 28 ++ 6 files changed, 415 insertions(+), 11 deletions(-) create mode 100644 crates/handwriting-core/src/render/glyph/circuit/flowchart.rs diff --git a/crates/handwriting-core/src/render/glyph/circuit.rs b/crates/handwriting-core/src/render/glyph/circuit.rs index 7a861c4f..b45ed03e 100644 --- a/crates/handwriting-core/src/render/glyph/circuit.rs +++ b/crates/handwriting-core/src/render/glyph/circuit.rs @@ -6,6 +6,7 @@ use rand_chacha::ChaCha8Rng; use std::f32::consts::{PI, TAU}; mod branch; +mod flowchart; #[derive(Clone, Copy)] enum Stroke { @@ -17,6 +18,7 @@ type CircuitPath = (Vec<(i32, i32)>, Stroke); struct Drawing { paths: Vec, scale: f32, + arrow_size: f32, naturalness: f32, rng: ChaCha8Rng, holes: Vec, @@ -201,7 +203,7 @@ impl Drawing { if len > 0. { let ux = dx / len; let uy = dy / len; - let back = 0.13_f32.min(len * 0.45); + let back = self.arrow_size.min(len * 0.45); let wing = back * 0.47; self.path(vec![ Point(b.0 - ux * back - uy * wing, b.1 - uy * back + ux * wing), @@ -212,7 +214,7 @@ impl Drawing { } } // 2026-11-22:按字体采样的小数笔宽覆盖像素,避免整数笔刷把两像素线扩成三像素。 -fn pen_paths(paths: Vec, width: f32) -> Result> { +fn pen_paths(paths: Vec, width: f32, pen_offset: f32) -> Result> { let mut points = paths.iter().flat_map(|(points, _)| points); let Some(&(x, y)) = points.next() else { return Ok(None); @@ -230,6 +232,11 @@ fn pen_paths(paths: Vec, width: f32) -> Result> { Stroke::Pen => width, Stroke::DotFill => 1., }; + let offset = if matches!(pen, Stroke::Pen) { + pen_offset + } else { + 0. + }; let reach = (diameter + 1.) * 0.5; for pair in points.windows(2) { let ((ax, ay), (bx, by)) = (pair[0], pair[1]); @@ -237,7 +244,7 @@ fn pen_paths(paths: Vec, width: f32) -> Result> { let length_sq = (dx * dx + dy * dy).max(1.); for y in ay.min(by) - pad..=ay.max(by) + pad { for x in ax.min(bx) - pad..=ax.max(bx) + pad { - let (px, py) = ((x - ax) as f32, (y - ay) as f32); + let (px, py) = ((x - ax) as f32 - offset, (y - ay) as f32 - offset); let t = ((px * dx + py * dy) / length_sq).clamp(0., 1.); let distance = (px - t * dx).hypot(py - t * dy); let alpha = @@ -270,7 +277,18 @@ impl Glyphs<'_> { f32::NEG_INFINITY, f32::NEG_INFINITY, ); - for p in circuit.segments.iter().flat_map(|s| [s.start, s.end]) { + for p in circuit + .segments + .iter() + .flat_map(|s| [s.start, s.end]) + .chain( + circuit + .decorations + .iter() + .filter(|_| circuit.flowchart) + .map(|d| d.point), + ) + { bounds.0 = bounds.0.min(p.0); bounds.1 = bounds.1.min(p.1); bounds.2 = bounds.2.max(p.0); @@ -278,9 +296,20 @@ impl Glyphs<'_> { } let span = (bounds.2 - bounds.0).max(bounds.3 - bounds.1).max(1.); let scale = (size * 1.75).clamp(10., 160.).min(1800. / span); + let standard = self.pen.thickness(size); + let width = if circuit.flowchart { + flowchart::pen_width(self.book.primary(), size, standard) + } else { + standard + }; let mut draw = Drawing { paths: Vec::new(), scale, + arrow_size: if circuit.flowchart { + (width * 4. / scale).max(0.20) + } else { + 0.13 + }, naturalness: self.pen.naturalness, rng: self.next_drawing_rng(), holes: Vec::new(), @@ -291,13 +320,29 @@ impl Glyphs<'_> { .chain(circuit.decorations.iter().map(|d| d.point)) .collect(), }; + let mut children = Vec::new(); + let nodes = if circuit.flowchart { + flowchart::nodes(self, circuit, &draw, size, depth, &mut children)? + } else { + Vec::new() + }; let mut labels: Vec<(String, Point, i32)> = Vec::new(); for segment in &circuit.segments { - branch::draw(&mut draw, segment, circuit.american, &mut labels)?; + if circuit.flowchart && segment.kind == "short" { + let segment = flowchart::clip(segment, &nodes)?; + draw.contacts.extend([segment.start, segment.end]); + branch::draw(&mut draw, &segment, circuit.american, &mut labels)?; + } else { + branch::draw(&mut draw, segment, circuit.american, &mut labels)?; + } + } + for node in &nodes { + node.outline(&mut draw); } for decoration in &circuit.decorations { let p = decoration.point; match decoration.kind.as_str() { + "circle" | "rectangle" | "diamond" => {} "circ" => draw.dot(p, false), "ocirc" => draw.dot(p, true), "ground" => { @@ -341,9 +386,9 @@ impl Glyphs<'_> { } } } - let mut children = Vec::new(); + let label_size = if circuit.flowchart { size } else { size * 0.69 }; for (text, p, anchor) in labels { - let g = self.sequence_at(&crate::text::parse(&text), size * 0.69, depth + 1)?; + let g = self.sequence_at(&crate::text::parse(&text), label_size, depth + 1)?; let (x, y) = draw.point(p); let x = match anchor { -1 => x - g.right(), @@ -353,7 +398,13 @@ impl Glyphs<'_> { let y = y - (g.top + g.bottom()) / 2; children.push((g, x, y)); } - if let Some(ink) = pen_paths(draw.finish(), self.pen.thickness(size))? { + // 刚性墨迹以 128 为阈值,偶数像素笔宽须落在两列/两行之间。 + let offset = if circuit.flowchart && (width.round() as u32).is_multiple_of(2) { + 0.5 + } else { + 0. + }; + if let Some(ink) = pen_paths(draw.finish(), width, offset)? { children.push((ink, 0, 0)); } let mut result = Self::compose(0., children, Vec::new())?; @@ -370,6 +421,7 @@ mod tests { Drawing { paths: Vec::new(), scale, + arrow_size: 0.13, naturalness: 1., rng: rand::SeedableRng::seed_from_u64(20261123), holes: Vec::new(), @@ -402,7 +454,7 @@ mod tests { #[test] fn horizontal_ink_coverage_tracks_fractional_pen_width() { for width in [0.75, 1., 1.4, 2., 2.8] { - let ink = pen_paths(vec![(vec![(0, 0), (20, 0)], Stroke::Pen)], width) + let ink = pen_paths(vec![(vec![(0, 0), (20, 0)], Stroke::Pen)], width, 0.) .unwrap() .unwrap(); let coverage: f32 = (0..ink.mask.height()) @@ -416,7 +468,7 @@ mod tests { fn subpixel_wires_survive_the_page_ink_threshold() { use imageproc::region_labelling::{Connectivity, connected_components}; for end in [(72, 31), (31, -72), (-72, -13), (-17, 72), (72, 0), (0, 72)] { - let wire = pen_paths(vec![(vec![(0, 0), end], Stroke::Pen)], 0.75) + let wire = pen_paths(vec![(vec![(0, 0), end], Stroke::Pen)], 0.75, 0.) .unwrap() .unwrap(); let ink = GrayImage::from_fn(wire.mask.width(), wire.mask.height(), |x, y| { diff --git a/crates/handwriting-core/src/render/glyph/circuit/flowchart.rs b/crates/handwriting-core/src/render/glyph/circuit/flowchart.rs new file mode 100644 index 00000000..b901a021 --- /dev/null +++ b/crates/handwriting-core/src/render/glyph/circuit/flowchart.rs @@ -0,0 +1,305 @@ +//! 2026-11-27:用正文字形定节点边框,以路径的原始中心坐标确定实际箭头接点。 +use super::{Circuit, Drawing, Glyphs, Point, PositionedGlyph, Result, TAU}; +use crate::{Error, text::circuit::Segment}; + +// 取字形前景像素所在的最短横截面;在转折、交叉处用中位数抑制局部膨大。 +pub(super) fn pen_width(font: &fontdue::Font, size: f32, fallback: f32) -> f32 { + let sample_size = size.round().clamp(1., 96.); + let mut widths = Vec::new(); + for c in ['B', 'n', '1', '十', '口'] { + if font.lookup_glyph_index(c) == 0 { + continue; + } + let m = font.metrics(c, sample_size); + if m.width > 192 || m.height > 192 || m.width * m.height > 16_384 { + continue; + } + let (_, pixels) = font.rasterize(c, sample_size); + if let Some(width) = stroke_section(&pixels, m.width, m.height) { + widths.push(width); + } + } + widths.sort_by(f32::total_cmp); + widths + .get(widths.len() / 2) + .map_or(fallback, |w| w * size / sample_size) + .max(1.) +} + +fn stroke_section(pixels: &[u8], width: usize, height: usize) -> Option { + let inside = |x: i32, y: i32| { + x >= 0 + && y >= 0 + && (x as usize) < width + && (y as usize) < height + && pixels[y as usize * width + x as usize] >= 128 + }; + let mut sections = vec![f32::INFINITY; pixels.len()]; + for (dx, dy) in [(1, 0), (0, 1), (1, 1), (1, -1)] { + let step = if dx * dy == 0 { + 1. + } else { + std::f32::consts::SQRT_2 + }; + for (i, &pixel) in pixels.iter().enumerate() { + let (x, y) = ((i % width) as i32, (i / width) as i32); + // 仅在线段起点扫描,使每个方向的总工作量与采样面积成正比。 + if pixel < 128 || inside(x - dx, y - dy) { + continue; + } + let mut n = 1; + while inside(x + n * dx, y + n * dy) { + n += 1; + } + let thickness = n as f32 * step; + for t in 0..n { + let slot = &mut sections[(y + t * dy) as usize * width + (x + t * dx) as usize]; + *slot = slot.min(thickness); + } + } + } + sections.retain(|v| v.is_finite()); + if sections.is_empty() { + return None; + } + let middle = sections.len() / 2; + let (_, value, _) = sections.select_nth_unstable_by(middle, f32::total_cmp); + Some(*value) +} + +enum Shape { + Circle, + Rectangle, + Diamond, +} + +pub(super) struct Frame { + shape: Shape, + center: Point, + half_width: f32, + half_height: f32, +} + +pub(super) fn nodes( + glyphs: &mut Glyphs<'_>, + circuit: &Circuit, + draw: &Drawing, + size: f32, + depth: usize, + children: &mut Vec, +) -> Result> { + let mut result = Vec::new(); + let mut label_pixels = 0; + for node in &circuit.decorations { + let shape = match node.kind.as_str() { + "circle" => Shape::Circle, + "rectangle" => Shape::Rectangle, + "diamond" => Shape::Diamond, + _ => continue, + }; + if result.iter().any(|f: &Frame| f.center == node.point) { + return Err(Error::new("invalid_layout", "流程图的节点中心不能重合")); + } + let label = glyphs.sequence_at(&crate::text::parse(&node.text), size, depth + 1)?; + label_pixels += label.mask.len(); + if label_pixels > 16_000_000 { + return Err(Error::new("invalid_layout", "流程图节点文字超过内存预算")); + } + let unit = |pixels: u32| (pixels as f32 / 2. + 0.18 * size) / draw.scale; + let (w, h) = (unit(label.mask.width()), unit(label.mask.height())); + let (half_width, half_height) = match shape { + Shape::Circle => { + let r = w.hypot(h); + (r, r) + } + Shape::Rectangle => (w, h), + Shape::Diamond => (2. * w, 2. * h), + }; + let (x, y) = draw.point(node.point); + let xy = ( + x - (label.left + label.right()) / 2, + y - (label.top + label.bottom()) / 2, + ); + children.push((label, xy.0, xy.1)); + result.push(Frame { + shape, + center: node.point, + half_width, + half_height, + }); + } + Ok(result) +} + +impl Frame { + fn boundary(&self, towards: Point) -> Point { + let (dx, dy) = (towards.0 - self.center.0, towards.1 - self.center.1); + let (x, y) = (dx.abs() / self.half_width, dy.abs() / self.half_height); + let divisor = match self.shape { + Shape::Circle => x.hypot(y), + Shape::Rectangle => x.max(y), + Shape::Diamond => x + y, + }; + Point(self.center.0 + dx / divisor, self.center.1 + dy / divisor) + } + + pub(super) fn outline(&self, draw: &mut Drawing) { + let Point(x, y) = self.center; + let (w, h) = (self.half_width, self.half_height); + if let Shape::Circle = self.shape { + // 在斜向箭头与圆的交点也采样,确保圆弧和箭尖共享同一像素。 + let mut angles: Vec<_> = (0..48).map(|i| TAU * i as f32 / 48.).collect(); + for p in &draw.contacts { + let (dx, dy) = (p.0 - x, p.1 - y); + if (dx.hypot(dy) - w).abs() < 0.0001 { + angles.push(dy.atan2(dx).rem_euclid(TAU)); + } + } + angles.sort_by(f32::total_cmp); + angles.push(TAU); + draw.path( + angles + .into_iter() + .map(|a| Point(x + w * a.cos(), y + h * a.sin())) + .collect(), + ); + return; + } + let corners = match self.shape { + Shape::Rectangle => [ + Point(x - w, y - h), + Point(x + w, y - h), + Point(x + w, y + h), + Point(x - w, y + h), + ], + _ => [ + Point(x - w, y), + Point(x, y - h), + Point(x + w, y), + Point(x, y + h), + ], + }; + for i in 0..4 { + draw.line(corners[i], corners[(i + 1) % 4]); + } + } +} + +pub(super) fn clip(segment: &Segment, nodes: &[Frame]) -> Result { + let endpoint = |start: Point, end: Point| { + nodes + .iter() + .find(|f| f.center == start) + .map_or(start, |f| f.boundary(end)) + }; + let mut clipped = segment.clone(); + clipped.start = endpoint(segment.start, segment.end); + clipped.end = endpoint(segment.end, segment.start); + let (dx, dy) = ( + segment.end.0 - segment.start.0, + segment.end.1 - segment.start.1, + ); + if (clipped.end.0 - clipped.start.0) * dx + (clipped.end.1 - clipped.start.1) * dy <= 0. { + return Err(Error::new( + "invalid_layout", + "流程图连线太短,请增大相邻节点或折点的间距", + )); + } + Ok(clipped) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{FontBook, text}; + + #[test] + fn flowchart_labels_and_outlines_follow_the_selected_body_font_and_size() { + let folder = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/font_assets"); + let chart = |s: &str| { + text::circuit::parse(&format!( + r"\begin{{circuitikz}}[flowchart]{s}\end{{circuitikz}}" + )) + .unwrap() + }; + for font in ["华阳手写体.ttf", "李国夫手写体.ttf"] { + let book = FontBook::new(&std::fs::read(folder.join(font)).unwrap(), &[]).unwrap(); + let mut glyphs = Glyphs::new(&book); + for size in [24., 34., 48.] { + let condition = "i ≤ 10"; + let label = glyphs + .circuit( + &chart(&format!(r"\draw (0,0) node[right]{{{condition}}};")), + size, + 0, + ) + .unwrap(); + let body = glyphs.sequence(&text::parse(condition), size).unwrap(); + assert_eq!(label.mask, body.mask, "{font} {size} condition"); + let body = glyphs.sequence(&text::parse("B6"), size).unwrap(); + let node = glyphs + .circuit(&chart(r"\draw (0,0) node[rectangle]{B6};"), size, 0) + .unwrap(); + let (w, h) = node.mask.dimensions(); + let (bw, bh) = body.mask.dimensions(); + assert!( + (0..=w - bw).any(|x| (0..=h - bh).any(|y| image::imageops::crop_imm( + &node.mask, x, y, bw, bh + ) + .to_image() + == body.mask)), + "{font} {size} node label" + ); + let border: f32 = (0..h) + .map(|y| f32::from(node.mask[(w / 2, y)][0]) / 255.) + .take_while(|v| *v > 0.) + .sum(); + let measured = pen_width(book.primary(), size, glyphs.pen.thickness(size)); + assert!( + (border - measured).abs() < 0.01, + "{font} {size} border: {border}" + ); + let solid_width = (0..h) + .map(|y| node.mask[(w / 2, y)][0]) + .take_while(|v| *v > 0) + .filter(|v| *v >= 128) + .count(); + assert_eq!(solid_width, measured.round() as usize, "{font} {size}"); + } + } + } + + #[test] + fn edges_stop_at_shaped_boundaries_in_writing_direction() { + let source = r"\begin{circuitikz}[flowchart]\draw[->] (0,0) -- (4,4);\end{circuitikz}"; + let segment = &text::circuit::parse(source).unwrap().segments[0]; + for (shape, first) in [ + (Shape::Circle, 2_f32.sqrt()), + (Shape::Rectangle, 2.), + (Shape::Diamond, 1.), + ] { + let nodes = [ + Frame { + shape, + center: Point(0., 0.), + half_width: 2., + half_height: 2., + }, + Frame { + shape: Shape::Rectangle, + center: Point(4., 4.), + half_width: 0.5, + half_height: 0.75, + }, + ]; + let clipped = clip(segment, &nodes).unwrap(); + assert!( + (clipped.start.0 - first).abs() < 0.0001 + && (clipped.start.1 - first).abs() < 0.0001 + ); + assert_eq!(clipped.end, Point(3.5, 3.5)); + assert!(clipped.end_arrow); + } + } +} diff --git a/crates/handwriting-core/src/text/circuit.rs b/crates/handwriting-core/src/text/circuit.rs index 8fe990d3..62cbac45 100644 --- a/crates/handwriting-core/src/text/circuit.rs +++ b/crates/handwriting-core/src/text/circuit.rs @@ -28,6 +28,7 @@ pub struct Decoration { #[derive(Debug, Clone, PartialEq)] pub struct Circuit { pub american: bool, + pub flowchart: bool, pub segments: Vec, pub decorations: Vec, } @@ -173,6 +174,8 @@ impl<'a> Parser<'a> { } [kind] if ANCHORS.contains(kind) + || (self.circuit.flowchart + && matches!(*kind, "circle" | "rectangle" | "diamond")) || matches!(*kind, "" | "ground" | "rground" | "circ" | "ocirc") => { (self.current, *kind) @@ -297,6 +300,7 @@ pub fn parse(source: &str) -> Option { names: HashMap::new(), circuit: Circuit { american: false, + flowchart: false, segments: Vec::new(), decorations: Vec::new(), }, @@ -309,6 +313,7 @@ pub fn parse(source: &str) -> Option { let options = p.group('[', ']')?; for option in split_options(&options)? { match option { + "flowchart" => p.circuit.flowchart = true, "american" | "american resistors" => p.circuit.american = true, "RPvoltages" | "voltage dir=RP" => p.rp = true, "thin" | "semithick" | "thick" => (), @@ -337,7 +342,7 @@ pub fn parse(source: &str) -> Option { return None; } } - if p.circuit.segments.is_empty() { + if p.circuit.segments.is_empty() && (!p.circuit.flowchart || p.circuit.decorations.is_empty()) { None } else { Some(p.circuit) diff --git a/crates/handwriting-core/src/text/circuit/labels.rs b/crates/handwriting-core/src/text/circuit/labels.rs index a6495024..20942183 100644 --- a/crates/handwriting-core/src/text/circuit/labels.rs +++ b/crates/handwriting-core/src/text/circuit/labels.rs @@ -82,6 +82,7 @@ impl Parser { "pm" => "±", "le" | "leq" => "≤", "ge" | "geq" => "≥", + "ne" | "neq" => "≠", "infty" => "∞", "angle" => "∠", "circ" => "°", diff --git a/crates/handwriting-core/tests/circuitikz.rs b/crates/handwriting-core/tests/circuitikz.rs index 3d498026..eb092dcb 100644 --- a/crates/handwriting-core/tests/circuitikz.rs +++ b/crates/handwriting-core/tests/circuitikz.rs @@ -69,6 +69,19 @@ fn relative_coordinates_reference_and_named_coordinates_remain_exact() { ] ); } + +#[test] +fn framed_nodes_are_opt_in_and_keep_named_edges_and_conditions() { + let body = r"\coordinate (rhs) at (4,1); + \draw (0,0) node[rectangle]{B3}; \draw (rhs) node[diamond]{B5}; + \draw[->] (0,0) -| (rhs) node[midway,left]{$t\neq 0$};"; + assert!(circuit::parse(&env(body)).is_none()); + let graph = circuit::parse(&env(&format!("[flowchart]{body}"))).unwrap(); + assert!(graph.flowchart); + assert_eq!(graph.decorations[2].text, "t≠ 0"); + assert_eq!(graph.segments[1].end, circuit::Point(4., 1.)); + assert!(graph.segments[1].end_arrow); +} #[test] fn flowchart_conditions_follow_their_wire_without_moving_its_endpoint() { let source = env(r"\draw[->] (0,0) -- (4,2) node[midway,above] {$i\le10$} diff --git a/crates/panache-mcp/tests/illustration_pen.py b/crates/panache-mcp/tests/illustration_pen.py index fe3da623..a78b2e18 100644 --- a/crates/panache-mcp/tests/illustration_pen.py +++ b/crates/panache-mcp/tests/illustration_pen.py @@ -42,3 +42,31 @@ async def preview(revision): exported = await call(client, "export_handwriting", revision=1, format="zip", **key) with ZipFile(Path(exported.structuredContent["path"])) as archive: assert archive.read("0.png") == original + + # A real Markdown worker passes the opt-in graph, including conditions, to Rust as one drawing. + chart = r"""\begin{circuitikz}[flowchart] +\draw (0,0) node[rectangle]{B2}; +\draw (3,-1) node[diamond]{B3}; +\draw[->] (0,0) -- (3,-1) node[midway,above]{i ≤ 10}; +\draw[->] (3,-1) -- (3,-2.6) -- (-1.4,-2.6) |- (0,0); +\end{circuitikz}""" + saved = await call(client, "save_section", markdown="图\n\n" + chart, + style={"font": "华阳手写体.ttf", "font_size": 24, "seed": 17}) + key = {"draft_id": saved.structuredContent["draft_id"]} + + async def chart_crop(revision): + layout = (await call(client, "preview_handwriting", **key, revision=revision, + view="layout")).structuredContent + assert layout["total"] == 2 + x, y, w, h = layout["glyphs"][1]["bounds"] + image = Image.open(io.BytesIO(await preview(revision))).convert("L") + return image.crop((x, y, x + w, y + h)) + + before = await chart_crop(1) + await call(client, "tune_handwriting", **key, expected_revision=1, + changes={"font": "李国夫手写体.ttf"}) + restyled = await chart_crop(2) + assert before.size != restyled.size or before.tobytes() != restyled.tobytes() + await call(client, "tune_handwriting", **key, expected_revision=2, changes={"font_size": 40}) + enlarged = await chart_crop(3) + assert enlarged.width > 1.3 * restyled.width and enlarged.height > 1.3 * restyled.height From e04015eac269dcb45d5d68f758dc1b5a0c529ade Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Fri, 27 Nov 2026 16:50:38 +0800 Subject: [PATCH 03/15] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=BB=BA?= =?UTF-8?q?=E7=A8=BF=E4=B8=8E=E9=A2=84=E8=A7=88=E6=97=B6=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E5=8E=9F=E7=BA=B8=E6=B8=85=E6=99=B0=E5=BA=A6=E5=92=8C=E7=AC=94?= =?UTF-8?q?=E7=94=BB=E5=A4=8D=E6=A0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:整页缩略图和新增墨迹的亮度读数会掩盖局部虚焦、渐变边界与图线粗细差异。 解决手段:在原纸上采样可比的笔画边缘,提供清晰、柔软及过渡区的原尺寸预览参数,区分弱证据与全页柔软。图文复核增加有效墨迹宽度与具体检查指引。 收益:客户端可以按原图坐标检查并比较标签、主笔与框线,在局部调整后复查清晰区,支持旧稿与保留历史复核的连接。 --- crates/panache-mcp/README.md | 14 +- crates/panache-mcp/src/inputs.rs | 4 + crates/panache-mcp/src/main.rs | 8 +- crates/panache-mcp/src/paper.rs | 16 +- crates/panache-mcp/src/paper/focus.rs | 423 +++++++++++++++++++ crates/panache-mcp/src/preview.rs | 28 +- crates/panache-mcp/src/review.rs | 4 +- crates/panache-mcp/src/review/consistency.rs | 54 ++- crates/panache-mcp/src/save.rs | 14 +- crates/panache-mcp/tests/paper_focus.py | 140 ++++++ crates/panache-mcp/tests/smoke.py | 2 + crates/panache-mcp/tool-design.md | 2 +- 12 files changed, 694 insertions(+), 15 deletions(-) create mode 100644 crates/panache-mcp/src/paper/focus.rs create mode 100644 crates/panache-mcp/tests/paper_focus.py diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 2bc48d44..d0d86e33 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -150,11 +150,23 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) +在照片上画新的流程图时,把下例直接写入节的 Markdown。节点文字继承稿件的字体,图框和箭头按其笔画绘制。先给分支条件、箭头和节点留够空间,再移动整图。把图缩进小格会连同标签字号一起改变。已有位图的标签保存在像素中,需要改字形时可从已知题意重建节点和连线。 + +```tex +\begin{circuitikz}[flowchart] +\draw (0,0) node[rectangle]{B1}; +\draw (0,-2) node[diamond]{B2}; +\draw[->] (0,0) -- (0,-2) node[midway,right]{i≤10}; +\end{circuitikz} +``` + +照片建稿和预览返回的 `paper_focus_check` 可用于比较不同位置印刷边缘的过渡宽度。请在推荐的原尺寸局部内对照底纸和成品,看同一位置的印字、细横线、手写字和图线。清晰度渐变时连同中间过渡区一起看。确有不协调时只选受影响的字或图块轻调柔化,复查改动区和原先清晰的区域。空白或低反差区域可能缺少测量依据。 + 作业表可用正文横线设置参考线,将同一页的课程、姓名等字块分别定位。若侧栏印字自下往上读,将原字块的左上、右上、右下、左下四角依次投到侧栏的左下、左上、右上、右下。复查时按栏核对读向、印字和留给老师的评分区。`changed_pixels_outside_reference` 也会计入正文参考区外有意填写的表头和侧栏,应结合这些栏位解读。 客户端已知目标值时,可在 `tune_handwriting` 中同时传 `changes={"perturb_theta_sigma":0.07}` 和 `readback_variation=["perturb_theta_sigma"]`。成功回执的 `effective_changes` 给出写入前后的有效值,用于直接核对本次写入,省去事后再读一次。最多点名本次提交的两个 `variation` 控件。提交 `null` 时读回继承值,有效值相同的键会省略。若要根据旧值决定改多少,仍应先用 `describe_controls` 读取该稿当前版本的值。 -同页复盘在有可比样本时给出 `adjacent_row_check` 和 `illustration_ink_check`。复用其 `preview_arguments`,或逐项调用 `separate_preview_arguments`,在原图尺度看邻行字宽和图线附近的正文。`evidence.adjacent_rows` 分别记录两行的横纵伸缩比和照片投影前的垂直缩放,能区分字被拉宽和整行等比放大,`evidence.illustration_contrast` 记录采样区相对底纸的亮度下降及像素数。应结合实际裁图判断书写效果。 +同页复盘在有可比样本时给出 `adjacent_row_check` 和 `illustration_ink_check`。复用其 `preview_arguments`,或逐项调用 `separate_preview_arguments`,在原图尺度看邻行字宽和图线附近的正文。`evidence.adjacent_rows` 分别记录两行的横纵伸缩比和照片投影前的垂直缩放,能区分字被拉宽和整行等比放大,`evidence.illustration_contrast` 记录采样区相对底纸的亮度下降及像素数。同一回执的 `ink_footprint_width_px` 用新增墨迹的面积与周长估算有效宽度,单位为原图像素。标签结构和节点交点都会影响数值,仍需看同倍率裁图中的具体字干、框线和箭杆。 如果字像贴在照片上,先分清是墨迹边缘过锐,还是纸面光照、阴影或墨色对比造成的观感。例如,纸面右侧有阴影,但用户认为笔画已经合适,就保留原样。如果用户明确指出笔画边缘过锐,或原尺寸成品裁图中的笔画边缘确实比附近可比的实拍印字或横线更锐,可以小幅柔化试一版。比如用户说“只改第一行,第二行保留”,用 `preview_handwriting(view=layout)` 找到第一行对应的字,再用 `adjust_glyphs` 的 `softness` 只调这些字。只有用户要调整整份稿子时,才用 `tune_handwriting` 的 `ink_softness`。用户要求保留墨迹时,直接沿用原版。 diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 8bff7c31..62f5b68b 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -169,6 +169,10 @@ pub struct Save { /// Optional photo-space baselines overriding auto detection on import. Give 2..32 guides, first row 0, last row the last writable line; intermediate guides refine the fit. pub paper_guides: Option>, /// Original Markdown of just this section. A new section starts on a fresh page. + /// For a new labeled diagram use native source, for example: + /// \begin{circuitikz}[flowchart] + /// \draw (0,0) node[rectangle]{B1}; \draw (0,-2) node[diamond]{B2}; + /// \draw[->] (0,0) -- (0,-2); \end{circuitikz} /// Embedded images remain intact in the source. Pages render them as hand-drawn outlines without their original colors. /// If color matters, explain this and offer a preview. Keep the image in the text rather than using it as the paper. pub markdown: String, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 2c61e53f..95b855ed 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -40,6 +40,7 @@ struct State { drafts: Drafts, preserve_reviews: bool, engine: Mutex, + paper_focus: paper::focus::Cache, fonts: Vec, local_fonts: LocalFonts, storage: storage::Storage, @@ -281,7 +282,7 @@ impl ServerHandler for Panache { "For a school assignment, even text alone, set style.homework=true on creation; omit font unless the user specifies one. For further variation (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ", "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. For a font comparison, show the labeled images from list_fonts(sample=...) on the actual draft paper and mixed text. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ", "For print-and-report, export once and report review.unreviewed_pages. Look up existing receipts with read_section(view=review); full-page preview_handwriting(view=review) files a check. Last-page lookups use current pagination and cannot confirm the historical last page. Follow photo_appearance.preview_arguments for a native detail crop. ", - "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", + "For a new labeled flowchart, use the native [flowchart] example in save_section.markdown so its lettering follows the selected font. For uploaded sheets, follow paper_focus_check on import and preview. Compare nearby printed edges with added strokes in the sharper, transition and softer areas at native size before export. If a mismatch is visible, adjust only the affected writing or diagram, then recheck the transition and the sharper area. Never soften the source photo. If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", "Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ", "If the intended writing area is ambiguous, ask which field to fill or leave clear. ", "Photo coordinates use native output pixels; local dx/dy use paper-space pixels. ", @@ -444,7 +445,7 @@ impl Panache { } #[tool( - description = "Create a draft from text or a problem supplied in chat. To show its first page, save first, then preview. Saves Markdown without rendering. For schoolwork with or without a photo, set style.homework=true. For a local text change try replace_section_text first to check saved placements. For pen-matched flowcharts, use a circuitikz environment with \\draw[->] paths and node labels. On creation, optionally import a local stationery image with paper_path. Append or revise a section with expected_revision. Each section starts a new page. Keep the returned draft_id and revision. Returns detected paper.alignment." + description = "Create a draft from text or a problem supplied in chat. To show its first page, save first, then preview. Saves Markdown without rendering. For schoolwork with or without a photo, set style.homework=true. For a local text change try replace_section_text first to check saved placements. For new flowcharts use \\begin{circuitikz}[flowchart] with node[rectangle], node[diamond] or node[circle] and \\draw[->] connections. The labels and outlines use the manuscript pen. Keep the diagram at natural scale and compare a label and an arrow shaft with nearby letters in the native crop. On creation, optionally import a local stationery image with paper_path. Append or revise a section with expected_revision. Each section starts a new page. Keep the returned draft_id and revision. Returns detected paper.alignment." )] async fn save_section(&self, Parameters(input): Parameters) -> CallToolResult { tool_result(save::run(self, input).await) @@ -548,7 +549,7 @@ impl Panache { #[tool( annotations(open_world_hint = false), - description = "Use view=image to see the page without filing a check. A full-page view=review without compare_revision renders and records a check. To look up an existing check without rendering use read_section(view=review, section, page). view=review returns paper, finished appearance, overlay and full-page evidence. With compare_revision and no region it reads stored data, review IDs, intervening edits and limitations. Add before_review_id to pin the earlier stored check for that draft, revision, section and page. With region it rerenders labeled crops in the current environment using native image coordinates and measures visible changes. The crops do not contain archived pixels. Add compare_revision for paired before/after and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers. illustrations_only selects raster illustrations, not generated circuitikz. Locate a circuit on the current image, then query its region at the same revision without that filter for the whole diagram ID. Edit its Markdown to change a label. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." + description = "Use view=image to see the page without filing a check. A full-page view=review without compare_revision renders and records a check. To look up an existing check without rendering use read_section(view=review, section, page). view=review returns paper, finished appearance, overlay and full-page evidence. On a photo inspect paper_focus_check for local edge changes. Open the supplied crop arguments at native size before adjusting softness. With compare_revision and no region it reads stored data, review IDs, intervening edits and limitations. Add before_review_id to pin the earlier stored check for that draft, revision, section and page. With region it rerenders labeled crops in the current environment using native image coordinates and measures visible changes. The crops do not contain archived pixels. Add compare_revision for paired before/after and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers. illustrations_only selects raster illustrations, not generated circuitikz. Locate a circuit on the current image, then query its region at the same revision without that filter for the whole diagram ID. Edit its Markdown to change a label. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." )] async fn preview_handwriting( &self, @@ -789,6 +790,7 @@ async fn main() -> Result<()> { .with_bundled_dir(font_dir), fonts: engine.names.clone(), engine: Mutex::new(engine), + paper_focus: Default::default(), worker: fs::read_to_string(worker)?.into(), render_slot: Arc::new(Semaphore::new(1)), prepare_slot: Arc::new(Semaphore::new(1)), diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index 0640547c..3a2fafae 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -1,3 +1,5 @@ +pub mod focus; + use crate::{Guide, PaperMode}; use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; @@ -144,6 +146,7 @@ impl PaperLayout { pub struct ImportedPaper { pub layout: PaperLayout, + pub focus: focus::Profile, pub bytes: Vec, } @@ -168,6 +171,7 @@ impl ImportedPaper { file.take(limits.max_file_bytes as u64 + 1) .read_to_end(&mut bytes)?; let image = imaging::decode(&bytes, &limits)?; + let mut corrected_background = false; let layout = if let Some(guides) = guides { ensure!(mode == PaperMode::Photo, "paper_guides require photo mode"); PaperLayout::from_guides(image.width(), image.height(), guides)? @@ -181,6 +185,7 @@ impl ImportedPaper { if mode == PaperMode::Flatten { if let Some(corrected) = lines.corrected_background.take() { bytes = STANDARD.decode(corrected)?; + corrected_background = true; ensure!( bytes.len() <= limits.max_file_bytes, "Aligned paper exceeds the file size limit" @@ -227,6 +232,15 @@ impl ImportedPaper { }; layout.apply(&mut params); params.validate(layout.width, layout.height, &limits)?; - Ok(Self { layout, bytes }) + let focus = if corrected_background { + focus::measure(&imaging::decode(&bytes, &limits)?) + } else { + focus::measure(&image) + }; + Ok(Self { + layout, + bytes, + focus, + }) } } diff --git a/crates/panache-mcp/src/paper/focus.rs b/crates/panache-mcp/src/paper/focus.rs new file mode 100644 index 00000000..3b339d3b --- /dev/null +++ b/crates/panache-mcp/src/paper/focus.rs @@ -0,0 +1,423 @@ +//! Sample the spread of repeatable dark printed edges on the untouched paper. +use crate::drafts::Snapshot; +use anyhow::Result; +use handwriting_core::{Limits, imaging}; +use image::{GenericImageView, Pixel, Rgba}; +use serde_json::{Value, json}; +use std::{collections::VecDeque, sync::Mutex}; + +const GRID: u32 = 4; +const TRACKS: u32 = 9; +const WINDOW: u32 = 240; + +#[derive(Clone, Copy)] +struct Edge { + at: usize, + contrast: i16, + width: f32, +} + +fn luma(pixel: Rgba) -> i16 { + let opacity = u16::from(pixel[3]); + (255 - ((255 - u16::from(pixel.to_luma()[0])) * opacity).div_ceil(255)) as i16 +} + +// Track the 20% and 80% crossings of a monotone edge relative to its own local contrast. +// Parallel profiles 2 px to either side reject isolated grain. Give diagonal edges to their +// stronger scan direction and correct the width of that projection. +fn stroke_edges(profile: &[[i16; 3]]) -> Vec<(usize, f32)> { + let mut out = Vec::new(); + let mut descending: Option = None; + let mut i = 0; + while i + 1 < profile.len() { + let sign = (profile[i + 1][1] - profile[i][1]).signum(); + if sign == 0 { + i += 1; + continue; + } + let start = i; + let mut peak = i; + let mut slope = 0; + while i + 1 < profile.len() { + let d = sign * (profile[i + 1][1] - profile[i][1]); + if d <= 0 { + break; + } + if d > slope { + peak = i; + slope = d; + } + i += 1; + } + let contrast = sign * (profile[i][1] - profile[start][1]); + if contrast < 22 || slope < 4 || i - start > 22 || start < 2 || i + 2 >= profile.len() { + continue; + } + let transverse = (profile[peak][2] + profile[peak + 1][2] + - profile[peak][0] + - profile[peak + 1][0]) as f32 + / 8.; + if transverse.abs() > f32::from(slope) { + continue; + } + let coherent = [0, 2].into_iter().all(|j| { + (-2isize..=2).any(|shift| { + let a = (start as isize + shift) as usize; + let b = (i as isize + shift) as usize; + let d = sign * (profile[b][j] - profile[a][j]); + d * 2 >= contrast && d <= contrast * 2 + }) + }); + if !coherent { + continue; + } + let crossing = |fraction: f32| { + let level = f32::from(contrast) * fraction; + let mut k = start; + while k + 1 < i && f32::from(sign * (profile[k + 1][1] - profile[start][1])) < level { + k += 1; + } + k as f32 + + (level - f32::from(sign * (profile[k][1] - profile[start][1]))) + / f32::from(sign * (profile[k + 1][1] - profile[k][1])) + }; + let width = + (crossing(0.8) - crossing(0.2)) * f32::from(slope) / f32::from(slope).hypot(transverse); + let edge = Edge { + at: peak, + contrast, + width, + }; + if sign < 0 { + descending = Some(edge); + } else if let Some(other) = descending.take() + && edge.at - other.at <= 36 + && edge.contrast.min(other.contrast) * 2 >= edge.contrast.max(other.contrast) + { + out.push((other.at, (other.width + edge.width) / 2.)); + } + } + out +} + +#[derive(Clone, Copy)] +struct Sample { + point: [u32; 2], + cell: [u32; 2], + horizontal_scan: bool, + width: f32, + strokes: usize, + tracks: usize, +} + +fn sample_cell( + img: &impl GenericImageView>, + cell: [u32; 2], + horizontal: bool, +) -> Option { + let [w, h] = [img.width(), img.height()]; + let axis = |v: [u32; 2]| if horizontal { v } else { [v[1], v[0]] }; + let [along, across] = axis([w, h]); + let [a, b] = axis(cell); + let start = along * a / GRID; + let end = along * (a + 1) / GRID; + let lo = across * b / GRID; + let hi = across * (b + 1) / GRID; + if end - start < 20 || hi - lo < 8 { + return None; + } + let windows = (end - start).div_ceil(WINDOW).min(3); + let length = (end - start) / windows; + let count = (hi - lo - 4).min(TRACKS); + let mut samples = Vec::new(); + let mut supported = 0; + for track in 0..count { + let cross = lo + 2 + (2 * track + 1) * (hi - lo - 4) / (2 * count); + let old = samples.len(); + for window in 0..windows { + let size = length.min(WINDOW); + let from = start + window * length + (length - size) / 2; + let profile: Vec<_> = (from..from + size) + .map(|x| { + [cross - 2, cross, cross + 2].map(|y| { + let [x, y] = axis([x, y]); + luma(img.get_pixel(x, y)) + }) + }) + .collect(); + for (at, width) in stroke_edges(&profile) { + samples.push((width, axis([from + at as u32, cross]))); + } + } + supported += usize::from(samples.len() > old); + } + if samples.len() < 6 || supported < 3 { + return None; + } + samples.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); + let (width, point) = samples[samples.len() / 2]; + Some(Sample { + point, + cell, + horizontal_scan: horizontal, + width, + strokes: samples.len(), + tracks: supported, + }) +} + +#[derive(Clone, Default)] +pub struct Profile { + size: [u32; 2], + samples: Vec, +} + +pub fn measure(img: &impl GenericImageView>) -> Profile { + let mut profile = Profile { + size: [img.width(), img.height()], + samples: Vec::new(), + }; + for y in 0..GRID { + for x in 0..GRID { + for horizontal in [true, false] { + if let Some(s) = sample_cell(img, [x, y], horizontal) { + profile.samples.push(s); + } + } + } + } + profile +} + +impl Profile { + pub fn report(&self, draft: &str, revision: u32, section: u32, page: usize) -> Value { + let [w, h] = self.size; + let crop = |[x, y]: [u32; 2]| { + let cw = w.min(240); + let ch = h.min(160); + let l = x.saturating_sub(cw / 2).min(w - cw); + let t = y.saturating_sub(ch / 2).min(h - ch); + json!({"draft_id":draft,"revision":revision,"section":section,"page":page,"view":"review", + "region":[[l,t],[l+cw,t],[l+cw,t+ch],[l,t+ch]]}) + }; + let site = |role: &str, s: &Sample| { + json!({"role":role,"sample_point":s.point,"median_edge_width_px":s.width,"sampled_strokes":s.strokes, + "supported_tracks":s.tracks,"scan_direction":if s.horizontal_scan {"horizontal"} else {"vertical"}, + "preview_arguments":crop(s.point)}) + }; + let mut cells = [false; 16]; + for s in &self.samples { + cells[(s.cell[1] * GRID + s.cell[0]) as usize] = true; + } + let coverage = cells.iter().filter(|v| **v).count(); + let mut largest = None; + let mut references = None; + for a in &self.samples { + for b in &self.samples { + let difference = b.width - a.width; + if a.horizontal_scan != b.horizontal_scan || a.cell == b.cell || difference < 0. { + continue; + } + if references.is_none_or(|(d, _, _)| difference > d) { + references = Some((difference, a, b)); + } + if b.width >= 2.0 + && difference >= 1.1 + && b.width >= 1.65 * a.width + && largest.is_none_or(|(d, _, _)| difference > d) + { + largest = Some((difference, a, b)); + } + } + } + let mut regions = Vec::new(); + let status = if let Some((_, a, b)) = largest { + regions.push(site("narrower_edges", a)); + regions.push(site("broader_edges", b)); + let mid = [(a.point[0] + b.point[0]) / 2, (a.point[1] + b.point[1]) / 2]; + let between = self + .samples + .iter() + .filter(|s| { + s.horizontal_scan == a.horizontal_scan + && s.cell != a.cell + && s.cell != b.cell + && s.width > a.width + 0.25 + && s.width < b.width - 0.25 + && (0..2).all(|k| { + (a.cell[k].min(b.cell[k])..=a.cell[k].max(b.cell[k])) + .contains(&s.cell[k]) + }) + }) + .min_by_key(|s| { + (0..2) + .map(|k| u64::from(s.point[k].abs_diff(mid[k])).pow(2)) + .sum::() + }); + regions.push(between.map_or_else( + || json!({"role":"between_samples","preview_arguments":crop(mid)}), + |s| site("intermediate_edges", s), + )); + "spatial_variation" + } else if let Some(broadest) = self + .samples + .iter() + .max_by(|a, b| a.width.total_cmp(&b.width)) + { + if let Some((_, a, b)) = references { + regions.push(site("narrower_reference", a)); + regions.push(site("broader_reference", b)); + } else { + regions.push(site("paper_edge_sample", broadest)); + } + let broad = self.samples.iter().all(|s| s.width >= 2.); + let spread = (0..GRID).all(|k| { + self.samples.iter().any(|s| s.cell[0] == k) + && self.samples.iter().any(|s| s.cell[1] == k) + }); + if broad && coverage >= 8 && spread { + "broad_edges_across_sheet" + } else if broadest.width >= 2. { + "broad_edges_in_samples" + } else { + "no_clear_softening_in_samples" + } + } else { + regions.push(json!({"role":"inspect_paper","preview_arguments":crop([w/2,h/2])})); + "insufficient_edge_support" + }; + let guidance = match status { + "spatial_variation" => { + "底纸不同位置的深色印刷边缘过渡宽度有差异。按区域参数用原尺寸从较清晰处经过交界到较软处,对照当地纸上细线、图形轮廓、图内标签和正文。between_samples 是待核对点。" + } + "broad_edges_across_sheet" | "broad_edges_in_samples" => { + "受支持的底纸样本有较宽的边缘过渡。按区域参数检查原尺寸印迹,比较各处图线、标签和正文与当地纸边。" + } + "insufficient_edge_support" => { + "底纸上可重复测量的深色边缘不足。用原尺寸检查原纸上的细线或印字,尤其留意用户标注的位置。" + } + _ => { + "采样差异未达显著门槛。有同向可比样本时,参考裁区给出较窄与较宽的实测边缘。缓慢渐变和很小的软区可能遗漏。沿同一条纸上印线或同类印字连续检查相邻区域,用原尺寸对照图线、图内标签和正文。" + } + }; + json!({"status":status,"supported_cells":coverage,"grid":[GRID,GRID],"regions":regions,"guidance":guidance, + "local_edit_guidance":"优先检查用户指明的位置,可平移 region 连续查看过渡,保留原纸与清晰区。仅在裁图或用户反馈支持时,对可独立选择的字或图块分区小调 softness 后复看。若布局只给流程图及其标签一个字形 ID,softness 会影响整张图;需要只改某一部分应在可局部修改的图源中处理。", + "method":"Native 20–80% lightness transition width on opposing, locally contrasted stroke edges, confirmed by parallel profiles. Comparisons use the same scan direction. Print, material and capture can all broaden an edge."}) + } +} + +#[derive(Default)] +pub struct Cache(Mutex>); + +impl Cache { + pub fn remember(&self, id: &str, profile: Profile) { + let mut entries = self.0.lock().unwrap_or_else(|e| e.into_inner()); + entries.retain(|e| e.0 != id); + entries.push_back((id.to_owned(), profile)); + if entries.len() > 32 { + entries.pop_front(); + } + } + + pub fn report(&self, draft: &Snapshot<'_>, section: u32, page: usize) -> Result> { + if draft.paper.is_none() { + return Ok(None); + } + let profile = self + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .find(|e| e.0 == draft.id) + .map(|e| e.1.clone()); + let profile = match profile { + Some(v) => v, + None => { + let Some(bytes) = draft.background()? else { + return Ok(None); + }; + let v = measure(&imaging::decode(&bytes, &Limits::default())?); + self.remember(draft.id, v.clone()); + v + } + }; + Ok(Some(profile.report( + draft.id, + draft.revision, + section, + page, + ))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use image::{DynamicImage, GrayImage, Luma, imageops}; + + fn rulings(vertical: bool, contrast: u8) -> GrayImage { + GrayImage::from_fn(480, 480, |x, y| { + let line = if vertical { x } else { y }; + Luma([if (line % 22) < 6 { 238 - contrast } else { 238 }]) + }) + } + + fn report(img: GrayImage) -> Value { + measure(&DynamicImage::ImageLuma8(img)).report("draft", 2, 3, 4) + } + + #[test] + fn widths_follow_blur_in_either_direction_without_equating_ink_contrast_to_focus() { + for vertical in [true, false] { + let lines = rulings(vertical, 160); + let soft = imageops::blur(&lines, 2.); + let medium = imageops::blur(&lines, 1.1); + let original = report(lines.clone()); + assert_eq!(original["status"], "no_clear_softening_in_samples"); + assert_eq!(original["regions"][0]["role"], "narrower_reference"); + assert_eq!(original["regions"][1]["role"], "broader_reference"); + assert_eq!( + original["regions"][0]["scan_direction"], + original["regions"][1]["scan_direction"] + ); + assert_ne!( + original["regions"][0]["sample_point"], + original["regions"][1]["sample_point"] + ); + assert_eq!(report(soft.clone())["status"], "broad_edges_across_sheet"); + let stages = GrayImage::from_fn(480, 480, |x, y| { + *[&lines, &medium, &medium, &soft][x as usize / 120].get_pixel(x, y) + }); + let result = report(stages); + assert_eq!(result["status"], "spatial_variation", "{result}"); + assert_eq!(result["regions"][2]["role"], "intermediate_edges"); + let thinner = result["regions"][0]["median_edge_width_px"] + .as_f64() + .unwrap(); + let broader = result["regions"][1]["median_edge_width_px"] + .as_f64() + .unwrap(); + assert!(broader > thinner + 1.); + let pale = rulings(vertical, 45); + let colors = + GrayImage::from_fn( + 480, + 480, + |x, y| if x < 240 { lines[(x, y)] } else { pale[(x, y)] }, + ); + assert_eq!(report(colors)["status"], original["status"]); + } + } + + #[test] + fn blank_shadow_and_weak_grain_supply_no_supported_strokes() { + let noisy = GrayImage::from_fn(480, 360, |x, y| { + Luma([(160 + x / 12 + (x.wrapping_mul(y) % 8)) as u8]) + }); + for img in [GrayImage::from_pixel(480, 360, Luma([225])), noisy] { + let r = report(img); + assert_eq!(r["status"], "insufficient_edge_support"); + assert_eq!(r["supported_cells"], 0); + } + } +} diff --git a/crates/panache-mcp/src/preview.rs b/crates/panache-mcp/src/preview.rs index 7e24852e..87bf0a9f 100644 --- a/crates/panache-mcp/src/preview.rs +++ b/crates/panache-mcp/src/preview.rs @@ -128,7 +128,8 @@ fn render( ); let baselines = engine.review_baselines(&draft, section.clone(), page, cancel)?; let (preview, _) = engine.preview(&draft, section, page, cancel)?; - return review::page(&draft, number, page, &preview.png, &baselines, cancel); + let result = review::page(&draft, number, page, &preview.png, &baselines, cancel)?; + return add_paper_focus(state, &draft, number, page, result); } if input.view == Some(PreviewView::Layout) { let result = engine.layout(&draft, section, input, cancel)?; @@ -138,7 +139,7 @@ fn render( input.offset.is_none() && input.limit.is_none(), "offset and limit require view=layout" ); - image( + let result = image( engine, &draft, section, @@ -146,7 +147,26 @@ fn render( input.fresh, !state.preserve_reviews, cancel, - ) + )?; + add_paper_focus(state, &draft, number, page, result) +} + +fn add_paper_focus( + state: &State, + draft: &Snapshot<'_>, + section: u32, + page: usize, + mut result: CallToolResult, +) -> Result { + if let Some(focus) = state.paper_focus.report(draft, section, page)? { + result + .content + .push(ContentBlock::text(format!("底纸边缘原尺寸检查 {focus}"))); + if let Some(data) = result.structured_content.as_mut() { + data["paper_focus_check"] = focus; + } + } + Ok(result) } fn paper(draft: &Snapshot<'_>) -> Result { @@ -181,7 +201,7 @@ fn image( let mut message = format!("第 {number} 节 · 第 {page} 页 · 版本 {}", draft.revision); let mut data = json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page_in_section":page,"cached":cached}); if contains_drawing { - let hint = "如果当前页既有手绘图又有文字,在判断笔迹一致前,用 view=review 加 region 框住一段图线和旁边的字,同倍率比较粗细和墨色。同页看图与字只传当前版,省略 compare_revision。看不清时说明还不能判断。"; + let hint = "如果当前页既有手绘图又有文字,在判断笔迹一致前,用 view=review 加 region 框住一段图线和旁边的字,同倍率比较粗细和墨色。先对照节点和分支标签与正文的字形、字号,再看箭杆和框线是否接近文字的主笔画。缩放整图会连同标签一起缩放。同页看图与字只传当前版,省略 compare_revision。看不清时说明还不能判断。"; message.push('\n'); message.push_str(hint); data["illustration_inspection"] = json!(hint); diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index b55cb42d..e6e8af2f 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -312,7 +312,7 @@ pub fn page( let observation = draft.record_review( section, page, - "paper-review/2", + "paper-review/3", &pixel_digest, &sample.content_sha256, &evidence, @@ -336,7 +336,7 @@ pub fn page( } if let Some(ink) = checks.ink { metadata["illustration_ink_check"] = ink.guidance(&arguments, - "Compare an actual diagram stroke or arrow and nearby writing at native size. The regions measure darkening against the saved paper. Different coverage, overlapping marks, color and paper lighting can affect the readings. Inspect thickness and darkness in the crops. If only the diagram needs changing, adjust its source or pen settings. Use each preview call as given for one revision; omit compare_revision."); + "At native size compare a diagram label and nearby writing, then compare a straight frame or arrow shaft with a letter stem. Inspect letterforms, size, width, edge softness and darkness. The regions measure added ink against the saved paper. Different coverage, overlapping marks, color and paper lighting can affect the readings. Inspect thickness and darkness in the crops. If only the diagram needs changing, adjust its source or pen settings. Use each preview call as given for one revision; omit compare_revision."); } if draft.paper.is_some() { let mut appearance = json!({ diff --git a/crates/panache-mcp/src/review/consistency.rs b/crates/panache-mcp/src/review/consistency.rs index 26eaf867..6108a280 100644 --- a/crates/panache-mcp/src/review/consistency.rs +++ b/crates/panache-mcp/src/review/consistency.rs @@ -263,6 +263,13 @@ fn darkness( let mut min_distance = f32::INFINITY; // Only boxes crossing this scan line can obscure ownership. Merge by marking the row spans. let mut excluded = vec![false; (r - l) as usize]; + // Count runs through the added ink in four directions for a Crofton perimeter estimate. + // A one-pixel empty border also closes runs touching an edge of the sample. + let mut previous = vec![false; excluded.len() + 2]; + let mut current = previous.clone(); + let mut axial_runs = 0u64; + let mut diagonal_runs = 0u64; + let mut width_pixels = 0u64; let mut excluded_pixels = 0u32; for y in t..b { excluded.fill(false); @@ -276,11 +283,19 @@ fn darkness( } cancel.check()?; for x in l..r { + let i = (x - l) as usize + 1; + current[i] = false; if excluded[(x - l) as usize] { excluded_pixels += 1; continue; } let delta = light(paper[(x, y)]).saturating_sub(light(finished[(x, y)])); + if delta >= 32 { + current[i] = true; + width_pixels += 1; + axial_runs += u64::from(!current[i - 1]) + u64::from(!previous[i]); + diagonal_runs += u64::from(!previous[i - 1]) + u64::from(!previous[i + 1]); + } if delta >= 8 { hist[usize::from(delta)] += 1; let dx = x as f32 - toward[0]; @@ -292,7 +307,11 @@ fn darkness( } } } + std::mem::swap(&mut current, &mut previous); } + let perimeter = std::f64::consts::FRAC_PI_4 + * (axial_runs as f64 + diagonal_runs as f64 * std::f64::consts::FRAC_1_SQRT_2); + let width = (width_pixels >= 24).then(|| 2.0 * width_pixels as f64 / perimeter); let count = hist.iter().sum::(); let percentile = |percent: u64| { let rank = (u64::from(count) * percent).div_ceil(100) as u32; @@ -303,7 +322,8 @@ fn darkness( }) }; Ok(( - json!({"region":region, "darkened_pixels":count, "overlap_pixels_excluded":excluded_pixels, "median_luma_drop":percentile(50),"p90_luma_drop":percentile(90)}), + json!({"region":region, "darkened_pixels":count, "overlap_pixels_excluded":excluded_pixels, "median_luma_drop":percentile(50),"p90_luma_drop":percentile(90), + "ink_footprint_width_px":width,"width_sample_pixels":width_pixels}), nearest, )) } @@ -393,6 +413,7 @@ pub(super) fn checks( let gap = drawing.gap(writing_box); ink = Some(Check { metrics: json!({"illustration":diagram,"nearby_text":writing,"minimum_luma_drop":8,"region_gap_px":gap, "distant_reference":gap > nearest.bounds.height().max(16.) * 6., + "width_method":"Width in native pixels estimated as twice the area divided by the four-direction Crofton perimeter of added ink with a luma drop of at least 32 (at least 24 pixels). Short strokes, joins, glyph shapes, softness and opacity affect this estimate. Compare the actual stems, lines and arrows in the crops.", "sampling":"Saved-paper luma minus output luma (0–255) among darkened pixels in each layout box. Text boxes overlapping the diagram are masked from its sample, and diagram pixels are excluded from the writing sample. A distant reference or too little sampled ink needs visual confirmation."}), regions: crops( [drawing, writing_box], @@ -414,6 +435,36 @@ mod tests { Bounds::from_corners([[left, top], [right, top], [right, bottom], [left, bottom]]) } + #[test] + fn equally_dark_lines_have_distinct_footprint_widths() { + let paper = RgbaImage::from_pixel(112, 18, Rgba([255; 4])); + let mut finished = paper.clone(); + for (y, height) in [(1, 2), (9, 5)] { + for row in y..y + height { + for x in 5..105 { + finished[(x, row)] = Rgba([40, 40, 40, 255]); + } + } + } + let measure = |y, end| { + darkness( + [[0, y], [112, y], [112, end], [0, end]], + &paper, + &finished, + [0., 0.], + &[], + &Cancellation::default(), + ) + .unwrap() + .0 + }; + let thin = measure(0, 7); + let thick = measure(8, 18); + assert_eq!(thin["median_luma_drop"], thick["median_luma_drop"]); + assert!((1.8..2.3).contains(&thin["ink_footprint_width_px"].as_f64().unwrap())); + assert!((4.6..5.4).contains(&thick["ink_footprint_width_px"].as_f64().unwrap())); + } + #[test] fn shared_pixels_do_not_count_as_diagram_or_body_ink() { let paper = RgbaImage::from_pixel(80, 60, Rgba([255; 4])); @@ -450,6 +501,7 @@ mod tests { assert_eq!(m["overlap_pixels_excluded"], 25); assert_eq!(m["darkened_pixels"], 0); assert!(m["p90_luma_drop"].is_null()); + assert!(m["ink_footprint_width_px"].is_null()); } } diff --git a/crates/panache-mcp/src/save.rs b/crates/panache-mcp/src/save.rs index 60bb43ed..4bac49e4 100644 --- a/crates/panache-mcp/src/save.rs +++ b/crates/panache-mcp/src/save.rs @@ -101,13 +101,20 @@ fn prepare_and_save(state: &State, input: &Save, mut style: Option