⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
inko-handwriting
>-
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
Inko 手写 Skill
简体中文 | English
1.6.0(2026-10-08):Lyric 1 / Logic 1 手写推理免费开放。 网页、API 和 Skill 都不按字收费,没有最低消费,余额为 0 也可生成。 网站内 DeepSeek 助手仅按实际 API 用量计费;本 Skill 的手写接口不调用 DeepSeek,接入 AI 自身的模型费用由其服务商收取。 每个用户另有 1 个免费专属字迹席位。旧版请重新安装,避免 AI 沿用旧收费规则。
1.5.0(2026-10-06):skill 不再抄写「模型能写什么」。 正文里各模型能写哪些不常见的字(希腊字母、拼音声调、上下标、½、罗马数字、⑪、「」、° …)
和 Logic 公式能用哪些 LaTeX 命令,改为从服务器实时读取——新命令 inko.py charset 和 inko.py models --symbols——模型学会新字,skill 不用更新也是对的;
网站上的排版助手从同一处取。doctor、models、charset 发现有更新版 skill 时会提示。同一天模型学会了 33 个希腊字母、拼音声调、上下标、½、罗马数字、⑪–⑳ 等。
1.4.0(2026-10-05):跟进网站上的排版助手。 英文手写重新训练过;长公式在等号 / 加减号处折行,不再整条缩小,生成的公式
和文字一样大;Logic 可以单独设常用字迹(default-style 编号 --model logic-1);补上「哪些字写不了、怎么问用户」的说明;
数学题不再为模型 / 字迹是否兼容停下来问;新增 inko.py delivered(API 的交付确认);去掉显式标识只需签署协议。
1.3.0:只产出标准二维平面图片与 PDF。 已移除拍照拟真、桌面场景、透视、纸张卷曲、扫描/复印效果和照片贴字功能。
用 Inko 将笔记、书信、作文、数学解答写成自然笔迹的平面页面:
- 标准 PNG 图片与 PDF,白纸、米黄纸、方格纸、横线纸、作文纸、田字格
- 自定义排版、标题、文本框与行距
- 修改墨色、笔型、粗细和字间距,保留可编辑笔迹包
- 可以读取题目照片作为输入,但结果只交付独立的平面答题页
「把这三道数学题写成横线纸上的手写解答,给我 PNG 和 PDF」 「把 notes.md 写成方格纸笔记,用蓝色圆珠笔」 「把这封信写在米黄色纸上,输出标准图片」
Logic 仍沿用 1.2.1 的最新符号规则:\eta 写成 n,\wedge / \vee 支持;详见数学说明。
怎么用(给用户)
- 在 https://inkotype.com → 账户 → API key 创建一个 key。建议给 AI 单独建一个,并设置每日花费上限。
- 把这个仓库链接和 key 发给你的 AI 助手,比如: 「帮我安装这个手写 skill:https://github.com/pretend1111/inko-skill ,我的 Inko API key 是 ink_live_…」
- 直接提要求。Lyric / Logic 手写推理免费,无需充值。AI 会先校验字符与排版,报价为 0 后按你的要求生成,不再反复询问付费确认。 新注册用户一次性赠送 ¥0.10 的 DeepSeek 体验额度,与免费手写推理分开;实际余额以账户接口为准。
- 可选:在网站的字迹库里设一款常用字迹、收藏几款喜欢的。之后 AI 默认用你的常用字迹写,除非你另外指定;需要它来挑时,先从你的收藏里挑。跟它说「以后都用这个字迹」,它会帮你把常用字迹改过去。
- 可选:用你自己的字(专属字迹)。每个用户有且仅有 1 个免费席位,包含 2 次训练。在网站上录入字样后,AI 就能用它来写(Lyric 1)。
给 AI 助手:安装步骤
在用户的项目目录里执行。不要把 API key 回显给用户,也不要把它写进项目文件或提交记录。
- 下载(放在临时目录即可):
没有 git:下载并解压git clone --depth 1 https://github.com/pretend1111/inko-skill.git inko-skill-srchttps://github.com/pretend1111/inko-skill/archive/refs/heads/main.zip。 - 安装(需要 Python 3.9+;缺 Pillow / numpy 时会自动 pip 安装):
它会识别你是哪种 AI 助手,把python inko-skill-src/install.py # 装到当前项目 python inko-skill-src/install.py --scope user # 或者:装给用户的所有项目inko-handwriting/复制到.claude/skills/(Claude Code)或.agents/skills/(Codex、Cursor、GitHub Copilot、Gemini CLI、OpenCode、goose、Amp);可用--agent claude|agents|both指定。 输出 JSON,含installed_to和下一步。之后可以删掉inko-skill-src。 - 保存 key(从标准输入传入,不出现在命令参数里):
PowerShell:printf '%s' 'ink_live_…' | python <installed_to>/scripts/inko.py auth'ink_live_…' | python <installed_to>\scripts\inko.py auth。key 会先经 API 验证,再存到用户配置目录 (~/.config/inko/key,Windows 为%APPDATA%\inko\key);加--project则存到./.inko/key(已自动 git 忽略)。 用户也可以自己设置环境变量INKO_API_KEY。 - 自检:
python <installed_to>/scripts/inko.py doctor,看到"ok": true、key 有效、余额。 - 开始:现在就读
<installed_to>/SKILL.md并照做——有的助手要重开会话才会列出新 Skill,但你不必等。 告诉用户已装好、key 存在哪里,并建议在网站上给这个 key 设每日花费上限。
以后更新:重复第 1–2 步即可(覆盖安装的副本,不动 key)。
里面有什么
| 文件 | 作用 |
|---|---|
SKILL.md、references/ | 标准平面输出流程、数学符号、排版、字迹、API 与排错 |
scripts/inko.py | 自检、字迹、报价、排版预览、生成与下载 |
scripts/scene.py | 可编辑笔迹包:移动、间距、笔型、浏览器编辑器、平面导出 |
scripts/ink.py | 修改墨色、粗细、深浅,提取透明手写层 |
scripts/paper.py make | 绘制标准二维纸张背景,不识别或处理照片 |
scripts/compose.py drift | 可选的二维行位置微调,不改变纸张几何 |
scripts/pdf.py | 平面图片合成 PDF |
图像脚本使用 Pillow 和 numpy,本地处理,不上传图片。更新安装会替换旧 Skill 目录,移除旧版脚本,不动 API key。
费用、key 与标识
- 手写推理免费:
inko.py generate不加--yes只预检;加--yes才提交生成。默认--max-cents 0,异常非零报价会被拦截。 重写和重新生成同样免费;重写接口仍限制每个成功原任务一次。DeepSeek 用量和外部 AI 模型费用不属于手写推理费。 - key 只存在你的电脑上(用户配置目录或
./.inko/key),随时可以在网站上吊销。 - AI 标识:按照 GB 45438-2025,Inko 每页都带显式标识「AI生成 · Inko」和隐式元数据。这些脚本在所有衍生图片和 PDF 上都保留隐式标识,并按规定大小重新加上显式标识;请不要去除。不带显式标识的页面只对在网站上 签了《AI 生成内容标识协议》的账户开放(隐式标识仍然保留)。
- 借条、收据、合同、证明、请假条、签名等文书会被拒绝(不扣费)。
开发
python tests/run_tests.py # 离线:平面页面、墨色、排版、PDF、标识与功能边界
python tests/test_logic_symbols.py # Logic 符号契约
evals/ 包含数学题输入与笔记转标准平面图片/PDF 的任务和评分脚本。
MIT 许可。Inko API 需要账户并遵守服务条款。
// HOW IT'S BUILT
// FILES
27 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
inko-handwriting/SKILL.md20 KBbb3fbf6e0f32upstream ↗
--- name: inko-handwriting description: >- Generate standard flat handwritten PNG pages and PDFs from text, notes, letters, essays and math solutions via Inko (inkotype.com), with free Lyric / Logic handwriting inference. Choose paper, handwriting and pen; edit layout and ink locally. Use for 手写、手写作业、 手写笔记、手写信、二维手写图片、handwritten pages or handwritten PDF. Input images may be read for their content; output is always a flat page, without camera effects or compositing into real-world scenes. --- # Inko handwriting Inko writes text the way a person does — real pen strokes, not a font — and returns A4 pages (PNG + PDF, 300 dpi). This skill makes you the expert operator: you prepare the content, pick paper / size / handwriting / pen with the user, generate for their request for free, and deliver standard flat page images or PDFs. Preserve the natural handwriting, not a simulated camera: no perspective, desk scenes, shadows, page curl, scanner effects or photo compositing. ## Current pricing — skill 1.6.0 (2026-10-08) **Lyric 1 and Logic 1 handwriting inference is free on both the website and this API / Skill.** No per-character fee, minimum charge, membership or recharge is required; an authenticated account with zero balance can generate. The website's DeepSeek assistant is billed separately for actual API token usage. This handwriting CLI does not call DeepSeek; the external AI agent's own model fees belong to its provider, not Inko handwriting inference. Each user also gets one free custom-handwriting seat; never suggest purchasing an extra seat. All scripts are in `scripts/` next to this file (call them with the path you installed to, e.g. `python .claude/skills/inko-handwriting/scripts/inko.py …`). They print JSON on stdout — read it, don't guess. What the models can write changes as they learn: this skill never lists it. Get it live — `inko.py charset` (plain text: Greek, pinyin tones, superscripts, `½`, `⑪`, `「」` … per model, and what custom handwritings can't write) and `inko.py models --symbols` (LaTeX commands inside `$…$`) — and let the free quote have the last word. For Logic math, read `references/writing-math.md` §5 before preparing formulas. When either command reports `skill_update`, tell the user once that a newer version of this skill is available (`git pull` the inko-skill clone, then `python install.py`). What changed in skill 1.5.0 (2026-10-06): the lists of writable characters and LaTeX commands moved out of these files into the live `inko.py charset` / `models --symbols`, so the skill stays right as the models learn (Greek letters, pinyin tones, superscripts, `½`, `⑪`, `「」` … were added on 2026-10-06). What changed on 2026-10-04 (skill 1.4.0): both models were retrained on English handwriting (word spacing, capitals, baseline); the layout engine breaks a formula wider than a whole line at `=`, `≤`, `+` … instead of shrinking it; generated formulas keep the same size as the text around them; Logic can have its own 常用字迹; removing the visible label needs only the signed agreement (no seat). ## First time in a session ```bash python scripts/inko.py doctor # Python deps, API reachable, key valid, balance, the user's 常用字迹 / favourites ``` - No key: ask the user to create one at https://inkotype.com (账户 → API key), ideally a separate key for you with a daily spending limit. Save it with `python scripts/inko.py auth` (reads the key from stdin; `--project` stores it in `./.inko/key` instead of the user config dir). Never repeat the key back, never write it into project files or commits. - Missing Pillow/numpy: `python -m pip install -r scripts/requirements.txt`. - `inko.py` keeps a small git-ignored `./.inko/` folder in the working directory: `jobs.jsonl` (job log), `plans/` (what each job was made from), optionally `key`. Results go to `./inko-output/<time>-<id>/`. You may keep the user's other choices in `./.inko/prefs.json` yourself (write it with your file tool, e.g. `{"pen": "gel|blue", "paper": "ruled8"}`): read it at the start of later sessions and reuse them — no script reads it for you. Their preferred handwriting lives on their Inko account instead (常用字迹, below), so every agent and the website share it. ## Rules that matter (and why) 1. **Free inference: validate first, then generate for the user's request.** `inko.py generate` without `--yes` only checks the content and settings. Quotes remain useful for character support, page count, fit and handwriting; the price should be 0. Once the user has requested generation and essential settings are resolved, run with `--yes` without asking for payment confirmation or a top-up. `--max-cents` defaults to 0: an unexpected positive quote is blocked, not silently hidden. Check the API base / service pricing and report the discrepancy instead of assuming inference is paid. Free does not mean unlimited: respect authentication, rate limits and queue capacity. 2. **Keep the AI labels.** Every page carries a visible label 「AI生成 · Inko」 and hidden AIGC metadata, required by Chinese law (GB 45438-2025) and Inko's terms. Never crop, cover, blur, recolour or paint over the label, never strip metadata, never re-save through tools that drop it. The scripts here re-apply the label (≥ 5 % of the shortest side, readable contrast) and copy the metadata on every output — use them rather than ad-hoc image code. If the user asks to remove the label, explain it's a legal requirement. Only accounts whose owner signed the AI-labelling agreement (《AI 生成内容标识协议》) on the website can request label-free pages themselves (`--label none`, see `account.can_remove_label`; anyone else gets 403 `label_required`; no seat or purchase is involved), and they still have to disclose AI generation when sharing. Don't bring up label removal unless the user asks. 3. **No forgeries.** Inko refuses IOUs, receipts, contracts, certificates, leave notes, signatures and similar documents (`content_blocked`, not charged). Don't try to work around it (splitting text, renaming things, compositing a signature). Don't imitate a specific real person's handwriting without their consent. 4. **Look before you hand over.** Open the PNG / final image yourself (you can view images; zoom into a few lines) and check it: all text present, nothing overlapping, no odd wide gaps (around formulas especially), writing sitting on the ruled lines (not crossing them), left edges not ruler-straight (drifted — see post-processing), label intact, and the usual weak spots — punctuation right after a formula, digits in dates, units. Layout / spacing / pen problems are fixed locally from `scene.zip` without regenerating (post-processing); only wrong characters need a rewrite. `inko.py rewrite JOB --yes` re-writes the **whole** job once for free with a new seed: other characters change too, so compare both versions and keep the better one; a rewrite can't be rewritten. If a character that matters is still wrong after that, rephrase the text around it (a digit in a heading → Chinese numeral, drop a comma right after a formula) and generate again — still free, but at most once or twice rather than retrying endlessly; otherwise deliver the best version and say which character is off. `inko.pdf` is made of the same pages as the PNGs — check the PNGs, and copy the PDF to a meaningful name when delivering. 5. **Content quality is your job.** Inko writes exactly what you give it. Typos, a wrong answer or a clumsy line break will be faithfully hand-written — proofread the text first. 6. **Do what was asked, exactly.** "Copy this" means every character, line break, capital and punctuation mark kept — no summarising, tidying or "fixing" the source. "Only the final answers" means only the results: no question text, no working, no checks, no 解 / 答 prefixes. A complete document is delivered as one document that may run over several pages, never shortened or split into repeated copies. If a question is unreadable or a condition is missing, ask — don't guess an answer. ## Workflow 1. **Understand the goal**: what content, for what (homework to hand in, notes, a letter, a mock-up…), on what paper, and the final form (flat PNG pages, PDF, or both). Images supplied as questions are input material only. 2. **Prepare the content** (the part users value most — see the scenario guides below). For math, solve it and write the solution the way a student writes it, not the way a textbook typesets it: each formula on the same line as its lead-in (`所以 $x=4$`, `移项得 $2x=8$`), never `$$…$$` (a centred line of its own — textbook look), no full stops (`。..`) anywhere in a solution, commas at most. Long `=` chains simply run on: with logic-1 `inko.py` cuts them into pieces that continue on the next line (`formula_splits`; `--keep-formulas` turns it off), and the layout engine breaks anything still wider than a line at `=` / `≤` / `+` — never break a chain into lines yourself. Prose keeps its `。`. Check every character against what the models can write (`references/writing-text.md`, "What can be written") before the quote does it for you. 3. **Choose** model, handwriting, size, paper, pen. Defaults are fine for anything the user doesn't care about. 4. **Confirm in one message** — see "Ask the user" below. Don't interrogate; ask only what changes the result. 5. **Free checks**: `inko.py quote` (plain) or `inko.py layout --preview` (custom layout) → fix any unsupported characters/symbols (the output says where) and any `math_style` warnings (`$$`, full stops, a lead-in cut off from its formula), show the preview if placement matters. 6. **Generate** (`inko.py generate … --yes`) → pages land in `./inko-output/<time>-<id>/` with `job.json` (and `plan.json` for layout jobs). 7. **Post-process** only as needed (table below). Keep the generated page flat; optional line-position adjustment uses drift (`scene.py drift` when the job came with `scene.zip`, else `compose.py drift`) → **look at the result** → deliver file paths, cost, and what the user can tweak next ("bluer ink? bolder strokes? a different handwriting? move something yourself in the editor?"). For image/PDF homework, also follow the completeness checklist in `references/scenarios.md`. Automatic preparation means reusing the user's defaults, not repeatedly asking style questions; it does not create permission for unrelated paid services. A website adapter's provided tools and layout rules take precedence over CLI-only instructions. ## Pick the model | Content | Model | Notes | |---|---|---| | Chinese / English prose, letters, essays, notes without formulas | `lyric-1` | Hundreds of preset handwritings (+ the user's own custom handwriting). No `$…$`. | | Anything with math: `$…$` formulas, Chinese mixed in | `logic-1` | Each account gets 8 curated handwritings. Only the symbols in `references/writing-math.md` §5 — unknown LaTeX commands are refused. | Formulas decide it: one `$x^2$` means `logic-1`. Chemistry like H₂O can be plain text in either model (whether the subscript ₂ is written as-is or as `H2O`: see `inko.py charset`). Answers that are only numbers ("只写最终答案": `x=4`, `-3`, `40`) need no formulas and can stay with `lyric-1`. Without `--model`, `inko.py` picks this way automatically and says so in its output. **Never ask the user to choose a model or to resolve a handwriting/model clash.** When the job needs `logic-1` but the handwriting they picked (or their 常用字迹) is Lyric-only — every custom handwriting and most presets are — use their Logic 常用字迹 (`default-style` shows `default_styles["logic-1"]`), else one of their Logic favourites, else leave out `--style` (Inko uses the account's Logic default), and say so in one line: 「含公式,公式部分用 Logic 1 的字迹写」. Only a handwriting they explicitly named for this job and that can't do Logic is worth a sentence before going on. **Choose the handwriting — the user's own choices come first.** Go down this list and stop at the first that applies: 1. They name one for this job (No.205, 「用我自己的字」, 「这次写工整点」) → `--style`, or filter by that description. 2. Their **常用字迹** (default handwriting, saved on their account): leave out `--style` and Inko uses it. There can be two: a general one and, optionally, Logic's own (one of the account's 8) — `inko.py default-style` lists what each model really uses (`default_styles`). The quote says which handwriting will be used (`style.source`: `default` = their 常用字迹; `system` = Inko's fallback). When no 常用字迹 can do this job's model — custom handwritings are Lyric-only, Logic only has the account's 8 — the quote's `style_note` says so; then continue with 3. 3. Their **favourites** (收藏): `inko.py styles --favorites --model <the job's model>` — pick the one that fits the job (neat for homework to hand in, relaxed for notes), or offer two or three. 4. Nothing saved: filter by what the job needs (`references/styles.md`). Never settle for the fallback: Lyric's is No.001, one of the most casual, joined-up hands. When the user says 「以后都用这个」, save it for them: `inko.py default-style CODE` (add `--model logic-1` for a Logic handwriting meant only for math; it changes their account, the website included — only on request). ## Plain pages or a custom layout? - **Plain** (`--text/--file`, `--paper white|cream|grid`, `--size small|medium|large`): paragraphs flow on A4. Fast, good for essays and "just write this". Every line of your text is a paragraph and gets a 2-character first-line indent (no switch) — for lists, notes and solutions use a layout with `"indent": 0`. Squared (5 mm grid) paper exists only here. - **Layout** (`--layout layout.json`): exact size in mm, line spacing, margins, ruled / 作文纸 / 田字格 / letter paper, titles centred and bigger, no indent, text boxes anywhere (answers, name, date), writing along a curve, per-character pen or handwriting. Use when exact page placement matters. Read `references/layout.md`; templates are in `assets/layouts/`; `inko.py` accepts shorthands so you never count character positions. Check with `inko.py layout --spec layout.json --preview preview.png` (free, local preview). For squared paper, use plain `--paper grid`; custom layouts currently use the built-in flat paper types. ## Ask the user (only what's missing) Put the open questions in **one** message, with your suggested default for each, in the user's language. Never ask in pieces over several turns, never re-ask what they already told you (in this request, earlier, or in `./.inko/prefs.json`), and never treat your recommendation as their answer. Typical: - **Detail level** (math/homework): 详细(每步都写,适合交作业/给人讲懂)/ 适中(关键步骤)/ 简洁(像草稿,跳步) - **Handwriting**: if they have a usable 常用字迹, just say you'll use it (no question needed). Otherwise offer 2–4 candidates as a contact sheet — favourites first (`inko.py styles --favorites` / `inko.py styles …` + `inko.py previews CODES`) — or ask "工整 / 自然 / 潦草,偏圆还是偏方?"; their own custom handwriting if they have one (lyric-1). - **Paper & size**: white / cream / grid / ruled 8 mm / 7 mm / 作文纸 / 田字格 / letter; character size (small ≈ 6 mm, medium ≈ 7 mm, large ≈ 8.5 mm tall). This is the one question worth asking for a first job when the user gave only the content: recommend 「A4 竖版白纸」 first. "A4" alone is already an answer (portrait, white, no lines); an uploaded page to write on is one too. - **Pen**: original / gel 中性笔 / ballpoint 圆珠笔 / fountain 钢笔 / pencil 铅笔; black / blue / blue-black; thinner–bolder. - **Output**: standard flat PNG pages / PDF / both. - **Characters the models can't write** (the live list: `inko.py charset`; the quote flags each one): ask once whether to use the writable equivalent the list suggests, with your recommendation first and one or two real examples from their text. If they already said how, or told you not to ask about such things, just apply the recommended form and mention it. - **Cost**: state that handwriting inference is free; do not ask for payment confirmation for a zero quote. If the user said "you decide" / 「随便」 / 「默认」 / 「不要问」 or the request is clear, decide, state your choices in one line, and proceed after validation. Don't stop for payment confirmation or optional layout preferences (margins, line spacing, alignment). ## Post-processing (all local, instant, free) | Need | Command | |---|---| | Fix spacing / position / size / pen of glyphs or lines, natural left edges — without regenerating (job has `scene.zip`, the default) | `scene.py inspect RUN/scene.zip` → `tighten` / `drift` / `move` / `pen` … → `scene.py render RUN/scene.zip -o final --pdf`; let the user drag things themselves: `scene.py editor RUN/scene.zip` (a Chinese page in their browser). See `references/scene.md` | | Natural left edges when there is no `scene.zip` | `compose.py drift --job RUN -o drifted` before `ink.py`; not on 作文纸 / 田字格 | | Everything is saved locally and the user wants Inko's copies gone early (otherwise kept 30 days) | `inko.py delivered JOB` — only after every file they want, `scene.zip` included, is saved | | Other ink colour, pen texture, bolder/thinner, lighter/darker | `ink.py restyle page.png -o out.png --color blue --texture ballpoint --weight 0.4` | | Transparent handwriting layer (for design tools) | `ink.py extract page.png -o ink.png` | | PDF of edited flat-page images | `pdf.py a.png b.jpg -o out.pdf --size A4` | Prefer the API's own `pen` options (`--pen-type/--pen-color/--pen-weight/--pen-ink`) when generating — they are applied at full quality; use `ink.py` for colours the API doesn't have (red, green, purple, #hex), textures like marker, or quick "what if" variants without regenerating. All edits stay on the flat page. `paper.py make` can draw a separate standard paper background; it does not paste handwriting into a photo. Details: `references/postprocess.md`. ## Scenario guides Read the relevant guide for content and flat-page layout decisions. - `references/scenarios.md` — math answers, notes, letters, essays and copying practice as flat pages or PDF. - `references/writing-math.md` — how students actually write solutions (解/由…得/所以/答), detail levels, the Logic symbol table, substitutions for unsupported symbols, LaTeX pitfalls. - `references/writing-text.md` — paragraphs, punctuation, letters, essays, English text, line breaks that look natural. - `references/styles.md` — choosing a handwriting from descriptions ("工整好看", "像男生写的", "潦草"), facets, previews. - `references/layout.md` — the layout JSON (papers, `d`, boxes, marks, pens), recipes, reading the plan. - `references/postprocess.md` — ink / PDF / optional flat-page drift options with examples. - `references/scene.md` — the editable glyph package (`scene.zip`): inspect, tighten gaps, drift, move, restyle, the browser editor for the user, rendering with the label. - `references/api.md` — endpoints, parameters, limits, billing, job states, files and expiry. - `references/troubleshooting.md` — every error code and what to do; common script problems. ## Writing JSON and LaTeX safely LaTeX backslashes die in shells and JSON (`\frac` → form-feed + `rac`, `\neq` → newline + `eq`). Write text and layout files with your file-writing tool (not `echo`/heredoc), double every backslash inside JSON strings (`"\\frac{a}{b}"`), and pass them with `--file` / `--layout`. `inko.py` refuses input that shows swallowed backslashes and says why.inko-handwriting/scripts/_common.py22 KBee77d7562cdfupstream ↗
"""Shared helpers for the Inko skill scripts. - Image I/O that carries Inko's AIGC labels along: the implicit label (PNG iTXt "AIGC" + XMP, JPEG/WebP XMP + EXIF) and the visible corner label 「AI生成 · Inko」. Every script saves through save_image() so labels survive editing. - Units (mm <-> px), CJK font lookup, small numpy image utilities. Only Pillow and numpy are required. Nothing here talks to the network. """ from __future__ import annotations import base64 import html import io import json import os import re import sys from pathlib import Path try: import numpy as np from PIL import Image, ImageDraw, ImageFilter, ImageFont from PIL.PngImagePlugin import PngInfo except ImportError: # pragma: no cover - explained to the agent instead sys.stderr.write("error: this script needs Pillow and numpy. Install them with:\n" " python -m pip install pillow numpy\n") sys.exit(2) Image.MAX_IMAGE_PIXELS = 400_000_000 # scans and phone photos can be large; still bounded if sys.platform == "win32": # JSON with Chinese on Windows consoles / pipes: always UTF-8 for _st in (sys.stdout, sys.stderr): try: _st.reconfigure(encoding="utf-8") except Exception: # noqa: BLE001 pass A4_MM = (210.0, 297.0) PX_PER_MM_300 = 300 / 25.4 # Inko pages are A4 at 300 dpi: 2480 x 3508 px LABEL_TEXT = "AI生成 · Inko" LABEL_MIN_FRAC = 0.05 # GB 45438-2025: visible label text height >= 5% of the shortest image side PRODUCER = "Inko (inkotype.com)" XMP_NS = "http://www.tc260.org.cn/ns/AIGC/1.0/" SKILL_TAG = "inko-handwriting skill" PAPER_SIZES_MM = { # width x height, portrait "A3": (297, 420), "A4": (210, 297), "A5": (148, 210), "A6": (105, 148), "B4": (250, 353), "B5": (176, 250), "B6": (125, 176), "16K": (184, 260), "32K": (130, 184), "LETTER": (215.9, 279.4), "LEGAL": (215.9, 355.6), } def die(msg: str, code: int = 1) -> None: sys.stderr.write(f"error: {msg}\n") sys.exit(code) def _jsonable(o): if isinstance(o, np.integer): return int(o) if isinstance(o, np.floating): return float(o) if isinstance(o, np.ndarray): return o.tolist() if isinstance(o, Path): return str(o) raise TypeError(f"not JSON serializable: {type(o).__name__}") def emit(obj) -> None: """Machine-readable result on stdout (agents parse this).""" sys.stdout.write(json.dumps(obj, ensure_ascii=False, indent=1, default=_jsonable) + "\n") sys.stdout.flush() def note(msg: str) -> None: sys.stderr.write(msg + "\n") sys.stderr.flush() def parse_size_mm(s: str) -> tuple[float, float]: """'A4' | 'b5' | 'letter' | '182x257' (mm) | '182x257mm' -> (w, h) in mm.""" k = s.strip().upper().replace(" ", "") if k in PAPER_SIZES_MM: return tuple(map(float, PAPER_SIZES_MM[k])) # type: ignore[return-value] m = re.fullmatch(r"([\d.]+)[X×\*]([\d.]+)(MM)?", k) if not m: die(f"paper size '{s}' not understood: use A4, B5, A5, Letter, 16K … or WxH in mm like 182x257") return float(m.group(1)), float(m.group(2)) # ── implicit label (metadata) ──────────────────────────────────────────────── def xmp_packet(fields: dict) -> str: js = html.escape(json.dumps(fields, ensure_ascii=False), quote=False) return ('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>' '<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">' f'<rdf:Description rdf:about="" xmlns:TC260="{XMP_NS}" xmlns:dc="http://purl.org/dc/elements/1.1/">' f'<TC260:AIGC>{js}</TC260:AIGC><dc:creator><rdf:Seq><rdf:li>{PRODUCER}</rdf:li></rdf:Seq></dc:creator>' '</rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="w"?>') def _aigc_from_xmp(xmp) -> dict | None: if not xmp: return None if isinstance(xmp, bytes): xmp = xmp.decode("utf-8", "replace") m = re.search(r"<TC260:AIGC>(.*?)</TC260:AIGC>", xmp, re.S) if not m: return None try: return json.loads(html.unescape(m.group(1))) except ValueError: return None def read_meta(img: Image.Image) -> dict: """Everything the skill keeps across edits: AIGC fields, the visible-label crop, ink-layer info, dpi.""" info = dict(getattr(img, "info", {}) or {}) text = dict(getattr(img, "text", {}) or {}) if hasattr(img, "text") else {} info.update(text) aigc = None if info.get("AIGC"): try: aigc = json.loads(info["AIGC"]) except (TypeError, ValueError): aigc = None aigc = aigc or _aigc_from_xmp(info.get("XML:com.adobe.xmp") or info.get("xmp")) if aigc is None: # JPEG written by this skill: EXIF ImageDescription try: desc = img.getexif().get(0x010E) if isinstance(desc, str) and desc.startswith("AIGC:"): aigc = json.loads(desc[5:]) except Exception: # noqa: BLE001 aigc = None ink = None if info.get("InkoInk"): try: ink = json.loads(info["InkoInk"]) except ValueError: ink = None drift = None # compose.py drift / lines --drift already moved the left edges if info.get("InkoDrift"): try: drift = json.loads(info["InkoDrift"]) except ValueError: drift = {"raw": str(info["InkoDrift"])} return {"aigc": aigc, "label_png": info.get("InkoLabel"), "ink": ink, "dpi": info.get("dpi"), "drift": drift} def merge_meta(*metas: dict) -> dict: """First non-empty value wins (e.g. background + Inko ink -> the ink's AIGC fields).""" out: dict = {"aigc": None, "label_png": None, "ink": None, "dpi": None} for m in metas: for k in out: if out[k] is None and m and m.get(k) is not None: out[k] = m[k] return out def open_image(path: str | Path) -> tuple[Image.Image, dict]: p = Path(path) if not p.exists(): die(f"file not found: {p}") try: img = Image.open(p) img.load() except Exception as e: # noqa: BLE001 die(f"cannot open image {p}: {e}") meta = read_meta(img) try: # phone photos: honour EXIF rotation from PIL import ImageOps img2 = ImageOps.exif_transpose(img) if img2 is not None: img = img2 except Exception: # noqa: BLE001 pass return img, meta def save_image(img: Image.Image, path: str | Path, meta: dict | None = None, dpi: float | None = None, quality: int = 92) -> Path: """Save PNG / JPEG / WebP keeping the AIGC implicit label (and the skill's own metadata for PNG).""" p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) meta = meta or {} aigc = meta.get("aigc") ext = p.suffix.lower() kw: dict = {} if dpi: kw["dpi"] = (dpi, dpi) if ext == ".png": info = PngInfo() if aigc: info.add_itxt("AIGC", json.dumps(aigc, ensure_ascii=False)) info.add_itxt("XML:com.adobe.xmp", xmp_packet(aigc)) if meta.get("label_png"): info.add_text("InkoLabel", meta["label_png"]) if meta.get("ink"): info.add_text("InkoInk", json.dumps(meta["ink"], ensure_ascii=False)) if meta.get("drift"): info.add_text("InkoDrift", json.dumps(meta["drift"], ensure_ascii=True)) info.add_text("Software", f"{PRODUCER} / {SKILL_TAG}") img.save(p, "PNG", pnginfo=info, compress_level=6, **kw) elif ext in (".jpg", ".jpeg"): im = img.convert("RGB") if img.mode not in ("RGB", "L") else img exif = Image.Exif() exif[0x0131] = f"{PRODUCER} / {SKILL_TAG}" # Software if aigc: exif[0x010E] = "AIGC:" + json.dumps(aigc, ensure_ascii=True) # ImageDescription (ASCII) extra = {"xmp": xmp_packet(aigc).encode("utf-8")} if aigc else {} try: im.save(p, "JPEG", quality=quality, subsampling=0 if quality >= 90 else 2, exif=exif, optimize=True, **extra, **kw) except TypeError: # older Pillow: no xmp= for JPEG im.save(p, "JPEG", quality=quality, exif=exif, optimize=True, **kw) elif ext == ".webp": extra = {"xmp": xmp_packet(aigc).encode("utf-8")} if aigc else {} img.save(p, "WEBP", quality=quality, method=4, **extra) else: die(f"unsupported output type '{ext}': use .png, .jpg or .webp (PDF: scripts/pdf.py)") return p # ── visible label 「AI生成 · Inko」 ─────────────────────────────────────────── def find_label_bbox(rgb: np.ndarray) -> tuple[int, int, int, int] | None: """Locate Inko's gray corner label on a generated page (bottom-right). Returns (x0, y0, x1, y1) or None.""" H, W = rgb.shape[:2] y0, x0 = int(H * 0.88), int(W * 0.40) reg = rgb[y0:, x0:].astype(np.int16) if reg.ndim == 2: reg = np.repeat(reg[..., None], 3, 2) mx, mn = reg.max(2), reg.min(2) gray = (mx - mn < 26) & (mn > 70) & (mx < 190) # neutral mid-gray (drawn at 128) rows = np.flatnonzero(gray.sum(1) >= 2) cols = np.flatnonzero(gray.sum(0) >= 2) if len(rows) < 8 or len(cols) < 20: return None # keep the largest run of rows (the label line), ignore stray gray pixels elsewhere runs, s = [], rows[0] for a, b in zip(rows, rows[1:]): if b - a > 12: runs.append((s, a)) s = b runs.append((s, rows[-1])) r0, r1 = max(runs, key=lambda r: r[1] - r[0]) sub = gray[r0:r1 + 1] cols = np.flatnonzero(sub.sum(0) >= 1) if len(cols) < 20: return None h, w = r1 - r0 + 1, cols[-1] - cols[0] + 1 short = min(H, W) if not (0.03 * short <= h <= 0.09 * short and 3.0 <= w / max(h, 1) <= 11.0): return None pad = max(4, int(h) // 10) return (int(max(0, x0 + cols[0] - pad)), int(max(0, y0 + r0 - pad)), int(min(W, x0 + cols[-1] + 1 + pad)), int(min(H, y0 + r1 + 1 + pad))) def _period(profile: np.ndarray, lo: int, hi: int) -> int: """Dominant period (px) of a 1-D profile, 0 if it isn't periodic (plain paper).""" p = np.asarray(profile, np.float64) - float(np.mean(profile)) if hi <= lo + 2 or len(p) <= hi or not np.any(p): return 0 ac = np.correlate(p, p, mode="full")[len(p) - 1:] if ac[0] <= 0: return 0 j = lo + int(np.argmax(ac[lo:hi])) return j if ac[j] > 0.3 * ac[0] else 0 def erase_label(rgb: np.ndarray, bbox: tuple[int, int, int, int]) -> np.ndarray: """Copy of rgb with the visible label replaced by the paper that would be under it. Candidates are copies of the same-size area further up or further left, shifted by whole ruled-line / grid periods; the one without handwriting whose surroundings best continue the label's surroundings wins — so grid squares continue under the label, and the empty bottom margin of a ruled page stays empty instead of getting lines copied into it.""" x0, y0, x1, y1 = bbox h, w = y1 - y0, x1 - x0 arr = np.asarray(rgb) Hh, Ww = arr.shape[:2] L = luminance(arr.astype(np.float32)) top, left = max(0, y0 - 4 * h), max(0, x0 - 2 * w) paper_l = float(np.percentile(L[top:y1, left:x1], 90)) if y1 > top else 255.0 vper = _period(L[top:y0, x0:x1].mean(1), 6, min((y0 - top) // 2, 3 * h)) if y0 - top > 12 else 0 hper = _period(L[y0:y1, left:x0].mean(0), 6, min((x0 - left) // 2, w)) if x0 - left > 12 else 0 vstep = int(np.ceil(h / vper) * vper) if vper else h hstep = int(np.ceil(w / hper) * hper) if hper else w b = 6 def ring(x: int, y: int) -> dict: r = {} if y - b >= 0: r["t"] = L[y - b:y, x:x + w] if y + h + b <= Hh: r["b"] = L[y + h:y + h + b, x:x + w] if x - b >= 0: r["l"] = L[y:y + h, x - b:x] return r target = ring(x0, y0) cands = [(x0, y0 - k * vstep) for k in range(1, 40)] + [(x0 - k * hstep, y0) for k in range(1, 20)] best, best_score = None, 1e9 for sx, sy in cands: if sx < 0 or sy < 0 or sx + w > Ww or sy + h > Hh: continue ink = float((L[sy:sy + h, sx:sx + w] < paper_l - 90).mean()) # handwriting, not printed lines src = ring(sx, sy) common = [k for k in target if k in src] edge = float(np.mean([np.abs(target[k] - src[k]).mean() for k in common])) if common else 50.0 score = edge + 4000.0 * ink if score < best_score: best, best_score = (sx, sy), score out = arr.copy() if best is not None: sx, sy = best out[y0:y1, x0:x1] = arr[sy:sy + h, sx:sx + w] else: # nowhere to copy from: plain paper colour ch = arr.shape[2] if arr.ndim == 3 else 1 out[y0:y1, x0:x1] = np.median(arr[max(0, y0 - h):y0, x0:x1].reshape(-1, ch), 0) if y0 > 0 else paper_l return out def label_from_page(rgb: np.ndarray, bbox: tuple[int, int, int, int], background: np.ndarray | None = None) -> Image.Image: """RGBA of the label alone (gray text on transparent), measured against the paper under it — so ruled lines or grid squares behind the label don't become part of it.""" if background is None: background = erase_label(rgb, bbox) x0, y0, x1, y1 = bbox reg = np.asarray(rgb)[y0:y1, x0:x1].astype(np.float32) bg = np.asarray(background)[y0:y1, x0:x1].astype(np.float32) lum, lbg = luminance(reg), luminance(bg) a = np.clip((lbg - lum) / np.maximum(1.0, lbg - 128.0), 0, 1) if reg.ndim == 3: a[(reg.max(2) - reg.min(2)) > 40] = 0 # coloured ink isn't the gray label a[a < 0.06] = 0 out = np.zeros((*a.shape, 4), np.uint8) out[..., :3] = 128 out[..., 3] = (a * 255).round().astype(np.uint8) return Image.fromarray(out, "RGBA") def label_crop(rgb: np.ndarray, bbox: tuple[int, int, int, int]) -> Image.Image: """RGBA crop of the label: gray text on transparent (kept for older callers).""" return label_from_page(np.asarray(rgb), bbox) def label_to_b64(label: Image.Image) -> str: buf = io.BytesIO() label.save(buf, "PNG") return base64.b64encode(buf.getvalue()).decode("ascii") def label_from_b64(s: str | None) -> Image.Image | None: if not s: return None try: return Image.open(io.BytesIO(base64.b64decode(s))).convert("RGBA") except Exception: # noqa: BLE001 return None def text_height(label: Image.Image) -> int: """Height of the label's letters (rows with solid strokes), in px.""" a = np.asarray(label.getchannel("A")) rows = np.flatnonzero((a > 128).any(1)) return int(rows[-1] - rows[0] + 1) if len(rows) else label.height def default_label() -> Image.Image: """The label drawn from text (used when a derived image needs a label but no crop of the original is at hand).""" font = cjk_font(96) probe = ImageDraw.Draw(Image.new("L", (10, 10))) x0, y0, x1, y1 = probe.textbbox((0, 0), LABEL_TEXT, font=font) im = Image.new("RGBA", (x1 - x0 + 16, y1 - y0 + 16), (128, 128, 128, 0)) ImageDraw.Draw(im).text((8 - x0, 8 - y0), LABEL_TEXT, font=font, fill=(128, 128, 128, 255)) return im def apply_label(img: Image.Image, label: Image.Image | None = None, frac: float = LABEL_MIN_FRAC * 1.06, where: str = "br", margin: tuple[float, float] = (0.035, 0.022), color: tuple[int, int, int] | str | None = "auto", at: tuple[float, float] | None = None) -> Image.Image: """Put the visible label 「AI生成 · Inko」 on img: text height >= frac x the shortest side, in a corner (bottom-right default). color="auto" keeps it readable: mid-gray on light backgrounds, light gray on dark ones.""" label = label or default_label() W, H = img.size target = max(frac, LABEL_MIN_FRAC) * min(W, H) k = target / max(1, text_height(label)) lab = label.resize((max(1, round(label.width * k)), max(1, round(label.height * k))), Image.LANCZOS) for _ in range(3): # resampling can shave a row: re-check the legal minimum th = text_height(lab) if th >= LABEL_MIN_FRAC * min(W, H): break g = LABEL_MIN_FRAC * min(W, H) * 1.02 / max(1, th) lab = label.resize((max(1, round(lab.width * g)), max(1, round(lab.height * g))), Image.LANCZOS) mx, my = round(margin[0] * W), round(margin[1] * H) if at is not None: # explicit bottom-right anchor (e.g. a custom flat-page corner) x, y = max(0, int(at[0] - lab.width)), max(0, int(at[1] - lab.height)) else: x = max(0, W - mx - lab.width if "r" in where else mx) y = max(0, H - my - lab.height if "b" in where else my) if color == "auto": region = np.asarray(img.convert("L").crop((x, y, x + lab.width, y + lab.height)), np.float32) bg = float(np.median(region)) if region.size else 255.0 color = (110, 110, 110) if bg >= 165 else (236, 236, 236) if bg < 110 else (40, 40, 40) if color is not None: c = Image.new("RGBA", lab.size, (*color, 255)) c.putalpha(lab.getchannel("A")) lab = c base = img.convert("RGBA") base.alpha_composite(lab, (x, y)) return base.convert(img.mode) if img.mode in ("RGB", "L") else base def label_box(img_wh: tuple[int, int], label: Image.Image | None = None, frac: float = LABEL_MIN_FRAC * 1.06, where: str = "br", margin: tuple[float, float] = (0.035, 0.022)) -> tuple[int, int, int, int]: """Where apply_label() will put the label (x0, y0, x1, y1) — to keep handwriting out of that corner.""" label = label or default_label() W, H = img_wh k = frac * min(W, H) / max(1, text_height(label)) w, h = round(label.width * k), round(label.height * k) mx, my = round(margin[0] * W), round(margin[1] * H) x = max(0, W - mx - w if "r" in where else mx) y = max(0, H - my - h if "b" in where else my) return x, y, x + w, y + h # ── fonts ─────────────────────────────────────────────────────────────────── _FONT_CANDIDATES = [ os.environ.get("INKO_FONT", ""), "C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/simhei.ttf", "C:/Windows/Fonts/simsun.ttc", "C:/Windows/Fonts/simkai.ttf", "/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/STHeiti Medium.ttc", "/Library/Fonts/Arial Unicode.ttf", "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", "/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc", ] _KAI_CANDIDATES = [os.environ.get("INKO_FONT_KAI", ""), "C:/Windows/Fonts/simkai.ttf", "/System/Library/Fonts/Supplemental/Kaiti.ttc", "/usr/share/fonts/truetype/arphic/ukai.ttc", "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc"] def cjk_font(size: int, kai: bool = False) -> ImageFont.ImageFont: for f in (_KAI_CANDIDATES if kai else []) + _FONT_CANDIDATES: if f and Path(f).exists(): try: return ImageFont.truetype(f, max(4, int(size))) except OSError: continue try: return ImageFont.load_default(size=max(4, int(size))) except TypeError: return ImageFont.load_default() # ── small numpy helpers ───────────────────────────────────────────────────── def luminance(rgb: np.ndarray) -> np.ndarray: if rgb.ndim == 2: return rgb.astype(np.float32) return rgb[..., :3].astype(np.float32) @ np.array([0.299, 0.587, 0.114], np.float32) def _box1d(a: np.ndarray, r: int, axis: int) -> np.ndarray: if r <= 0: return a pad = [(0, 0)] * a.ndim pad[axis] = (r + 1, r) p = np.pad(a, pad, mode="edge") c = np.cumsum(p, axis=axis, dtype=np.float64) n = a.shape[axis] hi = np.take(c, np.arange(2 * r + 1, 2 * r + 1 + n), axis=axis) lo = np.take(c, np.arange(0, n), axis=axis) return ((hi - lo) / (2 * r + 1)).astype(np.float32) def gaussian(arr: np.ndarray, sigma: float) -> np.ndarray: """Gaussian blur of a float32 2-D array (three box blurs per axis, O(N); no scipy needed).""" if sigma <= 0.3: return np.asarray(arr, np.float32) n = 3 w = (12 * sigma * sigma / n + 1) ** 0.5 wl = int(w) - (1 - int(w) % 2) # odd width below m = round((12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4)) out = np.asarray(arr, np.float32) for i in range(n): r = ((wl if i < m else wl + 2) - 1) // 2 out = _box1d(_box1d(out, r, 0), r, 1) return out def value_noise(h: int, w: int, cell: float, rng: np.random.Generator) -> np.ndarray: """Smooth random field in [-1, 1] with feature size ~cell px (bicubic-upsampled random grid).""" gh, gw = max(2, int(h / cell) + 3), max(2, int(w / cell) + 3) g = rng.uniform(-1, 1, (gh, gw)).astype(np.float32) im = Image.fromarray(g, "F").resize((int(gw * cell), int(gh * cell)), Image.BICUBIC) a = np.asarray(im, np.float32)[:h, :w] if a.shape != (h, w): a = np.pad(a, ((0, h - a.shape[0]), (0, w - a.shape[1])), mode="edge") m = np.abs(a).max() or 1.0 return a / m def px_per_mm_of(img: Image.Image, meta: dict | None = None, default: float = PX_PER_MM_300) -> float: ink = (meta or {}).get("ink") or {} if ink.get("px_per_mm"): return float(ink["px_per_mm"]) dpi = (meta or {}).get("dpi") or img.info.get("dpi") if dpi and float(dpi[0]) > 50: return float(dpi[0]) / 25.4 if img.size in ((2480, 3508), (3508, 2480)): return PX_PER_MM_300 return defaultinko-handwriting/scripts/_pen.py9.7 KB8c5a8db59685upstream ↗
"""Inko's pen post-processing, ported verbatim from the Inko worker (worker/inko_worker/pen.py). The server applies the pen AFTER generation, on the writer's raw ink, BEFORE the paper and the label: stroke weight, darkness, pen texture and ink colour. scene.py uses this port to re-render an inko-scene package (scene.zip) locally, so a page rendered here with a given pen is the same page the server would have produced with that pen. - pen = {"weight": -1..1, "ink": -1..1, "type": original|gel|ballpoint|fountain|pencil, "color": black|blue|blueblack}; missing = the original pen. With the original pen the caller skips apply() entirely (round(paper * ink)). - Every step stores float32 and computes in float64 (same as the server and its TypeScript twin web/src/lib/pen.ts). - Noise is sampled in page millimetres (pixel centre / px_per_mm), anchored at the page origin: the same sheet always gets the same texture, and a glyph that is moved picks up the texture of its new place. Keep this file in lock-step with the worker: do not "improve" the maths here, the renderer must match the server. Only numpy and the standard library are used. """ from __future__ import annotations import math import numpy as np TYPES = ("original", "gel", "ballpoint", "fountain", "pencil") COLORS = {"black": (0, 0, 0), "blue": (22, 58, 168), "blueblack": (22, 34, 86)} GRAPHITE = (58, 58, 64) # pencil ignores the colour: always graphite DEFAULT = {"weight": 0.0, "ink": 0.0, "type": "original", "color": "black"} WEIGHT_MM = 0.09 # weight = +-1: stroke edges grow / shrink by 0.09 mm BLUR_MM = 0.035 # fountain pen bleed (sigma) BALL_CELL_MM, PENCIL_CELL_MM = 1.5, 0.08 # noise cell: ballpoint density waves / pencil grain ROWS = 256 # noise is computed in row blocks to save memory def _num(v) -> float: if isinstance(v, bool): return 0.0 try: x = float(v) except (TypeError, ValueError, OverflowError): # OverflowError: huge JSON integers return 0.0 return min(1.0, max(-1.0, x)) if math.isfinite(x) else 0.0 def normalize(pen) -> dict: """Any input -> a valid pen: missing fields = default, numbers clamped to [-1, 1], unknown type / colour -> original / black.""" p = pen if isinstance(pen, dict) else {} t, c = p.get("type"), p.get("color") return {"weight": _num(p.get("weight", 0.0)), "ink": _num(p.get("ink", 0.0)), "type": t if isinstance(t, str) and t in TYPES else "original", "color": c if isinstance(c, str) and c in COLORS else "black"} def is_default(pen) -> bool: return normalize(pen) == DEFAULT def ink_rgb(pen) -> tuple[int, int, int]: p = normalize(pen) return GRAPHITE if p["type"] == "pencil" else COLORS[p["color"]] def is_colored(pen) -> bool: """The ink is not pure black (blue / blue-black / pencil graphite): the page cannot be saved as grayscale.""" return ink_rgb(pen) != (0, 0, 0) # -- steps 1-5: grayscale ink -> ink amount ------------------------------------------------------------------------------ def _half(r: int, dy: int) -> int: """Half width of row dy of the disk kernel of radius r (2(dx^2 + dy^2) <= 2r^2 + r: r = 1 is a 3x3 cross, r = 2 is 5x5 without corners).""" return math.isqrt((2 * r * r + r - 2 * dy * dy) // 2) def _morph(a: np.ndarray, r: int, grow: bool) -> np.ndarray: """Max (grow: ink spreads out) / min filter with the disk kernel. The kernel is split into horizontal runs: running extrema for every half width first, then row-shifted extrema; pixels outside the image do not take part.""" op = np.maximum if grow else np.minimum H, W = a.shape hor = [a] for w in range(1, r + 1): cur = hor[-1].copy() if w < W: op(cur[:, w:], a[:, :W - w], out=cur[:, w:]) op(cur[:, :W - w], a[:, w:], out=cur[:, :W - w]) hor.append(cur) out = hor[_half(r, 0)].copy() for dy in range(-r, r + 1): if dy == 0 or abs(dy) >= H: continue src = hor[_half(r, dy)] if dy > 0: op(out[:H - dy], src[dy:], out=out[:H - dy]) else: op(out[-dy:], src[:H + dy], out=out[-dy:]) return out def _weight(a: np.ndarray, weight: float, s: float) -> np.ndarray: """Stroke weight: r = 0.09 mm * |weight| * s px; a fractional radius interpolates linearly between the results of radius floor(r) and floor(r) + 1 (r < 1: between the image itself and the cross).""" r = WEIGHT_MM * abs(weight) * s if not r > 0: return a lo = math.floor(r) f = r - lo A = a if lo == 0 else _morph(a, lo, weight > 0) if f == 0: return A B = _morph(a, lo + 1, weight > 0).astype(np.float64) A = A.astype(np.float64) return (A + (B - A) * f).astype(np.float32) def _blur(a: np.ndarray, sigma: float) -> np.ndarray: """Separable Gaussian (radius ceil(3 sigma), at least 1; normalised weights); outside the image = no ink; horizontal pass, then vertical; float32 between the passes.""" R = max(1, math.ceil(3 * sigma)) ws = [math.exp(-(i * i) / (2 * sigma * sigma)) for i in range(-R, R + 1)] tot = 0.0 for w in ws: tot += w ws = [w / tot for w in ws] for axis in (1, 0): src = a.astype(np.float64) n = src.shape[axis] acc = np.zeros(src.shape, np.float64) for t, w in enumerate(ws): d = t - R # sample x + d if abs(d) >= n: continue lo, hi = max(0, -d), n - max(0, d) dst = acc[:, lo:hi] if axis == 1 else acc[lo:hi] dst += w * (src[:, lo + d:hi + d] if axis == 1 else src[lo + d:hi + d]) a = acc.astype(np.float32) return a def _hash(i: np.ndarray, j: np.ndarray) -> np.ndarray: """Lattice value ((i*73856093) XOR (j*19349663))*2654435761 mod 2^32 (32-bit unsigned products, like the TS Math.imul(...) >>> 0) / 2^32.""" hi = i.astype(np.uint32) * np.uint32(73856093) hj = j.astype(np.uint32) * np.uint32(19349663) return ((hi ^ hj) * np.uint32(2654435761)).astype(np.float64) / 4294967296.0 def noise(shape: tuple[int, int], s: float, cell_mm: float, origin: tuple[int, int] = (0, 0)) -> np.ndarray: """Value noise N(x, y; c) in [0, 1): which cell the pixel centre (in mm) / c falls in, bilinear inside the cell. origin = page pixel of this block's top-left corner.""" h, w = shape u = ((np.arange(w, dtype=np.float64) + origin[0] + 0.5) / s) / cell_mm v = ((np.arange(h, dtype=np.float64) + origin[1] + 0.5) / s) / cell_mm i, j = np.floor(u), np.floor(v) fx, fy = (u - i)[None, :], (v - j)[:, None] i, j = i.astype(np.int64)[None, :], j.astype(np.int64)[:, None] h00, h10, h01, h11 = _hash(i, j), _hash(i + 1, j), _hash(i, j + 1), _hash(i + 1, j + 1) top = h00 + (h10 - h00) * fx bot = h01 + (h11 - h01) * fx return top + (bot - top) * fy def _grain(a: np.ndarray, s: float, cell_mm: float, k: float, base: float, amp: float, origin: tuple[int, int]) -> np.ndarray: """a * k * (base + amp * N).""" out = np.empty_like(a) for y0 in range(0, a.shape[0], ROWS): blk = a[y0:y0 + ROWS] n = noise(blk.shape, s, cell_mm, (origin[0], origin[1] + y0)) out[y0:y0 + ROWS] = (blk.astype(np.float64) * k * (base + amp * n)).astype(np.float32) return out def apply(g: np.ndarray, pen, px_per_mm: float, origin: tuple[int, int] = (0, 0)) -> np.ndarray: """Grayscale ink g in [0, 1] (1 = paper white) -> ink amount a in [0, 1] (float32), steps 1-5. px_per_mm = pixels per millimetre (Inko pages: 2480/210); origin: see noise().""" p = normalize(pen) s = float(px_per_mm) if not (math.isfinite(s) and s > 0): raise ValueError(f"invalid px_per_mm: {px_per_mm}") a = (1.0 - np.asarray(g, np.float64)).astype(np.float32) # 1. ink amount a = _weight(a, p["weight"], s) # 2. weight if p["ink"] > 0: # 3. darkness a = (1.0 - (1.0 - a.astype(np.float64)) ** (1.0 + 1.2 * p["ink"])).astype(np.float32) elif p["ink"] < 0: a = (a.astype(np.float64) * (1.0 + 0.45 * p["ink"])).astype(np.float32) t = p["type"] # 4. pen texture if t == "gel": # gel: crisper edges, solid core a = np.clip((a.astype(np.float64) - 0.08) / 0.72, 0.0, 1.0).astype(np.float32) elif t == "ballpoint": # ballpoint: a bit lighter, slow density waves a = _grain(a, s, BALL_CELL_MM, 0.92, 0.88, 0.12, origin) elif t == "fountain": # fountain: wet, slightly bleeding edges a = np.clip(1.12 * _blur(a, BLUR_MM * s).astype(np.float64), 0.0, 1.0).astype(np.float32) elif t == "pencil": # pencil: gray, grainy a = _grain(a, s, PENCIL_CELL_MM, 0.68, 0.55, 0.45, origin) return a # -- step 6: colour ------------------------------------------------------------------------------------------------------ def composite(region: np.ndarray, a: np.ndarray, pen) -> np.ndarray: """Ink multiplied onto the paper: out = paper * (1 - a * (1 - ink/255)); ruled lines still show through the ink. region = paper RGB (H x W x 3); returns uint8.""" k = np.array([1.0 - c / 255.0 for c in ink_rgb(pen)], np.float64) mixed = np.asarray(region, np.float64) * (1.0 - a.astype(np.float64)[..., None] * k) return mixed.round().clip(0, 255).astype(np.uint8)inko-handwriting/scripts/compose.py29 KBa4adc3e75d9aupstream ↗
#!/usr/bin/env python3 """Adjust line positions on standard flat Inko pages. Only the ink moves; page geometry, AI labels and metadata stay intact. Optional: python compose.py drift --job RUN -o edited """ from __future__ import annotations import sys sys.dont_write_bytecode = True import argparse import json import re import shutil import time import warnings import zlib from pathlib import Path import numpy as np from _common import PRODUCER, SKILL_TAG, Image, ImageFilter, die, emit, gaussian, luminance, note, open_image, px_per_mm_of, save_image, xmp_packet import ink as INK LIFT = 0.14 def _natural(p: Path): return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", p.name)] def job_inputs(paths: list[str], job: str | None) -> tuple[list[Path], dict | None, dict | None, dict]: """-> (page files, plan, layout, generation params) of a job folder from inko.py (or of the pages given).""" plan = layout = None params: dict = {} files: list[Path] = [Path(p) for p in paths] if job: jd = Path(job) if not jd.is_dir(): die(f"--job {jd} is not a folder (give the folder inko.py generate printed as out_dir)") files = files or sorted([p for p in jd.glob("page-*.png")], key=_natural) if not files: files = sorted([p for p in jd.glob("page-*.webp")], key=_natural) for name in ("plan.json", "layout.json", "job.json"): f = jd / name if f.exists(): obj = json.loads(f.read_text(encoding="utf-8")) if name == "plan.json": plan = obj elif name == "layout.json": layout = obj else: params = obj.get("params") or {} if layout is None and isinstance(params.get("layout"), dict): layout = params["layout"] if not files: die("no pages given (pass page PNGs or --job <folder with page-1.png …>)") return files, plan, layout, params INKO_RULES = {"ruled8": (34.0, 274.0, 8.0), "ruled7": (33.0, 276.0, 7.0)} PLAIN_CHAR_PX = {"small": 71, "medium": 83, "large": 100} PLAIN_LINE_ADV = 1.75 def page_rules(page: dict, layout: dict | None) -> tuple[list[float], float] | None: """Ruled lines of a generated page (known for Inko's ruled papers, detected otherwise): (rule y's in px, spacing px).""" ppm = page["ppm"] pid = (layout or {}).get("paperId") if pid in INKO_RULES: a, b, sp = INKO_RULES[pid] return [y * ppm for y in np.arange(a, b + 1e-6, sp)], sp * ppm if page.get("is_layer"): return None import paper as PAPER img, _ = open_image(page["path"]) small = img.convert("RGB").resize((img.width // 2, img.height // 2), Image.BILINEAR) det = PAPER.detect_lines(luminance(np.asarray(small, np.float32))) reg = [l for l in det["lines"] if l.get("regular")] if len(reg) < 4 or not det["pitch"]: return None W2 = small.width ys = sorted(float(np.polyval(l["c"], W2 / 2)) * 2 for l in reg) return ys, float(np.median(np.diff(ys))) def rule_rows(alpha: np.ndarray, rules: list[float], sp: float, lift: float) -> list[dict]: """Rows of a page written on ruled lines: the writing that sits on each rule.""" H, W = alpha.shape rows = [] for ry in rules: a0, b0 = int(max(0, ry - 0.92 * sp)), int(min(H, ry + 0.08 * sp)) band = alpha[a0:b0] > 0.25 if band.sum() < 0.02 * sp * sp: continue cols = np.flatnonzero(band.any(0)) rows.append({"base": float(ry - lift * sp), "x0": float(cols[0]), "x1": float(cols[-1] + 1), "a": float((0.9 - lift) * sp), "d": float((lift + 0.06) * sp), "s": 0.62 * sp}) return rows def detect_rows(alpha: np.ndarray, ppm: float, prior: float | None = None) -> list[dict]: """Rows of handwriting from the ink itself (no plan): row centres = peaks of the horizontal ink profile at the dominant row period; each row's baseline = bottom of its dense core.""" H, W = alpha.shape ink = (alpha > 0.25).mean(1).astype(np.float32) if not ink.any(): return [] prof = gaussian(ink[None, :], 0.6 * ppm)[0] pc = prof - prof.mean() ac = np.correlate(pc, pc, mode="full")[H - 1:] lo, hi = (int(0.75 * prior), int(1.35 * prior)) if prior else (int(5.5 * ppm), int(min(H // 2, 40 * ppm))) lag = int(10 * ppm) if hi > lo + 2: # first strong local maximum = the row period seg = ac[lo - 1:hi + 1] mx = [i for i in range(1, len(seg) - 1) if seg[i] >= seg[i - 1] and seg[i] >= seg[i + 1]] top = max((seg[i] for i in mx), default=0) strong = [i for i in mx if seg[i] >= 0.5 * top and seg[i] > 0] if strong: lag = lo - 1 + strong[0] sm = gaussian(ink[None, :], 0.18 * lag)[0] thr = 0.12 * np.percentile(sm[sm > 0], 95) peaks = [] for i in np.argsort(-sm): if sm[i] < thr: break if all(abs(i - j) >= 0.6 * lag for j in peaks): peaks.append(int(i)) peaks.sort() rows = [] for n, c in enumerate(peaks): top = int((peaks[n - 1] + c) / 2) if n else max(0, int(c - 0.6 * lag)) bot = int((c + peaks[n + 1]) / 2) if n + 1 < len(peaks) else min(H, int(c + 0.6 * lag)) band = ink[top:bot] if band.sum() <= 0: continue cum = np.cumsum(band) / band.sum() base = top + int(np.searchsorted(cum, 0.9)) t = top + int(np.searchsorted(cum, 0.04)) cols = np.flatnonzero((alpha[top:bot] > 0.25).any(0)) s = max(1.0, (base - t) / 0.92) rows.append({"base": float(base), "x0": float(cols[0]), "x1": float(cols[-1] + 1), "a": float(base - top), "d": float(bot - base), "s": s}) return rows def gen_pitch(pages_rows: list[list[dict]], layout: dict | None, ppm: float) -> float: if layout: d = layout.get("d") or {} pid = layout.get("paperId") or "blank" if pid in ("ruled8", "ruled7"): return (8.0 if pid == "ruled8" else 7.0) * max(1, int(d.get("lineStep") or 1)) * ppm if pid == "blank": return float(d.get("size", 7.0)) * float(d.get("line", 1.7)) * ppm diffs = np.concatenate([np.diff([r["base"] for r in rows]) for rows in pages_rows if len(rows) >= 2] or [np.zeros(0)]) diffs = diffs[diffs > 2 * ppm] if not len(diffs): return 12.0 * ppm d0 = np.percentile(diffs, 20) return float(np.median(diffs[diffs < 1.35 * d0])) DRIFT_MODES = ("natural", "random", "none") DRIFT_CAP = 0.45 PROBLEM_RE = re.compile(r"[ \t ]*(?:\d{1,3}\s*(?:[..](?!\d)|[、::))])|[((]\s*\d{1,3}\s*[))]|[①-⑳]|" r"第\s*[\d一二三四五六七八九十]+\s*[题问]|[一二三四五六七八九十]{1,3}\s*[、..])") def drift_seed(seed: int, key: str | None) -> list[int]: """--seed mixed with the job's id: deterministic for one job, but two jobs never drift alike.""" return [int(seed) & 0xFFFFFFFF, zlib.crc32((key or "").encode("utf-8"))] def page_key(meta: dict, path) -> str: return str(((meta or {}).get("aigc") or {}).get("ProduceID") or Path(str(path)).name) def drift_series(n: int, mode: str, amount: float, seed, resets=()) -> np.ndarray: """Left-edge offsets of n successive written lines, in character heights (+ = to the right). natural: starts at 0..0.08, each line adds 0.015..0.05 (slow creep) plus a smooth AR(1) wobble (σ 0.03, ρ 0.6); the creep tops out near 0.42, where the writer now and then re-anchors; a line in `resets` (after a blank line, at a new problem) keeps only 30 % of the creep. random: the wobble alone (σ 0.06) around +0.12, so it rarely needs clipping at a margin line. none: zeros.""" out = np.zeros(n) if mode == "none" or n == 0 or not amount: return out rng = np.random.default_rng(seed) rho, sig = 0.6, (0.06 if mode == "random" else 0.03) e, creep, reset = rng.normal(0, sig), rng.uniform(0, 0.08), set(resets) for k in range(n): if k: e = rho * e + np.sqrt(1 - rho * rho) * rng.normal(0, sig) if mode == "natural": if k in reset: creep *= 0.3 else: creep += rng.uniform(0.015, 0.05) if creep > 0.42: creep = 0.42 if rng.random() > 0.25 else 0.3 * creep out[k] = (0.12 if mode == "random" else creep) + e return np.clip(out, -DRIFT_CAP, DRIFT_CAP) * amount def _py_index(text: str): """UTF-16 offsets (the layout engine's `i`) -> Python string indices.""" if all(ord(c) < 0x10000 for c in text): return lambda i: i m: list[int] = [] for n, c in enumerate(text): m.extend([n] * (2 if ord(c) > 0xFFFF else 1)) return lambda i: m[i] if 0 <= i < len(m) else len(text) def starts_problem(text: str | None, i16, pidx=None) -> bool: """Does the layout text at this offset start a paragraph with a problem number (1. / (2) / 3、 / ① / 第4题)?""" if not text or i16 is None: return False i = (pidx or _py_index(text))(int(i16)) if i >= len(text) or text[:i].rstrip(" \t ")[-1:] not in ("", "\n"): return False return bool(PROBLEM_RE.match(text, i)) def clamp_drift(d: float, left: float, right: float, lo: float, hi: float) -> float: """Shift d (px) limited so the line's ink [left, right] stays inside [lo, hi] — a line already outside is not pulled back, only kept from going further.""" return float(min(max(d, min(0.0, lo - left)), max(0.0, hi - right))) def drift_resets(bases: list[float], pitch: float, firsts: list, text: str | None) -> list[int]: """Indices of lines that start after a blank line (gap > 1.5 pitch) or begin a new problem (needs the layout text).""" pidx = _py_index(text) if text else None return [k for k in range(1, len(bases)) if (bases[k] is not None and bases[k - 1] is not None and bases[k] - bases[k - 1] > 1.5 * pitch) or starts_problem(text, firsts[k], pidx)] AREA_X_MM = {"ruled8": (24.0, 194.0), "ruled7": (24.0, 194.0), "letter": (22.0, 188.0), "blank": (20.0, 190.0)} CELL_PAPERS = ("compo", "tian") def plan_lines(plan: dict, page_i: int, ppm: float) -> tuple[list[dict], list[tuple[int, int, int, int]]]: """Visual lines of one page from the plan, in px: body items grouped by baseline (a plan row can be just a piece of a line); plus the rectangles of boxed items (answers in boxes / fields), which never move.""" pages = (plan.get("plan") or {}).get("pages") or [] items = pages[page_i] if page_i < len(pages) else [] boxes, body = [], [] for it in items: s = it["s"] if it.get("box"): boxes.append((int((it["x"] - 0.3 * s) * ppm), int((it["y"] - 1.1 * s) * ppm), int(np.ceil((it["x"] + it["w"] + 0.3 * s) * ppm)), int(np.ceil((it["y"] + 0.45 * s) * ppm)))) else: body.append(it) groups: list[list[dict]] = [] for it in sorted(body, key=lambda it: it["y"]): g = groups[-1] if groups else None if g and abs(it["y"] - float(np.median([q["y"] for q in g]))) < 0.3 * max(it["s"], max(q["s"] for q in g)): g.append(it) else: groups.append([it]) lines = [] for g in groups: s = float(np.median([q["s"] for q in g])) base = float(np.median([q["y"] for q in g])) # each item's own baseline: a formula with a fraction sits higher than the line (its y is not the median) top = min(min(q["y"] - (q["m"]["a"] if q.get("m") else 0.92) * q["s"] for q in g), base - 0.95 * s) bot = max(max(q["y"] + (q["m"]["d"] if q.get("m") else 0.25) * q["s"] for q in g), base + 0.3 * s) first = min(g, key=lambda q: q["x"]) lines.append({"base": base * ppm, "top": top * ppm, "bot": bot * ppm, "x0": first["x"] * ppm, "x1": max(q["x"] + q["w"] for q in g) * ppm, "s": s * ppm, "i0": first.get("i"), "items": g}) return lines, boxes def margin_line_x(rgb: np.ndarray, paper_id: str | None, ppm: float) -> float | None: """Right edge (px) of a red vertical margin line in the left 40 % of the page (Inko's ruled papers: 24 mm).""" small = rgb[::4, ::4] red = (small[..., 0] - np.maximum(small[..., 1], small[..., 2])) > 18 cols = np.flatnonzero(red.mean(0)[:int(0.4 * small.shape[1])] > 0.35) if len(cols): return float((cols[-1] + 1) * 4) return 24.3 * ppm if paper_id in ("ruled8", "ruled7") else None def _lum(v: np.ndarray) -> np.ndarray: return v[..., :3] @ np.array([0.299, 0.587, 0.114], np.float32) def _interp_across(rgb: np.ndarray, hole: np.ndarray, ys: np.ndarray, xs: np.ndarray, axis: int) -> tuple[np.ndarray, np.ndarray]: """Colour at hole pixels (ys, xs), linear between the nearest non-hole pixels along the row (axis 1) or column (0).""" n = hole.shape[axis] idx = np.broadcast_to(np.arange(n, dtype=np.int32).reshape((1, n) if axis == 1 else (n, 1)), hole.shape) lo = np.maximum.accumulate(np.where(hole, -1, idx), axis=axis) hi = np.flip(np.minimum.accumulate(np.flip(np.where(hole, n, idx), axis), axis=axis), axis) a, b = lo[ys, xs], hi[ys, xs] pos = xs if axis == 1 else ys ha, hb = a >= 0, b < n ac, bc = np.clip(a, 0, n - 1), np.clip(b, 0, n - 1) ca, cb = (rgb[ys, ac], rgb[ys, bc]) if axis == 1 else (rgb[ac, xs], rgb[bc, xs]) t = np.where(ha & hb, (pos - a) / np.maximum(b - a, 1), np.where(ha, 0.0, 1.0)).astype(np.float32)[:, None] return ca * (1 - t) + cb * t, ha | hb def _grow1(m: np.ndarray) -> np.ndarray: g = m.copy() g[1:] |= m[:-1] g[:-1] |= m[1:] return g def paper_under_ink(rgb: np.ndarray, hole: np.ndarray, paper_rgb) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """The paper under the handwriting -> (ys, xs, colours). Printed lines run the whole page, so they show up in the row / column medians: a pixel on a horizontal line (rule, grid) is interpolated along its row, one on a vertical line (margin, grid) along its column (crossings: the darker), plain paper along the row. Interpolation never starts from a pixel of a line running the other way — else a stroke ending on a grid line would smear its colour across the gap.""" with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) # rows / columns that are all ink Lm = np.where(hole, np.nan, luminance(rgb)) rowm, colm = np.nanmedian(Lm[:, ::2], axis=1), np.nanmedian(Lm[::2], axis=0) paper_l = float(np.nanmedian(Lm[::2, ::2])) srow, scol = _grow1(rowm < paper_l - 6), _grow1(colm < paper_l - 6) # printed lines (+ their soft edges) ys, xs = np.nonzero(hole) est, ok = _interp_across(rgb, hole | scol[None, :], ys, xs, 1) est[~ok] = np.array(paper_rgb, np.float32) sel = np.flatnonzero(scol[xs]) if len(sel): v, okv = _interp_across(rgb, hole | srow[:, None], ys[sel], xs[sel], 0) use = okv & (~srow[ys[sel]] | (_lum(v) < _lum(est[sel]))) est[sel[use]] = v[use] return ys, xs, est def _shift1(row: np.ndarray, k: int) -> np.ndarray: W = row.shape[0] r = np.ones_like(row) if -W < k < W: if k >= 0: r[k:] = row[:W - k] else: r[:W + k] = row[-k:] return r def shift_rows(fac: np.ndarray, dx: np.ndarray) -> np.ndarray: """out[y, x] = fac[y, x - dx[y]] (linear interpolation); uncovered pixels become 1 = no ink.""" out = fac.copy() inky = (fac < 0.999).reshape(fac.shape[0], -1).any(1) for y in np.flatnonzero(inky & (np.abs(dx) > 1e-3)): i = int(np.floor(dx[y])) f = float(dx[y] - i) out[y] = (1 - f) * _shift1(fac[y], i) + f * _shift1(fac[y], i + 1) return out def dx_field(H: int, lines: list[dict], offs: list[float]) -> np.ndarray: """Horizontal shift per pixel row: constant over each line's band, linear in between, fading out within half a character height above the first line and below the last.""" if not lines: return np.zeros(H) bands = sorted([[l["top"], l["bot"], d, l["s"]] for l, d in zip(lines, offs)], key=lambda b: b[0]) for p, q in zip(bands, bands[1:]): # overlapping neighbours meet halfway if p[1] > q[0]: p[1] = q[0] = min(q[1], (p[1] + q[0]) / 2) xp, fp = [bands[0][0] - 0.5 * bands[0][3]], [0.0] for t, b, d, _s in bands: xp += [t, max(t, b)] fp += [d, d] xp.append(bands[-1][1] + 0.5 * bands[-1][3]) fp.append(0.0) xp = np.maximum.accumulate(np.asarray(xp, np.float64) + np.arange(len(xp)) * 1e-6) return np.interp(np.arange(H, dtype=np.float64), xp, fp, left=0.0, right=0.0) def pages_pdf(paths: list[Path], out: Path) -> None: """The pages as one PDF at paper size with the AIGC metadata (/AIGC + XMP) — pdf.py's writer.""" import pdf as PDF pages, aigc = [], None for f in paths: img, meta = open_image(f) aigc = aigc or meta.get("aigc") pw, ph = PDF.page_size_pt(img, meta, "auto") k = min(pw / img.width, ph / img.height) w, h = img.width * k, img.height * k data, im = PDF.encode_image(img, 90, False) pages.append((data, im, (pw, ph), ((pw - w) / 2, (ph - h) / 2, w, h))) info = {"Title": out.stem, "Creator": SKILL_TAG, "Producer": PRODUCER, "CreationDate": time.strftime("D:%Y%m%d%H%M%S")} if aigc: info["AIGC"] = json.dumps(aigc, ensure_ascii=False) info["Keywords"] = "AIGC; AI生成 · Inko" PDF.write_pdf(pages, out, info, xmp_packet(aigc) if aigc else None) def cmd_drift(a) -> None: files, plan, layout, params = job_inputs(a.pages, a.job) if a.plan: plan = json.loads(Path(a.plan).read_text(encoding="utf-8")) if a.layout: layout = json.loads(Path(a.layout).read_text(encoding="utf-8")) layout = layout.get("layout", layout) plan = json.loads(json.dumps(plan)) if plan else None # a copy: its x's get the shifts for the output paper_id = (layout or {}).get("paperId") or (((plan or {}).get("plan") or {}).get("paper") or {}).get("id") if paper_id in CELL_PAPERS: die(f"'{paper_id}' paper has one character per cell: shifting lines would push them out of their cells — leave it as it is") out = Path(a.out) single = len(files) == 1 and out.suffix.lower() == ".png" if out.suffix and not single: die("-o: give a folder (the pages keep their names there), or a .png file when there is one page") if a.drift_amount < 0: die("--drift-amount must be >= 0 (0.5 = half as much)") targets = [out] if single else [out / (f.stem + ".png") for f in files] if len({t.resolve() for t in targets}) < len(targets): die("two pages have the same file name, they would overwrite each other in -o: rename them or run them one at a time") for f, t in zip(files, targets): if t.resolve() == f.resolve() and not a.force: die(f"{t} is the original page: write the drifted pages somewhere else (-o drifted/), or add --force") d = (layout or {}).get("d") or {} lift = float(d.get("lift", LIFT)) size = params.get("size") pages = [] for i, f in enumerate(files): # 1) lines, label, margin of every page img, meta = open_image(f) if meta.get("drift") and not a.force: die(f"{f} was drifted already ({meta['drift'].get('by', 'compose.py')}, {meta['drift'].get('mode')}): start from the " "original page, or add --force to drift it once more") sep = INK.separate(img) if sep["is_layer"]: die(f"{f} is a transparent ink layer: drift the page itself, then extract the ink from the result") ppm = px_per_mm_of(img, meta) alpha = sep["alpha"] lab = sep["label_bbox"] if lab: x0, y0, x1, y1 = lab alpha[y0:y1, x0:x1] = 0 # the label is never handwriting if plan: lines, boxes = plan_lines(plan, i, ppm) how = "plan.json" else: boxes = [] if paper_id in INKO_RULES: rules, sp = page_rules({"ppm": ppm}, {"paperId": paper_id}) rows, how = rule_rows(alpha, rules, sp, lift), "the page's ruled lines" else: # from the ink (grid squares are not rows) prior = PLAIN_CHAR_PX[size] * PLAIN_LINE_ADV * ppm / (300 / 25.4) if size in PLAIN_CHAR_PX else None rows, how = detect_rows(alpha, ppm, prior), "the ink (no plan.json)" lines = [{"base": r["base"], "top": r["base"] - 0.95 * r["s"], "bot": r["base"] + 0.3 * r["s"], "x0": r["x0"], "x1": r["x1"], "s": r["s"], "i0": None} for r in rows] lines.sort(key=lambda l: l["base"]) pages.append({"path": f, "meta": meta, "ppm": ppm, "size": img.size, "hole": alpha > 0.03, "label": lab, "boxes": boxes, "paper_rgb": sep["paper_rgb"], "lines": lines, "how": how, "margin": margin_line_x(sep["rgb"], paper_id, ppm)}) del sep, alpha # 2) one offset per written line, creeping on across pages; re-anchored after blank lines and at new problems seq = [(pi, l) for pi, p in enumerate(pages) for l in p["lines"]] ppm0 = pages[0]["ppm"] pitch = gen_pitch([[{"base": l["base"]} for l in p["lines"]] for p in pages], layout, ppm0) / ppm0 # mm bases = [None if (k and seq[k - 1][0] != pi) else l["base"] / pages[pi]["ppm"] for k, (pi, l) in enumerate(seq)] resets = drift_resets(bases, pitch, [l.get("i0") for _, l in seq], (layout or {}).get("text") if plan else None) ser = drift_series(len(seq), a.drift, a.drift_amount, drift_seed(a.seed, page_key(pages[0]["meta"], files[0])), resets) s_mm = float(np.median([l["s"] / pages[pi]["ppm"] for pi, l in seq])) if seq else 5.0 area = AREA_X_MM.get(paper_id or "", (None, None)) # writing area (mm): the layout's margins, else the paper's mg = list(d.get("margins") or []) + [None] * 4 for p in pages: k, W = p["ppm"], p["size"][0] p["sd"] = s_mm * k if not p["lines"]: continue left_a = mg[3] if mg[3] is not None else area[0] right_a = (W / k - mg[1]) if mg[1] is not None else area[1] # with a margin line: never left of where the line was (can't cross it); else at most a hair left of the writing # area; on the right at most a hair past it p["lo"] = None if p["margin"] is not None else \ min(([left_a * k] if left_a is not None else []) + [q["x0"] for q in p["lines"]]) - 0.2 * p["sd"] p["hi"] = min(max(([right_a * k] if right_a is not None else []) + [q["x1"] for q in p["lines"]]) + 0.3 * p["sd"], W - 2 * k) for (pi, l), dv in zip(seq, ser): p = pages[pi] lo, hi = (l["x0"] if p["lo"] is None else p["lo"]), p["hi"] if p["lo"] is None: # a margin line: the wobble folds back to the right — clipping it at 0 would leave dv = abs(dv) # several lines at exactly the old, ruler-straight edge for bx0, by0, bx1, by1 in p["boxes"]: # a box beside the line (wrap: true): don't write into it if by0 < l["bot"] and by1 > l["top"]: if bx0 >= l["x1"] - 1: hi = min(hi, bx0) elif bx1 <= l["x0"] + 1: lo = max(lo, bx1) else: # the line runs on both sides of the box: keep it dv = 0.0 l["dx"] = clamp_drift(dv * p["sd"], l["x0"], l["x1"], lo, hi) # 3) move the ink of each page, never the paper outs, written = [], [] for p, t in zip(pages, targets): img, meta = open_image(p["path"]) rgb = np.asarray(img.convert("RGB"), np.float32) H, W = rgb.shape[:2] res_full = rgb.copy() hole = np.asarray(Image.fromarray(p["hole"].astype(np.uint8) * 255).filter(ImageFilter.MaxFilter(5)), np.uint8) > 0 if p["label"]: x0, y0, x1, y1 = p["label"] hole[y0:y1, x0:x1] = False offs = [l["dx"] for l in p["lines"]] dx = dx_field(H, p["lines"], offs) rows = np.flatnonzero(hole.any(1) & (np.abs(dx) > 1e-3)) if len(rows): r0, r1 = int(rows[0]), int(rows[-1]) + 1 sub, hs, dxs = rgb[r0:r1], hole[r0:r1], dx[r0:r1] ys, xs, est = paper_under_ink(sub, hs, p["paper_rgb"] or (255, 255, 255)) fac = np.ones_like(sub) fac[ys, xs] = np.clip(sub[ys, xs] / np.maximum(est, 1.0), 0, 1) base = sub.copy() base[ys, xs] = est # the paper with the handwriting lifted off bm = np.zeros(hs.shape, bool) for bx0, by0, bx1, by1 in p["boxes"]: # boxed answers stay exactly where they are bm[max(0, by0 - r0):max(0, by1 - r0), max(0, bx0):max(0, bx1)] = True kept = fac[bm].copy() fac[bm] = 1.0 warped = shift_rows(fac, dxs) res = base * warped res[bm] *= kept same = (bm & (warped.min(2) >= 0.999)) | (np.abs(dxs) <= 1e-3)[:, None] res[same] = sub[same] # untouched pixels stay bit-identical res_full[r0:r1] = res if p["label"]: # the label goes back unchanged x0, y0, x1, y1 = p["label"] res_full[y0:y1, x0:x1] = rgb[y0:y1, x0:x1] mm = [round(float(v / p["ppm"]), 2) for v in offs] mark = {"by": "compose.py drift", "mode": a.drift, "amount": a.drift_amount, "seed": a.seed, "offsets_mm": mm} dpi = float(meta["dpi"][0]) if meta.get("dpi") else p["ppm"] * 25.4 save_image(Image.fromarray(np.clip(res_full, 0, 255).round().astype(np.uint8), "RGB"), t, {**meta, "drift": mark} if any(mm) else meta, dpi=dpi) # nothing moved: not marked as drifted written.append(t) outs.append({"page": str(p["path"]), "out": str(t), "rows_from": p["how"], "lines": len(p["lines"]), "offsets_mm": mm, "boxed_items_kept": len(p["boxes"]), "margin_line": p["margin"] is not None, "visible_label": bool(p["label"]), "aigc_metadata": bool(meta.get("aigc"))}) for l in p["lines"]: # the plan follows the ink for it in l.get("items", []): it["x"] = round(it["x"] + l["dx"] / p["ppm"], 3) pdf_out = None if not single and a.job: jd = Path(a.job) for name in ("layout.json", "job.json", "text.txt"): if (jd / name).exists() and (jd / name).resolve() != (out / name).resolve(): shutil.copy(jd / name, out / name) if plan: plan["drift"] = {"by": "compose.py drift", "mode": a.drift, "amount": a.drift_amount, "seed": a.seed} (out / "plan.json").write_text(json.dumps(plan, ensure_ascii=False), encoding="utf-8") if (jd / "inko.pdf").exists(): pdf_out = out / "inko.pdf" pages_pdf(written, pdf_out) if not seq: note("found no lines of body text to move (everything in boxes, or no handwriting) — the pages are unchanged") emit({"outputs": outs, "pdf": str(pdf_out) if pdf_out else None, "mode": a.drift, "amount": a.drift_amount, "seed": a.seed, "reanchored_lines": [k + 1 for k in resets], "help": "offsets_mm: how far each written line (top to bottom) was moved right; only the handwriting moved — " "ruled lines, margin line, boxed answers and the label are untouched", "next": "Look at the pages (zoom into the left edges and where strokes cross ruled lines) before handing them over. " "Less: --drift-amount 0.5 · another pattern: --seed N · wobble without creeping: --drift random."}) def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sp = ap.add_subparsers(dest="cmd", required=True) s = sp.add_parser("drift", help="uneven, natural left edges on Inko pages handed over as they are (only the ink moves)") s.add_argument("pages", nargs="*", help="page PNGs (or use --job)") s.add_argument("--job", help="folder from inko.py generate (page-*.png + plan.json / layout.json, inko.pdf)") s.add_argument("--plan", help="plan JSON (if not in the job folder): exact lines, boxed answers stay put") s.add_argument("--layout", help="the layout JSON used to generate (if not in the job folder)") s.add_argument("-o", "--out", required=True, help="output folder (same file names; plus inko.pdf / plan.json for a job), " "or a .png file for a single page") s.add_argument("--drift", default="natural", choices=["natural", "random"], help="natural (default): creep right line by line, re-anchored at a new problem | random: small wobble") s.add_argument("--drift-amount", type=float, default=1.0, help="scale of the drift (0.5 = half)") s.add_argument("--seed", type=int, default=7, help="another number = another pattern (mixed with the job's id)") s.add_argument("--force", action="store_true", help="drift pages that were drifted before / overwrite the input") a = ap.parse_args() cmd_drift(a) if __name__ == "__main__": main()inko-handwriting/scripts/ink.py17 KB9bcd41ff4499upstream ↗
#!/usr/bin/env python3 """Ink tools for Inko pages — all local, instant and free (no API call). python ink.py extract page-1.png -o ink.png Separate the handwriting from the paper: transparent RGBA layer, ruled lines / grid / paper colour removed. The corner label 「AI生成 · Inko」 stays in the layer (and is remembered in the file for later scripts). python ink.py restyle page-1.png -o page-1-blue.png --color blue --texture ballpoint --weight 0.4 Change ink colour, stroke weight, darkness and pen texture of a page (keeps its paper) or of an ink layer. python ink.py info page-1.png What is in the image: page or layer, paper colour, ink colour, stroke width, label position. Prefer the API's `pen` options when generating (they are applied at full quality before the label is drawn); use restyle for quick after-the-fact tweaks, previews of alternatives, or colours the API doesn't offer. """ from __future__ import annotations import sys sys.dont_write_bytecode = True # run from the skill folder without leaving __pycache__ in it import argparse import numpy as np from _common import (Image, ImageFilter, die, emit, find_label_bbox, gaussian, label_crop, label_from_b64, label_to_b64, luminance, open_image, px_per_mm_of, save_image, value_noise) INK_COLORS = { "black": (24, 24, 28), "blue": (30, 62, 168), "blueblack": (30, 40, 78), "red": (196, 34, 42), "green": (28, 112, 64), "purple": (92, 42, 128), "brown": (96, 58, 32), "pencil": (74, 74, 80), "gray": (90, 90, 96), } TEXTURES = ("none", "gel", "ballpoint", "fountain", "pencil", "marker") # ── separation ────────────────────────────────────────────────────────────── def _structure_mask(rgb: np.ndarray, lum: np.ndarray, paper_l: float) -> tuple[np.ndarray, float]: """The paper's own printing (ruled lines, grid, margin line, header text) -> (mask, typical line luminance).""" chroma = rgb.max(2) - rgb.min(2) light = (lum < paper_l - 6) & (lum > 100) lines = np.zeros_like(light) rows = light.mean(1) > 0.25 # long horizontal lines cols = light.mean(0) > 0.25 # long vertical lines (grid, margin) if rows.any(): lines[rows, :] |= light[rows, :] if cols.any(): lines[:, cols] |= light[:, cols] mask = lines.copy() line_l = float(np.median(lum[lines])) if lines.sum() > 500 else paper_l - 70 if lines.sum() > 500: # printed text in the line colour (e.g. "No.__ Date__") med = np.median(rgb[lines & (chroma > 8)], axis=0) if (lines & (chroma > 8)).sum() > 200 else None if med is not None: mask |= (np.abs(rgb - med).max(2) < 30) & (chroma > 8) d0 = med - med.mean() # same hue as the lines, any lightness (anti-aliased header text) dv = rgb - rgb.mean(2, keepdims=True) cos = (dv @ d0) / (np.linalg.norm(dv, axis=2) * np.linalg.norm(d0) + 1e-6) mask |= (cos > 0.95) & (chroma > 6) & (lum > line_l - 30) hue_red = rgb[..., 0] - np.maximum(rgb[..., 1], rgb[..., 2]) mask |= (hue_red > 18) & (hue_red > 0.28 * (255 - rgb.min(2))) # red/pink margin lines, letterhead (Inko never writes red) return mask, line_l def separate(img: Image.Image) -> dict: """page image -> {alpha (0..1), ink_rgb, paper_rgb, label_bbox, is_layer}""" if img.mode in ("RGBA", "LA") and np.asarray(img.getchannel("A")).min() < 250: rgba = np.asarray(img.convert("RGBA"), np.float32) alpha = rgba[..., 3] / 255.0 core = alpha > 0.8 ink = np.median(rgba[core][:, :3], axis=0) if core.any() else np.array([24, 24, 28], np.float32) return {"alpha": alpha, "ink_rgb": tuple(int(v) for v in ink), "paper_rgb": None, "label_bbox": None, "is_layer": True, "rgb": rgba[..., :3]} rgb = np.asarray(img.convert("RGB"), np.float32) lum = luminance(rgb) label = find_label_bbox(np.asarray(img.convert("RGB"))) body = np.ones(lum.shape, bool) # statistics ignore the gray AI label if label: x0, y0, x1, y1 = label body[y0:y1, x0:x1] = False bright = (lum >= np.percentile(lum[body], 55)) & body # >=: a clean page is mostly one exact paper colour paper = np.median(rgb[bright], axis=0) paper_l = float(paper @ np.array([0.299, 0.587, 0.114])) dark = (lum < paper_l - 60) & body ink_l = float(np.percentile(lum[dark], 8)) if dark.sum() > 200 else 40.0 ink_l = min(ink_l, paper_l - 80) alpha = np.clip((paper_l - lum) / max(20.0, paper_l - ink_l), 0, 1) struct, line_l = _structure_mask(rgb, lum, paper_l) alpha[struct & (lum > min(line_l, paper_l - 40) - 26)] = 0 # printed lines go; ink that crosses them is darker and stays alpha[alpha < 0.04] = 0 core = (alpha > 0.85) & body ink = np.median(rgb[core], axis=0) if core.sum() > 50 else np.array([24, 24, 28], np.float32) return {"alpha": alpha.astype(np.float32), "ink_rgb": tuple(int(v) for v in ink), "paper_rgb": tuple(int(v) for v in paper), "label_bbox": label, "is_layer": False, "rgb": rgb, "body": body} def body_mask(sep: dict, meta: dict | None = None) -> np.ndarray: """Pixels that are handwriting territory (everything except the AI label box).""" m = sep.get("body") if m is not None: return m m = np.ones(sep["alpha"].shape, bool) lab = sep.get("label_bbox") or ((meta or {}).get("ink") or {}).get("label_bbox") if lab: x0, y0, x1, y1 = lab m[y0:y1, x0:x1] = False return m def stroke_width_px(alpha: np.ndarray) -> float: """Rough median stroke width: ink area / skeleton-ish length (edge count / 2).""" m = alpha > 0.5 if m.sum() < 100: return 0.0 edges = (m[:, 1:] != m[:, :-1]).sum() + (m[1:, :] != m[:-1, :]).sum() return float(2 * m.sum() / max(1, edges)) def clean_paper(rgb: np.ndarray, alpha: np.ndarray, width_px: float) -> np.ndarray: """Paper with the handwriting removed (fills stroke pixels from their surroundings).""" size = int(max(3, min(15, round(width_px * 2 + 3)))) | 1 out = rgb.copy() hole = alpha > 0.03 if not hole.any(): return out im = Image.fromarray(np.clip(rgb, 0, 255).astype(np.uint8), "RGB") filled = np.asarray(im.filter(ImageFilter.MaxFilter(size)), np.float32) # brightest neighbour = paper grow = np.asarray(Image.fromarray((hole * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(3)), np.uint8) > 0 out[grow] = filled[grow] return out # ── restyling ─────────────────────────────────────────────────────────────── def _dilate(a: np.ndarray, px: int) -> np.ndarray: if px <= 0: return a im = Image.fromarray((a * 255).astype(np.uint8), "L").filter(ImageFilter.MaxFilter(2 * px + 1)) return np.asarray(im, np.float32) / 255.0 def _erode(a: np.ndarray, px: int) -> np.ndarray: if px <= 0: return a im = Image.fromarray((a * 255).astype(np.uint8), "L").filter(ImageFilter.MinFilter(2 * px + 1)) return np.asarray(im, np.float32) / 255.0 def adjust_weight(alpha: np.ndarray, delta_px: float) -> np.ndarray: """Grow (delta > 0) or shrink strokes by delta pixels per side, fractional amounts blended.""" if abs(delta_px) < 0.05: return alpha n = int(abs(delta_px)) frac = abs(delta_px) - n op = _dilate if delta_px > 0 else _erode a0 = op(alpha, n) if n else alpha a1 = op(alpha, n + 1) out = a0 * (1 - frac) + a1 * frac return gaussian(out, 0.45) if delta_px > 0 else out def adjust_darkness(alpha: np.ndarray, d: float) -> np.ndarray: if abs(d) < 0.01: return alpha if d > 0: return 1 - (1 - alpha) ** (1 + 1.6 * d) return (alpha ** (1 + 1.1 * -d)) * (1 - 0.3 * -d) def apply_texture(alpha: np.ndarray, kind: str, ppm: float, seed: int) -> tuple[np.ndarray, np.ndarray | None]: """-> (alpha, per-pixel colour multiplier or None)""" rng = np.random.default_rng(seed) H, W = alpha.shape if kind in ("none", "", None): return alpha, None if kind == "gel": a = np.clip(alpha * 1.18, 0, 1) return np.where(alpha > 0.05, np.maximum(a, alpha), alpha), None if kind == "ballpoint": low = value_noise(H, W, 2.6 * ppm, rng) fine = value_noise(H, W, 0.22 * ppm, rng) skip = np.clip((fine - 0.55) * 3, 0, 1) a = alpha * (0.80 + 0.14 * low) * (1 - 0.42 * skip) return np.clip(a, 0, 1), (1.0 + 0.10 * low)[..., None] if kind == "fountain": b = gaussian(alpha, 0.10 * ppm) edge = np.clip(alpha - gaussian(alpha, 0.14 * ppm), 0, 1) a = np.clip(np.maximum(alpha, 0.45 * b) + 0.55 * edge, 0, 1) low = value_noise(H, W, 4 * ppm, rng) return a, (1.0 + 0.12 * low)[..., None] if kind == "pencil": grain = (value_noise(H, W, 0.11 * ppm, rng) + 1) / 2 streak = (value_noise(H, W, 0.35 * ppm, rng) + 1) / 2 a = gaussian(alpha, 0.03 * ppm) * (0.30 + 0.50 * grain + 0.20 * streak) * 0.92 return np.clip(a, 0, 1), None if kind == "marker": a = np.clip(adjust_weight(alpha, 0.18 * ppm) * 1.3, 0, 1) return a, None die(f"unknown texture '{kind}' (use one of {', '.join(TEXTURES)})") return alpha, None def parse_color(s: str | None, default) -> tuple[int, int, int]: if not s: return tuple(int(v) for v in default) s = s.strip().lower() if s in INK_COLORS: return INK_COLORS[s] if s.startswith("#") and len(s) == 7: return tuple(int(s[i:i + 2], 16) for i in (1, 3, 5)) # type: ignore[return-value] die(f"colour '{s}' not understood: use {', '.join(INK_COLORS)} or #RRGGBB") return (0, 0, 0) def composite(paper_rgb: np.ndarray, alpha: np.ndarray, ink_rgb, mult: np.ndarray | None = None) -> np.ndarray: """Ink sits 'in' the paper: multiply blend (paper texture and lines show through faintly).""" ink = np.array(ink_rgb, np.float32)[None, None, :] if mult is not None: ink = np.clip(ink * mult, 0, 255) a = alpha[..., None] return np.clip(paper_rgb * (1 - a + a * ink / 255.0), 0, 255) # ── commands ──────────────────────────────────────────────────────────────── def layer_image(alpha: np.ndarray, ink_rgb, mult: np.ndarray | None = None) -> Image.Image: H, W = alpha.shape out = np.zeros((H, W, 4), np.float32) col = np.array(ink_rgb, np.float32)[None, None, :] * (mult if mult is not None else 1.0) out[..., :3] = np.clip(col, 0, 255) out[..., 3] = np.clip(alpha, 0, 1) * 255 return Image.fromarray(out.round().astype(np.uint8), "RGBA") def cmd_extract(a) -> None: img, meta = open_image(a.input) sep = separate(img) if sep["is_layer"]: die("input already is a transparent ink layer") alpha = sep["alpha"] lab = sep["label_bbox"] label_b64 = None if lab: crop = label_crop(np.asarray(img.convert("RGB")), lab) label_b64 = label_to_b64(crop) ppm = px_per_mm_of(img, meta) out = layer_image(alpha, sep["ink_rgb"]) if lab: # label stays visible in the layer, in its own gray x0, y0, x1, y1 = lab arr = np.asarray(out).copy() arr[y0:y1, x0:x1] = np.asarray(label_from_b64(label_b64)) out = Image.fromarray(arr, "RGBA") body = body_mask(sep) ys, xs = np.nonzero((alpha > 0.3) & body) bbox = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1] if len(xs) else None meta = dict(meta) meta["label_png"] = label_b64 or meta.get("label_png") meta["ink"] = {"px_per_mm": ppm, "ink_rgb": sep["ink_rgb"], "paper_rgb": sep["paper_rgb"], "label_bbox": lab, "ink_bbox": bbox, "stroke_px": round(stroke_width_px(alpha * body), 2), "source": str(a.input), "size": list(img.size)} save_image(out, a.out, meta, dpi=ppm * 25.4) emit({"out": a.out, "ink_rgb": sep["ink_rgb"], "paper_rgb": sep["paper_rgb"], "label": bool(lab), "label_bbox": lab, "ink_bbox_px": bbox, "px_per_mm": round(ppm, 3), "stroke_px": meta["ink"]["stroke_px"]}) def cmd_restyle(a) -> None: img, meta = open_image(a.input) sep = separate(img) alpha = sep["alpha"].copy() ppm = px_per_mm_of(img, meta) lab = sep["label_bbox"] or ((meta.get("ink") or {}).get("label_bbox")) keep = None if lab: # never restyle the AI label: cut it out, paste it back unchanged x0, y0, x1, y1 = lab keep = (alpha[y0:y1, x0:x1].copy(), sep["rgb"][y0:y1, x0:x1].copy()) alpha[y0:y1, x0:x1] = 0 base_ink = sep["ink_rgb"] width = stroke_width_px(alpha) delta = a.weight_mm * ppm if a.weight_mm else a.weight * 0.09 * ppm # ±1 ≈ ±0.09 mm per side, like the API if delta: alpha = adjust_weight(alpha, delta) alpha = adjust_darkness(alpha, a.darkness) color = parse_color(a.color, INK_COLORS["pencil"] if a.texture == "pencil" and not a.color else base_ink) alpha, mult = apply_texture(alpha, a.texture, ppm, a.seed) if a.bleed: alpha = np.clip(np.maximum(alpha, 0.55 * gaussian(alpha, a.bleed * 0.25 * ppm)), 0, 1) if a.opacity != 1.0: alpha = alpha * a.opacity if sep["is_layer"]: out = layer_image(alpha, color, mult) if keep is not None: arr = np.asarray(out).copy() x0, y0, x1, y1 = lab arr[y0:y1, x0:x1, :3] = 128 arr[y0:y1, x0:x1, 3] = (keep[0] * 255).astype(np.uint8) out = Image.fromarray(arr, "RGBA") else: paper = clean_paper(sep["rgb"], sep["alpha"], width) res = composite(paper, alpha, color, mult) if keep is not None: x0, y0, x1, y1 = lab res[y0:y1, x0:x1] = keep[1] out = Image.fromarray(res.round().astype(np.uint8), "RGB") save_image(out, a.out, meta, dpi=ppm * 25.4, quality=a.quality) emit({"out": a.out, "color": color, "texture": a.texture, "weight": a.weight, "darkness": a.darkness, "bleed": a.bleed, "kept_label": bool(lab)}) def cmd_info(a) -> None: img, meta = open_image(a.input) sep = separate(img) ppm = px_per_mm_of(img, meta) body = body_mask(sep, meta) alpha = sep["alpha"] * body ys, xs = np.nonzero(alpha > 0.3) emit({"size_px": list(img.size), "px_per_mm": round(ppm, 3), "kind": "ink layer" if sep["is_layer"] else "page", "paper_rgb": sep["paper_rgb"], "ink_rgb": sep["ink_rgb"], "stroke_px": round(stroke_width_px(alpha), 2), "stroke_mm": round(stroke_width_px(alpha) / ppm, 3), "label_bbox": sep["label_bbox"] or (meta.get("ink") or {}).get("label_bbox"), "ink_bbox_px": [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1] if len(xs) else None, "aigc_metadata": bool(meta.get("aigc"))}) def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sp = ap.add_subparsers(dest="cmd", required=True) s = sp.add_parser("extract", help="page -> transparent ink layer") s.add_argument("input") s.add_argument("-o", "--out", required=True, help="output .png (transparent)") s = sp.add_parser("restyle", help="change colour / weight / darkness / texture") s.add_argument("input") s.add_argument("-o", "--out", required=True) s.add_argument("--color", help=f"{', '.join(INK_COLORS)} or #RRGGBB (default: keep)") s.add_argument("--weight", type=float, default=0.0, help="-1..1 like the API's pen.weight (±1 ≈ ±0.09 mm per side); larger values allowed") s.add_argument("--weight-mm", type=float, help="grow/shrink strokes by this many mm per side instead") s.add_argument("--darkness", type=float, default=0.0, help="-1..1") s.add_argument("--texture", default="none", choices=TEXTURES) s.add_argument("--bleed", type=float, default=0.0, help="0..1 ink soaking into cheap paper") s.add_argument("--opacity", type=float, default=1.0) s.add_argument("--seed", type=int, default=7) s.add_argument("--quality", type=int, default=92, help="JPEG/WebP quality if the output is .jpg/.webp") s = sp.add_parser("info") s.add_argument("input") a = ap.parse_args() {"extract": cmd_extract, "restyle": cmd_restyle, "info": cmd_info}[a.cmd](a) if __name__ == "__main__": main()inko-handwriting/scripts/inko.py87 KBfc8126052067upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/scripts/paper.py8.6 KBc9542a74ec0cupstream ↗
#!/usr/bin/env python3 """Draw standard flat paper backgrounds (blank, ruled, grid, dots, tian, compo). No image input or camera effects. python paper.py make -o paper.png --kind ruled --size A4 """ from __future__ import annotations import sys sys.dont_write_bytecode = True import argparse import json from pathlib import Path import numpy as np from _common import Image, ImageDraw, emit, note, parse_size_mm, save_image def suggest_layout(pitch_mm: float, width_mm: float, n_free: int) -> dict: """Suggest an A4 layout with writing proportions derived from the flat paper.""" k = min(1.0, 186.0 / max(1.0, width_mm)) # keep the line inside an A4 frame p = pitch_mm * k size = round(0.62 * p, 2) # Inko's own ruled papers write at 0.62 x line spacing w = round(width_mm * k, 1) cpl = int(w // (size * 1.06)) return {"paperId": "blank", "d": {"size": size, "line": round(p / size, 4), "margins": [22, round(210 - 20 - w, 1), 26, 20], "indent": 2}, "scale": round(k, 4), "chars_per_line_est": cpl, "lines_per_generated_page": int((297 - 22 - 26) // p), "free_lines": n_free, "capacity_chars_est": cpl * n_free} LINE_COLORS = {"blue": (152, 179, 211), "gray": (175, 175, 178), "green": (108, 159, 128), "red": (207, 138, 128), "black": (90, 90, 90)} PAPER_COLORS = {"white": (253, 253, 250), "cream": (250, 245, 232), "yellow": (252, 244, 205), "kraft": (214, 190, 150), "gray": (236, 236, 234)} def make_paper(kind: str, size_mm: tuple, dpi: float, pitch: float, color: str, paper: str, margin_line: float | None, top: float, bottom: float, side: float) -> tuple[Image.Image, dict]: ppm = dpi / 25.4 W, H = round(size_mm[0] * ppm), round(size_mm[1] * ppm) im = Image.new("RGB", (W, H), PAPER_COLORS.get(paper, PAPER_COLORS["white"])) d = ImageDraw.Draw(im) c = LINE_COLORS.get(color, LINE_COLORS["blue"]) lw = max(1, round(0.22 * ppm)) info: dict = {"kind": kind, "size_mm": list(size_mm), "dpi": dpi, "pitch_mm": pitch} if kind == "ruled": ys, y = [], top + pitch while y <= size_mm[1] - bottom + 1e-6: d.line([(side * ppm, y * ppm), ((size_mm[0] - side) * ppm, y * ppm)], fill=c, width=lw) ys.append(round(y, 3)) y += pitch if margin_line: d.line([(margin_line * ppm, (top - 2) * ppm), (margin_line * ppm, (size_mm[1] - bottom + 4) * ppm)], fill=(227, 164, 155), width=max(1, round(0.35 * ppm))) info["lines_mm"] = ys elif kind in ("grid", "dots"): xs = list(np.arange(side, size_mm[0] - side + 1e-6, pitch)) ys = list(np.arange(top, size_mm[1] - bottom + 1e-6, pitch)) for x in xs: if kind == "grid": d.line([(x * ppm, top * ppm), (x * ppm, ys[-1] * ppm)], fill=c, width=max(1, lw // 2 + 1)) for y in ys: if kind == "grid": d.line([(side * ppm, y * ppm), (xs[-1] * ppm, y * ppm)], fill=c, width=max(1, lw // 2 + 1)) else: r = max(1, round(0.25 * ppm)) for x in xs: d.ellipse([x * ppm - r, y * ppm - r, x * ppm + r, y * ppm + r], fill=c) info["lines_mm"] = [round(float(y), 3) for y in ys] elif kind in ("tian", "compo"): cell, gap = pitch, (0 if kind == "tian" else pitch / 3) cols = int((size_mm[0] - 2 * side) // cell) x0 = (size_mm[0] - cols * cell) / 2 y, rows = top, [] while y + cell <= size_mm[1] - bottom + 1e-6: d.rectangle([x0 * ppm, y * ppm, (x0 + cols * cell) * ppm, (y + cell) * ppm], outline=c, width=lw) for q in range(1, cols): d.line([((x0 + q * cell) * ppm, y * ppm), ((x0 + q * cell) * ppm, (y + cell) * ppm)], fill=c, width=lw) if kind == "tian": dash = 0.9 * ppm for q in range(cols): cx, cy = (x0 + q * cell + cell / 2) * ppm, (y + cell / 2) * ppm for t in np.arange(0, cell * ppm, 2 * dash): d.line([(cx, y * ppm + t), (cx, y * ppm + min(cell * ppm, t + dash))], fill=c, width=1) d.line([((x0 + q * cell) * ppm + t, cy), ((x0 + q * cell) * ppm + min(cell * ppm, t + dash), cy)], fill=c, width=1) rows.append(round(y, 3)) y += cell + gap info["cells"] = {"x0_mm": round(x0, 3), "cols": cols, "cell_mm": cell, "gap_mm": round(gap, 3), "rows_top_mm": rows} return im, info def paper_json_for_made(info: dict, size_mm: tuple, dpi: float, margin_line: float | None, side: float, out: str, row_step: int = 1) -> dict: """Exact paper.json for a ruled or grid paper drawn by `make` (no detection needed). On grid paper a line of text uses row_step squares (2 = one line per two 5 mm squares) and sits on a grid line.""" ppm = dpi / 25.4 W, H = round(size_mm[0] * ppm), round(size_mm[1] * ppm) info = dict(info) if info["kind"] == "grid" and row_step > 1: info["lines_mm"] = info["lines_mm"][row_step::row_step] p = info["pitch_mm"] * (row_step if info["kind"] == "grid" else 1) x0, x1 = side * ppm, (size_mm[0] - side) * ppm wx0 = (margin_line + 0.3 * p) * ppm if margin_line else x0 + max(0.3 * p, 8 - side) * ppm wx1 = x1 - max(0.3 * p, 8 - side) * ppm lines = [{"i": i + 1, "y": round(y * ppm, 1), "poly": [y * ppm, 0.0, 0.0], "x0": round(x0, 1), "x1": round(x1, 1), "write_x0": round(wx0, 1), "write_x1": round(wx1, 1), "written": False, "written_x1": None, "inferred": False, "regular": True, "strength": 1.0} for i, y in enumerate(info.get("lines_mm", []))] res = {"source": str(Path(out).resolve()), "analyzed_image": str(Path(out).resolve()), "image_px": [W, H], "kind": info["kind"], "tilt_deg": 0.0, "pitch_px": round(p * ppm, 3), "px_per_mm": round(ppm, 4), "scale_from": "exact (made by paper.py)", "pitch_mm": p, "margin_line_x_px": round(margin_line * ppm, 1) if margin_line else None, "right_margin_line_x_px": None, "write_x0_px": round(wx0, 1), "write_x1_px": round(wx1, 1), "write_width_mm": round((wx1 - wx0) / ppm, 1), "lines": lines, "free_lines": [l["i"] for l in lines], "written_lines": [], "first_free_line": 1 if lines else None} if lines: res["suggested_layout"] = suggest_layout(p, res["write_width_mm"], len(lines)) return res def cmd_make(a) -> None: size = parse_size_mm(a.size) if a.landscape: size = (size[1], size[0]) im, info = make_paper(a.kind, size, a.dpi, a.pitch, a.color, a.paper, a.margin_line, a.top, a.bottom, a.side) save_image(im, a.out, None, dpi=a.dpi) out = {"out": a.out, **{k: v for k, v in info.items() if k != "lines_mm"}, "lines": len(info.get("lines_mm", []))} if a.json: if a.kind not in ("ruled", "grid"): note("--json is only written for ruled and grid paper; the requested PNG was saved") else: pj = paper_json_for_made(info, size, a.dpi, a.margin_line, a.side, a.out, a.row_step if a.kind == "grid" else 1) Path(a.json).write_text(json.dumps(pj, ensure_ascii=False, indent=1), encoding="utf-8") out.update({"json": a.json, "suggested_layout": pj.get("suggested_layout")}) emit(out) def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sp = ap.add_subparsers(dest="cmd", required=True) s = sp.add_parser("make") s.add_argument("-o", "--out", required=True) s.add_argument("--kind", default="ruled", choices=["ruled", "grid", "dots", "blank", "tian", "compo"]) s.add_argument("--size", default="A4") s.add_argument("--landscape", action="store_true") s.add_argument("--pitch", type=float, default=8.0, help="line spacing / grid cell in mm") s.add_argument("--color", default="blue", choices=list(LINE_COLORS)) s.add_argument("--paper", default="white", choices=list(PAPER_COLORS)) s.add_argument("--margin-line", type=float, help="red vertical margin line at this x (mm)") s.add_argument("--top", type=float, default=20) s.add_argument("--bottom", type=float, default=25, help="bottom margin (mm) — keeps the corner free for the AI label") s.add_argument("--side", type=float, default=10) s.add_argument("--dpi", type=float, default=300) s.add_argument("--json", help="also write the paper geometry JSON (ruled and grid paper)") s.add_argument("--row-step", type=int, default=2, help="grid paper: squares per line of text in the paper.json (default 2)") a = ap.parse_args() cmd_make(a) if __name__ == "__main__": main()inko-handwriting/scripts/pdf.py7.6 KB526dd9151e15upstream ↗
#!/usr/bin/env python3 """Images -> one PDF at real paper size, keeping Inko's AI-generation labels. python pdf.py page-1.png page-2.png -o homework.pdf python pdf.py final.jpg final-2.jpg -o notes.pdf --size B5 --margin 0 python pdf.py page.jpg -o pages.pdf --size auto --jpeg 85 Page size: "auto" (default) uses the image's dpi (Inko pages: A4 at 300 dpi) and falls back to A4 in the image's orientation; or A4 / A5 / B5 / Letter / 16K … / WxH in mm. Images are fitted inside the page (never cropped, so the visible label 「AI生成 · Inko」 stays whole). The implicit label goes into the PDF's Info (/AIGC) and XMP metadata. Inko's own `inko.pdf` (from `inko.py generate`) is already a finished PDF — use this for edited flat-page images. """ from __future__ import annotations import sys sys.dont_write_bytecode = True # run from the skill folder without leaving __pycache__ in it import argparse import io import json import time import uuid import zlib from pathlib import Path from _common import PRODUCER, SKILL_TAG, Image, die, emit, open_image, parse_size_mm, xmp_packet PT_PER_MM = 72 / 25.4 def _pdf_str(s: str) -> bytes: """PDF text string: plain ASCII in (), anything else as UTF-16BE hex with BOM.""" if all(32 <= ord(c) < 127 for c in s): return b"(" + s.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)").encode("ascii") + b")" return b"<FEFF" + s.encode("utf-16-be").hex().upper().encode("ascii") + b">" def encode_image(img: Image.Image, jpeg_q: int, lossless: bool) -> tuple[bytes, dict]: gray = img.mode in ("L", "LA", "1") or (img.mode == "RGB" and _is_gray(img)) im = img.convert("L" if gray else "RGB") if img.mode in ("RGBA", "LA", "P"): # flatten transparency onto white bg = Image.new("RGB", img.size, (255, 255, 255)) bg.paste(img.convert("RGBA"), mask=img.convert("RGBA").getchannel("A")) im = bg.convert("L" if gray else "RGB") cs = b"/DeviceGray" if gray else b"/DeviceRGB" if lossless: data = zlib.compress(im.tobytes(), 6) return data, {"filter": b"/FlateDecode", "cs": cs, "w": im.width, "h": im.height} buf = io.BytesIO() im.save(buf, "JPEG", quality=jpeg_q, subsampling=0 if jpeg_q >= 90 else 2, optimize=True) return buf.getvalue(), {"filter": b"/DCTDecode", "cs": cs, "w": im.width, "h": im.height} def _is_gray(img: Image.Image) -> bool: small = img.convert("RGB").resize((min(256, img.width), min(256, img.height))) px = small.getdata() return all(max(p) - min(p) <= 3 for p in px) def page_size_pt(img: Image.Image, meta: dict, size: str) -> tuple[float, float]: if size.lower() == "auto": dpi = meta.get("dpi") or img.info.get("dpi") if dpi and float(dpi[0]) > 50: w, h = img.width / float(dpi[0]) * 72, img.height / float(dpi[1] if len(dpi) > 1 else dpi[0]) * 72 if 60 * PT_PER_MM <= max(w, h) <= 450 * PT_PER_MM: # a real sheet size (not a 72-dpi camera default) return w, h w, h = 210.0, 297.0 if img.width > img.height: w, h = h, w return w * PT_PER_MM, h * PT_PER_MM w, h = parse_size_mm(size) if (img.width > img.height) != (w > h): # follow the image's orientation w, h = h, w return w * PT_PER_MM, h * PT_PER_MM def write_pdf(pages: list[tuple[bytes, dict, tuple[float, float], tuple[float, float, float, float]]], out: Path, info: dict, xmp: str | None) -> None: objs: list[bytes] = [] def add(b: bytes) -> int: objs.append(b) return len(objs) cat_id = add(b"") # placeholders, filled below pages_id = add(b"") kids = [] for data, im, (pw, ph), (x, y, w, h) in pages: img_id = add(b"<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace %s /BitsPerComponent 8 /Filter %s /Length %d >>\nstream\n" % (im["w"], im["h"], im["cs"], im["filter"], len(data)) + data + b"\nendstream") content = b"q %.3f 0 0 %.3f %.3f %.3f cm /Im0 Do Q" % (w, h, x, y) c_id = add(b"<< /Length %d >>\nstream\n" % len(content) + content + b"\nendstream") kids.append(add(b"<< /Type /Page /Parent %d 0 R /MediaBox [0 0 %.3f %.3f] /Resources << /XObject << /Im0 %d 0 R >> >> /Contents %d 0 R >>" % (pages_id, pw, ph, img_id, c_id))) meta_id = None if xmp: xb = xmp.encode("utf-8") meta_id = add(b"<< /Type /Metadata /Subtype /XML /Length %d >>\nstream\n" % len(xb) + xb + b"\nendstream") objs[pages_id - 1] = b"<< /Type /Pages /Kids [" + b" ".join(b"%d 0 R" % k for k in kids) + b"] /Count %d >>" % len(kids) objs[cat_id - 1] = b"<< /Type /Catalog /Pages %d 0 R" % pages_id + (b" /Metadata %d 0 R" % meta_id if meta_id else b"") + b" >>" info_id = add(b"<< " + b" ".join(b"/" + k.encode("ascii") + b" " + _pdf_str(v) for k, v in info.items()) + b" >>") buf = io.BytesIO() buf.write(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n") offs = [] for i, o in enumerate(objs, 1): offs.append(buf.tell()) buf.write(b"%d 0 obj\n" % i + o + b"\nendobj\n") xref = buf.tell() buf.write(b"xref\n0 %d\n0000000000 65535 f \n" % (len(objs) + 1)) for off in offs: buf.write(b"%010d 00000 n \n" % off) fid = uuid.uuid4().hex.upper().encode("ascii") buf.write(b"trailer\n<< /Size %d /Root %d 0 R /Info %d 0 R /ID [<%s> <%s>] >>\nstartxref\n%d\n%%%%EOF\n" % (len(objs) + 1, cat_id, info_id, fid, fid, xref)) out.parent.mkdir(parents=True, exist_ok=True) out.write_bytes(buf.getvalue()) def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("images", nargs="+") ap.add_argument("-o", "--out", required=True) ap.add_argument("--size", default="auto", help="auto | A4 | A5 | B5 | Letter | 16K … | WxH (mm)") ap.add_argument("--margin", type=float, default=0.0, help="white margin around each image, mm") ap.add_argument("--fit", default="contain", choices=["contain", "stretch"]) ap.add_argument("--jpeg", type=int, default=90, help="JPEG quality for embedded images") ap.add_argument("--lossless", action="store_true", help="embed pixels losslessly (bigger file)") ap.add_argument("--title", default="") a = ap.parse_args() pages, aigc = [], None for f in a.images: img, meta = open_image(f) aigc = aigc or meta.get("aigc") pw, ph = page_size_pt(img, meta, a.size) m = a.margin * PT_PER_MM bw, bh = pw - 2 * m, ph - 2 * m if bw <= 0 or bh <= 0: die("--margin is larger than the page") if a.fit == "stretch": w, h = bw, bh else: k = min(bw / img.width, bh / img.height) w, h = img.width * k, img.height * k x, y = (pw - w) / 2, (ph - h) / 2 data, im = encode_image(img, a.jpeg, a.lossless) pages.append((data, im, (pw, ph), (x, y, w, h))) info = {"Title": a.title or Path(a.out).stem, "Creator": SKILL_TAG, "Producer": PRODUCER, "CreationDate": time.strftime("D:%Y%m%d%H%M%S")} if aigc: info["AIGC"] = json.dumps(aigc, ensure_ascii=False) info["Keywords"] = "AIGC; AI生成 · Inko" write_pdf(pages, Path(a.out), info, xmp_packet(aigc) if aigc else None) emit({"out": a.out, "pages": len(pages), "page_size_mm": [round(pages[0][2][0] / PT_PER_MM, 1), round(pages[0][2][1] / PT_PER_MM, 1)], "bytes": Path(a.out).stat().st_size, "aigc_metadata": bool(aigc)}) if __name__ == "__main__": main()inko-handwriting/scripts/preview.py8.9 KB4797cfb60063upstream ↗
#!/usr/bin/env python3 """Render a layout plan (the JSON from `inko.py layout --out plan.json` or POST /v1/layout) as a quick preview image, so the user can check where every line goes before free handwriting generation. python preview.py plan.json -o preview.png [--spec layout.json] [--scale 6] The preview uses a system font (楷体 if available), not the real handwriting — positions and sizes are exact, the glyph shapes are not. Formulas are shown as their LaTeX source in a light-blue box of the right size. """ from __future__ import annotations import sys sys.dont_write_bytecode = True # run from the skill folder without leaving __pycache__ in it import argparse import json import math from pathlib import Path from _common import Image, ImageDraw, LABEL_TEXT, cjk_font, die, emit PAPERS = { # same geometry as the Inko paper presets (mm, origin top-left) "blank": {"w": 210, "h": 297}, "ruled8": {"w": 210, "h": 297, "rules": (34, 274, 8), "rx": (12, 198), "margin": 24, "color": (0x98, 0xb3, 0xd3), "head": True}, "ruled7": {"w": 210, "h": 297, "rules": (33, 276, 7), "rx": (12, 198), "margin": 24, "color": (0x98, 0xb3, 0xd3), "head": True}, "letter": {"w": 210, "h": 297, "rules": (52, 268, 9), "rx": (22, 188), "color": (0xe2, 0xa5, 0x9d), "letter": True}, "compo": {"w": 210, "h": 297, "grid": (15, 34, 20, 20, 9, 9, 3, False), "color": (0x6c, 0x9f, 0x80)}, "tian": {"w": 210, "h": 297, "grid": (21, 30, 12, 15, 14, 14, 2.4, True), "color": (0xcf, 0x8a, 0x80)}, } def draw_paper(pid: str, k: float) -> Image.Image: p = PAPERS.get(pid, PAPERS["blank"]) W, H = round(p["w"] * k), round(p["h"] * k) im = Image.new("RGB", (W, H), (255, 254, 251)) d = ImageDraw.Draw(im) lw = max(1, round(0.22 * k)) if "rules" in p: y0, y1, sp = p["rules"] x0, x1 = p["rx"] y = y0 while y <= y1 + 1e-6: d.line([(x0 * k, y * k), (x1 * k, y * k)], fill=p["color"], width=lw) y += sp if p.get("margin"): d.line([(p["margin"] * k, 26 * k), (p["margin"] * k, (p["h"] - 16) * k)], fill=(0xe3, 0xa4, 0x9b), width=max(1, round(0.35 * k))) # the exercise-book header exactly as on generated pages: right end at x = 192 mm, baseline y = 24 mm, 3 mm text. # Date blanks ≈ x 175.9–182.5 and 185.3–191.9 mm (a box at y 20, h 5.4, size 4 writes the date on it) d.text(((p["w"] - 18) * k, 24 * k), "No. ________ Date ____ / ____", fill=p["color"], font=cjk_font(max(6, 3 * k), kai=False), anchor="rs") if p.get("letter"): d.text((p["w"] / 2 * k, 22 * k), "Inko 信笺", fill=(0xc8, 0x45, 0x2f), font=cjk_font(max(6, 6.4 * k), kai=False), anchor="ms") d.line([(20 * k, 30 * k), ((p["w"] - 20) * k, 30 * k)], fill=(0xd6, 0x77, 0x6a), width=max(1, round(0.55 * k))) d.line([(20 * k, 31.4 * k), ((p["w"] - 20) * k, 31.4 * k)], fill=(0xd6, 0x77, 0x6a), width=max(1, round(0.2 * k))) if "grid" in p: gx, gy, cols, rows, cw, ch, gap, tian = p["grid"] for r in range(rows): top = gy + r * (ch + gap) d.rectangle([gx * k, top * k, (gx + cols * cw) * k, (top + ch) * k], outline=p["color"], width=lw) for q in range(1, cols): d.line([((gx + q * cw) * k, top * k), ((gx + q * cw) * k, (top + ch) * k)], fill=p["color"], width=lw) return im def _text_img(txt: str, size_px: float, color, kai: bool = True) -> tuple[Image.Image, int]: """Text drawn on a transparent canvas; returns (image, baseline y inside the image).""" f = cjk_font(max(6, size_px), kai=kai) try: asc, desc = f.getmetrics() except AttributeError: asc, desc = int(size_px), int(size_px * 0.25) w = max(1, int(f.getlength(txt)) + 4) if hasattr(f, "getlength") else max(1, int(size_px * len(txt)) + 4) im = Image.new("RGBA", (w, asc + desc + 4), (0, 0, 0, 0)) ImageDraw.Draw(im).text((2, asc + 2), txt, font=f, fill=color, anchor="ls") return im, asc + 2 def render(res: dict, out: str, scale: float = 6.0, spec: dict | None = None) -> list[str]: plan = res.get("plan", res) paper = plan.get("paper", {"id": "blank", "w": 210, "h": 297}) k = scale files = [] pages = plan.get("pages", []) for pi, items in enumerate(pages): im = draw_paper(paper.get("id", "blank"), k).convert("RGBA") d = ImageDraw.Draw(im) for b in (spec or {}).get("boxes", []): # the boxes you asked for (dashed outlines) if b.get("page", 0) != pi: continue col = (60, 110, 200, 255) if b.get("block") else (170, 110, 60, 255) if b.get("own") is not None else (110, 110, 110, 255) if b.get("kind") == "rect": x, y, w, h = (b[t] * k for t in ("x", "y", "w", "h")) cx, cy = x + w / 2, y + h / 2 th = math.radians(b.get("rot", 0) or 0) pts = [(cx + (px - cx) * math.cos(th) - (py - cy) * math.sin(th), cy + (px - cx) * math.sin(th) + (py - cy) * math.cos(th)) for px, py in ((x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y))] for (ax, ay), (bx, by) in zip(pts, pts[1:]): n = max(1, int(math.hypot(bx - ax, by - ay) / 8)) for t in range(0, n, 2): d.line([(ax + (bx - ax) * t / n, ay + (by - ay) * t / n), (ax + (bx - ax) * (t + 1) / n, ay + (by - ay) * (t + 1) / n)], fill=col, width=2) d.text((x + 2, y - 14), b.get("id", ""), fill=col) elif b.get("kind") == "area": for st in b.get("strokes", []): if st.get("erase"): continue r = st["r"] * k for px, py in st["pts"]: d.ellipse([px * k - r, py * k - r, px * k + r, py * k + r], fill=(col[0], col[1], col[2], 28)) elif b.get("kind") == "path": for pth in b.get("paths", []): d.line([(px * k, py * k) for px, py in pth["pts"]], fill=col, width=2) for it in items: # every character / formula at its planned place s = it["s"] * k if it.get("m"): a, dd = it["m"]["a"], it["m"]["d"] top, bot = it["y"] * k - a * s, it["y"] * k + dd * s x0 = it["x"] * k - (it["w"] * k / 2 if it.get("cx") else 0) d.rounded_rectangle([x0, top, x0 + it["w"] * k, bot], radius=3, fill=(214, 228, 250, 255), outline=(120, 150, 210, 255)) t, _ = _text_img(it["c"], max(6, (bot - top) * 0.45), (30, 60, 140, 255), kai=False) if t.width > it["w"] * k: t = t.resize((max(1, int(it["w"] * k)), max(1, int(t.height * it["w"] * k / t.width)))) im.alpha_composite(t, (int(x0 + (it["w"] * k - t.width) / 2), int((top + bot) / 2 - t.height / 2))) continue g, base = _text_img(it["c"], s * 1.05, (25, 25, 30, 255)) x = it["x"] * k - (g.width / 2 if it.get("cx") else 0) - 2 y = it["y"] * k - base if it.get("r"): # rotate about the glyph's baseline start, like the real page cx_, cy_ = 2, base g2 = g.rotate(-it["r"], expand=True, resample=Image.BICUBIC, center=(cx_, cy_)) x -= (g2.width - g.width) / 2 y -= (g2.height - g.height) / 2 g = g2 im.alpha_composite(g, (int(x), int(y))) lab, lb = _text_img(LABEL_TEXT, 0.05 * min(im.size) * 1.12, (128, 128, 128, 200), kai=False) # where the AI label will be im.alpha_composite(lab, (int(im.width - 8 * k - lab.width), int(im.height - 7 * k - lb))) p = Path(out) if pi == 0 else Path(out).with_name(f"{Path(out).stem}-{pi + 1}{Path(out).suffix}") p.parent.mkdir(parents=True, exist_ok=True) im.convert("RGB").save(p) files.append(str(p)) return files def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("plan", help="plan JSON from `inko.py layout --out`") ap.add_argument("-o", "--out", default="preview.png") ap.add_argument("--spec", help="the layout JSON you sent (draws your boxes / areas as outlines)") ap.add_argument("--scale", type=float, default=6.0, help="pixels per mm (6 ≈ 1260 x 1780 for A4)") a = ap.parse_args() try: res = json.loads(Path(a.plan).read_text(encoding="utf-8-sig")) except (OSError, ValueError) as e: die(f"cannot read plan: {e}") spec = None if a.spec: spec = json.loads(Path(a.spec).read_text(encoding="utf-8-sig")) spec = spec.get("layout", spec) emit({"files": render(res, a.out, a.scale, spec), "note": "System font stand-in: positions/sizes are exact, glyph shapes are not."}) if __name__ == "__main__": main()inko-handwriting/scripts/requirements.txt167 B014de0934301upstream ↗
# inko.py (the API client) needs only the Python standard library (3.9+). # The image scripts (preview, ink, paper, compose, scene, pdf) need: pillow>=9.1 numpy>=1.22inko-handwriting/scripts/scene.py75 KBf01f2f818f3eupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/scripts/scene_editor.html46 KB46b5f08e1a8dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/api.md8.0 KB4a9508b35ab7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/layout.md11 KBb6e2140273c3upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/postprocess.md4.7 KB33ef911995ceupstream ↗
# Post-processing reference All scripts run locally (Pillow + numpy), take a second or two per page, cost nothing, and keep the AI labels: the visible 「AI生成 · Inko」 is carried or re-applied at ≥ 5 % of the output's shortest side, the AIGC metadata is copied into PNG / JPEG / WebP / PDF outputs. Pages generated without a visible label stay without one. Contents: ink.py · compose.py drift · paper.py make · pdf.py · flat-page output ## ink.py — colour, weight, darkness, texture ```bash python scripts/ink.py info page-1.png # paper colour, ink colour, stroke width, label position python scripts/ink.py restyle page-1.png -o out.png [options] python scripts/ink.py extract page-1.png -o ink.png # transparent RGBA handwriting layer (ruled lines removed) ``` restyle options: - `--color black|blue|blueblack|red|green|purple|brown|pencil|gray|#RRGGBB` - `--texture none|gel|ballpoint|fountain|pencil|marker` — gel: solid core; ballpoint: slight skips and pressure variation; fountain: wet edges; pencil: graphite grain (default colour graphite); marker: bold and flat - `--weight -1..1` (±1 ≈ ±0.09 mm per side, like the API; larger values allowed) or `--weight-mm 0.05` - `--darkness -1..1`, `--bleed 0..1` (ink soaking into cheap paper), `--opacity`, `--seed` - Output `.jpg` / `.webp` with `--quality`. Works on a page (keeps its paper and ruled lines) or on an ink layer. The label is cut out before and pasted back unchanged after, so it never changes colour. When to prefer the API instead: the API's `pen` (`--pen-type gel|ballpoint|fountain|pencil`, `--pen-color black|blue|blueblack`, `--pen-weight`, `--pen-ink`) is applied during rendering at full quality. Use `ink.py` for colours the API lacks, for quick A/B variants, and for pages already generated. ### compose.py drift — left edges that aren't ruler-straight Optional two-dimensional line-position adjustment. The page remains front-facing and its background stays fixed. Standard pages can be delivered unchanged; use this only when the user wants looser line alignment. ```bash python scripts/compose.py drift --job inko-output/<run> -o drifted [--drift natural|random] [--drift-amount 1] [--seed N] ``` `-o` is a folder (the pages keep their names; `plan.json`, `layout.json` and a rebuilt `inko.pdf` come along), or a `.png` for a single page; the JSON `outputs` list each written page and its `offsets_mm`. - `natural` (default): a slow creep to the right plus a little wobble, like a hand moving down the page, easing back at a new problem or after a blank line; `random`: the small wobble without the creep. `--drift-amount` scales it (0.6 subtler, 1.4 stronger); `--seed` gives another variation. - It moves only the ink, line by line (rows from `plan.json`, else found on the page); the paper, ruled lines, margin line and answers in boxes stay where they are. The label and AIGC metadata are kept; if the job had a PDF, a new one is written from the drifted pages. - Use it on pages delivered as they are — homework, notes, letters, anything with several left-aligned lines — before `ink.py`. It refuses 作文纸 / 田字格 (characters belong in their cells) and a page it has already drifted (`--force` overrides the latter). - Look at the result: the text must still clear the margin line and the right edge. ## paper.py make — papers Inko doesn't have ```bash python scripts/paper.py make -o b5.png --kind ruled --size B5 --pitch 8 --margin-line 20 --paper cream --color blue --json b5.json python scripts/paper.py make -o grid.png --kind grid --size A5 --pitch 5 --color green python scripts/paper.py make -o dots.png --kind dots --size A4 --pitch 5 ``` Kinds `ruled grid dots blank tian compo`; sizes A3–A6, B4–B6, 16K, 32K, Letter, Legal or `WxH` mm; `--landscape`; paper `white cream yellow kraft gray`; line colour `blue gray green red black`; `--top/--bottom/--side` margins; `--dpi`. `--json` writes geometry and a suggested layout for the blank background (no image detection or compositing). This draws a separate paper image; handwriting generation uses the API's supported paper choices. ## pdf.py — PDF from images ```bash python scripts/pdf.py final.jpg final-2.jpg -o homework.pdf [--size auto|A4|B5|Letter|WxH] [--margin 0] [--jpeg 90 | --lossless] [--title "…"] ``` Fits each image inside the page (never crops), writes /AIGC into the PDF Info and XMP. For untouched Inko pages the job's own `inko.pdf` is already the PDF. ## Output scope Deliver standard flat PNG/JPEG pages or PDFs. No photographic rendering, perspective, scene backgrounds, paper curl, simulated scans, or compositing onto a photograph. Keep AI labels and metadata; do not crop them off. Use the original generated PDF for untouched pages, or `pdf.py` after edits.inko-handwriting/references/scenarios.md4.9 KBc7fa5139ae03upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/scene.md12 KB6dd418c17f37upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/styles.md6.7 KBec6289dbde03upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/troubleshooting.md8.3 KB86b02f46f11dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/writing-math.md19 KB7433f166754dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/references/writing-text.md6.4 KBe003b5d310b8upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/assets/layouts/answers-boxes.json390 Be2c0111fa414upstream ↗
{ "paperId": "blank", "boxes": [ {"id": "Q1", "text": "$x=3$", "x": 32, "y": 64, "w": 80, "h": 18, "form": {"size": 6}}, {"id": "Q2", "text": "面积是 $12\\pi$ 平方厘米", "x": 32, "y": 121, "w": 120, "h": 18, "form": {"size": 6}}, {"id": "Q3", "text": "∵ $a>0$,∴ 函数在 $(0,+\\infty)$ 上单调递增", "x": 32, "y": 178, "w": 150, "h": 30, "form": {"size": 6}} ] }inko-handwriting/assets/layouts/essay-compo.json316 B9008a78e53e6upstream ↗
{ "text": "我的秋天\n秋天来了,校园里的银杏叶一片一片变黄,像一把把小扇子。下课的时候,我和同学们在树下捡叶子,比谁找到的最完整。", "paperId": "compo", "marks": [ { "id": "title", "line": 0, "f": { "align": "center" } } ], "d": {} }inko-handwriting/assets/layouts/homework-ruled8.json258 B05c4c93a8913upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/assets/layouts/letter.json783 Bb3e37e9105a1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
inko-handwriting/assets/layouts/notes-blank.json474 B76d9e5eefcd0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/pretend1111-inko-skill-inko-handwriting.md