Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/handwriting-core/src/fine_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ pub struct Adjustments {
/// Original paper-space ink bounds, before any per-glyph adjustment.
#[derive(Serialize)]
pub struct GlyphBounds {
#[serde(skip)]
pub is_text: bool,
pub illustration: Option<u32>,
pub id: u32,
pub bounds: [i32; 4],
Expand All @@ -61,6 +63,7 @@ pub fn inspect_page(
.into_iter()
.map(|t| GlyphBounds {
id: t.id,
is_text: t.is_text,
illustration: t.illustration,
bounds: [t.x, t.y, t.mask.width() as i32, t.mask.height() as i32],
source_utf16: t.source,
Expand Down Expand Up @@ -127,6 +130,7 @@ pub(crate) fn document_key(text: &str, p: &Parameters) -> String {
}

pub(crate) struct Tile {
pub is_text: bool,
pub illustration: Option<u32>,
pub id: u32,
pub x: i32,
Expand Down
3 changes: 3 additions & 0 deletions crates/handwriting-core/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ use ink::{blank_paper, normal, paint_math_unit, paste_mask, perturb};
use units::{fixed_cell, keeps_grid_cell, layout_units};
// 2026-10-15:先缓存整行,知道最高根式/最低分母后再统一落笔,避免后出现的公式撞进上一行。
struct LineUnit {
is_text: bool,
glyph: Glyph,
rigid: bool,
align_to_rulings: bool,
Expand Down Expand Up @@ -556,6 +557,7 @@ fn render_planes(
let advance = g.step(unit, p, extra, compound);
pages.x = x + advance;
pages.line.push(LineUnit {
is_text: unit.iter().all(|node| matches!(node, Node::Char(_))),
glyph: g,
rigid: compound || cell.is_some(),
align_to_rulings: matches!(node, Node::Circuit(_) | Node::Table(_))
Expand Down Expand Up @@ -585,6 +587,7 @@ mod ruled_tests {

fn sample_line() -> Vec<LineUnit> {
vec![LineUnit {
is_text: true,
glyph: Glyph {
mask: GrayImage::from_pixel(8, 40, Luma([255])),
advance: 8.,
Expand Down
1 change: 1 addition & 0 deletions crates/handwriting-core/src/render/fine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ fn capture_one(
let mut mask = GrayImage::new(crop.width() + pad * 2, crop.height() + pad * 2);
ink::paste_mask(&mut mask, &crop, pad as i32, pad as i32);
Ok(Some(fine_edit::Tile {
is_text: unit.is_text,
id: unit.id,
illustration: None,
x: origin.0 + left as i32 - radius as i32 - pad as i32,
Expand Down
1 change: 1 addition & 0 deletions crates/handwriting-core/src/render/illustration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ pub(super) fn tiles(
let mut padded = GrayImage::new(mask.width() + 2 * PAD, mask.height() + 2 * PAD);
imageops::replace(&mut padded, &mask, PAD.into(), PAD.into());
Tile {
is_text: false,
id: part,
illustration: Some(id),
x: x + dx as i32 - PAD as i32,
Expand Down
40 changes: 40 additions & 0 deletions crates/panache-mcp/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,47 @@ 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])],
])
});
Ok(crate::review::PageSample {
illustration_and_text,
baselines,
content_sha256: format!("{:x}", membership.finalize()),
})
Expand Down
1 change: 1 addition & 0 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ pub struct Preview {
/// In layout view, only return raster illustration outlines and isolated details. Omit for generated circuitikz: its labels and lines are one glyph.
pub illustrations_only: Option<bool>,
/// "image" (default), "paper" for saved stationery, "layout" for glyph geometry, or "review" for appearance evidence.
/// For a hand-drawn diagram, compare its lines with nearby writing in a small review region at the same zoom.
pub view: Option<PreviewView>,
/// For image (the default): render the page again instead of reusing its cached PNG,
/// e.g. after replacing a configured font file. Does not change the draft or file a review.
Expand Down
14 changes: 10 additions & 4 deletions crates/panache-mcp/src/preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,17 @@ fn image(
cancel: &Cancellation,
) -> Result<CallToolResult> {
let number = section.number;
let contains_inline_image = section.text.contains("](data:image/");
let (preview, cached) = engine.preview_with_refresh(draft, section, page, fresh, cancel)?;
let mut result = reply(
format!("第 {number} 节 · 第 {page} 页 · 版本 {}", draft.revision),
json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page_in_section":page,"cached":cached}),
);
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 {
let hint = "如果当前页既有手绘图又有文字,在判断笔迹一致前,用 view=review 加 region 框住一段图线和旁边的字,同倍率比较粗细和墨色。同页看图与字只传当前版,省略 compare_revision。看不清时说明还不能判断。";
message.push('\n');
message.push_str(hint);
data["illustration_inspection"] = json!(hint);
}
let mut result = reply(message, data);
result
.content
.push(ContentBlock::image(preview.png, "image/png"));
Expand Down
33 changes: 32 additions & 1 deletion crates/panache-mcp/src/review.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ pub fn contains(poly: &[[i32; 2]], [x, y]: [f32; 2]) -> bool {
== 1
}

const REVIEW_MAX_EDGE: u32 = 900;

fn thumbnail(img: &impl GenericImageView<Pixel = Rgba<u8>>) -> RgbaImage {
let scale = (900. / img.width().max(img.height()) as f32).min(1.);
let scale = (REVIEW_MAX_EDGE as f32 / img.width().max(img.height()) as f32).min(1.);
imageops::thumbnail(
img,
(img.width() as f32 * scale).round().max(1.) as u32,
Expand Down Expand Up @@ -80,6 +82,7 @@ fn ruling_offset(paper: &RgbaImage, point: [f32; 2], radius: i32) -> Option<i32>
pub struct PageSample {
pub baselines: Vec<[f32; 2]>,
pub content_sha256: String,
pub illustration_and_text: Option<[[f32; 2]; 2]>,
}

// Suggest a crop around a sampled text line at native resolution, including neighboring paper.
Expand Down Expand Up @@ -309,6 +312,34 @@ 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;
}
if draft.paper.is_some() {
let mut appearance = json!({
"inspect":"Compare contrast and size with photographed marks. Check letter size against writing space. Baselines measure placement only. Without images, credit the user's observations; ask the user to inspect the crop if visual evidence is needed.",
Expand Down
79 changes: 79 additions & 0 deletions crates/panache-mcp/tests/illustration_ink_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Inspect a raster diagram alongside writing in real MCP review pixels."""

import argparse
import asyncio
import base64
import io
from pathlib import Path
from tempfile import TemporaryDirectory

from PIL import Image, ImageDraw

from mcp_client import call, isolated_session, open_db
from review_comparison import slanted_sheet


async def verify(client, home):
paper = home / "ruled.png"
guides = slanted_sheet(paper)
art = Image.new("RGB", (100, 55), "white")
draw = ImageDraw.Draw(art)
draw.rectangle((6, 8, 45, 45), outline="black", width=4)
draw.line((45, 24, 94, 24), fill="black", width=4)
stream = io.BytesIO()
art.save(stream, format="PNG")
diagram = "![diagram](data:image/png;base64," + base64.b64encode(stream.getvalue()).decode() + ")"
arrow = "\\begin{circuitikz}\n\\draw[->] (0,0) -- (2,0);\n\\end{circuitikz}"
drawings = f"{diagram}\n\n{arrow}"
cases = [
("drawings_only", drawings, False),
("drawings_then_text", drawings + "\n\n字", True),
("mixed", "循环 i = 10\n" + diagram, True),
("text", "循环 i = 10", False),
("image", diagram, False),
]
result = {}
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})
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")
full = await call(client, "preview_handwriting", **key, view="review")
check = full.structuredContent.get("illustration_ink_check")
assert bool(check) == expect_crop, name
if check:
args = check["preview_arguments"]
assert all(args[k] == v for k, v in key.items())
local = await call(client, "preview_handwriting", **args)
meta = local.structuredContent
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)
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)
# The fixture ends with a single character after the native arrow.
arrow_item, character = [i for i in page.structuredContent["glyphs"] if "kind" not in i]
assert arrow_item["id"] < character["id"]
assert character["id"] in {i["id"] for i in items}
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)
with open_db(home) as db:
assert db.execute("SELECT count(*) FROM review_observations").fetchone()[0] == len(cases)
return result


async def main(binary):
with TemporaryDirectory() as temp:
home = Path(temp)
async with isolated_session(binary, home) as (client, _):
print(await verify(client, home))


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("binary", type=Path)
asyncio.run(main(parser.parse_args().binary.resolve()))