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 crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ cargo build --locked --release -p panache-mcp

遇到手摆保护时,先告诉用户文字尚未修改、位置仍在原版。整节保存会重新排版,新版不会自动继承手摆。让用户选择保留现版,或允许重新排版后看预览。用户要求保持原位时,不能仅凭旧字形编号或相同的移动距离就声称位置已经恢复。明确同意重新排版后,可以按同一版本读全原文、保留其余内容,用相同版本号调用 `save_section` 并预览新版。若无法确保图片等内容能完整重存,应先告诉用户并保留原稿。

写作业时,客户端可直接传 `{"markdown":"第一题","style":{"homework":true}}`。纯文字、预设纸和照片底纸共用作业默认值:优先使用随包的李国夫手写体,字的大小和倾斜有轻微变化。指定字体会优先使用;想让字更整齐可加 `"relaxed_handwriting":false`。同一稿件的随机种子随稿保存。

使用自己的纸张时,在第一次调用 `save_section` 时传入 `paper_path`,例如 `{"markdown":"第一题","paper_path":"C:/作业/南昌大学横线纸.jpg"}`。路径指向运行 MCP 的电脑上的图片。默认保留原照片,按识别到的横线投影字迹和插图。`paper` 返回排版尺寸、边距、行距、识线结果,投影时另有原照尺寸。可用 `preview_handwriting(view="paper")` 单独看底纸,或在导入时通过 `paper_guides` 指定参考线。需要校平底纸时传 `paper_mode="flatten"`。无可靠横线时保留底图,使用普通行距。纸张随稿件保存一次,后续追加、回查、预览和导出可在原图移动后继续使用。

如果照片是聊天附件,先用客户端支持的文件传送功能,把照片交给 Panache。云端没有这项功能时,可在照片所在电脑连接桌面版再使用。复制手机或另一台电脑上的路径不能传照片。带视觉能力的模型可以查看客户端转交的预览图。客户端或模型只能处理文字时,可读取版面和像素测量,并请用户打开导出文件确认外观,再按反馈修改。
Expand Down
4 changes: 4 additions & 0 deletions crates/panache-mcp/src/controls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,10 @@ pub fn parameters(draft: &Snapshot<'_>, section: u32, changes: &Changes) -> Resu
full_preview: false,
..Default::default()
};
if style.relaxed_handwriting == Some(true) {
params.font_size_sigma = 1.5;
params.perturb_theta_sigma = 0.07;
}
if let Some(layout) = &draft.paper {
layout.apply(&mut params);
}
Expand Down
21 changes: 14 additions & 7 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,11 @@ pub struct Style {
pub ink: String,
/// Pixels at the paper's native resolution (794 × 1123 for presets). Accepted range 16–72.
pub font_size: u8,
/// Homework paragraph layout. On a new photo sheet this also selects a handwriting font when font is omitted.
/// Use for a school assignment, with or without a paper photo. Selects homework layout and its handwriting defaults.
pub homework: bool,
/// Slightly vary letter size and tilt. Defaults on for new homework. Use false for the usual, steadier variation.
#[serde(skip_serializing_if = "Option::is_none")]
pub relaxed_handwriting: Option<bool>,
/// Keep this value to reproduce handwriting variations.
#[schemars(transform = remove_schema_default)]
pub seed: u32,
Expand All @@ -66,6 +69,7 @@ impl Default for Style {
ink: "#302c30".into(),
font_size: 34,
homework: false,
relaxed_handwriting: None,
seed: u32::from_le_bytes(Uuid::new_v4().as_bytes()[..4].try_into().unwrap()),
}
}
Expand Down Expand Up @@ -113,14 +117,17 @@ fn explicit_font<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String
}

impl CreationStyle {
pub fn resolve(&self, photo: bool, bundled: &[String]) -> Style {
pub fn resolve(&self, bundled: &[String]) -> Style {
let mut style = self.settings.clone();
if let Some(font) = &self.font {
style.font.clone_from(font);
} else if photo && style.homework && bundled.iter().any(|id| id == "李国夫手写体.ttf")
{
} else if style.homework && bundled.iter().any(|id| id == "李国夫手写体.ttf") {
style.font = "李国夫手写体.ttf".into();
}
if style.homework {
// Resolve only on creation: older saved styles keep their original rendering.
style.relaxed_handwriting.get_or_insert(true);
}
style
}
}
Expand All @@ -146,9 +153,9 @@ pub struct Save {
pub section: Option<u32>,
/// Set only on creation.
pub title: Option<String>,
/// For a handwritten assignment on a photo sheet, homework=true uses homework layout and, when bundled,
/// 李国夫手写体.ttf for an omitted font. Honor an explicitly requested font or formal style.
/// Preview a sample with letters and digits on the actual sheet. Set only on creation.
/// For homework, including text alone, set homework=true. Omit font to use the bundled 李国夫手写体.ttf
/// when available. Honor a named font, and use relaxed_handwriting=false for steadier letters if requested.
/// Set only on creation.
#[schemars(with = "Option<Style>")]
pub style: Option<CreationStyle>,
}
Expand Down
9 changes: 6 additions & 3 deletions crates/panache-mcp/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,9 +276,9 @@ impl ServerHandler for Panache {
let instructions = concat!(
"If a required area of a photo is outside the frame, or blur, occlusion or perspective prevents locating it, identify that area before drafting. ",
"Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ",
"For looser, less uniform homework or lab handwriting (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ",
"For a school assignment, even text alone, set style.homework=true on creation; omit font unless the user specifies one. For further variation (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ",
"Use save_section(markdown), then its draft_id and revision for preview_handwriting or export_handwriting. ",
"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 an undecided homework or lab-report style, see list_fonts for sample guidance. Use list_drafts to resume. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ",
"English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. When the user wants to compare fonts, see list_fonts for sample guidance. Use list_drafts to resume. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ",
"For print-and-report, export once and report review.unreviewed_pages. Look up existing receipts with read_section(view=review); full-page preview_handwriting(view=review) files a check. Last-page lookups use current pagination and cannot confirm the historical last page. Follow photo_appearance.preview_arguments for a native detail crop. ",
"If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ",
"Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ",
Expand Down Expand Up @@ -428,7 +428,7 @@ impl Panache {
}

#[tool(
description = "Save Markdown without rendering. For a local text change try replace_section_text first to check saved placements. For pen-matched flowcharts, use a circuitikz environment with \\draw[->] paths and node labels. On creation, optionally import a local stationery image with paper_path. Append or revise a section with expected_revision. Each section starts a new page. Keep the returned draft_id and revision. Returns detected paper.alignment."
description = "Save Markdown without rendering. For schoolwork with or without a photo, set style.homework=true. For a local text change try replace_section_text first to check saved placements. For pen-matched flowcharts, use a circuitikz environment with \\draw[->] paths and node labels. On creation, optionally import a local stationery image with paper_path. Append or revise a section with expected_revision. Each section starts a new page. Keep the returned draft_id and revision. Returns detected paper.alignment."
)]
async fn save_section(&self, Parameters(input): Parameters<Save>) -> CallToolResult {
tool_result(save::run(self, input).await)
Expand Down Expand Up @@ -460,6 +460,9 @@ impl Panache {
row["sections"]
));
}
if input.offset.unwrap_or(0) == 0 && input.before_draft_id.is_none() && result["drafts"].as_array().is_some_and(Vec::is_empty) {
lines.push("尚无已存稿件。用户已提供新作业正文时,直接用 save_section(markdown, style.homework=true) 建稿,再用返回的编号预览第一页;只在用户要求写在特定底纸上时才需要那张纸。".to_owned());
}
if let Some(id) = result["next_before_draft_id"].as_str() {
lines.push(format!("下一页:`before_draft_id=\"{id}\"`"));
}
Expand Down
56 changes: 50 additions & 6 deletions crates/panache-mcp/src/save.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,10 @@ fn validate(input: &Save, bundled: &[String]) -> Result<Option<Style>> {
.is_none_or(|v| v.chars().count() <= 150),
"Title too long"
);
let photo = input.paper_path.is_some()
&& input.paper_mode.unwrap_or_default() == crate::PaperMode::Photo;
let style = input
.style
.as_ref()
.map(|s| s.resolve(photo, bundled))
.map(|s| s.resolve(bundled))
.unwrap_or_default();
style.ink_rgba()?;
ensure!(
Expand Down Expand Up @@ -134,7 +132,47 @@ mod tests {
use serde_json::json;

#[test]
fn photo_homework_font_is_a_creation_default() {
fn homework_variation_is_saved_on_creation_and_respects_overrides() -> Result<()> {
use crate::{controls, drafts::Drafts};
let root = tempfile::tempdir()?;
let drafts = Drafts::open(root.path())?;
for (args, legacy, size, angle) in [
(json!({"homework":true}), false, 1.5, 0.07),
(
json!({"homework":true,"relaxed_handwriting":false}),
false,
1.,
0.05,
),
(json!({"homework":true}), true, 1., 0.05),
(json!({}), false, 1., 0.05),
] {
let input: Save = serde_json::from_value(json!({"markdown":"作业","style":args}))?;
let style = if legacy {
// Archived styles predate the creation-time variation choice.
serde_json::from_value(args)?
} else {
validate(&input, &[])?.unwrap()
};
let saved = drafts.save(&input, "作业", Some(&style), None, None)?;
let draft = drafts.snapshot(saved["draft_id"].as_str().unwrap(), Some(1))?;
let params = controls::parameters(&draft, 1, &draft.controls)?;
assert_eq!(
(params.font_size_sigma, params.perturb_theta_sigma),
(size, angle)
);
let patch = serde_json::from_value(json!({"perturb_theta_sigma":0.0}))?;
let tuned = controls::parameters(&draft, 1, &patch)?;
assert_eq!(
(tuned.font_size_sigma, tuned.perturb_theta_sigma),
(size, 0.)
);
}
Ok(())
}

#[test]
fn homework_font_is_a_creation_default_on_any_paper() {
let bundled = vec!["李国夫手写体.ttf".to_owned(), "霞鹜文楷.ttf".to_owned()];
let font = |args: Value, fonts: &[String]| {
let mut args = args;
Expand All @@ -147,10 +185,16 @@ mod tests {
let homework = json!({"paper_path":"example.png","style":{"homework":true}});
assert_eq!(font(homework.clone(), &bundled), bundled[0]);
assert_eq!(font(homework.clone(), &bundled[1..]), bundled[1]);
for plain in [
for assignment in [
json!({"style":{"homework":true}}),
json!({"paper_path":"example.png"}),
json!({"style":{"homework":true,"paper":"ruled"}}),
json!({"paper_path":"example.png","paper_mode":"flatten","style":{"homework":true}}),
] {
assert_eq!(font(assignment, &bundled), bundled[0]);
}
for plain in [
json!({}),
json!({"paper_path":"example.png"}),
json!({"paper_path":"example.png","style":{"homework":false}}),
] {
assert_eq!(font(plain, &bundled), bundled[1]);
Expand Down
2 changes: 2 additions & 0 deletions crates/panache-mcp/tests/list_drafts.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ async def page(expected, **arguments):
next_id = expected[19]["draft_id"] if more else None
assert data == ({**legacy, "next_before_draft_id": next_id} if more else legacy)
lines = result.content[0].text.splitlines()
if not expected and offset == 0 and "before_draft_id" not in arguments:
assert "style.homework=true" in lines.pop()
if more:
assert lines[-1] == f'下一页:`before_draft_id="{next_id}"`'
else:
Expand Down