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 @@ -134,6 +134,8 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/

作业表可用正文横线设置参考线,将同一页的课程、姓名等字块分别定位。若侧栏印字自下往上读,将原字块的左上、右上、右下、左下四角依次投到侧栏的左下、左上、右上、右下。复查时按栏核对读向、印字和留给老师的评分区。`changed_pixels_outside_reference` 也会计入正文参考区外有意填写的表头和侧栏,应结合这些栏位解读。

客户端已知目标值时,可在 `tune_handwriting` 中同时传 `changes={"perturb_theta_sigma":0.07}` 和 `readback_variation=["perturb_theta_sigma"]`。成功回执的 `effective_changes` 给出写入前后的有效值,用于直接核对本次写入,省去事后再读一次。最多点名本次提交的两个 `variation` 控件。提交 `null` 时读回继承值,有效值相同的键会省略。若要根据旧值决定改多少,仍应先用 `describe_controls` 读取该稿当前版本的值。

如果字像贴在照片上,先分清是墨迹边缘过锐,还是纸面光照、阴影或墨色对比造成的观感。例如,纸面右侧有阴影,但用户认为笔画已经合适,就保留原样。如果用户明确指出笔画边缘过锐,或原尺寸成品裁图中的笔画边缘确实比附近可比的实拍印字或横线更锐,可以小幅柔化试一版。比如用户说“只改第一行,第二行保留”,用 `preview_handwriting(view=layout)` 找到第一行对应的字,再用 `adjust_glyphs` 的 `softness` 只调这些字。只有用户要调整整份稿子时,才用 `tune_handwriting` 的 `ink_softness`。用户要求保留墨迹时,直接沿用原版。

需要核对时,照片整页复盘的 `photo_appearance.preview_arguments` 可直接交给 `preview_handwriting`。有页内文字基线样本时,会返回字迹附近的原尺寸底纸和成品裁图,也可以自己圈选。试调后在新版本沿用原选区,用 `compare_revision` 指向旧版本,对照底纸、改前和改后三张实际裁图:底纸用来看原有阴影和印记,两张成品用来看细笔是否糊掉、对比度是否下降。如果用户点名第二行要保留,也对照第二行的改前和改后。效果变差或拿不准就保留原版。只有文字回执时,把用户观察到的情况说清楚,例如“你觉得边缘已经合适”;还需要目视判断时,请用户看裁图。字号与可写空间是否相称可另查 `layout` 或 `typography` 组。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比;只改墨迹组参数会保留已有的单字移位和透视调整。更换字体、字号或参考线后,应在新版本重新检查选区。
Expand Down
4 changes: 4 additions & 0 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ pub struct Describe {
#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Tune {
/// Request before/after values for up to two variation keys in changes. effective_changes omits keys whose effective value stayed the same.
#[serde(default)]
#[schemars(length(max = 2))]
pub readback_variation: Vec<String>,
/// 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,
Expand Down
44 changes: 37 additions & 7 deletions crates/panache-mcp/src/tuning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ pub fn apply(state: &State, mut input: Tune) -> Result<CallToolResult> {
} else {
controls::merge(&draft.controls, &patch, &fonts)?
};
let keys = &input.readback_variation;
let before = if keys.is_empty() {
None
} else {
ensure!(
keys.len() <= 2
&& keys.iter().all(|k| input.changes.contains_key(k)
&& controls::catalog()["variation"].get(k).is_some()),
"readback_variation must name up to two variation controls in changes"
);
Some(serde_json::to_value(controls::parameters(
&draft,
1,
&draft.controls,
)?)?)
};
if let Some(guides) = &input.paper_guides {
let paper = draft
.paper
Expand Down Expand Up @@ -101,13 +117,26 @@ pub fn apply(state: &State, mut input: Tune) -> Result<CallToolResult> {
"Supply controls, font_path or paper_guides"
);
draft.require_current_revision()?;
let mut receipt = json!({"draft_id":draft.id,"revision":draft.revision,"changed":false,"paper":null,
"controls":changes,"fine_layout":"preserved"});
if !keys.is_empty() {
receipt["effective_changes"] = json!({});
}
return Ok(reply(
format!("Controls already match revision {}.", draft.revision),
json!({"draft_id":draft.id,"revision":draft.revision,"changed":false,"paper":null,
"controls":changes,"fine_layout":"preserved"}),
receipt,
));
}
controls::parameters(&draft, 1, &changes)?;
let params = controls::parameters(&draft, 1, &changes)?;
let mut delta = controls::Changes::new();
if let Some(before) = before {
let after = serde_json::to_value(&params)?;
for k in keys {
if before[k] != after[k] {
delta.insert(k.clone(), json!({"before":before[k],"after":after[k]}));
}
}
}
let preserve_layout = changes.keys().chain(draft.controls.keys()).all(|key| {
controls::catalog()["ink"].get(key).is_some()
|| controls::catalog()["camera"].get(key).is_some()
Expand All @@ -131,8 +160,9 @@ pub fn apply(state: &State, mut input: Tune) -> Result<CallToolResult> {
font.as_ref().map(|(k, v)| (k.as_str(), v.as_slice())),
&details,
)?;
Ok(reply(
format!("Saved revision {next}."),
json!({"draft_id":draft.id,"revision":next,"changed":true,"paper":paper.map(|p|p.summary()),"controls":changes,"fine_layout":if preserve_layout { "preserved" } else { "inspect_again" }}),
))
let mut receipt = json!({"draft_id":draft.id,"revision":next,"changed":true,"paper":paper.map(|p|p.summary()),"controls":changes,"fine_layout":if preserve_layout { "preserved" } else { "inspect_again" }});
if !keys.is_empty() {
receipt["effective_changes"] = json!(delta);
}
Ok(reply(format!("Saved revision {next}."), receipt))
}
117 changes: 117 additions & 0 deletions crates/panache-mcp/tests/variation_readback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# /// script
# dependencies = ["mcp>=1.12,<2"]
# ///
"""Compare optional variation receipts with independent reads at the saved revisions."""

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

from mcp_client import call, isolated_session, open_db


async def run(binary, home):
async with isolated_session(binary, home) as (client, _):
saved = await call(client, "save_section", markdown="观察记录", style={"seed": 31})
key = {"draft_id": saved.structuredContent["draft_id"]}

async def values(revision):
response = await call(
client, "describe_controls", **key, revision=revision, group="variation"
)
return response.structuredContent["values"]

tilt, shift = "perturb_theta_sigma", "perturb_x_sigma"
before = await values(1)
one = await call(
client,
"tune_handwriting",
**key,
expected_revision=1,
changes={tilt: 0.09},
readback_variation=[tilt],
)
after = await values(2)
assert after[tilt] > before[tilt]
assert one.structuredContent["effective_changes"] == {
tilt: {"before": before[tilt], "after": after[tilt]}
}

two = await call(
client,
"tune_handwriting",
**key,
expected_revision=2,
changes={tilt: None, shift: 1.5},
readback_variation=[tilt, shift],
)
reset = await values(3)
assert reset[tilt] == (await values(1))[tilt] and reset[shift] == 1.5
assert two.structuredContent["effective_changes"] == {
k: {"before": after[k], "after": reset[k]} for k in (tilt, shift)
}

proposed = {tilt: 0.11, shift: 2, "ink_depth_sigma": 9}
with open_db(home) as db:
unchanged = list(db.iterdump())
for revision, keys, changes, error in (
(2, [tilt], proposed, "Revision conflict"),
(3, [shift], {tilt: 0.11}, "readback_variation"),
(3, ["font_size"], {"font_size": 36}, "readback_variation"),
(3, list(proposed), proposed, "readback_variation"),
):
rejected = await client.call_tool(
"tune_handwriting",
{
**key,
"expected_revision": revision,
"changes": changes,
"readback_variation": keys,
},
)
assert rejected.isError and error in rejected.content[0].text
with open_db(home) as db:
assert list(db.iterdump()) == unchanged

noop = await call(
client,
"tune_handwriting",
**key,
expected_revision=3,
changes={"variation": {shift: 1.5}},
readback_variation=[shift],
)
assert (
noop.structuredContent["changed"] is False and noop.structuredContent["revision"] == 3
)
assert noop.structuredContent["effective_changes"] == {}
# Saving an explicit override at the inherited value does not change the effective value.
equal = await call(
client,
"tune_handwriting",
**key,
expected_revision=3,
changes={tilt: reset[tilt]},
readback_variation=[tilt],
)
assert equal.structuredContent["effective_changes"] == {}
default = await call(
client,
"tune_handwriting",
**key,
expected_revision=equal.structuredContent["revision"],
changes={tilt: 0.12},
)
assert "effective_changes" not in default.structuredContent
print(
"Checked effective values, reset, grouped no-op, four rejections and default receipt."
)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("binary", type=Path)
args = parser.parse_args()
with TemporaryDirectory() as temp:
asyncio.run(run(args.binary.resolve(), Path(temp)))