From 04f9b06d22b1ebe1afb23d287cfd6fe37ab918d0 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Wed, 2 Dec 2026 03:33:22 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(crates/handwriting-core):=20=E6=8C=89?= =?UTF-8?q?=E5=AE=9E=E6=B5=8B=E6=A8=AA=E7=BA=BF=E7=AB=AF=E7=82=B9=E5=92=8C?= =?UTF-8?q?=E5=A2=A8=E8=BF=B9=E8=BE=B9=E7=95=8C=E6=8E=92=E5=86=99=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:手工标定的纸张仍会叠加作业版心缩进,字体基线贴齐也可能让下伸笔画碰线,斜拍纸张上的弯曲横线难以用两个点表达。 解决手段:新建或重新标定的手工参考线保留实测端点和可选中间点,按实际笔迹与格高留白,编号首行保留缩进,原生图形按整格预留空间。 收益:书写区域随每条横线变化,正文与图后首行可按同一尺度检查,历史稿件沿用保存时的排版策略。 --- crates/handwriting-core/src/parameters.rs | 4 + crates/handwriting-core/src/render.rs | 2 + .../handwriting-core/src/render/homework.rs | 4 + crates/handwriting-core/src/render/line.rs | 45 +++++- .../handwriting-core/src/render/paragraph.rs | 24 +-- .../tests/generation_pipeline.rs | 144 ++++++++++++++++++ crates/panache-mcp/src/inputs.rs | 11 +- crates/panache-mcp/src/paper.rs | 124 +++++++++++++-- 8 files changed, 327 insertions(+), 31 deletions(-) diff --git a/crates/handwriting-core/src/parameters.rs b/crates/handwriting-core/src/parameters.rs index d87b6812..eada5716 100644 --- a/crates/handwriting-core/src/parameters.rs +++ b/crates/handwriting-core/src/parameters.rs @@ -103,6 +103,9 @@ pub struct Parameters { pub fill: [u8; 4], pub underlined: bool, pub background_ruled: bool, + /// Use the measured writing area and keep body ink above its photographed ruling. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub guided_rows: bool, pub english_spacing: bool, pub grid_layout: bool, pub width: Option, @@ -156,6 +159,7 @@ impl Default for Parameters { fill: [0, 0, 0, 255], underlined: false, background_ruled: false, + guided_rows: false, english_spacing: false, grid_layout: false, width: Some(2481), diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index f9da9b5c..d7ee9990 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -189,6 +189,7 @@ impl) -> Result<()>> Pages<'_, F> { if layout.overflows(anchor) { anchor = layout.fit_empty_page(&mut units); } + let line_tile_start = self.tiles.len(); for u in units { let origin = ( u.x + u.glyph.left, @@ -248,6 +249,7 @@ impl) -> Result<()>> Pages<'_, F> { paste_mask(&mut self.mask, &u.glyph.mask, origin.0, origin.1); } } + layout.settle_tiles(&mut self.tiles[line_tile_start..], anchor); self.written_lines += 1; self.previous_bottom = layout.ink_bottom(anchor); self.y = anchor + self.p.line_spacing; diff --git a/crates/handwriting-core/src/render/homework.rs b/crates/handwriting-core/src/render/homework.rs index 69677b3a..48531045 100644 --- a/crates/handwriting-core/src/render/homework.rs +++ b/crates/handwriting-core/src/render/homework.rs @@ -4,6 +4,10 @@ use crate::{Parameters, text::Node}; pub(super) fn parameters(source: &Parameters, width: u32, height: u32) -> Parameters { let mut p = source.clone(); + if p.guided_rows { + // The guide endpoints already delimit the intended writing area. + return p; + } let available = width as f32 - p.left_margin - p.effective_right_margin(); let inset = (available * 0.06).min(((available - p.font_size * 4.) / 2.).max(0.)); p.left_margin += inset; diff --git a/crates/handwriting-core/src/render/line.rs b/crates/handwriting-core/src/render/line.rs index 5e335765..5f262343 100644 --- a/crates/handwriting-core/src/render/line.rs +++ b/crates/handwriting-core/src/render/line.rs @@ -1,6 +1,6 @@ //! Vertical placement of buffered ink, including formulas spanning multiple paper rulings. use super::LineUnit; -use crate::{LayoutStyle, Parameters}; +use crate::{LayoutStyle, Parameters, fine_edit}; pub(super) struct LineLayout { top: f32, @@ -11,6 +11,7 @@ pub(super) struct LineLayout { legacy: bool, min_y: i32, max_y: i32, + aligned_ink: bool, } impl LineLayout { @@ -32,7 +33,23 @@ impl LineLayout { scale_units(units, min_y, factor, f32::floor, legacy); (min_y, max_y) = ink_bounds(units); } - if ruled && p.layout_style == LayoutStyle::Standard { + let aligned_ink = p.guided_rows + && (units.iter().all(|unit| unit.is_text) + || matches!(units, [unit] if unit.is_native_diagram)); + if aligned_ink { + // Roomy cells can spare a wider gap above a thick photographed rule. + // Leave most of the unused height above the writing in tighter cells. + let spare = p.line_spacing - (max_y - min_y) as f32; + gap = gap.max((p.font_size * 0.18).round().min((spare * 0.25).floor())); + // A font baseline can run through the visible descenders. Translate the + // line as a unit so its strokes retain their relative sizes and positions. + let raise = (max_y + gap as i32).max(0); + for unit in units { + unit.dy -= raise; + } + min_y -= raise; + max_y -= raise; + } else if ruled && p.layout_style == LayoutStyle::Standard { gap = gap.min((p.line_spacing - p.font_size).max(2.)); let height = (p.line_spacing - gap).floor() as i32; let descent = (p.font_size * 0.30).round() as i32; @@ -49,6 +66,7 @@ impl LineLayout { legacy, min_y, max_y, + aligned_ink, } } @@ -73,6 +91,29 @@ impl LineLayout { anchor + self.max_y as f32 } + pub(super) fn settle_tiles(&self, tiles: &mut [fine_edit::Tile], anchor: f32) { + if !self.aligned_ink || tiles.is_empty() { + return; + } + // Tile capture includes the actual rotation and displacement of each pen + // stroke plus fixed transparent padding. Preserve jitter inside the cell. + let pad = fine_edit::PAD as i32; + let top = tiles.iter().map(|tile| tile.y + pad).min().unwrap(); + let bottom = tiles + .iter() + .map(|tile| tile.y + tile.mask.height() as i32 - pad) + .max() + .unwrap(); + let lower_bound = (anchor - self.spacing + self.gap).ceil() as i32 - top; + let upper_bound = (anchor - self.gap).floor() as i32 - bottom; + // Large drawings can occupy several cells. Keep their bottom aligned and + // their aspect ratio intact, even when they do not fit a single cell. + let dy = 0.clamp(lower_bound.min(upper_bound), upper_bound); + for tile in tiles { + tile.y += dy; + } + } + pub(super) fn overflows(&self, anchor: f32) -> bool { self.ink_bottom(anchor) > self.bottom } diff --git a/crates/handwriting-core/src/render/paragraph.rs b/crates/handwriting-core/src/render/paragraph.rs index 9cdadba7..376549ff 100644 --- a/crates/handwriting-core/src/render/paragraph.rs +++ b/crates/handwriting-core/src/render/paragraph.rs @@ -58,18 +58,22 @@ impl<'a> ParagraphLayout<'a> { } else { style.indent.min(available * 0.15) }; - let prefix: Vec<_> = self.units[i..] - .iter() - .flat_map(|unit| unit.iter()) - .take(style.prefix_chars) - .cloned() - .collect(); - let hanging = if prefix.is_empty() { - 0. + self.continuation = if p.guided_rows { + p.left_margin } else { - glyphs.unit(&prefix, p.font_size, i)?.advance + p.word_spacing + let prefix: Vec<_> = self.units[i..] + .iter() + .flat_map(|unit| unit.iter()) + .take(style.prefix_chars) + .cloned() + .collect(); + let hanging = if prefix.is_empty() { + 0. + } else { + glyphs.unit(&prefix, p.font_size, i)?.advance + p.word_spacing + }; + p.left_margin + indent + hanging.min(available * 0.25) }; - self.continuation = p.left_margin + indent + hanging.min(available * 0.25); pages.x = p.left_margin + indent; if style.gap_before { if (style.title || pages.written_lines - self.section_line_start >= 3) diff --git a/crates/handwriting-core/tests/generation_pipeline.rs b/crates/handwriting-core/tests/generation_pipeline.rs index 8573ad7e..d2bd153f 100644 --- a/crates/handwriting-core/tests/generation_pipeline.rs +++ b/crates/handwriting-core/tests/generation_pipeline.rs @@ -90,6 +90,150 @@ fn projected_ink_only_keeps_photo_coordinates_and_pdf_paper() { assert_eq!(on_paper[(x, y)], ink[(x, y)]); } +#[test] +fn guided_homework_keeps_visible_strokes_inside_the_measured_rows() { + use image::RgbaImage; + let mut req = request("进程状态\ngypq\n(1) 就绪\n(2) 运行\n转换说明\n进程状态"); + req.fonts = FontBook::new( + &std::fs::read(root().join("assets/font_assets/李国夫手写体.ttf")).unwrap(), + &[], + ) + .unwrap(); + req.params = Parameters { + width: Some(320), + height: Some(330), + layout_style: LayoutStyle::Homework, + guided_rows: true, + background_ruled: true, + fine_edit: true, + transparent_background: true, + left_margin: 42., + right_margin: 40., + top_margin: 18., + bottom_margin: 24., + perturb_x_sigma: 1., + perturb_y_sigma: 1., + perturb_theta_sigma: 0.07, + font_size_sigma: 1.5, + ..req.params + }; + let cols = std::array::from_fn(|i| i as f32 * 40.); + let map = photo::PaperProjection::Rulings { + first: 54., + step: 36., + layout_edges: [42., 280.], + columns: cols, + rows: (0..8) + .map(|row| { + let r = row as f32; + photo::Ruling { + edges: [52. - r * 4., 260. + r * 5.], + heights: cols.map(|x| 62. + 25. * r + 1.3 * r * r - 0.04 * x), + } + }) + .collect(), + }; + let photo = RgbaImage::new(320, 330); + for seed in [1, 12, 27, 42, 101] { + req.params.seed = seed; + let mut lefts = [f32::INFINITY; 6]; + handwriting_core::render::render_on_photo( + &req, + &Cancellation::default(), + 1, + &map, + &photo, + |_, ink| { + for (x, y, _) in ink.enumerate_pixels().filter(|(_, _, p)| p[3] >= 32) { + let [px, py] = map.paper_point([x as f32, y as f32]); + let row = ((py - 18.) / 36.).floor() as i32; + assert!((0..6).contains(&row), "seed {seed}, row {row}"); + let clearance = 54. + row as f32 * 36. - py; + assert!( + (2.0..34.).contains(&clearance), + "seed {seed}, row {row}, gap {clearance}" + ); + lefts[row as usize] = lefts[row as usize].min(px - 42.); + } + Ok(()) + }, + ) + .unwrap(); + for (row, start) in lefts.into_iter().enumerate() { + let expected = if [2, 3].contains(&row) { 24. } else { 0. }; + assert!( + (start - expected).abs() < 9., + "seed {seed}, row {row}, start {start}" + ); + } + } + req.text = "(1) ".to_owned() + &"进程状态".repeat(5); + let (_, glyphs) = fine_edit::inspect_page(&req, 1, &Cancellation::default()).unwrap(); + let wrapped = glyphs + .iter() + .find(|glyph| glyph.baseline > glyphs[0].baseline) + .unwrap(); + assert!((wrapped.bounds[0] + fine_edit::PAD as i32 - 42).abs() < 9); +} + +#[test] +fn guided_diagram_reserves_whole_rows_before_the_following_text() { + let mut req = request( + "题目\n\\begin{circuitikz}\n\\draw (0,0) to[V,l=$U_s$] (0,3) to[R,l=$R_1$] (4,3) to[C,l=$C_1$] (4,0) -- (0,0);\n\\end{circuitikz}\n转换说明", + ); + req.params.height = Some(460); + req.params.fine_edit = true; + req.params.guided_rows = true; + req.params.background_ruled = true; + req.params.layout_style = LayoutStyle::Homework; + let (_, glyphs) = fine_edit::inspect_page(&req, 1, &Cancellation::default()).unwrap(); + let diagram = glyphs.iter().find(|g| g.is_native_diagram).unwrap(); + let padding = fine_edit::PAD as i32; + let ink_top = |g: &fine_edit::GlyphBounds| g.bounds[1] + padding; + let ink_bottom = |g: &fine_edit::GlyphBounds| g.bounds[1] + g.bounds[3] - padding; + let after = glyphs.iter().find(|g| g.id > diagram.id).unwrap(); + let step = req.params.line_spacing as i32; + assert!(ink_bottom(diagram) - ink_top(diagram) > step); + assert!(ink_top(diagram) > glyphs[0].baseline); + assert!(ink_bottom(diagram) < diagram.baseline); + assert_eq!(after.baseline, diagram.baseline + step); + assert!(ink_top(after) > diagram.baseline); +} + +#[test] +fn guided_large_type_can_use_multiple_rows_and_pages() { + let mut req = request("进程状态\n银行家算法\n转换说明\n进程状态"); + req.params.fine_edit = true; + req.params.full_preview = true; + req.params.preview = false; + req.params.guided_rows = true; + req.params.background_ruled = true; + req.params.font_size = req.params.line_spacing; + req.params.font_size_sigma = 100.; + req.params.perturb_y_sigma = 1.; + let cancel = Cancellation::default(); + for seed in [1, 12, 27, 42] { + req.params.seed = seed; + let count = handwriting_core::render::count_pages(&req, &cancel).unwrap(); + let mut ids = Vec::new(); + for page in 1..=count { + let (_, glyphs) = fine_edit::inspect_page(&req, page, &cancel).unwrap(); + for g in glyphs { + let pad = fine_edit::PAD as i32; + let top = g.bounds[1] + pad; + let bottom = g.bounds[1] + g.bounds[3] - pad; + assert!( + top >= 10 && bottom <= 170, + "seed {seed}, page {page}, [{top}, {bottom})" + ); + ids.push(g.id); + } + } + assert!(ids.windows(2).all(|p| p[0] < p[1])); + assert!(count > 1); + } +} + #[test] fn standard_wrap_keeps_words_and_closing_punctuation_with_their_neighbours() { fn lines(text: &str, width: u32) -> Vec { diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index ceb5cc28..24090b4a 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -120,9 +120,14 @@ pub enum PaperMode { pub struct Guide { /// Count writable baselines from row 0. At the image center, leave one full row interval above row 0; on a tight crop start at the next visible ruling. pub row: u16, - /// Left and right endpoints [x,y] of this same baseline in original photo pixels. + /// Left end [x,y] of this ruling or chosen field in native photo pixels. For full-width ruled writing, measure its actual end on this row, including any change in x with perspective. pub left: [u32; 2], + /// Right end [x,y] of the same ruling or field. On a printed line use its center, leaving ink clearance to the layout. pub right: [u32; 2], + /// Optional interior [x,y] measurements for a curved ruling, ordered left to right. Use up to seven points across the visible line; the projection samples the profile at nine evenly spaced photo columns. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars(length(max = 7))] + pub via: Vec<[u32; 2]>, } // Only creation distinguishes an omitted font from an explicitly selected default. @@ -168,7 +173,7 @@ pub struct Save { /// Keep the header, rulings and perspective even for PDF export. Use flatten for a requested straightened sheet; /// recreate a blank template only when requested. pub paper_mode: Option, - /// 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. + /// Optional photo-space baselines overriding auto detection. Cover the writing area with 2..32 guides, first writable baseline row 0. On photographed ruled paper measure each visible writable line when possible. Keep the actual row numbers for skipped lines; their positions are interpolated. pub paper_guides: Option>, /// Original Markdown of just this section. A new section starts on a fresh page. /// In prose, put a space on both sides of `/` when it separates terms, as in `输入 / 输出` or `input / output`. @@ -241,7 +246,7 @@ pub struct Tune { /// Set to true only when the user wants to preserve manual glyph adjustments. Reject reflow that would stop applying them. Ink and camera changes can still be saved. #[serde(default)] pub preserve_local_adjustments: bool, - /// Replace the writing area on the saved paper with 2..32 photo-space baselines. Use the top and bottom writable lines even on unruled paper. Pass [] to restore the original import calibration. Existing text is reflowed. + /// Replace the writing area with 2..32 photo-space baselines from first to last writable row. On ruled paper trace both actual ends per row; on unruled paper choose the intended field. Pass [] to restore the original import calibration. Existing text is reflowed. /// Setting guides (including []) clears saved top_margin, bottom_margin, left_margin, right_margin, and text line_spacing unless those keys are included in changes in the same call. /// To keep specific overrides, resend only their approved saved values in changes; omit them to inherit from the paper. Restoring those numbers still reflows hand-placed text. If its placement must stay, also set preserve_local_adjustments=true. If refused, leave the draft as it is. pub paper_guides: Option>, diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index 3a2fafae..c540bd9b 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -22,10 +22,28 @@ pub struct PaperLayout { pub projection: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub guided: bool, + // Missing on saved layouts whose paragraph insets and baseline placements must replay. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub guided_rows: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub photo_size: Option<[u32; 2]>, } +impl Guide { + fn points(&self) -> impl Iterator + '_ { + std::iter::once(self.left) + .chain(self.via.iter().copied()) + .chain(std::iter::once(self.right)) + } + + fn height_at(&self, x: f32) -> f32 { + let i = self.via.partition_point(|p| (p[0] as f32) < x); + let [ax, ay] = if i == 0 { self.left } else { self.via[i - 1] }; + let [bx, by] = self.via.get(i).copied().unwrap_or(self.right); + ay as f32 + (by as f32 - ay as f32) * (x - ax as f32) / (bx - ax) as f32 + } +} + impl PaperLayout { pub fn summary(&self) -> serde_json::Value { let mut data = serde_json::json!({"width":self.width,"height":self.height,"ruled":self.ruled,"line_spacing":self.line_spacing,"left":self.left,"right":self.right,"top":self.top,"bottom":self.bottom}); @@ -51,23 +69,17 @@ impl PaperLayout { for g in guides { ensure!( g.row <= 512 - && g.right[0] > g.left[0] - && [g.left, g.right] - .iter() - .all(|p| p[0] < width && p[1] < height), - "Invalid guide coordinates or row number" + && g.via.len() <= 7 + && g.points().all(|[x, y]| x < width && y < height) + && g.points().zip(g.points().skip(1)).all(|(a, b)| a[0] < b[0]), + "Invalid guide coordinates or row number: use left, up to seven via points, and right in strictly increasing x order within the photo" ); } let columns = std::array::from_fn(|i| i as f32 * (width - 1) as f32 / 8.); - let line = |g: &Guide, x: f32| { - g.left[1] as f32 - + (g.right[1] as f32 - g.left[1] as f32) * (x - g.left[0] as f32) - / (g.right[0] - g.left[0]) as f32 - }; let center = width as f32 / 2.; let last = guides.last().unwrap(); - let first_y = line(&guides[0], center); - let last_y = line(last, center); + let first_y = guides[0].height_at(center); + let last_y = last.height_at(center); let step = (last_y - first_y) / f32::from(last.row); ensure!( step.is_finite() && step >= 1. && last_y < height as f32, @@ -84,9 +96,10 @@ impl PaperLayout { let (a, b) = (&pair[0], &pair[1]); ensure!( b.row > a.row - && [0., width as f32 - 1.] + && [0, width - 1] .into_iter() - .all(|x| line(b, x) > line(a, x)), + .chain(a.points().chain(b.points()).map(|p| p[0])) + .all(|x| b.height_at(x as f32) > a.height_at(x as f32)), "Guides must be ordered and may not cross within the image" ); let wa = (a.right[0] - a.left[0]) as f32; @@ -101,13 +114,13 @@ impl PaperLayout { point(a.left[0] as f32, b.left[0] as f32), point(a.right[0] as f32, b.right[0] as f32), ], - heights: columns.map(|x| point(line(a, x), line(b, x))), + heights: columns.map(|x| point(a.height_at(x), b.height_at(x))), }); } } rows.push(handwriting_core::photo::Ruling { edges: [last.left[0] as f32, last.right[0] as f32], - heights: columns.map(|x| line(last, x)), + heights: columns.map(|x| last.height_at(x)), }); Ok(Self { width, @@ -126,6 +139,7 @@ impl PaperLayout { rows, }), guided: true, + guided_rows: true, photo_size: Some([width, height]), }) } @@ -133,6 +147,7 @@ impl PaperLayout { params.width = None; params.height = None; params.background_ruled = self.ruled; + params.guided_rows = self.guided_rows; params.line_spacing = self.line_spacing; if self.ruled && params.font_size >= self.line_spacing { params.font_size = (self.line_spacing * 0.72).round().max(1.); @@ -199,6 +214,7 @@ impl ImportedPaper { .as_ref() .map(|_| [image.width(), image.height()]), guided: false, + guided_rows: false, projection: lines.projection, width: lines.image_width, height: lines.image_height, @@ -212,6 +228,7 @@ impl ImportedPaper { } Err(err) if err.code == "identification_unreliable" => PaperLayout { guided: false, + guided_rows: false, projection: None, photo_size: None, width: image.width(), @@ -244,3 +261,78 @@ impl ImportedPaper { }) } } + +#[cfg(test)] +mod guide_tests { + use super::*; + use serde_json::json; + + fn guide(row: u16, y: u32, via: Vec<[u32; 2]>) -> Guide { + Guide { + row, + left: [0, y], + right: [400, y], + via, + } + } + + #[test] + fn measured_bend_is_preserved_across_interpolated_rows_and_storage() { + let guides = [ + guide(0, 90, vec![[200, 104]]), + guide(2, 170, vec![[200, 180]]), + ]; + let layout = PaperLayout::from_guides(401, 240, &guides).unwrap(); + let replay: PaperLayout = + serde_json::from_value(serde_json::to_value(layout).unwrap()).unwrap(); + let projection = replay.projection.unwrap(); + let PaperProjection::Rulings { first, step, .. } = projection else { + panic!("expected row projection") + }; + for (row, center_y) in [104., 142., 180.].into_iter().enumerate() { + let paper_y = first + step * row as f32; + assert_eq!(projection.photo_point(200., paper_y), [200., center_y]); + assert_eq!( + projection.photo_point(0., paper_y), + [0., 90. + 40. * row as f32] + ); + } + let legacy: Guide = + serde_json::from_value(json!({"row":0,"left":[10,50],"right":[390,60]})).unwrap(); + assert!(legacy.via.is_empty()); + assert_eq!(legacy.height_at(200.), 55.); + } + + #[test] + fn stored_manual_guides_replay_the_original_writing_area_policy() { + let layout = + PaperLayout::from_guides(401, 240, &[guide(0, 90, vec![]), guide(1, 130, vec![])]) + .unwrap(); + let mut stored = serde_json::to_value(layout).unwrap(); + for applies in [true, false] { + if !applies { + stored.as_object_mut().unwrap().remove("guided_rows"); + } + let restored: PaperLayout = serde_json::from_value(stored.clone()).unwrap(); + let mut params = Parameters::default(); + restored.apply(&mut params); + assert!(restored.guided); + assert_eq!(params.guided_rows, applies); + } + } + + #[test] + fn bad_interior_measurements_are_rejected_before_projecting() { + for via in [ + vec![[210, 90], [200, 94]], + vec![[0, 90]], + vec![[200, 301]], + vec![[150, 180]], + ] { + assert!( + PaperLayout::from_guides(401, 300, &[guide(0, 100, via), guide(1, 150, vec![])]) + .is_err() + ); + } + } +} From 8186a0d0ff4864734ccf919be4aa28b674cb8a25 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Wed, 2 Dec 2026 03:33:30 +0800 Subject: [PATCH 2/3] =?UTF-8?q?feat(crates/panache-mcp):=20=E5=9C=A8?= =?UTF-8?q?=E9=A2=84=E8=A7=88=E5=92=8C=E4=BA=A4=E4=BB=98=E5=9B=9E=E6=89=A7?= =?UTF-8?q?=E4=B8=AD=E9=80=90=E8=A1=8C=E5=A4=8D=E6=A0=B8=E6=A8=AA=E7=BA=BF?= =?UTF-8?q?=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:按页汇总的基线偏差和图框无法说明每一行实际墨迹是否碰到印线,普通预览也难以定位起笔或字号异常。 解决手段:在原纸追踪横线,将字框内可归属的成图差分逐列对照印线边缘,返回每行净空、首笔、相对格高和原尺寸裁区;图框报告跨格位置,导出回执引用同版待复核页。 收益:客户端在普通预览中即可定位疑点,能区分确有墨迹变化、缺少实线依据和图文重叠,按同一位置复核修订后的成品。 --- CHANGELOG.md | 2 + crates/panache-mcp/README.md | 4 +- crates/panache-mcp/src/drafts/observations.rs | 15 +- crates/panache-mcp/src/engine.rs | 1 + crates/panache-mcp/src/main.rs | 16 +- crates/panache-mcp/src/preview.rs | 29 +- crates/panache-mcp/src/review.rs | 39 ++- crates/panache-mcp/src/review/consistency.rs | 7 +- crates/panache-mcp/src/review/drawing.rs | 19 +- crates/panache-mcp/src/review/paper_ink.rs | 1 + crates/panache-mcp/src/review/ruled_rows.rs | 272 ++++++++++++++++++ .../src/review/ruled_rows/tests.rs | 218 ++++++++++++++ .../src/review/ruled_rows/tracking.rs | 221 ++++++++++++++ crates/panache-mcp/src/save.rs | 6 + .../panache-mcp/tests/diagram_perspective.py | 20 ++ .../panache-mcp/tests/ruled_row_alignment.py | 128 +++++++++ crates/panache-mcp/tests/smoke.py | 2 + crates/panache-mcp/tool-design.md | 2 +- 18 files changed, 977 insertions(+), 25 deletions(-) create mode 100644 crates/panache-mcp/src/review/ruled_rows.rs create mode 100644 crates/panache-mcp/src/review/ruled_rows/tests.rs create mode 100644 crates/panache-mcp/src/review/ruled_rows/tracking.rs create mode 100644 crates/panache-mcp/tests/ruled_row_alignment.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8672fff0..6e4433e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 未发布 +- MCP 在手工标定的横线纸上从实测线端排写正文,编号保留小缩进,字迹在下方横线上留出净空。弯曲横线可补中间测点。照片预览和整页复查可逐行核对墨迹净空、起笔和相对格高,流程图复查可查看四角的跨格位置。 + - MCP 的 TeX 包目录可按中英文学科词(可多个词)、ID 或命令搜索用途和写法,AI 客户端可在建稿前查看默认包和用户选用的自定义命令。 - MCP 新建稿件默认启用内置 TeX 扩展包,也可从用户配置的本地文件选择自定义包。续写沿用建稿时的包定义,已有旧稿继续按原方式处理。 diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 39369095..9a3ae3e1 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -173,10 +173,12 @@ 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)` 在原照片上重排全文。至少给两条参考线,每条提供行号与左右端点。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 +3. 调用 `tune_handwriting(draft_id, expected_revision, paper_guides, note)` 在原照片上重排全文。沿整行书写时,从首个可写格的下边线起编号,量取每条横线自己的左右端点。纸张弯曲处可补最多 7 个中间测点,如 `{"row":0,"left":[32,96],"via":[[180,106]],"right":[365,91]}`。2 至 32 条参考线可覆盖整个书写区,跳行时保留实际行号。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 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`。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 +在横线底纸上交付作业时,用最终版本的 `view="image"` 看整页和 `ruled_row_check`。其中每行给出可见墨迹距上下印线的最小净空、首笔距本行可见左端的水平距离,以及字高占当地格高的比例。零净空表示紧邻,负值表示墨迹进入或越过印线边缘。先打开提示的原尺寸裁图,再对照缩进相同的几行、图前图后的字号和所有可疑行。纸线模糊、端点裁切或归行有歧义时应查看原纸。`view="review"` 将逐行读数保存在 `evidence.ruled_rows.rows`。已有同版整页检查的稿件,导出回执会列出疑似碰线或多行落入同一格的页码及检查单 ID。流程图预留整格时,`diagram_perspective_check.items[].ruling_positions` 可辅助核对图框四角和左右侧跨格数。 + 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) 在照片上画新的流程图时,把下例直接写入节的 Markdown。节点文字继承稿件的字体,图框和箭头按其笔画绘制。先给分支条件、箭头和节点留够空间,再移动整图。把图缩进小格会连同标签字号一起改变。已有位图的标签保存在像素中,需要改字形时可从已知题意重建节点和连线。 diff --git a/crates/panache-mcp/src/drafts/observations.rs b/crates/panache-mcp/src/drafts/observations.rs index 269f23af..f8deaaf6 100644 --- a/crates/panache-mcp/src/drafts/observations.rs +++ b/crates/panache-mcp/src/drafts/observations.rs @@ -8,6 +8,7 @@ pub struct PageReview { pub review_id: String, pub earlier_reference: Option, pub visibility_flag: bool, + pub flagged_ruled_cells: u32, pub pixel_sha256: Option, } @@ -193,7 +194,10 @@ impl Snapshot<'_> { let mut statement = db.prepare( "SELECT cur.section, cur.page, COALESCE(json_extract(cur.evidence,'$.visibility') IN ('no_visible_change','very_low_contrast'), 0), cur.pixel_sha256, cur.review_id, - prior.revision, prior.review_id + prior.revision, prior.review_id, + (SELECT count(*) FROM json_each(cur.evidence,'$.ruled_rows.rows') AS cell + WHERE cell.value->>'status' = 'ink_near_or_across_ruling' + OR cell.value->>'layout_rows_in_cell' > 1) FROM review_observations cur LEFT JOIN review_observations prior ON prior.seq=( SELECT prev.seq FROM review_observations prev WHERE prev.draft=cur.draft AND prev.section=cur.section AND prev.page=cur.page @@ -213,6 +217,7 @@ impl Snapshot<'_> { .zip(row.get::<_, Option>(6)?) .map(|(revision, id)| json!({"revision":revision,"review_id":id})), visibility_flag: row.get(2)?, + flagged_ruled_cells: row.get(7)?, pixel_sha256: row.get(3)?, }, )) @@ -411,7 +416,11 @@ mod tests { "b", "other-pixels", "content", - &json!({"visibility":"very_low_contrast","photo_size":[400,500]}), + &json!({"visibility":"very_low_contrast","photo_size":[400,500],"ruled_rows":{"rows":[ + {"status":"ink_near_or_across_ruling","layout_rows_in_cell":2}, + {"status":"multiple_layout_rows_in_cell","layout_rows_in_cell":2}, + {"status":"insufficient_evidence","layout_rows_in_cell":1} + ]}}), )?; assert_ne!(first["review_id"], changed["review_id"]); assert_ne!(changed["review_id"], upgraded["review_id"]); @@ -419,6 +428,7 @@ mod tests { assert_eq!(old.page_observation(1, 1, false)?, legacy); let reviewed = rev2.reviewed_pages()?; assert!(reviewed[&(1, 1)].visibility_flag); + assert_eq!(reviewed[&(1, 1)].flagged_ruled_cells, 2); assert_eq!( reviewed[&(1, 1)].pixel_sha256.as_deref(), Some("other-pixels") @@ -426,6 +436,7 @@ mod tests { assert!(old.reviewed_pages()?[&(1, 1)].pixel_sha256.is_none()); let rev3 = drafts.snapshot("d", Some(3))?; rev3.record_review(1, 1, "a", "pixels", "content", &observation)?; + assert_eq!(rev3.reviewed_pages()?[&(1, 1)].flagged_ruled_cells, 0); assert!(reviewed[&(1, 1)].earlier_reference.is_none()); assert_eq!( rev3.reviewed_pages()?[&(1, 1)].earlier_reference, diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index bf6a927c..997337e5 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -487,6 +487,7 @@ impl Engine { let top = glyph_point(g, edit, [0., -hh]); let bottom = glyph_point(g, edit, [0., hh]); text.push(crate::review::TextSample { + source_baseline: g.baseline, bounds, baseline, paper_vertical_scale: edge(top, bottom) / g.bounds[3] as f32, diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 71639b32..8fef34dd 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -354,6 +354,7 @@ impl ServerHandler for Panache { "Standard TeX needs no package selection. For unfamiliar disciplinary notation, use list_tex_packages by topic or command before saving. New drafts enable default built-ins; [] disables extensions. Only query configured custom packages when the user asks to use them. Keep literal commands in Markdown backticks. Existing drafts keep their saved definitions. ", "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. ", + "For handwriting on photographed ruled paper, check the final revision page by page. Use ruled_row_check when available and compare the finished page and native crops with the original rulings. Trace each prose row between its two rules, check the first ink against that row's left endpoint and intended indent, and compare letter height relative to the local row gap above and below a drawing. For a whole-cell diagram reservation, check both edges against its reserved rows. If placement drifts, measure the actual endpoints across the writing area for paper_guides, reflow and recheck affected pages. ", "For a new labeled flowchart, use the native [flowchart] example in save_section.markdown so its lettering follows the selected font. For diagrams or icons on a paper photo, inspect diagram_perspective_check in the page review at the final position. Compare both horizontal edges and both side directions, near/far widths and nearby writing against the actual paper. Projection already covers the complete drawing. If it matches, retain it. If only this drawing differs and four actual reference corners can be located, apply target_quad with whole_drawing=true and verify the labels and arrows together. 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. At native size compare local_paper_ink_check for the first written row with nearby photographed marks. If the top looks too dark, taper local opacity into the body and recheck. Use opacity_ramp within a tall drawing that crosses the transition. For a plain PNG export leave blur unset. For a lightly softened PNG with no direction specified, start with uniform export_blur_px=0.6. For a photographed worksheet PNG, after local edits check whether review supplies png_finish_comparison. If it does, compare its clear and gradient native crops at both locations before choosing. Keep the clear finish when both fit or delicate writing fades. Only when the requested PNG finish should soften paper and ink together across the photograph, use export_blur_gradient instead. Position its two anchors from the request or inspected photo. Preview the same revision at both ends and in between with view=image and region, then export ZIP using the same finish. 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. ", @@ -510,7 +511,7 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "List groups with {}. Pass group for fields, units, ranges and choices; add draft_id for effective values (optional revision). Use layout for text spacing and geometry, paper_guides for stationery lines, variation for loose writing, strike for occasional crossed-out mistakes and typography for Latin font, scale and digits." + description = "List groups with {}. Pass group for fields, units, ranges and choices; add draft_id for effective values (optional revision). Use layout for text spacing and geometry, tune_handwriting.paper_guides for measured stationery lines, variation for loose writing, strike for occasional crossed-out mistakes and typography for Latin font, scale and digits." )] fn describe_controls(&self, Parameters(input): Parameters) -> CallToolResult { tool_result((|| { @@ -568,7 +569,7 @@ impl Panache { } #[tool( - description = "Revise a draft's controls, font_path or paper_guides. If the user wants earlier hand-placed text kept in place, pass preserve_local_adjustments=true on this call. Ink-only changes keep placement. Map the writing area onto the first/last writable baselines even on artwork or unruled paper. After a font, size or guide change, inspect the new layout. Use view=image to inspect without filing a check." + description = "Revise a draft's controls, font_path or paper_guides. If the user wants earlier hand-placed text kept in place, pass preserve_local_adjustments=true on this call. Ink-only changes keep placement. Map the writing area onto the first/last writable baselines even on artwork or unruled paper. After a font, size or guide change, inspect the new layout and ruled_row_check on lined paper. Use view=image to inspect without filing a check." )] async fn tune_handwriting(&self, Parameters(input): Parameters) -> CallToolResult { let state = self.0.clone(); @@ -777,7 +778,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. For a diagram on photographed paper, open diagram_perspective_check in review to compare the current four corners with the local paper axes. Its layout_arguments identify the whole drawing. To adjust only new ink on a photo, use full-page view=review; if photo_ink_adjustment is returned, pass its describe_arguments unchanged to describe_controls (group=ink), compare native crops, and preserve the print. Only when the requested PNG finish can soften both paper and ink, set export_blur_px for uniform softness or export_blur_gradient for two full-page focus anchors in image view. Use the same finish for ZIP. Add region for a 1:1 crop. 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. drawings_only selects native diagrams and whole raster drawings. illustrations_only selects raster units including independently editable details. 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. On imported ruled paper its ruled_row_check compares visible ink with the photographed lines. 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. For a diagram on photographed paper, open diagram_perspective_check in review to compare the current four corners with the local paper axes. Its layout_arguments identify the whole drawing. To adjust only new ink on a photo, use full-page view=review; if photo_ink_adjustment is returned, pass its describe_arguments unchanged to describe_controls (group=ink), compare native crops, and preserve the print. Only when the requested PNG finish can soften both paper and ink, set export_blur_px for uniform softness or export_blur_gradient for two full-page focus anchors in image view. Use the same finish for ZIP. Add region for a 1:1 crop. 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. drawings_only selects native diagrams and whole raster drawings. illustrations_only selects raster units including independently editable details. 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, @@ -895,6 +896,7 @@ impl Panache { let reviewed_pages = draft.reviewed_pages()?; let mut unreviewed = Vec::new(); let mut visibility_flags = 0; + let mut ruled_flags = Vec::new(); let reflect = draft.style.homework && !state.preserve_reviews; let mut evidence = Vec::new(); let topics = if reflect { @@ -915,6 +917,10 @@ impl Panache { match reviewed_pages.get(&(section, page)) { Some(record) => { visibility_flags += usize::from(record.visibility_flag); + if record.flagged_ruled_cells > 0 { + ruled_flags.push(json!({"section":section,"page":page,"review_id":record.review_id, + "flagged_cells":record.flagged_ruled_cells})); + } if reflect && record.pixel_sha256.is_some() && evidence.len() < 8 { evidence.push(json!({"section":section,"page":page, "earlier_reference":record.earlier_reference, @@ -1013,6 +1019,10 @@ impl Panache { } else { comparison }; } let mut message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}{pixel_warning}\n\n运行 Panache 的电脑上的文件:`{}`", draft.revision, path.display()); + if !ruled_flags.is_empty() { + message.push_str(&format!("\n本版有 {} 页的检查单提示墨迹紧邻或跨过横线,或多行文字落入同一格。按 review_id 查看具体位置并核对原图。", ruled_flags.len())); + review["pages_with_ruled_row_flags"] = json!(ruled_flags); + } let mut metadata = json!({ "draft_id": input.draft_id, "revision": draft.revision, "export_id": export_id, "path": path, "pages": pages, "review": review, }); diff --git a/crates/panache-mcp/src/preview.rs b/crates/panache-mcp/src/preview.rs index e9b540e7..e10f5531 100644 --- a/crates/panache-mcp/src/preview.rs +++ b/crates/panache-mcp/src/preview.rs @@ -267,7 +267,11 @@ fn image( let number = section.number; let contains_drawing = section.text.contains("](data:image/") || section.text.contains("\\begin{circuitikz}"); - let read_only_sample = if draft.paper.is_some() && !review_allowed { + let paper_sample = if draft + .paper + .as_ref() + .is_some_and(|p| p.ruled || !review_allowed) + { Some(engine.review_baselines(draft, section.clone(), page, cancel)?) } else { None @@ -286,13 +290,24 @@ fn image( 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"}); + if draft.paper.as_ref().is_some_and(|p| p.ruled) { + message.push_str("\n先看 ruled_row_check 中接近横线和缺少依据的行,核对首笔、当地格高和图形占格,按 preview_arguments 复看同版原尺寸裁图。"); + } } - if let Some(sample) = read_only_sample - && let Some(check) = - review::local_ink_preview(draft, number, page, &preview.png, &sample, cancel)? - { - message.push_str(&format!("\n原纸与新增笔迹的局部反差 {check}")); - data["local_paper_ink_check"] = check; + if let Some(sample) = paper_sample { + let checks = review::photo_checks_preview( + draft, + number, + page, + &preview.png, + &sample, + !review_allowed, + cancel, + )?; + for (key, value) in checks { + message.push_str(&format!("\n{key} {value}")); + data[key] = value; + } } let mut result = reply(message, data); result diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index b5584031..e6ebaedd 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -3,6 +3,7 @@ mod drawing; pub(crate) use drawing::Drawing; pub mod local; mod paper_ink; +mod ruled_rows; pub(crate) use consistency::{Bounds, TextSample}; use crate::{controls, drafts::Snapshot, reply}; @@ -177,25 +178,40 @@ fn composite_on_paper( } // Used by read-only image previews as well. All measurements use the visible output on the saved paper. -pub fn local_ink_preview( +pub fn photo_checks_preview( draft: &Snapshot<'_>, section: u32, page: usize, png: &str, sample: &PageSample, + include_local_ink: bool, cancel: &Cancellation, -) -> Result> { - if draft.paper.is_none() { - return Ok(None); - } +) -> Result> { + let mut data = serde_json::Map::new(); + let Some(layout) = &draft.paper else { + return Ok(data); + }; let params = controls::parameters(draft, section, &draft.controls)?; let mut finished = decode_page(png)?; let paper = reference_paper(draft, finished.dimensions(), ¶ms)?; if params.transparent_background { composite_on_paper(&mut finished, &paper, cancel)?; } - Ok(paper_ink::measure(sample, &paper, &finished, None, cancel)? - .map(|e| paper_ink::report(&e, draft.id, draft.revision, section, page))) + if include_local_ink + && let Some(e) = paper_ink::measure(sample, &paper, &finished, None, cancel)? + { + data.insert( + "local_paper_ink_check".into(), + paper_ink::report(&e, draft.id, draft.revision, section, page), + ); + } + if layout.ruled { + let evidence = ruled_rows::measure(layout, sample, &paper, &finished, cancel)?; + let mut rows = ruled_rows::report(&evidence, draft.id, draft.revision, section, page); + rows["rows"] = evidence["rows"].clone(); + data.insert("ruled_row_check".into(), rows); + } + Ok(data) } // Paper measurements identify places worth inspecting, not a defect in the new ink. @@ -257,7 +273,7 @@ impl PendingPage { tx, (&self.draft_id, self.revision), (self.section, self.page), - "paper-review/4", + "paper-review/5", &self.pixel_digest, &self.content_digest, &self.evidence, @@ -439,6 +455,9 @@ pub fn page( if let Some(value) = &local_ink { evidence["local_paper_ink"] = value.clone(); } + if let Some(layout) = draft.paper.as_ref().filter(|p| p.ruled) { + evidence["ruled_rows"] = ruled_rows::measure(layout, sample, &paper, &finished, cancel)?; + } let next = if peak == 0 { "If this page should contain text, check ink opacity/color, local edits and off-page placement. Review the new revision." } else if outside > 0 || draft.paper.as_ref().is_some_and(|p| !p.ruled) { @@ -459,6 +478,10 @@ 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(rows) = evidence.get("ruled_rows") { + metadata["ruled_row_check"] = + ruled_rows::report(rows, draft.id, draft.revision, section, page); + } if let Some(region) = table_crop { metadata["table_clearance_check"] = json!({"region":region, "inspect":"The bottom of a table may touch the following text. Read the last row and the text in the attached native crop. Adjust spacing only if their strokes interfere."}); diff --git a/crates/panache-mcp/src/review/consistency.rs b/crates/panache-mcp/src/review/consistency.rs index 17afab20..23e4271d 100644 --- a/crates/panache-mcp/src/review/consistency.rs +++ b/crates/panache-mcp/src/review/consistency.rs @@ -48,7 +48,7 @@ impl Bounds { }) } - fn union(self, b: Self) -> Self { + pub(super) fn union(self, b: Self) -> Self { Self { left: self.left.min(b.left), top: self.top.min(b.top), @@ -103,6 +103,7 @@ impl Bounds { pub(crate) struct TextSample { pub bounds: Bounds, pub baseline: f32, + pub source_baseline: i32, // 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. @@ -509,6 +510,7 @@ mod tests { text: vec![TextSample { bounds: bounds(15., 15., 20., 20.), baseline: 22., + source_baseline: 22, stretch: 1., paper_vertical_scale: 1., }], @@ -547,6 +549,7 @@ mod tests { text: vec![TextSample { bounds: bounds(1100., 0., 1150., 40.), baseline: 40., + source_baseline: 40, stretch: 1., paper_vertical_scale: 1., }], @@ -582,6 +585,7 @@ mod tests { TextSample { bounds: bounds(x, baseline - 16. * paper_vertical_scale, x + 14., baseline), baseline, + source_baseline: baseline as i32, stretch, paper_vertical_scale, } @@ -616,6 +620,7 @@ mod tests { TextSample { bounds: bounds(l, y - 15., l + 10., y), baseline: y, + source_baseline: y as i32, stretch, paper_vertical_scale: 1., } diff --git a/crates/panache-mcp/src/review/drawing.rs b/crates/panache-mcp/src/review/drawing.rs index c1baeae8..37b9f6fb 100644 --- a/crates/panache-mcp/src/review/drawing.rs +++ b/crates/panache-mcp/src/review/drawing.rs @@ -1,5 +1,6 @@ use super::{Bounds, PageSample, photo_point}; use crate::drafts::Snapshot; +use handwriting_core::photo::PaperProjection; use serde_json::{Value, json}; type Quad = [[f32; 2]; 4]; @@ -85,7 +86,7 @@ pub(super) fn add_check( let reference = paper.projection.as_ref().map(|_| drawing.reference(draft)); let preview = json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, "view":"review","region":region}); - items.push(json!({"id":drawing.id,"kind":drawing.kind,"current_photo_quad":drawing.photo_corners, + let mut item = json!({"id":drawing.id,"kind":drawing.kind,"current_photo_quad":drawing.photo_corners, "paper_aligned_photo_quad":reference, "axis_difference_deg_top_bottom_left_right":reference.map(|r|edge_differences(drawing.photo_corners,r)), "bottom_to_top_width_ratio":bottom_to_top_width_ratio(drawing.photo_corners), @@ -95,7 +96,20 @@ pub(super) fn add_check( "native_image_arguments":{"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, "view":"image","region":region,"export_blur_px":0}, "layout_arguments":{"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, - "view":"layout","drawings_only":true,"offset":drawing.layout_offset,"limit":1}})); + "view":"layout","drawings_only":true,"offset":drawing.layout_offset,"limit":1}}); + if let Some(PaperProjection::Rulings { + first, step, rows, .. + }) = &paper.projection + { + // Use the edited corners in paper space. Photo-pixel heights change with perspective. + let [tl, tr, br, bl] = drawing.paper_corners.map(|p| (p[1] - first) / step); + item["ruling_positions"] = json!({ + "corners_tl_tr_br_bl":[tl,tr,br,bl], + "height_in_rows_left_right":[bl-tl,br-tr], + "calibrated_row_range":[0,rows.len()-1], + }); + } + items.push(item); } if items.is_empty() { return; @@ -106,6 +120,7 @@ pub(super) fn add_check( metadata["diagram_perspective_check"] = json!({ "alignment":paper.summary()["alignment"],"items":items,"visible_drawings_in_crop":total, "guidance":hint, + "ruling_units":"有逐行标定时,ruling_positions 用格数表示图框四角的位置,0 是第一条参考线。需要整格留位时,在原图核对预留的上、下边界和相邻正文。左右两侧分别跨多少格可辅助判断斜放或挤占邻格。图框含留白,标定范围外为外推值。", "interpretation":"四角按左上、右上、右下、左下排列。参考框为以当前大小和位置沿纸面两轴放置后经现有模型投影的框。零角差只说明图框跟随模型;要在原纸上核对模型及图内线条、节点和标签。底边/顶边宽度比反映上下宽窄。rotated 只校准了整体旋转。拆分细节的偏移表示与按外框共同变换的预期位置之差;有意单独移字时可能合理。保留有意的斜线和已协调的图形。参考轴不足时报告不确定。", "placement":"图文都偏时,先核对纸面标定,再决定是否用 paper_guides。仅此图不符且能在原纸上定位四角时,使用同版 layout_arguments 找整图 ID,再用 adjust_glyphs(whole_drawing=true, target_quad=实测四角) 同步框线、箭头和标签。只移位置用 whole_drawing=true 与 place_center。对比修前、修后裁区,核对相邻正文;移动后在新位置重查。超过八个图时可用 drawings_only 分页检查。" }); diff --git a/crates/panache-mcp/src/review/paper_ink.rs b/crates/panache-mcp/src/review/paper_ink.rs index 20ec07c9..1c77d1be 100644 --- a/crates/panache-mcp/src/review/paper_ink.rs +++ b/crates/panache-mcp/src/review/paper_ink.rs @@ -331,6 +331,7 @@ mod tests { [x as f32, 88.], ]), baseline: 88., + source_baseline: 88, stretch: 1., paper_vertical_scale: 1., }); diff --git a/crates/panache-mcp/src/review/ruled_rows.rs b/crates/panache-mcp/src/review/ruled_rows.rs new file mode 100644 index 00000000..182eb79c --- /dev/null +++ b/crates/panache-mcp/src/review/ruled_rows.rs @@ -0,0 +1,272 @@ +//! Check visible writing against dark rulings traced on the unmarked photograph. +mod tracking; + +use super::{Bounds, PageSample, contains, rgb_delta}; +use crate::paper::PaperLayout; +use anyhow::Result; +use handwriting_core::Cancellation; +use image::RgbaImage; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; +use tracking::{Track, median_guide_offset}; + +fn rounded(v: f32) -> f64 { + (f64::from(v) * 100.).round() / 100. +} + +fn minimum(value: &mut Option, n: f32) { + *value = Some(value.map_or(n, |v| v.min(n))); +} + +fn crop(point: [u32; 2], spacing: f32, size: (u32, u32)) -> [[u32; 2]; 4] { + let width = (spacing * 8.).round().clamp(160., 640.) as u32; + let height = (spacing * 3.).round().clamp(96., 400.) as u32; + let (w, h) = (width.min(size.0), height.min(size.1)); + let l = point[0].saturating_sub(w / 2).min(size.0 - w); + let t = point[1].saturating_sub(h / 2).min(size.1 - h); + [[l, t], [l + w, t], [l + w, t + h], [l, t + h]] +} + +pub(super) fn measure( + layout: &PaperLayout, + sample: &PageSample, + paper: &RgbaImage, + finished: &RgbaImage, + cancel: &Cancellation, +) -> Result { + let first = layout.top as f32 + layout.line_spacing; + let mut rows = BTreeMap::>::new(); + for g in &sample.text { + if g.baseline.is_finite() { + let row = ((g.baseline - first) / layout.line_spacing).round() as i32; + rows.entry(row).or_default().push(g); + } + } + let row_bounds: Vec<_> = rows + .iter() + .map(|(&row, glyphs)| { + ( + row, + glyphs + .iter() + .map(|g| g.bounds) + .reduce(Bounds::union) + .unwrap(), + ) + }) + .collect(); + let offset = median_guide_offset(layout, paper, rows.keys().copied()); + let mut tracks = BTreeMap::new(); + let mut metrics = Vec::new(); + let size = paper.dimensions(); + let mut budget = u64::from(size.0) * u64::from(size.1) * 4; + for (&row, glyphs) in &rows { + cancel.check()?; + for index in [row.saturating_sub(1), row] { + if let std::collections::btree_map::Entry::Vacant(entry) = tracks.entry(index) { + entry.insert(Track::trace(paper, layout, index, offset, cancel)?); + } + } + let upper = tracks[&row.saturating_sub(1)].as_ref(); + let lower = tracks[&row].as_ref(); + let mut upper_gap = None; + let mut lower_gap = None; + let mut start = None::<[u32; 2]>; + let mut problem = None; + let mut worst_gap = f32::INFINITY; + let mut heights = Vec::new(); + let mut missing = false; + let mut skipped = 0; + let mut unknown_start = u32::MAX; + let extent = glyphs + .iter() + .map(|g| g.bounds) + .reduce(Bounds::union) + .unwrap(); + let neighbors: Vec<_> = row_bounds + .iter() + .filter(|(other, _)| *other != row) + .filter(|(_, bounds)| bounds.intersects(extent)) + .flat_map(|(other, _)| &rows[other]) + .collect(); + for g in glyphs { + cancel.check()?; + let Some([[l, t], _, [r, b], _]) = g.bounds.region(0., size) else { + skipped += 1; + unknown_start = 0; + continue; + }; + let area = u64::from(r - l) * u64::from(b - t); + if area > budget || !g.bounds.on_page(size) { + skipped += 1; + unknown_start = unknown_start.min(l); + continue; + } + budget -= area; + // Overlapping rows cannot claim the same visible pixels. + let ambiguous: Vec<_> = neighbors + .iter() + .filter(|other| other.bounds.intersects(g.bounds)) + .filter_map(|other| other.bounds.region(0., size)) + .collect(); + let illustrations: Vec<_> = sample + .drawings + .iter() + .filter(|d| d.bounds().intersects(g.bounds)) + .map(|d| d.photo_corners.map(|p| p.map(|v| v.round() as i32))) + .collect(); + let mut glyph_top = f32::INFINITY; + let mut glyph_bottom = f32::NEG_INFINITY; + let mut visible = false; + for x in l..r { + let mut ys = (t..b).filter(|&y| { + if rgb_delta(paper[(x, y)], finished[(x, y)]) < 8 { + return false; + } + let overlap = ambiguous.iter().any(|a| { + (a[0][0]..a[2][0]).contains(&x) && (a[0][1]..a[2][1]).contains(&y) + }); + let overlap = overlap + || illustrations + .iter() + .any(|q| contains(q, [x as f32 + 0.5, y as f32 + 0.5])); + if overlap { + unknown_start = unknown_start.min(x); + } + missing |= overlap; + !overlap + }); + let Some(y0) = ys.next() else { continue }; + let y1 = ys.next_back().unwrap_or(y0); + visible = true; + if start.is_none_or(|p| x < p[0]) { + start = Some([x, y0]); + } + let high = upper + .and_then(|track| track.at(x as i32)) + .map(|(_, bottom)| bottom); + let low = lower + .and_then(|track| track.at(x as i32)) + .map(|(top, _)| top); + if let Some((high, low)) = high.zip(low) { + let space = low - high - 1.; + if space <= 0. { + missing = true; + continue; + } + // Express the first and last ink-pixel edges in local cell coordinates. + glyph_top = glyph_top.min((y0 as f32 - high - 1.) / space); + glyph_bottom = glyph_bottom.max((y1 as f32 - high) / space); + } + let hi = high.map(|bottom| y0 as f32 - bottom - 1.); + let lo = low.map(|top| top - y1 as f32 - 1.); + missing |= hi.is_none() || lo.is_none(); + for (gap, y) in [(hi, y0), (lo, y1)] { + if let Some(gap) = gap + && gap <= 0. + && gap < worst_gap + { + worst_gap = gap; + problem = Some([x, y]); + } + } + if let Some(gap) = hi { + minimum(&mut upper_gap, gap); + } + if let Some(gap) = lo { + minimum(&mut lower_gap, gap); + } + } + missing |= !visible; + if glyph_top <= glyph_bottom { + heights.push(glyph_bottom - glyph_top); + } + } + heights.sort_unstable_by(f32::total_cmp); + let source_rows = glyphs + .iter() + .map(|g| g.source_baseline) + .collect::>() + .len(); + let left = lower.map(Track::left_x); + let endpoint_clipped = lower.map(Track::left_is_clipped); + let first_ink = start.filter(|p| p[0] <= unknown_start); + let offset = left.zip(first_ink).map(|(x, p)| p[0] as i32 - x); + let status = if problem.is_some() { + "ink_near_or_across_ruling" + } else if source_rows > 1 { + "multiple_layout_rows_in_cell" + } else if start.is_none() || missing || skipped > 0 { + "insufficient_evidence" + } else { + "sampled_clearance" + }; + let anchor = problem + .or(start) + .unwrap_or_else(|| glyphs[0].bounds.center().map(|p| p as u32)); + metrics.push(json!({"row":row,"status":status,"min_upper_clearance_px":upper_gap.map(rounded), + "min_lower_clearance_px":lower_gap.map(rounded),"first_ink":first_ink,"ruling_left_x":left,"start_offset_px":offset, + "left_endpoint_at_image_edge":endpoint_clipped, "guide_to_paper_center_dy_px":lower.map(|v|rounded(v.guide_offset)), + "median_glyph_height_in_cells":heights.get(heights.len()/2).copied().map(rounded), + "measured_glyphs":heights.len(), "layout_rows_in_cell":source_rows, + "partial":start.is_none() || missing || skipped>0,"region":crop(anchor,layout.line_spacing,size)})); + tracks.retain(|&index, _| index == row); + } + Ok( + json!({"status":if metrics.is_empty() {"no_body_text"} else {"inspect_rows"},"rows":metrics}), + ) +} + +pub(super) fn report( + evidence: &Value, + draft: &str, + revision: u32, + section: u32, + page: usize, +) -> Value { + let rows = evidence["rows"].as_array().unwrap(); + let worst_gap = |r: &Value| { + ["min_upper_clearance_px", "min_lower_clearance_px"] + .iter() + .filter_map(|key| r[key].as_f64()) + .min_by(f64::total_cmp) + }; + let first = rows + .iter() + .filter(|r| r["status"] == "ink_near_or_across_ruling") + .min_by(|a, b| worst_gap(a).unwrap().total_cmp(&worst_gap(b).unwrap())) + .or_else(|| { + rows.iter() + .find(|r| r["layout_rows_in_cell"].as_u64().is_some_and(|n| n > 1)) + }) + .or_else(|| rows.iter().max_by_key(|r| r["start_offset_px"].as_i64())) + .or_else(|| rows.first()); + let contacts = rows + .iter() + .filter(|r| r["status"] == "ink_near_or_across_ruling") + .count(); + let partial = rows.iter().filter(|r| r["partial"] == true).count(); + let mut data = json!({"status":evidence["status"],"occupied_cells":rows.len(),"possible_contact_cells":contacts,"partial_cells":partial, "inspect":"按 rows 核对每个正文行,row 从首个可写格起按 0 编号。余量是新增可见像素与原纸暗线半对比度边缘间的空白像素数,零表示紧邻,负数表示进入或越过印线边缘。start_offset_px 比较首笔与下方实测线的可见左端;核对题号缩进。按格高归一的字高用于比较同类字。数字来自字框内成图与原纸单个 RGB 通道至少 8 级的可见差分,叠字、标点、线端裁切和纸上装饰需看原尺寸。null 或 partial 表示证据不全。layout_rows_in_cell 大于 1 时,查看是否把多个原文行移进了同一格。先核对底纸上的横线及左右端,再决定是否修订 paper_guides。用任一行的 region 查看同版局部。"}); + for (key, metric) in [ + ("start_offset_range", "start_offset_px"), + ("glyph_height_range", "median_glyph_height_in_cells"), + ] { + let mut ranked: Vec<_> = rows + .iter() + .filter_map(|r| Some((r[metric].as_f64()?, &r["row"]))) + .collect(); + ranked.sort_by(|a, b| a.0.total_cmp(&b.0)); + if let (Some((min, a)), Some((max, b))) = (ranked.first(), ranked.last()) { + data[key] = json!({"min":min,"min_row":a,"max":max,"max_row":b}); + } + } + if let Some(row) = first { + data["inspect_row"] = json!({"row":row["row"],"min_upper_clearance_px":row["min_upper_clearance_px"], + "min_lower_clearance_px":row["min_lower_clearance_px"],"start_offset_px":row["start_offset_px"]}); + data["preview_arguments"] = json!({"draft_id":draft,"revision":revision,"section":section,"page":page,"view":"review","region":row["region"]}); + } + data +} + +#[cfg(test)] +mod tests; diff --git a/crates/panache-mcp/src/review/ruled_rows/tests.rs b/crates/panache-mcp/src/review/ruled_rows/tests.rs new file mode 100644 index 00000000..bd7ed67b --- /dev/null +++ b/crates/panache-mcp/src/review/ruled_rows/tests.rs @@ -0,0 +1,218 @@ +use super::*; +use crate::{ + Guide as PaperGuide, + review::{Bounds, TextSample}, +}; +use image::Rgba; + +fn sample() -> PageSample { + PageSample { + text: vec![], + baselines: vec![], + drawings: vec![], + table_candidates: vec![], + content_sha256: String::new(), + } +} + +fn glyph(x: u32, top: u32, bottom: u32, baseline: f32) -> TextSample { + TextSample { + bounds: Bounds::from_corners( + [[x, top], [x + 8, top], [x + 8, bottom + 1], [x, bottom + 1]] + .map(|p| p.map(|v| v as f32)), + ), + source_baseline: baseline as i32, + baseline, + stretch: 1., + paper_vertical_scale: 1., + } +} + +#[test] +fn measures_visible_strokes_and_endpoint_on_the_original_paper() { + let guides: Vec<_> = [48, 78, 108] + .into_iter() + .enumerate() + .map(|(i, y)| PaperGuide { + via: Vec::new(), + row: i as u16, + left: [50, y], + right: [180, y], + }) + .collect(); + let layout = PaperLayout::from_guides(240, 150, &guides).unwrap(); + let mut paper = RgbaImage::from_pixel(240, 150, Rgba([230, 230, 230, 255])); + // The supplied guides are 10 px too high and stop inside the true lines. + for (left, y) in [(40, 28), (30, 58), (20, 88), (10, 118)] { + for x in left..210 { + for yy in y - 1..=y + 1 { + paper[(x, yy)] = Rgba([110, 110, 110, 255]); + } + } + } + // A darker neighboring header is closer to the first virtual guide. + // The other rows establish which side of the virtual guide carries its ruling. + for x in 20..215 { + paper[(x, 40)] = Rgba([40, 40, 40, 255]); + } + let mut finished = paper.clone(); + let mut sample = sample(); + for (x, min_y, max_y, baseline) in [(53, 37, 50, 48.), (70, 65, 87, 78.), (76, 94, 107, 108.)] { + // The padded glyph bounds touch a rule even when the visible writing clears it. + sample.text.push(glyph(x, min_y - 4, max_y + 5, baseline)); + for y in min_y..=max_y { + finished[(x + 2, y)] = Rgba([10, 10, 10, 255]); + } + } + let evidence = measure( + &layout, + &sample, + &paper, + &finished, + &Cancellation::default(), + ) + .unwrap(); + let rows = evidence["rows"].as_array().unwrap(); + assert_eq!(rows.len(), 3); + assert_eq!(rows[0]["start_offset_px"], 25); + assert_eq!(rows[0]["guide_to_paper_center_dy_px"], 10.); + assert_eq!(rows[0]["min_upper_clearance_px"], 7.); + assert_eq!(rows[0]["min_lower_clearance_px"], 6.); + assert_eq!(rows[1]["min_lower_clearance_px"], -1.); + assert_eq!(rows[0]["status"], "sampled_clearance"); + assert_eq!(rows[1]["status"], "ink_near_or_across_ruling"); + assert_eq!(rows[1]["start_offset_px"], 52); + assert_eq!( + rows[2]["median_glyph_height_in_cells"], + rows[0]["median_glyph_height_in_cells"] + ); + let check = report(&evidence, "sample", 3, 2, 1); + assert_eq!(check["preview_arguments"]["region"], rows[1]["region"]); + assert_eq!(check["possible_contact_cells"], 1); + assert_eq!(check["start_offset_range"]["max"], 68.); + assert_eq!(check["glyph_height_range"]["max_row"], 1); +} + +#[test] +fn reports_shared_cells_and_skips_ambiguous_ink_between_rows() { + let layout = PaperLayout::from_guides( + 220, + 140, + &[40, 70, 100] + .into_iter() + .enumerate() + .map(|(row, y)| PaperGuide { + row: row as u16, + left: [10, y], + right: [210, y], + via: vec![], + }) + .collect::>(), + ) + .unwrap(); + let paper = RgbaImage::from_fn(220, 140, |_, y| { + if y % 30 == 10 { + Rgba([90, 90, 90, 255]) + } else { + Rgba([230, 230, 230, 255]) + } + }); + let mut finished = paper.clone(); + let mut sample = sample(); + sample.text.push(glyph(20, 14, 34, 40.)); + let mut moved = glyph(40, 18, 37, 40.); + moved.source_baseline = 70; + sample.text.push(moved); + for (x, y) in [(22, 25), (42, 28), (92, 70)] { + finished[(x, y)] = Rgba([0, 0, 0, 255]); + } + // The visible stroke lies inside both rows' overlapping boxes. + sample.text.push(glyph(90, 63, 77, 70.)); + sample.text.push(glyph(90, 66, 85, 100.)); + // A diagram fully covers the first glyph of a later row. The next + // visible letter cannot establish that row's left inset. + let corners = [[14., 108.], [38., 108.], [38., 130.], [14., 130.]]; + sample.drawings.push(crate::review::Drawing { + id: 42, + kind: "image", + layout_offset: 0, + paper_corners: corners, + photo_corners: corners, + details: None, + }); + sample.text.push(glyph(20, 111, 126, 130.)); + sample.text.push(glyph(68, 111, 126, 130.)); + for x in [21, 70] { + finished[(x, 117)] = Rgba([0, 0, 0, 255]); + } + let data = measure( + &layout, + &sample, + &paper, + &finished, + &Cancellation::default(), + ) + .unwrap(); + assert_eq!(data["rows"][0]["status"], "multiple_layout_rows_in_cell"); + assert_eq!(data["rows"][3]["partial"], true); + assert!(data["rows"][3]["first_ink"].is_null()); + assert!(data["rows"][3]["start_offset_px"].is_null()); + for row in [1, 2] { + let item = &data["rows"][row]; + assert_eq!(item["status"], "insufficient_evidence"); + assert!(item["min_lower_clearance_px"].is_null()); + assert!(item["first_ink"].is_null()); + } +} + +#[test] +fn unsupported_guides_and_invisible_writing_stay_unverified() { + let layout = PaperLayout::from_guides( + 180, + 100, + &[ + PaperGuide { + via: Vec::new(), + row: 0, + left: [16, 48], + right: [160, 48], + }, + PaperGuide { + via: Vec::new(), + row: 1, + left: [16, 78], + right: [160, 78], + }, + ], + ) + .unwrap(); + let mut paper = RgbaImage::from_pixel(180, 100, Rgba([240; 4])); + // Isolated dark decorations at the center do not support a full ruling. + for y in [18, 48] { + for x in 81..91 { + paper[(x, y)] = Rgba([80, 80, 80, 255]); + } + } + let mut finished = paper.clone(); + let mut sample = sample(); + sample.text.push(glyph(32, 32, 46, 48.)); + for write in [false, true] { + if write { + finished[(33, 39)] = Rgba([32, 32, 32, 255]); + } + let evidence = measure( + &layout, + &sample, + &paper, + &finished, + &Cancellation::default(), + ) + .unwrap(); + let row = &evidence["rows"][0]; + assert_eq!(row["status"], "insufficient_evidence"); + assert_eq!(row["partial"], true); + assert!(row["ruling_left_x"].is_null()); + assert!(row["min_lower_clearance_px"].is_null()); + assert_eq!(row["first_ink"].is_array(), write); + } +} diff --git a/crates/panache-mcp/src/review/ruled_rows/tracking.rs b/crates/panache-mcp/src/review/ruled_rows/tracking.rs new file mode 100644 index 00000000..03b87110 --- /dev/null +++ b/crates/panache-mcp/src/review/ruled_rows/tracking.rs @@ -0,0 +1,221 @@ +//! Trace both edges of a printed stroke on the original photograph. +use crate::paper::{PaperLayout, focus::luma}; +use anyhow::Result; +use handwriting_core::Cancellation; +use image::RgbaImage; + +struct Guide { + // Sampling paper space also handles a rotated page and piecewise curved rulings. + points: [[f32; 2]; 17], +} + +impl Guide { + fn new(layout: &PaperLayout, row: i32) -> Self { + let left = layout.left as f32; + let width = (layout.width - layout.right) as f32 - left; + let y = layout.top as f32 + (row as f32 + 1.) * layout.line_spacing; + Self { + points: std::array::from_fn(|i| { + let x = left + width * i as f32 / 16.; + layout + .projection + .as_ref() + .map_or([x, y], |p| p.photo_point(x, y)) + }), + } + } + + fn y(&self, x: f32) -> f32 { + let i = self + .points + .partition_point(|p| p[0] < x) + .saturating_sub(1) + .min(15); + let ([ax, ay], [bx, by]) = (self.points[i], self.points[i + 1]); + ay + (by - ay) * ((x - ax) / (bx - ax)) + } +} + +#[derive(Clone, Copy)] +struct Band { + x: i32, + top: f32, + bottom: f32, +} + +impl Band { + fn center(self) -> f32 { + (self.top + self.bottom) / 2. + } +} + +// Pick a thin dark stroke with brighter paper on both sides. Its half-contrast band +// includes the visible width of a thick ruling; a one-sided paper edge has no support. +fn find_band( + paper: &RgbaImage, + x: i32, + y: f32, + radius: i32, + probe: i32, + contrast: i16, +) -> Option { + let height = paper.height() as i32; + let gray = |yy: i32| luma(paper[(x as u32, yy as u32)]); + let center = y.round() as i32; + let (score, _, best) = (center.saturating_sub(radius).max(probe) + ..=center.saturating_add(radius).min(height - 1 - probe)) + .map(|yy| { + ( + gray(yy - probe).min(gray(yy + probe)) - gray(yy), + -(yy - center).abs(), + yy, + ) + }) + .max()?; + if score < contrast { + return None; + } + let half = gray(best) + score / 2; + let mut top = best; + let mut bottom = best; + while top > best - probe && gray(top - 1) <= half { + top -= 1; + } + while bottom < best + probe && gray(bottom + 1) <= half { + bottom += 1; + } + Some(Band { + x, + top: top as f32, + bottom: bottom as f32, + }) +} + +// An earlier draft may use virtual baselines between two dark strokes. Infer +// the shared offset at page center before tracking individual lines; otherwise +// a darker neighboring header can be mistaken for the first text ruling. +pub(super) fn median_guide_offset( + layout: &PaperLayout, + paper: &RgbaImage, + rows: impl Iterator, +) -> Option { + let mut offsets = Vec::new(); + for row in rows { + let guide = Guide::new(layout, row); + let [x, y] = guide.points[8]; + let spacing = Guide::new(layout, row.saturating_add(1)).y(x) - y; + if !(5. ..=1024.).contains(&spacing) || !(0. ..paper.width() as f32).contains(&x) { + continue; + } + if let Some(band) = find_band( + paper, + x.round().clamp(0., paper.width() as f32 - 1.) as i32, + y, + (spacing * 0.48).round().min(96.) as i32, + (spacing * 0.17).round().clamp(3., 16.) as i32, + 12, + ) { + offsets.push((band.center() - y) / spacing); + } + } + offsets.sort_unstable_by(f32::total_cmp); + (offsets.len() >= 3).then(|| offsets[offsets.len() / 2]) +} + +pub(super) struct Track { + bands: Vec, + stride: i32, + pub(super) guide_offset: f32, +} + +impl Track { + pub(super) fn left_x(&self) -> i32 { + self.bands[0].x + } + + pub(super) fn left_is_clipped(&self) -> bool { + self.left_x() < self.stride + } + + pub(super) fn trace( + paper: &RgbaImage, + layout: &PaperLayout, + row: i32, + offset: Option, + cancel: &Cancellation, + ) -> Result> { + let guide = Guide::new(layout, row); + let neighbor = Guide::new(layout, row.saturating_add(1)); + let [cx, cy] = guide.points[8]; + let width = paper.width() as i32; + let mid = cx.round() as i32; + if !(0..width).contains(&mid) { + return Ok(None); + } + let spacing = (neighbor.y(cx) - cy).abs(); + if !spacing.is_finite() || spacing < 5. { + return Ok(None); + } + let probe = (spacing * 0.17).round().clamp(3., 16.) as i32; + let search = (spacing * if offset.is_some() { 0.34 } else { 0.48 }) + .round() + .clamp(2., 96.) as i32; + let Some(seed) = find_band( + paper, + mid, + cy + offset.unwrap_or(0.) * spacing, + search, + probe, + 12, + ) else { + return Ok(None); + }; + let stride = (width / 360).clamp(1, 8); + let mut bands = vec![seed]; + for direction in [-1, 1] { + let mut last = seed; + let mut x = mid + direction * stride; + while (0..width).contains(&x) { + cancel.check()?; + let expected = last.center() + guide.y(x as f32) - guide.y(last.x as f32); + if let Some(next) = find_band(paper, x, expected, (probe / 2).max(2), probe, 8) + && (next.center() - guide.y(x as f32) - (seed.center() - cy)).abs() + <= (0.48 * spacing).max(8.) + { + bands.push(next); + last = next; + } else if (x - last.x).abs() >= 3 * stride { + break; + } + x += direction * stride; + } + } + let guide_width = guide.points[16][0] - guide.points[0][0]; + if bands.len() < 5 || ((bands.len() * stride as usize) as f32) < guide_width * 0.40 { + return Ok(None); + } + bands.sort_unstable_by_key(|b| b.x); + Ok(Some(Self { + bands, + stride, + guide_offset: seed.center() - cy, + })) + } + + pub(super) fn at(&self, x: i32) -> Option<(f32, f32)> { + let i = self.bands.partition_point(|p| p.x < x); + let next = self.bands.get(i)?; + if next.x == x { + return Some((next.top, next.bottom)); + } + let prev = self.bands.get(i.checked_sub(1)?)?; + if next.x - prev.x > 2 * self.stride { + return None; + } + let t = (x - prev.x) as f32 / (next.x - prev.x) as f32; + Some(( + prev.top + t * (next.top - prev.top), + prev.bottom + t * (next.bottom - prev.bottom), + )) + } +} diff --git a/crates/panache-mcp/src/save.rs b/crates/panache-mcp/src/save.rs index 373b4441..1f1c9a38 100644 --- a/crates/panache-mcp/src/save.rs +++ b/crates/panache-mcp/src/save.rs @@ -299,6 +299,12 @@ fn saved_reply(mut saved: Value) -> CallToolResult { if let Some(focus) = saved.get("paper_focus_check") { message.push_str(&format!("\n底纸边缘原尺寸检查 {focus}。核对新增笔迹与原有印迹的反差时,调用 preview_handwriting {},按 local_paper_ink_check 查看页首、过渡行与下方正文。", saved["photo_ink_preview_arguments"])); } + if saved["paper"]["ruled"] == true && saved.get("photo_ink_preview_arguments").is_some() { + let hint = "横线纸交付前按最终版本逐页复查。先看整页,再按 ruled_row_check 的行号看原尺寸裁图。检查正文是否逐行写在上下横线之间,首笔是否跟随本行左端,分项缩进是否一致。用当地格高比较上下字号,图前图后都要看。横线或端点缺少测量依据时,回看原纸。"; + saved["ruled_layout_guidance"] = json!(hint); + message.push('\n'); + message.push_str(hint); + } if let Some(search) = saved.get("experience_search") { message.push_str(&format!( "\n{} search_homework_experience {}", diff --git a/crates/panache-mcp/tests/diagram_perspective.py b/crates/panache-mcp/tests/diagram_perspective.py index 5481d65d..fa7ebc2f 100644 --- a/crates/panache-mcp/tests/diagram_perspective.py +++ b/crates/panache-mcp/tests/diagram_perspective.py @@ -58,6 +58,16 @@ def slope(quad): return (y1 - y0) / (x1 - x0) +def ruling_position(point, guides): + x, y = point + heights = [] + for guide in guides: + (lx, ly), (rx, ry) = guide["left"], guide["right"] + heights.append(ly + (ry - ly) * (x - lx) / (rx - lx)) + i = min(max(sum(h < y for h in heights) - 1, 0), len(heights) - 2) + return i + (y - heights[i]) / (heights[i + 1] - heights[i]) + + async def verify(client, home): photo = home / "drawing-perspective.png" guides = ruled_photo(photo) @@ -95,6 +105,13 @@ async def items(rev, **options): assert gap(item["current_photo_quad"], item["paper_aligned_photo_quad"]) < 1.5 assert max(abs(a) for a in item["axis_difference_deg_top_bottom_left_right"]) < 1 tl, tr, br, bl = item["current_photo_quad"] + positions = item["ruling_positions"] + expected = [ruling_position(p, guides) for p in (tl, tr, br, bl)] + assert positions["calibrated_row_range"] == [0, len(guides) - 1] + assert all(abs(a - b) < 0.01 for a, b in zip(positions["corners_tl_tr_br_bl"], expected, strict=True)) + assert all(abs(a - b) < 0.01 for a, b in zip( + positions["height_in_rows_left_right"], [expected[3] - expected[0], expected[2] - expected[1]], strict=True + )) ratio = math.dist(bl, br) / math.dist(tl, tr) assert math.isclose(item["bottom_to_top_width_ratio"], ratio, rel_tol=1e-5) assert math.isclose(item["paper_bottom_to_top_width_ratio"], ratio, rel_tol=1e-5) @@ -121,6 +138,8 @@ async def items(rev, **options): assert gap(rotated["current_photo_quad"], rotated["paper_aligned_photo_quad"]) > 5 assert slope(rotated["current_photo_quad"]) > slope(rotated["paper_aligned_photo_quad"]) + 0.15 assert abs(rotated["axis_difference_deg_top_bottom_left_right"][0]) > 10 + top_left, top_right, *_ = rotated["ruling_positions"]["corners_tl_tr_br_bl"] + assert abs(top_left - top_right) > 0.2 # Color only the letter. Warping the full drawing must keep that letter inside the frame. await edit(3, label, color="#ce2020") @@ -179,6 +198,7 @@ async def label_center(revision): assert uncalibrated["kind"] == "native_diagram" and len(uncalibrated["current_photo_quad"]) == 4 assert uncalibrated["paper_aligned_photo_quad"] is None assert uncalibrated["axis_difference_deg_top_bottom_left_right"] is None + assert "ruling_positions" not in uncalibrated async def main(binary): diff --git a/crates/panache-mcp/tests/ruled_row_alignment.py b/crates/panache-mcp/tests/ruled_row_alignment.py new file mode 100644 index 00000000..0f89adfd --- /dev/null +++ b/crates/panache-mcp/tests/ruled_row_alignment.py @@ -0,0 +1,128 @@ +"""Compare MCP's ruled-row review with visible pixels on a perspective worksheet.""" + +import argparse +import asyncio +from pathlib import Path +from statistics import median +from tempfile import TemporaryDirectory + +from PIL import Image, ImageDraw + +from coursework_form import finished_image, ink_mask +from mcp_client import call, isolated_session + + +def worksheet(path): + paper = Image.new("RGB", (520, 460), "#faf7ef") + draw = ImageDraw.Draw(paper) + lines = [] + for row in range(10): + y = 48 + 25 * row + row * (row + 1) // 2 + left = [62 - 4 * row, y] + right = [432 + 5 * row, y - 12 - row] + draw.line((tuple(left), tuple(right)), fill="#90949a", width=2) + lines.append((left, right)) + paper.save(path) + return paper, lines + + +def line_y(line, x): + (lx, ly), (rx, ry) = line + return ly + (x - lx) * (ry - ly) / (rx - lx) + + +def row_pixels(mask, lines): + # The oracle uses only the known printed lines and the source/PNG difference. + # Attribute pixels to a cell using its local boundaries at that x. + rows = [[] for _ in lines[1:]] + for y in range(mask.height): + for x in range(mask.width): + if not mask.getpixel((x, y)): + continue + for row, (upper, lower) in enumerate(zip(lines, lines[1:])): + top = y - line_y(upper, x) + bottom = line_y(lower, x) - y + if min(top, bottom) >= 0: + rows[row].append((x, y)) + break + else: + raise AssertionError(f"Ink outside all writable cells at {(x, y)}") + return rows + + +async def verify(client, directory): + path = directory / "row-alignment.png" + paper, lines = worksheet(path) + guides = [ + {"row": row, "left": left, "right": right} + for row, (left, right) in enumerate(lines[1:]) + ] + text = ["春风", "夏雨", "秋叶", "冬雪"] + saved = await call( + client, "save_section", markdown="\n\n".join(text), paper_path=str(path), + paper_guides=guides, + style={"font": "李国夫手写体.ttf", "font_size": 19, "seed": 35, "homework": True}, + ) + key = {"draft_id": saved.structuredContent["draft_id"], "section": 1, "page": 1} + + async def render(revision): + result = await call(client, "preview_handwriting", **key, revision=revision) + return ink_mask(paper, finished_image(result)), result.structuredContent["ruled_row_check"] + + before, initial = await render(1) + assert initial["occupied_cells"] == len(text) + rows = row_pixels(before, lines) + assert [i for i, pixels in enumerate(rows) if pixels] == list(range(len(text))) + for index, pixels in enumerate(rows[:len(text)]): + clearance = min( + min(y - line_y(lines[index], x), line_y(lines[index + 1], x) - y) + for x, y in pixels + ) + assert clearance > 0.5, (index, clearance) + inset = min(p[0] for p in pixels) - guides[index]["left"][0] + assert -3 <= inset < 12, (index, inset) + + # Displace exactly one line until visible ink straddles a ruling, with an + # intentional left inset. Leave the other rows and the reference guides fixed. + layout = (await call( + client, "preview_handwriting", **key, revision=1, view="layout", limit=32, + )).structuredContent + ids = [g["id"] for g in layout["glyphs"] if g.get("text") in set(text[1])] + assert len(ids) == 2 + selected = rows[1] + # The shift should leave some ink above and some below the same sloping line. + dy = round(median(line_y(lines[2], x + 44) - y for x, y in selected)) + await call(client, "adjust_glyphs", **key, expected_revision=1, ids=ids, dx=44, dy=dy) + after, check = await render(2) + contact = [ + (x, y) for x in range(90, 180) for y in range(75, 125) + if after.getpixel((x, y)) and abs(line_y(lines[2], x) - y) <= 1 + ] + assert contact, "Adjusted strokes must independently reproduce visible contact" + assert check["possible_contact_cells"] >= 1 + stored = (await call(client, "read_section", **key, revision=2, view="review")).structuredContent + assert stored["review_id"] is None + crop = await call(client, "preview_handwriting", **check["preview_arguments"]) + assert sum(block.type == "image" for block in crop.content) == 2 + review = (await call(client, "preview_handwriting", **key, revision=2, view="review")).structuredContent + records = review["evidence"]["ruled_rows"]["rows"] + assert records == check["rows"] + shifted = next(r for r in records if r["row"] == 1) + assert shifted["min_lower_clearance_px"] <= 1, shifted + assert shifted["start_offset_px"] >= 35, shifted + assert "ruled_row_check" in review + export = (await call(client, "export_handwriting", draft_id=key["draft_id"], revision=2, format="zip")).structuredContent + flagged, = export["review"]["pages_with_ruled_row_flags"] + assert flagged["review_id"] == review["review_id"] and flagged["flagged_cells"] >= 1 + + +async def main(binary): + with TemporaryDirectory() as temp: + async with isolated_session(binary, Path(temp)) as (client, _): + await verify(client, Path(temp)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("binary", type=Path) + asyncio.run(main(parser.parse_args().binary.resolve())) diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 47bfd8b9..c8e661e6 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -28,6 +28,7 @@ import paper_ink_check import font_samples import review_comparison +import ruled_row_alignment from mcp_client import call from mcp import ClientSession, StdioServerParameters @@ -513,6 +514,7 @@ async def smoke(command, arguments, out, *, rsi_enabled=False): await paper_focus.verify(client, Path(temp)) await photo_ink_finish.verify(client, Path(temp)) await paper_ink_check.verify(client, Path(temp)) + await ruled_row_alignment.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 29f67e4b..22ef32a6 100644 --- a/crates/panache-mcp/tool-design.md +++ b/crates/panache-mcp/tool-design.md @@ -38,7 +38,7 @@ 建稿时传入服务端能读取的 `paper_path`。默认的 `paper_mode="photo"` 在原照片上写字,保留拍照时的透视;`flatten` 使用校平后的底纸。先看返回的画布尺寸、边距、行距和横线识别结果,再决定是否需要手动校准。 -- **有清楚的横线,但字没贴上去。** 在同一份稿上用 `tune_handwriting(paper_guides=…)` 指出第一条和最后一条可写基线,必要时补中间几行。每条包含行号 `row` 和原图上的两个端点 `left:[x,y]`、`right:[x,y]`,首行编号为 0。两个端点沿纸纹取,即使横线在照片里向上斜,也能给模型一个明确的书写方向。传空数组可恢复建稿时的校准。 +- **有清楚的横线,但字没贴上去。** 在同一份稿上用 `tune_handwriting(paper_guides=…)` 标定从第一条到最后一条可写基线。首个可写格的下边线编号为 0。沿整行书写时,逐行量取原图上横线的真实左右端点 `left:[x,y]`、`right:[x,y]`。透视会同时改变线端的 x 和 y。纸弯处沿线从左到右补 `via:[[x,y],…]`,最多 7 点,投影沿原图全宽按 9 列采样。最多提交 32 条参考线,中间跳过的横线要保留行号间距。传空数组可恢复建稿时的校准。 - **没有横线,或者纸上有画。** `alignment="unverified"` 表示没找到可靠横线。用户已指定右下角或委托选位时,可以在该区域试排。左右都有空白、位置会影响画面时,再问用户想写在哪、哪里要留白。若任务要求填写表头,但表头被裁掉或遮住了,先请用户补拍,或确认只写可见部分。 - **只需调一块文字。** 在 `view="layout"` 中用原图像素圈选字形中心。投影稿的 `photo_quad` 给出原始字框的左上、右上、右下、左下四角,`photo_baseline` 给出原始基线两端,已有调整另列。要把一组字挪到图中的某点,用 `place_center`;让同一原始行的文字顺着照片上的横线或斜栏书写,用 `natural_line` 指定基线两端,跨行沿用同一缩放比例。需要精确映射到四角时才用 `target_quad`,结合回执中的轴向形变和相邻行判断效果。只需相对移动时用 `dx/dy`,它们的单位是投影前的纸面像素。纸面上水平移动,在照片上可能同时改变 x 和 y。 From 0433c84d70a98a5de58dae6be34be613e766fdec Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Wed, 2 Dec 2026 04:30:53 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(crates/panache-mcp):=20=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E6=89=8B=E5=B7=A5=E6=A8=AA=E7=BA=BF=E7=9A=84=E5=AE=9E?= =?UTF-8?q?=E6=B5=8B=E6=8A=98=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:固定采样列会抹去列间的纸面弯曲,排版、反向取样和逐行验收会偏离手工标定。 解决手段:为新曲线保存相邻参考行的折点,沿同一投影生成和追踪墨迹,覆盖存储重放、行间插值、双向坐标和实际像素。 收益:在实测位置保留线形,同时沿用历史稿件保存的九列投影。 --- CHANGELOG.md | 2 +- .../handwriting-core/src/imaging/rulings.rs | 1 + crates/handwriting-core/src/photo.rs | 14 ++++ .../tests/generation_pipeline.rs | 1 + crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/src/paper.rs | 82 ++++++++++++++++--- .../src/review/ruled_rows/tracking.rs | 76 +++++++++++------ 7 files changed, 140 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc8d2efd..ee171828 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 未发布 -- MCP 在手工标定的横线纸上从实测线端排写正文,编号保留小缩进,字迹在下方横线上留出净空。弯曲横线可补中间测点。照片预览和整页复查可逐行核对墨迹净空、起笔和相对格高,流程图复查可查看四角的跨格位置。 +- MCP 在手工标定的横线纸上从实测线端排写正文,编号保留小缩进,字迹在下方横线上留出净空。弯曲横线可补中间测点,保存后排版和复查均沿实测折线。照片预览和整页复查可逐行核对墨迹净空、起笔和相对格高,流程图复查可查看四角的跨格位置。 - MCP 的 RSI 完整验证报告区分首次导出就与检查单匹配和后来才匹配,并显示导出文件总数和多次发布的任务数。 diff --git a/crates/handwriting-core/src/imaging/rulings.rs b/crates/handwriting-core/src/imaging/rulings.rs index 21eff7eb..b96db838 100644 --- a/crates/handwriting-core/src/imaging/rulings.rs +++ b/crates/handwriting-core/src/imaging/rulings.rs @@ -353,6 +353,7 @@ pub(super) fn flatten( .map(|i| Ruling { edges: [left_edges[i] as f32 / ratio, right_edges[i] as f32 / ratio], heights: std::array::from_fn(|j| grid.tracks[j][i] / ratio), + curve: Vec::new(), }) .collect(); left_edges.sort_unstable(); diff --git a/crates/handwriting-core/src/photo.rs b/crates/handwriting-core/src/photo.rs index 7d276620..88b3cd7c 100644 --- a/crates/handwriting-core/src/photo.rs +++ b/crates/handwriting-core/src/photo.rs @@ -23,6 +23,9 @@ pub enum PaperProjection { pub struct Ruling { pub edges: [f32; 2], pub heights: [f32; 9], + /// Exact photo-space vertices when manual guides bend between sampled columns. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub curve: Vec<[f32; 2]>, } fn lerp(a: f32, b: f32, t: f32) -> f32 { @@ -30,6 +33,15 @@ fn lerp(a: f32, b: f32, t: f32) -> f32 { } fn height(row: &Ruling, cols: &[f32; 9], x: f32) -> f32 { + if row.curve.len() >= 2 { + let i = row + .curve + .partition_point(|p| p[0] < x) + .saturating_sub(1) + .min(row.curve.len() - 2); + let ([ax, ay], [bx, by]) = (row.curve[i], row.curve[i + 1]); + return lerp(ay, by, (x - ax) / (bx - ax)); + } let i = cols .partition_point(|v| *v < x) .saturating_sub(1) @@ -405,10 +417,12 @@ mod tests { rows: vec![ Ruling { edges: [20., 44.], + curve: Vec::new(), heights: columns.map(|x| 24. - x / 8.), }, Ruling { edges: [8., 56.], + curve: Vec::new(), heights: columns.map(|x| 48. - x / 8.), }, ], diff --git a/crates/handwriting-core/tests/generation_pipeline.rs b/crates/handwriting-core/tests/generation_pipeline.rs index d2bd153f..d7847b59 100644 --- a/crates/handwriting-core/tests/generation_pipeline.rs +++ b/crates/handwriting-core/tests/generation_pipeline.rs @@ -129,6 +129,7 @@ fn guided_homework_keeps_visible_strokes_inside_the_measured_rows() { photo::Ruling { edges: [52. - r * 4., 260. + r * 5.], heights: cols.map(|x| 62. + 25. * r + 1.3 * r * r - 0.04 * x), + curve: Vec::new(), } }) .collect(), diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 24090b4a..376a39a8 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -124,7 +124,7 @@ pub struct Guide { pub left: [u32; 2], /// Right end [x,y] of the same ruling or field. On a printed line use its center, leaving ink clearance to the layout. pub right: [u32; 2], - /// Optional interior [x,y] measurements for a curved ruling, ordered left to right. Use up to seven points across the visible line; the projection samples the profile at nine evenly spaced photo columns. + /// Optional interior [x,y] measurements for a curved ruling, ordered left to right. The projection follows straight segments through these points (up to seven per guide). #[serde(default, skip_serializing_if = "Vec::is_empty")] #[schemars(length(max = 7))] pub via: Vec<[u32; 2]>, diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index c540bd9b..e057a416 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -42,6 +42,30 @@ impl Guide { let [bx, by] = self.via.get(i).copied().unwrap_or(self.right); ay as f32 + (by as f32 - ay as f32) * (x - ax as f32) / (bx - ax) as f32 } + + fn ruling(&self, next: &Guide, t: f32, columns: &[f32; 9]) -> handwriting_core::photo::Ruling { + let mix = |a: f32, b: f32| a + (b - a) * t; + let height = |x| mix(self.height_at(x), next.height_at(x)); + // Between measured rows the slope may change at a vertex of either guide. + let curve = if self.via.is_empty() && next.via.is_empty() { + Vec::new() + } else { + let mut xs: Vec<_> = self.points().chain(next.points()).map(|p| p[0]).collect(); + xs.sort_unstable(); + xs.dedup(); + xs.into_iter() + .map(|x| [x as f32, height(x as f32)]) + .collect() + }; + handwriting_core::photo::Ruling { + edges: [ + mix(self.left[0] as f32, next.left[0] as f32), + mix(self.right[0] as f32, next.right[0] as f32), + ], + heights: columns.map(height), + curve, + } + } } impl PaperLayout { @@ -108,20 +132,10 @@ impl PaperLayout { let t = f32::from(idx - a.row) / f32::from(b.row - a.row); // Equal distances on a plane divide a receding pair of edges projectively. let t = t * wa / ((1. - t) * wb + t * wa); - let point = |u: f32, v: f32| u + (v - u) * t; - rows.push(handwriting_core::photo::Ruling { - edges: [ - point(a.left[0] as f32, b.left[0] as f32), - point(a.right[0] as f32, b.right[0] as f32), - ], - heights: columns.map(|x| point(a.height_at(x), b.height_at(x))), - }); + rows.push(a.ruling(b, t, &columns)); } } - rows.push(handwriting_core::photo::Ruling { - edges: [last.left[0] as f32, last.right[0] as f32], - heights: columns.map(|x| last.height_at(x)), - }); + rows.push(last.ruling(last, 0., &columns)); Ok(Self { width, height, @@ -303,6 +317,50 @@ mod guide_tests { assert_eq!(legacy.height_at(200.), 55.); } + #[test] + fn off_grid_vertices_survive_storage_row_interpolation_and_rasterization() { + let guides = [ + guide(0, 100, vec![[150, 100], [175, 120], [200, 100]]), + guide(2, 160, vec![[205, 160], [232, 180], [245, 160]]), + ]; + let layout = PaperLayout::from_guides(401, 240, &guides).unwrap(); + let stored = serde_json::to_value(&layout).unwrap(); + let replay: PaperLayout = serde_json::from_value(stored.clone()).unwrap(); + let projection = replay.projection.unwrap(); + let mut ink = image::RgbaImage::new(401, 240); + let mark = image::Rgba([20, 30, 40, 255]); + let points = [ + (175, 100, 120), + (175, 130, 140), + (232, 130, 140), + (232, 160, 180), + ]; + for (x, paper_y, photo_y) in points { + let paper = [x as f32, paper_y as f32]; + let photo = [x as f32, photo_y as f32]; + assert_eq!(projection.photo_point(paper[0], paper[1]), photo); + assert_eq!(projection.paper_point(photo), paper); + ink[(x, paper_y)] = mark; + } + let background = image::RgbaImage::new(401, 240); + let rendered = projection + .composite(&background, &ink, &Default::default()) + .unwrap(); + for (x, _, photo_y) in points { + assert_eq!(rendered[(x, photo_y)], mark); + } + // A previously stored nine-column layout still replays its sampled profile. + let mut old = stored; + for row in old["projection"]["Rulings"]["rows"].as_array_mut().unwrap() { + row.as_object_mut().unwrap().remove("curve"); + } + let old: PaperLayout = serde_json::from_value(old).unwrap(); + assert_eq!( + old.projection.unwrap().photo_point(175., 100.), + [175., 100.] + ); + } + #[test] fn stored_manual_guides_replay_the_original_writing_area_policy() { let layout = diff --git a/crates/panache-mcp/src/review/ruled_rows/tracking.rs b/crates/panache-mcp/src/review/ruled_rows/tracking.rs index 03b87110..4d31a9fd 100644 --- a/crates/panache-mcp/src/review/ruled_rows/tracking.rs +++ b/crates/panache-mcp/src/review/ruled_rows/tracking.rs @@ -4,35 +4,44 @@ use anyhow::Result; use handwriting_core::Cancellation; use image::RgbaImage; -struct Guide { - // Sampling paper space also handles a rotated page and piecewise curved rulings. - points: [[f32; 2]; 17], +struct Guide<'a> { + layout: &'a PaperLayout, + paper_y: f32, + center: [f32; 2], + photo_width: f32, + paper_width: f32, } -impl Guide { - fn new(layout: &PaperLayout, row: i32) -> Self { +impl<'a> Guide<'a> { + fn new(layout: &'a PaperLayout, row: i32) -> Self { let left = layout.left as f32; - let width = (layout.width - layout.right) as f32 - left; - let y = layout.top as f32 + (row as f32 + 1.) * layout.line_spacing; + let paper_width = (layout.width - layout.right) as f32 - left; + let paper_y = layout.top as f32 + (row as f32 + 1.) * layout.line_spacing; + let project = |x| { + layout + .projection + .as_ref() + .map_or([x, paper_y], |p| p.photo_point(x, paper_y)) + }; Self { - points: std::array::from_fn(|i| { - let x = left + width * i as f32 / 16.; - layout - .projection - .as_ref() - .map_or([x, y], |p| p.photo_point(x, y)) - }), + layout, + paper_y, + center: project(left + paper_width / 2.), + photo_width: project(left + paper_width)[0] - project(left)[0], + paper_width, } } fn y(&self, x: f32) -> f32 { - let i = self - .points - .partition_point(|p| p[0] < x) - .saturating_sub(1) - .min(15); - let ([ax, ay], [bx, by]) = (self.points[i], self.points[i + 1]); - ay + (by - ay) * ((x - ax) / (bx - ax)) + // At a fixed paper y, photo x is affine for both rotation and ruled projections. + // Evaluate the same curve as the renderer, including off-grid measurements. + self.layout.projection.as_ref().map_or(self.paper_y, |p| { + let fraction = 0.5 + (x - self.center[0]) / self.photo_width; + p.photo_point( + self.layout.left as f32 + fraction * self.paper_width, + self.paper_y, + )[1] + }) } } @@ -102,7 +111,7 @@ pub(super) fn median_guide_offset( let mut offsets = Vec::new(); for row in rows { let guide = Guide::new(layout, row); - let [x, y] = guide.points[8]; + let [x, y] = guide.center; let spacing = Guide::new(layout, row.saturating_add(1)).y(x) - y; if !(5. ..=1024.).contains(&spacing) || !(0. ..paper.width() as f32).contains(&x) { continue; @@ -146,7 +155,7 @@ impl Track { ) -> Result> { let guide = Guide::new(layout, row); let neighbor = Guide::new(layout, row.saturating_add(1)); - let [cx, cy] = guide.points[8]; + let [cx, cy] = guide.center; let width = paper.width() as i32; let mid = cx.round() as i32; if !(0..width).contains(&mid) { @@ -190,7 +199,7 @@ impl Track { x += direction * stride; } } - let guide_width = guide.points[16][0] - guide.points[0][0]; + let guide_width = guide.photo_width; if bands.len() < 5 || ((bands.len() * stride as usize) as f32) < guide_width * 0.40 { return Ok(None); } @@ -219,3 +228,22 @@ impl Track { )) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::Guide as PaperGuide; + + #[test] + fn tracker_uses_the_measured_bend_between_sampling_columns() { + let guides = [100, 160].map(|y| PaperGuide { + row: u16::from(y != 100), + left: [0, y], + right: [400, y], + via: vec![[155, y], [163, y + 20], [170, y]], + }); + let layout = PaperLayout::from_guides(401, 240, &guides).unwrap(); + let guide = Guide::new(&layout, 0); + assert!((guide.y(163.) - 120.).abs() < 1e-4); + } +}