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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## 未发布

- MCP 在手工标定的横线纸上从实测线端排写正文,编号保留小缩进,字迹在下方横线上留出净空。弯曲横线可补中间测点,保存后排版和复查均沿实测折线。照片预览和整页复查可逐行核对墨迹净空、起笔和相对格高,流程图复查可查看四角的跨格位置。

- MCP 的 RSI 完整验证报告区分首次导出就与检查单匹配和后来才匹配,并显示导出文件总数和多次发布的任务数。

- MCP 的 TeX 包目录可按中英文学科词(可多个词)、ID 或命令搜索用途和写法,AI 客户端可在建稿前查看默认包和用户选用的自定义命令。
Expand Down
1 change: 1 addition & 0 deletions crates/handwriting-core/src/imaging/rulings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 4 additions & 0 deletions crates/handwriting-core/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>,
Expand Down Expand Up @@ -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),
Expand Down
14 changes: 14 additions & 0 deletions crates/handwriting-core/src/photo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,25 @@ 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 {
a + (b - a) * t
}

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)
Expand Down Expand Up @@ -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.),
},
],
Expand Down
2 changes: 2 additions & 0 deletions crates/handwriting-core/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ impl<F: FnMut(usize, RgbaImage, Option<PageInk>) -> 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,
Expand Down Expand Up @@ -248,6 +249,7 @@ impl<F: FnMut(usize, RgbaImage, Option<PageInk>) -> 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;
Expand Down
4 changes: 4 additions & 0 deletions crates/handwriting-core/src/render/homework.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
45 changes: 43 additions & 2 deletions crates/handwriting-core/src/render/line.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -11,6 +11,7 @@ pub(super) struct LineLayout {
legacy: bool,
min_y: i32,
max_y: i32,
aligned_ink: bool,
}

impl LineLayout {
Expand All @@ -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;
Expand All @@ -49,6 +66,7 @@ impl LineLayout {
legacy,
min_y,
max_y,
aligned_ink,
}
}

Expand All @@ -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
}
Expand Down
24 changes: 14 additions & 10 deletions crates/handwriting-core/src/render/paragraph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
145 changes: 145 additions & 0 deletions crates/handwriting-core/tests/generation_pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,151 @@ 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),
curve: Vec::new(),
}
})
.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<String> {
Expand Down
4 changes: 3 additions & 1 deletion crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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。节点文字继承稿件的字体,图框和箭头按其笔画绘制。先给分支条件、箭头和节点留够空间,再移动整图。把图缩进小格会连同标签字号一起改变。已有位图的标签保存在像素中,需要改字形时可从已知题意重建节点和连线。
Expand Down
Loading
Loading