AI mentor that corrects your written math visually with local harnesses.
Python
penmentor: a maths mentor at the tip of your pen
Abdullah A.f5fea240ef1c
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..47584ad--- /dev/null+++ b/.gitignore@@ -0,0 +1,5 @@+__pycache__/+*.egg-info/+build/+dist/+.venv/diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..6e0dff3--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Abdullah Alhariri++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..6ca995b--- /dev/null+++ b/README.md@@ -0,0 +1,40 @@+<p align="center"><img src="docs/banner.png" alt="penmentor" width="100%"></p>++<p align="center">+A maths mentor at the tip of your pen. Press a key while you work by hand: Claude marks your work on the screen like a<br>+teacher with coloured pens, gives you hints instead of answers, and shows the idea as a 3Blue1Brown-style animation.+</p>++<p align="center"><img src="docs/showme.gif" alt="Show me: Riemann sums closing in on the integral of sin x from 0 to π" width="760"></p>++## Why I use it++I study calculus with a pen tablet in xournal++. I kept screenshotting my work into Claude and reading long answers+back, when what I wanted was a teacher looking over my shoulder: circle the mistake, tick what's right, nudge me toward+the next step, and *show* me why. penmentor is that, one key away, on my own Claude subscription.++## How it helps you learn++- **Hints, not answers.** A ladder from a nudge to naming the technique to a faint ghost of the next line: you do+ the thinking, which is what makes it stick.+- **Feedback on your own work.** The first real mistake circled where you made it, correct lines ticked, later lines+ that inherit the mistake underlined.+- **Practice that makes you recall.** Questions on your key steps (answer by typing or by writing), find-the-error+ drills, "which technique fits?".+- **See it.** Box what you want to understand and get an interactive animation made with 3Blue1Brown's own+ [manim](https://github.com/3b1b/manim): drag the bounds, retype a value, watch Riemann sums close in.+- **Whole page aware.** A small xournal++ plugin shares the page you are on, not just what fits on screen.++## Quick start++```sh+git clone https://github.com/AbdullahAlhariri/penmentor ~/src/penmentor+~/src/penmentor/bin/penmentor --selftest+```++Linux on X11 (best with i3), with [Claude Code](https://claude.com/claude-code) logged in, `rofi`, `slop`, `xdotool`+and PyQt6. Bind `bin/penmentor` to a key ([example](contrib/i3.conf)). Setup, keys and how it works: [the guide](docs/guide.md).++## License++[MIT](LICENSE)diff --git a/bin/penmentor b/bin/penmentornew file mode 100755index 0000000..f7e5005--- /dev/null+++ b/bin/penmentor@@ -0,0 +1,9 @@+#!/usr/bin/env python3+"""Run penmentor from a checkout without installing it: bin/penmentor [options]. See src/penmentor/cli.py for the options."""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'src'))+from penmentor.cli import run # noqa: E402++run()diff --git a/contrib/i3.conf b/contrib/i3.confnew file mode 100644index 0000000..938e96b--- /dev/null+++ b/contrib/i3.conf@@ -0,0 +1,5 @@+# penmentor key bindings for ~/.config/i3/config (adjust the path to your checkout, or use `penmentor` once installed).+bindsym $mod+Shift+a exec --no-startup-id ~/src/penmentor/bin/penmentor+# straight to one question, no menu (handy for tablet buttons, see wacom.sh)+bindsym $mod+Ctrl+Shift+m exec --no-startup-id ~/src/penmentor/bin/penmentor --ask check+bindsym $mod+Ctrl+Shift+s exec --no-startup-id ~/src/penmentor/bin/penmentor --ask finaldiff --git a/contrib/wacom.sh b/contrib/wacom.shnew file mode 100755index 0000000..8be3c87--- /dev/null+++ b/contrib/wacom.sh@@ -0,0 +1,10 @@+#!/bin/bash+# Map two Wacom pad buttons to penmentor's --ask bindings (see i3.conf). Start it from your i3 config:+# exec --no-startup-id ~/src/penmentor/contrib/wacom.sh+# Bluetooth tablets forget their mapping when they reconnect, so this re-applies it whenever it was reset.+PAD="Wacom Intuos BT M Pad pad" # yours: xsetwacom --list devices+while sleep 3; do+ [[ $(xsetwacom get "$PAD" Button 1 2>/dev/null) == button* ]] || continue+ xsetwacom set "$PAD" Button 1 "key +alt +ctrl +shift m -shift -ctrl -alt" # did I make any mistakes?+ xsetwacom set "$PAD" Button 2 "key +alt +ctrl +shift s -shift -ctrl -alt" # solution check+donediff --git a/docs/assets.py b/docs/assets.pynew file mode 100644index 0000000..7a85142--- /dev/null+++ b/docs/assets.py@@ -0,0 +1,76 @@+"""Renders the README's pictures with manim, the way penmentor draws its own:++ ~/.local/share/penmentor/manim/bin/python docs/assets.py writes docs/banner.png and docs/showme.gif (needs ffmpeg)+"""+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++DOCS = Path(__file__).resolve().parent+sys.path.insert(0, str(DOCS.parent / 'src'))+from penmentor import plot # noqa: E402 (sets up manim with 3b1b's settings)+from penmentor.plot import (BLUE, DOWN, GREEN, GREY_B, LEFT, RIGHT, UP, WHITE, YELLOW, Axes, Circle, Dot, # noqa: E402+ Scene, Tex, Text, VGroup, curve, np, region)+++class Banner(Scene):+ """The wordmark beside a little plot: an area filling under a curve, rectangles, a teacher's circle. Laid out in+ the middle strip of manim's 16:9 frame (its camera assumes 16:9), which banner() then crops out."""++ def construct(self):+ word = Text('penmentor', font_size=104)+ line = Text('a maths mentor at the tip of your pen:\nhints, not answers, so you really learn', font_size=26).set_color(GREY_B)+ left = VGroup(word, line).arrange(DOWN, aligned_edge=LEFT, buff=.3).move_to(LEFT * 3.7)+ axes = Axes((0, 4, 1), (0, 1.2, .5), width=6.4, height=3.1).move_to(RIGHT * 3.4 + DOWN * .1)+ f = lambda x: 1.6 * x * np.exp(-x) + .1+ xs = np.linspace(0, 4, 300)+ rects = VGroup(*[plot.Polygon(axes.c2p(x, 0), axes.c2p(x + .25, 0), axes.c2p(x + .25, f(x + .125)), axes.c2p(x, f(x + .125)))+ for x in np.arange(.5, 3, .25)])+ rects.set_submobject_colors_by_gradient(BLUE, GREEN).set_style(stroke_color='#000000', stroke_width=1.5, fill_opacity=.75)+ peak = axes.c2p(1, f(1))+ ring = Circle(radius=.36).move_to(peak).stretch(1.3, 0).rotate(.2).set_stroke(YELLOW, 4)+ mark = VGroup(Dot(peak, radius=.055, fill_color=WHITE), Tex(r'(1,\ 0.69)', font_size=24).next_to(peak, UP, buff=.45))+ self.add(left, region(axes, xs, f(xs), 0 * xs, BLUE, .18), rects, axes, curve(axes, xs, f(xs), BLUE, 4), ring, mark)+++def banner(out):+ plot.cmu_serif()+ scene = Banner(camera_config=dict(resolution=(2560, 1440)), skip_animations=True)+ scene.run()+ scene.update_frame(force_draw=True)+ scene.get_image().convert('RGB').crop((0, 360, 2560, 1080)).save(out) # the middle strip: 2560 x 720+++class Recording(plot.Show):+ """A Show-me window's intro, frame by frame."""++ def __init__(self, folder, **kw):+ self.folder, self.n = folder, 0+ super().__init__(**kw)++ def emit_frame(self):+ self.get_image().convert('RGB').save(self.folder / f'{self.n:05d}.png')+ self.n += 1+++def gif(spec, out, seconds_after=1.5):+ plot.cmu_serif()+ with tempfile.TemporaryDirectory() as d:+ scene = Recording(Path(d), spec=spec)+ scene.setup()+ scene.construct()+ scene.wait(seconds_after) # hold the last frame a little+ # two-pass palette: smooth gradients and crisp text at a sane size+ subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-framerate', '30', '-i', f'{d}/%05d.png', '-vf',+ 'fps=20,scale=960:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=128:stats_mode=diff[p];'+ '[b][p]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle', str(out)], check=True)+++if __name__ == '__main__':+ if not shutil.which('ffmpeg'):+ sys.exit('needs ffmpeg')+ banner(DOCS / 'banner.png')+ gif(dict(kind='riemann', f='sin(x)', a='0', b='pi', n=32, title=r'Riemann sums for $\int_0^\pi \sin x\,dx$'), DOCS / 'showme.gif')+ print('wrote', DOCS / 'banner.png', DOCS / 'showme.gif')diff --git a/docs/banner.png b/docs/banner.pngnew file mode 100644index 0000000..32e918aBinary files /dev/null and b/docs/banner.png differdiff --git a/docs/guide.md b/docs/guide.mdnew file mode 100644index 0000000..e663088--- /dev/null+++ b/docs/guide.md@@ -0,0 +1,110 @@+# penmentor: the full guide++Press a key while you work through maths by hand, and Claude answers by drawing on your screen, the way a teacher+marks work with coloured pens: rings round the mistake, ticks on the right lines, a faint ghost of the next step,+arrows from cause to effect. Words are a last resort.++Built for [xournal++](https://xournalpp.github.io/) and a pen tablet on Linux (X11, works best with i3), for calculus,+but it reads whatever maths is on screen.++## What it can do++| Menu entry | What you get |+|---|---|+| Did I make any mistakes? | the first real error circled with its fix, later lines that inherit it underlined, correct lines ticked |+| Solution check | is the final answer right, and is anything missing (+C, bounds, absolute values…)? |+| Give me a hint | the smallest nudge: one thing highlighted, the next step not given away |+| Which technique? | the features that point to a method are coloured, no method named; you pick one (`p`) and Claude says whether it fits |+| Quiz me on my steps | a question at the 1 or 2 steps that matter most; answer by typing (`a`) or by writing on the page (`w`) |+| Find-the-error drill | a new worked problem like yours with one planted mistake; tap the wrong line |+| Show me (animation) | box what you want to see (one box or several), then get an animation of it made with 3Blue1Brown's own [manim](https://github.com/3b1b/manim), on the other monitor, that you can play with: Riemann sums, areas, improper integrals, substitution as a stretch of the axis, solids of revolution, series, Taylor polynomials, polar and parametric curves |+| Ask about a box | drag a box round something and ask about just that |++In the answer overlay:++| Key | |+|---|---|+| `h` | more help, one rung up the ladder: nudge → name the technique → ghost the next line → full fix |+| `?` | a follow-up question |+| `g` | show me: box what to animate, then watch it |+| `w` | step aside so you can write more; tap the badge at the top (or press an penmentor key) when done and it checks the new part |+| `t` / `s` | what Claude read / model, tokens and plan usage |+| `r` | replay the marks |+| `Esc` | stop penmentor, wherever you are: in a menu, while Claude is still thinking (Claude stops too), or while you write |++Show me starts on the frozen screen: drag boxes round what to animate (right-click takes one back), then tap the badge+or press Enter. The window opens straight away (a loading animation runs while Claude thinks) and stays until you+press `q` in it (Esc leaves it open). Drag in it to move the bound, the number of rectangles, the degree, the point on the+curve (or turn a 3D solid); where curves cross, and where the bounds x = a and x = b meet them, is marked with+its coordinates. Change the maths in place: click a value in the row at the bottom (the function, a, b, n) and type a+new one, or drag a bound line; it redraws at once (and goes in the history). Scroll to zoom, arrows to step, space to replay. Every animation is kept: *Settings →+history* plays an old one again, without asking Claude.++Hover or tap a mark for its one-line "why". Questions build on each other (one Claude conversation) until you pick+*Clear context*; turn that off in *Settings*, where you also choose the model and effort.++## How it works, and what leaves your computer++A screenshot of every monitor, plus (with the xournal++ plugin) the whole current page of your notes, goes to Claude+through the [Claude Code](https://claude.com/claude-code) CLI (`claude -p`), so it runs on your Claude subscription.+Claude answers in JSON (what it read, a verdict, marks with boxes); penmentor snaps the boxes onto your ink and draws them+on a frozen copy of the screen. Nothing else is sent and nothing runs in the background between questions.++## Install++Linux with X11. On Arch:++```sh+sudo pacman -S python-pyqt6 python-numpy python-scipy python-pillow python-matplotlib rofi slop xdotool libnotify+sudo pacman -S texlive-latex texlive-latexextra texlive-fontsextra # optional: real LaTeX and the CMU fonts+```++Install [Claude Code](https://claude.com/claude-code) and log in once (`claude`). Then:++```sh+git clone <this repo> ~/src/penmentor+~/src/penmentor/bin/penmentor --selftest+```++Bind a key: see [contrib/i3.conf](../contrib/i3.conf) (or `pip install .` and bind `penmentor`).++**xournal++ plugin** (so Claude also sees the parts of the page that are scrolled away, and your unsaved strokes):++```sh+ln -s ~/src/penmentor/xournalpp-plugin/penmentor ~/.config/xournalpp/plugins/penmentor+```++and restart xournal++. It adds *Plugin → penmentor: share the current page* on Ctrl+Alt+Shift+F12, which penmentor presses for you.++**Show me** needs manimgl (3Blue1Brown's manim) and its OpenGL window. Put it in its own environment, where penmentor+looks for it:++```sh+uv venv --system-site-packages ~/.local/share/penmentor/manim+uv pip install -p ~/.local/share/penmentor/manim/bin/python manimgl audioop-lts+```++(or `pip install '.[show]'` into the Python that runs penmentor).++**Tablet buttons:** `penmentor --ask check` skips the menu; [contrib/wacom.sh](../contrib/wacom.sh) maps two pad buttons to it.++## Development++```sh+bin/penmentor --selftest # page analysis, text, formulas, plots, drill logic; no Claude, no screen+bin/penmentor --test shot.png check # ask Claude about a saved screenshot: shot.penmentor.json and shot.penmentor.png+bin/penmentor --render shot.png shot.penmentor.json # redraw a saved answer without Claude (tune the visuals)+PYTHONPATH=src ~/.local/share/penmentor/manim/bin/python -m penmentor.plot --png spec.json out.png # one animation's last frame+~/.local/share/penmentor/manim/bin/python docs/assets.py # the README's banner and GIF+```++| Module | |+|---|---|+| `cli.py` | entry point: capture, menu, settings |+| `prompts.py` | everything Claude is told, and the JSON schema it answers in |+| `claude.py` | the `claude -p` call, sessions, token and usage stats |+| `desktop.py`, `xournal.py` | screenshots, monitors, i3 windows, rofi; the whole-page export |+| `page.py` | where the ink is: snapping boxes onto strokes, finding empty space |+| `overlay.py`, `draw.py`, `style.py` | the frozen frame, the marks, the modes |+| `typeset.py` | LaTeX (or mathtext) into images |+| `plot.py`, `show.py`, `expr.py` | Show me: the manim scenes (run by manim's Python), opening their window and its history, and a safe evaluator for Claude's formulas |diff --git a/docs/showme.gif b/docs/showme.gifnew file mode 100644index 0000000..b95eb24Binary files /dev/null and b/docs/showme.gif differdiff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..43c1f2c--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,32 @@+[build-system]+requires = ["setuptools>=77"]+build-backend = "setuptools.build_meta"++[project]+name = "penmentor"+version = "0.2.0"+description = "A maths mentor at the tip of your pen: Claude marks your handwritten work with hints, not answers, and shows the idea with manim."+readme = "README.md"+license = "MIT"+requires-python = ">=3.10"+dependencies = ["numpy", "scipy", "pillow", "PyQt6", "matplotlib"]+keywords = ["xournal", "handwriting", "calculus", "tutor", "claude", "x11", "i3"]+classifiers = [+ "Environment :: X11 Applications :: Qt",+ "Intended Audience :: Education",+ "Operating System :: POSIX :: Linux",+ "Topic :: Scientific/Engineering :: Mathematics",+]++[project.urls]+Homepage = "https://github.com/AbdullahAlhariri/penmentor"+Issues = "https://github.com/AbdullahAlhariri/penmentor/issues"++[project.optional-dependencies]+show = ["manimgl", "audioop-lts; python_version >= '3.13'"] # Show me: 3Blue1Brown's manim (pydub needs audioop on 3.13+)++[project.scripts]+penmentor = "penmentor.cli:run"++[tool.setuptools.packages.find]+where = ["src"]diff --git a/src/penmentor/__init__.py b/src/penmentor/__init__.pynew file mode 100644index 0000000..f28d6f2--- /dev/null+++ b/src/penmentor/__init__.py@@ -0,0 +1,5 @@+"""penmentor: press a key, ask Claude about the maths on your screen, and see the answer drawn on it."""+import os++os.environ.setdefault('QT_ENABLE_HIGHDPI_SCALING', '0') # 1 Qt pixel == 1 screen pixel; set before anything imports Qt+__version__ = '0.2.0'diff --git a/src/penmentor/__main__.py b/src/penmentor/__main__.pynew file mode 100644index 0000000..27cfa48--- /dev/null+++ b/src/penmentor/__main__.py@@ -0,0 +1,3 @@+from .cli import run++run()diff --git a/src/penmentor/claude.py b/src/penmentor/claude.pynew file mode 100644index 0000000..5b9f7a0--- /dev/null+++ b/src/penmentor/claude.py@@ -0,0 +1,108 @@+"""Asking Claude through the Claude Code CLI (`claude -p`), so it runs on your Claude subscription."""+import atexit+import base64+import io+import json+import shutil+import subprocess+import time+import uuid+from pathlib import Path++from PIL import Image, ImageDraw, ImageFont++from .config import CACHE, CONF, SESSION+from .prompts import SCHEMA, SYSTEM++CLAUDE = shutil.which('claude') or str(Path.home() / '.local/bin/claude') # i3's PATH may lack ~/.local/bin+SEND_EDGE = 1568 # long edge of the image Claude sees; its boxes come back in that space+++def prepare(shot, boxes=()):+ """PNG bytes Claude sees (your boxes drawn on in cyan: [(number or None, (x0, y0, x1, y1))]; shrunk) and its size."""+ img = shot.copy()+ draw = ImageDraw.Draw(img)+ for n, box in boxes:+ draw.rectangle(box, outline=(0, 220, 255), width=4)+ if n:+ draw.text((box[0] + 8, box[1] + 4), str(n), fill=(0, 220, 255), font=ImageFont.load_default(30))+ s = min(1, SEND_EDGE / max(img.size))+ if s < 1:+ img = img.resize((round(img.width * s), round(img.height * s)), Image.LANCZOS)+ buf = io.BytesIO()+ img.save(buf, 'PNG')+ return buf.getvalue(), img.size+++def session():+ try:+ return json.loads(SESSION.read_text())+ except (OSError, ValueError):+ return None+++RUNNING = set() # claude processes still answering+++def stop():+ """Kill Claude mid-answer: Esc, or penmentor quitting for any reason, must not leave it running on your plan."""+ for p in list(RUNNING):+ p.kill()+++def image(png):+ return {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': base64.b64encode(png).decode()}}+++def ask(shots, text, main=0, new_shot=True, keep=True, page=None):+ """shots: [(png, (w, h))] per monitor, left to right; main: the focused one; page: (png, label) of the whole xournal page.+ new_shot=False: a follow-up on the screenshots Claude already has. keep=False: no shared context (offline tests)."""+ content = [{'type': 'text', 'text': text}]+ if new_shot:+ content = []+ for i, (png, (w, h)) in enumerate(shots):+ content += [{'type': 'text', 'text': f'Screen {i}' + (' (focused)' if i == main else '') + f': {w}x{h} px'}, image(png)]+ if page:+ content += [{'type': 'text', 'text': f'The whole {page[1]} of the xournal notes, for context only (no marks on it):'},+ image(prepare(Image.open(io.BytesIO(page[0])).convert('RGB'))[0])]+ content.append({'type': 'text', 'text': 'Give every box in its own screen\'s pixels.\n\n' + text})+ msg = {'type': 'user', 'message': {'role': 'user', 'content': content}}+ s = session() if keep else None+ sid = s['id'] if s else str(uuid.uuid4())+ # isolated from your own Claude Code setup: no tools, hooks, plugins or MCP servers+ cmd = [CLAUDE, '-p', '--restricted', '--strict-mcp-config', '--tools', '', '--disable-slash-commands',+ *(['--resume', sid] if s else ['--session-id', sid] if keep else ['--no-session-persistence']),+ '--model', CONF['model'], '--effort', CONF['effort'], '--system-prompt', SYSTEM,+ '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose',+ '--json-schema', json.dumps(SCHEMA)]+ CACHE.mkdir(parents=True, exist_ok=True)+ t = time.monotonic()+ with subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=CACHE) as p:+ RUNNING.add(p)+ try:+ out, err = p.communicate(json.dumps(msg), timeout=300)+ finally:+ p.kill() # only does something on a timeout or when penmentor stops+ RUNNING.discard(p)+ for line in reversed(out.splitlines()):+ try:+ e = json.loads(line)+ except ValueError:+ continue+ if e.get('type') == 'result':+ if e.get('is_error') or 'structured_output' not in e:+ raise RuntimeError(str(e.get('result') or e.get('subtype')))+ if keep:+ SESSION.write_text(json.dumps({'id': sid}))+ u = e.get('usage') or {} # this question only; modelUsage adds up the whole session, every model in it+ spent = sum(u.get(k, 0) for k in ('input_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens', 'output_tokens'))+ total = sum(m.get(k, 0) for m in (e.get('modelUsage') or {}).values()+ for k in ('inputTokens', 'cacheCreationInputTokens', 'cacheReadInputTokens', 'outputTokens'))+ lim = [json.loads(l)['rate_limit_info'] for l in out.splitlines() if '"rate_limit_event"' in l]+ return dict(e['structured_output'], _secs=round(time.monotonic() - t, 1), _tokens=[spent, u.get('cache_read_input_tokens', 0), total],+ _limits=lim[-1].get('unifiedWindows', {}) if lim else {}) # plan usage: 5-hour and weekly+ if s and 'No conversation found' in err: # Claude Code pruned the old session: start a new one, screenshots included+ SESSION.unlink()+ return ask(shots, text, main, True, keep, page)+ raise RuntimeError(err.strip()[-300:] or 'no answer from claude')diff --git a/src/penmentor/cli.py b/src/penmentor/cli.pynew file mode 100644index 0000000..f31e13a--- /dev/null+++ b/src/penmentor/cli.py@@ -0,0 +1,195 @@+"""penmentor: press a key, ask about the maths on screen, Claude draws the answer on it.++ penmentor screenshot every monitor, rofi question, overlay+ penmentor --last show the last answer again+ penmentor --ask MODE skip the menu (for pen-tablet buttons); MODE is one of the presets in prompts.py+ penmentor --test IMG [MODE|"question"] offline: ask Claude about IMG, writes IMG.penmentor.{json,png}+ penmentor --render IMG JSON offline: redraw a saved answer (tune visuals without Claude)+ penmentor --selftest++Overlay keys: h more help, ? follow-up, g show me (box what to animate), w write more, t what Claude read, s stats, r replay.+Esc stops penmentor at any point, Claude included.+Hover or tap a mark for its one-line "why".+"""+import faulthandler+import fcntl+import json+import os+import signal+import sys+import time+import traceback+from pathlib import Path++from . import claude, show, xournal+from .config import CACHE, CHOICES, CONF, SESSION, STATE, save, set_state+from .desktop import Oops, capture, notify, on_escape, rofi, select_region+from .prompts import BOX_QS, PRESETS, TASKS++SETTINGS_ROW, CLEAR_ROW, HISTORY_ROW = '⚙ Settings', '✕ Clear context', 'history'+++def settings(reopen):+ """Pick model / effort / context until Esc; each pick is saved at once. History: reopen(spec) an old animation."""+ while c := rofi([f'{k:<8}{CONF[k]}' for k in CHOICES] + [HISTORY_ROW], 'settings'):+ if c == HISTORY_ROW:+ return past_animations(reopen)+ key = c.split()[0]+ if key not in CHOICES:+ continue+ rows = [f'{"●" if a == CONF[key] else "○"} {a:<8}{name}' for a, name in CHOICES[key]]+ free = key == 'model' # any full model id works; a mistyped effort would only break the next ask+ if (v := rofi(rows, key)) is None:+ return+ v = dict(zip(rows, (a for a, _ in CHOICES[key]))).get(v, v if free else None)+ if v:+ save(**{key: v})+++def past_animations(reopen):+ """Every Show-me animation, newest first; the one you pick plays again (no Claude needed)."""+ from .typeset import plain+ past = show.history()+ rows = [f'{time.strftime("%d %b %H:%M", time.localtime(h["t"]))} {plain(h["spec"].get("title") or h["spec"].get("kind", "?"))}'+ for h in past]+ if not rows:+ return notify('No animations yet: ask "Show me" first.', ms=3000)+ if (pick := rofi(rows, 'history')) in rows:+ reopen(past[rows.index(pick)]['spec'])+++def nudge_running():+ """Another penmentor holds the lock. If it is waiting for you to finish writing, this key press means done."""+ try:+ state = STATE.read_text().split()+ if state[0] == 'waiting' and b'penmentor' in Path(f'/proc/{int(state[1])}/cmdline').read_bytes():+ return os.kill(int(state[1]), signal.SIGUSR1)+ except (OSError, ValueError, IndexError):+ pass+ notify('Still answering the last question…', ms=2500)+++def app_and_overlay():+ from PyQt6.QtCore import QThread+ from PyQt6.QtWidgets import QApplication+ from .overlay import Overlay+ if not QThread.isMainThread(): # Qt got loaded on another thread: its windows would hold the keyboard and ignore it+ raise RuntimeError('Qt was started off the main thread')+ return QApplication(sys.argv), Overlay+++def watchdog(app):+ """Last resort: if the Qt loop ever stalls for 20 s (while the overlay may hold your keyboard and mouse),+ write where it hung to ~/.cache/penmentor/freeze.log and exit, so X gives them back."""+ from PyQt6.QtCore import QTimer+ log = open(CACHE / 'freeze.log', 'w')+ arm = lambda: faulthandler.dump_traceback_later(20, exit=True, file=log)+ arm()+ QTimer(app, interval=2000, timeout=arm).start()+++def show_last():+ from PIL import Image+ d = json.loads((CACHE / 'last.json').read_text())+ app, Overlay = app_and_overlay()+ ov = Overlay(Image.open(CACHE / 'last.png').convert('RGB'), d['geom'], None, d.get('screens'), d.get('main', 0),+ d.get('wins'), d.get('mode', 'check'))+ ov.set_result(d['result'])+ ov.present()+ watchdog(app)+ app.exec()+++def offline(a):+ from PIL import Image+ from .claude import ask+ os.environ['QT_QPA_PLATFORM'] = 'offscreen'+ img = Path(a[1])+ shot = Image.open(img).convert('RGB')+ mode = a[2] if a[0] == '--test' and len(a) > 2 else 'check'+ app, Overlay = app_and_overlay()+ ov = Overlay(shot, (0, 0, *shot.size), mode=mode) # ponytail: one screen; offline multi-monitor needs a saved screens list+ if a[0] == '--test':+ t = time.time()+ r = ask(ov.shots, TASKS.get(mode, mode), keep=False)+ print(f'{CONF["model"]}/{CONF["effort"]}: {time.time() - t:.1f}s', file=sys.stderr)+ img.with_suffix('.penmentor.json').write_text(json.dumps({'result': r}, indent=1, ensure_ascii=False))+ else:+ r = json.loads(Path(a[2]).read_text())['result']+ ov.set_result(r)+ ov.t0 = -1e9 # skip the animation+ ov.grab().save(str(img.with_suffix('.penmentor.png')))+ print(json.dumps(r, indent=1, ensure_ascii=False))+++def main(a):+ if a[:1] == ['--selftest']:+ from .selftest import selftest+ return selftest()+ if a[:1] in (['--test'], ['--render']):+ return offline(a)+ CACHE.mkdir(parents=True, exist_ok=True)+ lock = open(CACHE / 'lock', 'w')+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ return nudge_running()+ set_state('busy')+ if a[:1] == ['--last']:+ return show_last()+ shot, screens, main_screen, wins = capture() # before rofi draws over the screen+ page = xournal.PageRequest() # now, while the keyboard still goes to xournal+ on_escape(lambda: (claude.stop(), os._exit(0))) # Esc anywhere stops penmentor, even while Claude thinks+ geom = (0, 0, *shot.size)+ on = CONF['context'] == 'on'+ if a[:1] == ['--ask']: # a tablet button: straight to the question+ choice = next((label for label, m in PRESETS if a[1:2] == [m]), None)+ if not choice:+ raise Oops(f'penmentor --ask needs one of: {", ".join(m for _, m in PRESETS)}')+ while not a[:1] == ['--ask']:+ on = CONF['context'] == 'on'+ choice = rofi([label for label, _ in PRESETS] + [SETTINGS_ROW] + [CLEAR_ROW] * on, 'ask')+ if choice == SETTINGS_ROW:+ return settings(lambda spec: show.open_window(show.rect(show.monitor(screens, main_screen, geom)), spec))+ elif on and choice == CLEAR_ROW:+ SESSION.unlink(missing_ok=True)+ else:+ break+ if not choice:+ return+ if not on: # context off: start fresh, but follow-ups in this overlay still share one conversation+ SESSION.unlink(missing_ok=True)+ mode = dict(PRESETS).get(choice, 'free')+ task = TASKS.get(mode, choice)+ boxes = None+ if mode == 'box':+ if not (box := select_region(geom)) or not (q := rofi(BOX_QS, 'about the box')):+ return+ boxes, task = [box], TASKS['explain'] if q == BOX_QS[0] else task + q+ app, Overlay = app_and_overlay()+ keep = []++ def ask(boxes, task):+ keep.append(ov := Overlay(shot, geom, boxes, screens, main_screen, wins, mode, page))+ ov.request(task)+ if mode == 'show': # box what to show first+ from .overlay import BoxPicker, qimage+ keep.append(picker := BoxPicker(qimage(shot), geom, screens[main_screen],+ lambda boxes: ask(boxes, TASKS['show_boxes'] if boxes else task)))+ picker.present()+ else:+ ask(boxes, task)+ watchdog(app)+ app.exec()+++def run():+ try:+ main(sys.argv[1:])+ except Oops as ex:+ notify(str(ex))+ except Exception as ex:+ CACHE.mkdir(parents=True, exist_ok=True)+ (CACHE / 'error.log').write_text(traceback.format_exc())+ notify(f'{type(ex).__name__}: {str(ex)[:200]}\nDetails: ~/.cache/penmentor/error.log', critical=True, title='penmentor crashed')+ raisediff --git a/src/penmentor/config.py b/src/penmentor/config.pynew file mode 100644index 0000000..c0b3092--- /dev/null+++ b/src/penmentor/config.py@@ -0,0 +1,33 @@+"""Where penmentor keeps things, and your settings (model, effort, context), saved in ~/.config/penmentor/settings.json."""+import json+import os+from pathlib import Path++CACHE = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'penmentor'+SETTINGS = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'penmentor' / 'settings.json'+SESSION = CACHE / 'session.json' # the Claude conversation every question builds on, until Clear context+DATA = Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share') / 'penmentor' # kept: Show-me history, manim+MANIM = DATA / 'manim' / 'bin' / 'python' # a venv with manimgl (README), for Show me+STATE = CACHE / 'state' # 'busy', or 'waiting <pid>' while penmentor waits for you to write; read by a second penmentor++CHOICES = { # claude --model aliases, --effort levels, shared context+ 'model': [('opus', 'Opus 5.5'), ('sonnet', 'Sonnet 5.5'), ('haiku', 'Haiku 5.5'), ('fable', 'Fable 5.1')],+ 'effort': [('low', 'fastest'), ('medium', 'balanced'), ('high', 'more careful'), ('xhigh', 'slower'), ('max', 'slowest, most careful')],+ 'context': [('on', 'each question builds on the earlier ones'), ('off', 'each question starts fresh')],+}+CONF = {'model': 'opus', 'effort': 'medium', 'context': 'on', 'stats': False, 'read': False} # stats/read: s and t panels, kept on between questions+try:+ CONF |= json.loads(SETTINGS.read_text())+except (OSError, ValueError):+ pass+++def save(**kw):+ CONF.update(kw)+ SETTINGS.parent.mkdir(parents=True, exist_ok=True)+ SETTINGS.write_text(json.dumps(CONF))+++def set_state(s):+ CACHE.mkdir(parents=True, exist_ok=True)+ STATE.write_text(s)diff --git a/src/penmentor/desktop.py b/src/penmentor/desktop.pynew file mode 100644index 0000000..577e139--- /dev/null+++ b/src/penmentor/desktop.py@@ -0,0 +1,135 @@+"""The X11 desktop: screenshots, monitors, i3 windows, rofi menus, notifications."""+import ctypes+import json+import re+import subprocess+import threading++from PIL import ImageGrab+++class Oops(Exception):+ """A problem you can fix: shown as a plain notification, no traceback."""+++def sh(*cmd):+ return subprocess.run(cmd, capture_output=True, text=True, check=True).stdout+++def notify(msg, ms=None, critical=False, title='penmentor'):+ subprocess.run(['notify-send', *(['-t', str(ms)] if ms else []), *(['-u', 'critical'] if critical else []), title, msg])+++def monitors():+ """Active monitors (x, y, w, h), left to right."""+ try:+ out = sh('xrandr', '--listactivemonitors')+ except (OSError, subprocess.CalledProcessError):+ return []+ return sorted((int(x), int(y), int(w), int(h)) for w, h, x, y in re.findall(r'(\d+)/\d+x(\d+)/\d+\+(\d+)\+(\d+)', out))+++def windows(tree, visible):+ """Windows (x, y, w, h) on the visible i3 workspaces, the rect of whatever has the focus,+ and each monitor's area without its i3 bars."""+ wins, focus, areas = [], None, []++ def walk(n, on):+ nonlocal focus+ on = on or (n.get('type') == 'workspace' and n.get('name') in visible)+ r = n.get('rect') or {}+ rect = (r.get('x', 0), r.get('y', 0), r.get('width', 0), r.get('height', 0))+ if n.get('focused'):+ focus = rect # a window, or an empty workspace+ if n.get('type') == 'con' and n.get('name') == 'content' and rect[2] > 0 < rect[3]:+ areas.append(rect)+ if on and n.get('window') and rect[2] > 0 and rect[3] > 0 and rect not in wins:+ wins.append(rect)+ for c in n.get('nodes', []) + n.get('floating_nodes', []):+ walk(c, on)+ walk(tree, False)+ return wins, focus, sorted(areas)+++def capture():+ """Everything on screen: (desktop image, monitors left to right, index of the focused one, visible windows)."""+ try:+ shot = ImageGrab.grab(xdisplay='').convert('RGB') # whole X screen, no cursor; ~15x faster than maim's PNG+ except OSError:+ raise Oops('Could not take a screenshot.')+ try:+ wins, focus, screens = windows(json.loads(sh('i3-msg', '-t', 'get_tree')),+ {w['name'] for w in json.loads(sh('i3-msg', '-t', 'get_workspaces')) if w['visible']})+ if not wins:+ raise Oops('Nothing on screen to look at. Open your notes, then press the key again.')+ except (OSError, subprocess.CalledProcessError, ValueError):+ wins, focus, screens = [], None, [] # not i3: one page per monitor+ screens = screens or monitors() or [(0, 0, *shot.size)] # i3's areas skip the bars, so panels sit above them; xrandr is slow (~0.6 s)+ if focus is None: # focus follows the mouse+ try:+ g = dict(kv.split('=', 1) for kv in sh('xdotool', 'getmouselocation', '--shell').split())+ focus = (int(g['X']), int(g['Y']), 1, 1)+ except (OSError, subprocess.CalledProcessError, KeyError, ValueError):+ focus = screens[0]+ cx, cy = focus[0] + focus[2] / 2, focus[1] + focus[3] / 2+ main = next((i for i, (x, y, w, h) in enumerate(screens) if x <= cx < x + w and y <= cy < y + h), 0)+ return shot, screens, main, wins+++def active_window():+ """The focused app's X window id (to hand the focus back later), or None."""+ p = subprocess.run(['xdotool', 'getactivewindow'], capture_output=True, text=True)+ return p.stdout.strip() or None+++def activate(window):+ """Give the focus back: once the overlay has had the keyboard, neither X nor i3 returns it to the app by itself."""+ if window:+ subprocess.run(['xdotool', 'windowactivate', window], capture_output=True)+++def on_escape(callback):+ """callback() on a thread whenever Escape is pressed, wherever the focus is (other keys still reach your apps),+ so Esc stops penmentor while Claude thinks. Windows that grab the keyboard (rofi, the overlay) get their Esc themselves."""+ try:+ x = ctypes.CDLL('libX11.so.6')+ except OSError:+ return+ dpy_t = ctypes.c_void_p+ x.XOpenDisplay.restype, x.XDefaultRootWindow.restype, x.XSetErrorHandler.restype = dpy_t, ctypes.c_ulong, ctypes.c_void_p+ x.XDefaultRootWindow.argtypes, x.XKeysymToKeycode.argtypes = [dpy_t], [dpy_t, ctypes.c_ulong]+ x.XGrabKey.argtypes = [dpy_t, ctypes.c_int, ctypes.c_uint, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_int]+ x.XSync.argtypes, x.XNextEvent.argtypes = [dpy_t, ctypes.c_int], [dpy_t, ctypes.c_char_p]+ on_escape.ignore = ctypes.CFUNCTYPE(ctypes.c_int, dpy_t, dpy_t)(lambda *a: 0) # kept alive: C calls it later+ x.XSetErrorHandler.argtypes = [type(on_escape.ignore)]+ dpy = x.XOpenDisplay(None) # our own connection: Qt's is only ever touched by Qt's thread+ if not dpy:+ return+ x.XSetErrorHandler(on_escape.ignore) # BadAccess if another program already has a combination: skip that one+ root, esc = x.XDefaultRootWindow(dpy), x.XKeysymToKeycode(dpy, 0xFF1B) # XK_Escape+ for mods in (0, 2, 16, 18): # plain, with Caps Lock, Num Lock, both+ x.XGrabKey(dpy, esc, mods, root, 1, 1, 1) # owner_events, GrabModeAsync pointer and keyboard+ x.XSync(dpy, 0)+ event = ctypes.create_string_buffer(192) # sizeof(XEvent)++ def wait():+ while True:+ x.XNextEvent(dpy, event)+ if event.raw[0] == 2: # KeyPress+ callback()+ threading.Thread(target=wait, daemon=True).start()+++def rofi(options, prompt):+ """The picked (or typed) row, None on Esc. No options: a plain text box."""+ p = subprocess.run(['rofi', '-dmenu', '-i', '-p', prompt],+ input='\n'.join(options), capture_output=True, text=True)+ return p.stdout.strip() if p.returncode == 0 else None+++def select_region(geom):+ p = subprocess.run(['slop', '-f', '%x %y %w %h', '-b', '3', '-c', '0,0.86,1,0.9'], capture_output=True, text=True)+ if p.returncode or not p.stdout.strip():+ return None+ x, y, w, h = map(int, p.stdout.split())+ return (x - geom[0], y - geom[1], x - geom[0] + w, y - geom[1] + h)diff --git a/src/penmentor/draw.py b/src/penmentor/draw.pynew file mode 100644index 0000000..9f35cd8--- /dev/null+++ b/src/penmentor/draw.py@@ -0,0 +1,95 @@+"""Pen strokes that look hand-drawn: rings, ticks, curved arrows, the loading arc."""+import math+import random+import time++from PyQt6.QtCore import QPointF, QRectF, Qt+from PyQt6.QtGui import QColor, QPainterPath, QPen, QPolygonF++from .style import PANEL, SPIN+++def panel(p, r, radius=10, alpha=228):+ """Dark rounded panel behind text."""+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(*PANEL, alpha))+ p.drawRoundedRect(r, radius, radius)+++def pen(color, width=3.2, dashed=False):+ p = QPen(QColor(color), width, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin)+ if dashed:+ p.setDashPattern([2.2, 2.2])+ return p+++def line_pts(*pts, n=12):+ out = []+ for (ax, ay), (bx, by) in zip(pts, pts[1:]):+ out += [QPointF(ax + (bx - ax) * i / n, ay + (by - ay) * i / n) for i in range(n)]+ return out + [QPointF(*pts[-1])]+++def ring(r, seed):+ """Hand-drawn circle: starts top-left, overshoots, slightly uneven, like a teacher's pen."""+ rnd = random.Random(seed)+ c = r.center()+ a, b = r.width() / 2 * 1.12 + 9, r.height() / 2 * 1.2 + 8+ a0, ph = rnd.uniform(-2.7, -2.1), rnd.uniform(0, 6.3)+ pts = []+ for i in range(73):+ t = a0 + (2 * math.pi + .5) * i / 72+ f = 1 + .035 * math.sin(2 * t + ph) + .07 * i / 72+ pts.append(QPointF(c.x() + a * f * math.cos(t), c.y() + b * f * math.sin(t)))+ return pts+++def curve(a, b, bend=.18):+ mx, my = (a.x() + b.x()) / 2, (a.y() + b.y()) / 2+ dx, dy = b.x() - a.x(), b.y() - a.y()+ c = QPointF(mx - dy * bend, my + dx * bend)+ path = QPainterPath(a)+ path.quadTo(c, b)+ return [path.pointAtPercent(i / 40) for i in range(41)]+++def edge(r, toward, pad=5):+ """Point on r's border (plus pad) on the way from its centre to `toward`."""+ c = r.center()+ dx, dy = toward.x() - c.x(), toward.y() - c.y()+ if not dx and not dy:+ return c+ s = min(abs((r.width() / 2 + pad) / dx) if dx else 1e9, abs((r.height() / 2 + pad) / dy) if dy else 1e9)+ return QPointF(c.x() + dx * s, c.y() + dy * s)+++def arrowhead(p, a, b, color, size=11):+ ang = math.atan2(b.y() - a.y(), b.x() - a.x())+ tri = QPolygonF([b] + [QPointF(b.x() - size * math.cos(ang + s), b.y() - size * math.sin(ang + s)) for s in (.45, -.45)])+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(color))+ p.drawPolygon(tri)+++def qrect(t):+ return QRectF(QPointF(t[0], t[1]), QPointF(t[2], t[3]))+++def tup(r):+ return r.left(), r.top(), r.right(), r.bottom()+++def spin(p, c, t0, r=8):+ """Loading arc around c: a thin ring that turns while it stretches and shrinks."""+ t = time.monotonic() - t0+ box = QRectF(c.x() - r, c.y() - r, 2 * r, 2 * r)+ p.setBrush(Qt.BrushStyle.NoBrush)+ p.setPen(pen('#33ffffff', 2.4))+ p.drawEllipse(box)+ p.setPen(pen(SPIN, 2.4))+ p.drawArc(box, int(-t * 330 * 16) % 5760, int((40 + 230 * (.5 - .5 * math.cos(t * 4))) * 16))+++def ring_rect(b):+ return QRectF(b.center().x() - b.width() / 2 * 1.2 - 12, b.center().y() - b.height() / 2 * 1.28 - 11,+ b.width() * 1.2 + 24, b.height() * 1.28 + 22)diff --git a/src/penmentor/expr.py b/src/penmentor/expr.pynew file mode 100644index 0000000..b5fdf5a--- /dev/null+++ b/src/penmentor/expr.py@@ -0,0 +1,77 @@+"""Claude's plot formulas, e.g. "x**2*exp(-x)", turned into numpy functions.++The text comes from a model that read your screen, so it is untrusted: only numbers, arithmetic, comparisons and the+names below get through; anything else (attributes, indexing, lambdas, imports, unknown names) is refused.+"""+import ast+import re++import numpy as np+++def _factorial(x):+ from scipy.special import gamma+ return gamma(np.asarray(x, float) + 1)+++FUNCS = {+ 'sin': np.sin, 'cos': np.cos, 'tan': np.tan, 'sec': lambda x: 1 / np.cos(x), 'csc': lambda x: 1 / np.sin(x),+ 'cot': lambda x: 1 / np.tan(x), 'arcsin': np.arcsin, 'arccos': np.arccos, 'arctan': np.arctan, 'asin': np.arcsin,+ 'acos': np.arccos, 'atan': np.arctan, 'sinh': np.sinh, 'cosh': np.cosh, 'tanh': np.tanh, 'arcsinh': np.arcsinh,+ 'arccosh': np.arccosh, 'arctanh': np.arctanh, 'exp': np.exp, 'log': np.log, 'ln': np.log, 'log10': np.log10,+ 'log2': np.log2, 'sqrt': np.sqrt, 'cbrt': np.cbrt, 'abs': np.abs, 'sign': np.sign, 'floor': np.floor, 'ceil': np.ceil,+ 'factorial': _factorial, 'where': np.where, 'min': np.minimum, 'max': np.maximum,+}+CONSTS = {'pi': np.pi, 'e': np.e, 'inf': np.inf, 'oo': np.inf}+ALIASES = {'theta': 't', 'θ': 't', 'π': 'pi', '∞': 'inf'}+NODES = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Call, ast.Name, ast.Load, ast.Constant, ast.Compare,+ ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.Mod, ast.USub, ast.UAdd, ast.Lt, ast.LtE, ast.Gt, ast.GtE)+++def formula(src, names=('x',), finite=True):+ """f(**{name: array}) -> float array (NaN where undefined or infinite, unless finite=False).+ Raises ValueError for anything that is not a formula."""+ s = str(src).replace('^', '**').replace('−', '-').replace('·', '*')+ for a, b in ALIASES.items():+ s = re.sub(rf'(?<![\w]){a}(?![\w])', b, s)+ s = re.sub(r'(?<![\w.])(\d+\.?\d*)\s*(?![eE][-+]?\d)([a-zA-Z(])', r'\1*\2', s) # 2x -> 2*x (not log10(x) or 1e-5)+ try:+ tree = ast.parse(s.strip(), mode='eval')+ except SyntaxError:+ raise ValueError(f'not a formula: {src!r}')+ for node in ast.walk(tree):+ if not isinstance(node, NODES):+ raise ValueError(f'not allowed in a formula: {type(node).__name__} in {src!r}')+ if isinstance(node, ast.Name) and node.id not in FUNCS and node.id not in CONSTS and node.id not in names:+ raise ValueError(f'unknown name {node.id!r} in {src!r}')+ if isinstance(node, ast.Call) and (not isinstance(node.func, ast.Name) or node.func.id not in FUNCS or node.keywords):+ raise ValueError(f'unknown function in {src!r}')+ if isinstance(node, ast.Constant):+ if type(node.value) not in (int, float):+ raise ValueError(f'not a number: {node.value!r} in {src!r}')+ node.value = float(node.value) # float powers overflow to inf; int powers like 9**9**9 would hang+ code = compile(tree, '<formula>', 'eval')+ env = {'__builtins__': {}, **FUNCS, **CONSTS}++ def f(**kw):+ with np.errstate(all='ignore'):+ try:+ v = np.asarray(eval(code, env, {k: np.asarray(v, float) for k, v in kw.items()}), float)+ except OverflowError:+ v = np.asarray(np.inf)+ shape = np.broadcast(*map(np.asarray, kw.values())).shape if kw else ()+ v = np.broadcast_to(v, shape).astype(float)+ return np.where(np.isfinite(v), v, np.nan) if finite else v+ return f+++def number(src, default=None):+ """A constant like "pi/2", "-inf" or 3 as a float."""+ if src in (None, ''):+ return default+ if isinstance(src, (int, float)):+ return float(src)+ v = float(formula(src, (), finite=False)())+ if np.isnan(v):+ raise ValueError(f'not a number: {src!r}')+ return vdiff --git a/src/penmentor/overlay.py b/src/penmentor/overlay.pynew file mode 100644index 0000000..8f66c18--- /dev/null+++ b/src/penmentor/overlay.py@@ -0,0 +1,833 @@+"""The overlay: a frozen frame of your screen with Claude's marks drawn on it, and the small badge at the top."""+import json+import math+import re+import os+import signal+import threading+import time++import numpy as np+from PyQt6.QtCore import QPointF, QRect, QRectF, Qt, QTimer, pyqtSignal+from PyQt6.QtGui import QColor, QFontMetrics, QImage, QPainter, QPainterPath, QPolygonF, QRegion+from PyQt6.QtWidgets import QApplication, QWidget++from . import show, xournal+from .claude import ask, prepare+from .config import CACHE, CONF, save, set_state+from .desktop import Oops, activate, active_window, capture, rofi+from .draw import arrowhead, curve, edge, line_pts, panel, pen, qrect, ring, ring_rect, spin, tup+from .page import Page+from .prompts import FOLLOWUPS, MORE, TASKS, TECHNIQUES+from .style import BAR, DRILL, FIX, GHOST, HEAD, LEGEND, NOTE, NOTE_CH, PALETTE, READ, SPIN, TIP, TIP_CH, TOP, VERDICT+from .typeset import as_math, lines_key, read_line, shrink, tex, tex_lines, text_img, typeset, ui_font+++def tex_jobs(r):+ """Every (text, size) the overlay draws for answer r, so LaTeX typesets them all in one run."""+ jobs = [(r.get('headline', ''), HEAD)] + [(read_line(l), READ) for l in r.get('read_as', [])]+ for m in r.get('marks', []):+ jobs += [lines_key(m.get('note'), NOTE, NOTE_CH), lines_key(m.get('why'), TIP, TIP_CH)]+ if m.get('write'):+ jobs.append((as_math(m['write']), GHOST if m['shape'] == 'ghost' else FIX))+ d = r.get('drill') or {}+ jobs += [lines_key(display(d.get('problem')), DRILL, 60)] + [(display(l), DRILL) for l in [*(d.get('lines') or []), d.get('fix')]]+ return [j for j in jobs + [lines_key(d.get('why'), TIP, TIP_CH)] if j[0]]+++def display(s):+ """Full-size integrals and sums, as in a worked solution (inline maths shrinks them)."""+ return re.sub(r'\$([^$]+)\$', lambda m: '$\\displaystyle ' + m[1] + '$', s or '')+++def qimage(pil):+ return QImage(pil.tobytes(), pil.width, pil.height, 3 * pil.width, QImage.Format.Format_RGB888).copy()+++def save_last(ov, result):+ ov.shot_pil.save(CACHE / 'last.png', compress_level=1) # the whole desktop: fast beats small+ (CACHE / 'last.json').write_text(json.dumps({'geom': ov.geom, 'screens': ov.screens, 'main': ov.main,+ 'wins': ov.wins, 'mode': ov.mode, 'result': result}))+++class Pill(QWidget):+ """The badge at the top: 'Thinking' while Claude works, or a button. Never takes the focus from xournal.+ Without a compositor X can't make its corners transparent, so it paints the screenshot behind its rounded ends."""++ def __init__(self, backdrop, geom, text='Thinking', on_click=None, busy=True):+ super().__init__(None, Qt.WindowType.ToolTip | Qt.WindowType.FramelessWindowHint |+ Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.X11BypassWindowManagerHint)+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)+ self.backdrop, self.text, self.busy, self.on_click = backdrop, text, busy, on_click or QApplication.quit+ self.err, self.t0 = False, time.monotonic()+ self.set_size(geom, (66 if busy else 44) + QFontMetrics(ui_font(18)).horizontalAdvance(text))+ QTimer(self, interval=16 if busy else 250, timeout=lambda: self.update()).start() # Python, so signal handlers get to run++ def set_size(self, geom, w, h=42):+ x, y, W, _ = geom+ self.geom = geom+ self.setGeometry(x + (W - w) // 2, y + TOP, w, h)++ def fail(self, msg):+ self.text, self.err, self.busy = msg, True, False+ self.set_size(self.geom, min(900, 40 + 9 * len(msg)))+ QTimer.singleShot(9000, QApplication.quit)++ def paintEvent(self, e):+ p = QPainter(self)+ p.setRenderHint(QPainter.RenderHint.Antialiasing)+ r = QRectF(self.rect())+ p.drawImage(r, self.backdrop, QRectF(self.geometry()))+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor('#9b1c1c' if self.err else '#16161a'))+ p.drawRoundedRect(r, r.height() / 2, r.height() / 2)+ p.setFont(ui_font(18))+ if self.busy:+ spin(p, QPointF(29, r.height() / 2), self.t0)+ p.setPen(QColor('white' if self.err else '#E6E6E6'))+ p.drawText(r.adjusted(48, 0, 0, 0) if self.busy else r, Qt.AlignmentFlag.AlignVCenter |+ (Qt.AlignmentFlag.AlignLeft if self.busy else Qt.AlignmentFlag.AlignHCenter), self.text)++ def mousePressEvent(self, e):+ (QApplication.quit if e.button() == Qt.MouseButton.RightButton or self.err else self.on_click)()+++class BoxPicker(QWidget):+ """Show me, step one: drag boxes round what to show (as many as you like) on the frozen frame. Tap the badge or+ press Enter to send them, right-click to take the last one back; Esc stops penmentor, as everywhere."""+ CYAN = QColor(0, 220, 255)++ def __init__(self, shot, geom, top, done):+ super().__init__(None, Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint |+ Qt.WindowType.X11BypassWindowManagerHint)+ self.shot, self.done, self.boxes, self.drag, self.start = shot, done, [], None, QPointF()+ self.setGeometry(*geom)+ self.setCursor(Qt.CursorShape.CrossCursor)+ x, y, w, _ = top # the focused monitor, in shot pixels (= ours)+ self.badge = QRectF(x + w / 2 - 260, y + TOP, 520, 44)++ def present(self):+ self.show()+ self.raise_()+ QTimer.singleShot(80, lambda: (self.activateWindow(), self.grabKeyboard()))++ def finish(self):+ self.releaseKeyboard()+ self.close()+ self.done([tup(b) for b in self.boxes])++ def paintEvent(self, e):+ p = QPainter(self)+ p.setRenderHint(QPainter.RenderHint.Antialiasing)+ p.drawImage(0, 0, self.shot)+ p.setFont(ui_font(18))+ for i, b in enumerate(self.boxes + [self.drag] * bool(self.drag)):+ p.setPen(pen(self.CYAN, 3))+ p.setBrush(Qt.BrushStyle.NoBrush)+ p.drawRect(b)+ if i < len(self.boxes) and len(self.boxes) > 1:+ p.setFont(ui_font(26))+ p.drawText(b.topLeft() + QPointF(10, 30), str(i + 1))+ p.setFont(ui_font(18))+ panel(p, self.badge, self.badge.height() / 2, 240)+ n = len(self.boxes)+ p.setPen(QColor('#E6E6E6'))+ p.drawText(self.badge, Qt.AlignmentFlag.AlignCenter, 'Box what to show, then tap here' if not n else+ f'{n} box{"es" * (n > 1)} · tap here to show {"them" if n > 1 else "it"}')++ def mousePressEvent(self, e):+ if e.button() == Qt.MouseButton.RightButton:+ self.boxes = self.boxes[:-1]+ elif self.badge.contains(e.position()):+ return self.finish()+ else:+ self.start = e.position()+ self.drag = QRectF(self.start, self.start)+ self.update()++ def mouseMoveEvent(self, e):+ if self.drag is not None:+ self.drag = QRectF(self.start, e.position()).normalized()+ self.update()++ def mouseReleaseEvent(self, e):+ if self.drag is not None and self.drag.width() > 12 and self.drag.height() > 12: # a tap is not a box+ self.boxes.append(self.drag)+ self.drag = None+ self.update()++ def keyPressEvent(self, e):+ if e.key() == Qt.Key.Key_Escape:+ QApplication.quit()+ elif e.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter, Qt.Key.Key_Space):+ self.finish()+ elif e.key() == Qt.Key.Key_Backspace or e.text() == 'z':+ self.boxes = self.boxes[:-1]+ self.update()+++class Overlay(QWidget):+ """Frozen frame: the screenshot plus Claude's marks, over every monitor it came from.+ Needs no compositor and can't drift when you scroll; Esc returns to the live apps.+ geom: where the shot sits on the desktop. screens (monitors) and wins (windows) are (x, y, w, h) in shot pixels;+ the panels go on screens[main], the focused monitor."""+ done = pyqtSignal(object)+ asked = pyqtSignal(object)++ def __init__(self, shot, geom, region=None, screens=None, main=0, wins=None, mode='check', page=None):+ # region: your boxes [(x0, y0, x1, y1)] in shot pixels, drawn on what Claude sees+ super().__init__(None, Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint |+ Qt.WindowType.X11BypassWindowManagerHint)+ self.geom, self.region, self.mode, self.page_req = tuple(geom), region, mode, page # page: a xournal.PageRequest+ self.cache, self.locks = {}, {'pages': threading.Lock(), 'shots': threading.Lock()}+ self.load(shot, screens, main, wins)+ self.result, self.items, self.read_imgs, self.head, self.head_box, self.drill = None, [], None, None, None, None+ self.busy, self.error, self.hover, self.pinned = False, None, None, None+ self.want_plot, self.pending = mode == 'show', None # pending: what to ask once you are done writing+ self.app_window = active_window() # xournal, usually: it gets the focus back when the overlay steps aside+ self.pill, self.t0, self.end, self.tip_pos, self.pin_pos = None, time.monotonic(), 0, QPointF(0, 0), QPointF(0, 0)+ self.setGeometry(*geom)+ self.setMouseTracking(True)+ self.done.connect(self.on_done)+ self.asked.connect(self.on_asked)+ self.tips, self.head_img, self.legend = {}, QImage(), None+ self.tick = QTimer(self, interval=16, timeout=self.update)++ def load(self, shot, screens, main, wins):+ """Freeze this frame. Its pages and Claude's copies are made from it lazily (the pages on a background thread)."""+ self.shot_pil = shot+ self.screens = [tuple(r) for r in screens or [(0, 0, *shot.size)]]+ self.main, self.wins = main if 0 <= main < len(self.screens) else 0, [tuple(r) for r in wins or []]+ self.M = QRectF(*self.screens[self.main])+ self.shot = qimage(shot)+ self.pal = PALETTE['dark'] # the focused window's, once its page is known+ threading.Thread(target=lambda: self.pages, daemon=True).start() # ~0.5 s a monitor: while Claude thinks++ def per_frame(self, name, make):+ """make(shot) once per frame; a second caller waits for the first instead of doing it again."""+ shot = self.shot_pil+ with self.locks[name]:+ if self.cache.get(name, (None,))[0] is not shot:+ self.cache[name] = shot, make(shot)+ return self.cache[name][1]++ @property+ def pages(self):+ """One Page per visible window, and per monitor without one: each app has its own paper colour and chrome."""+ def make(shot):+ W, H = shot.size+ bare = [(x, y, w, h) for x, y, w, h in self.screens+ if not any(x <= a + c / 2 < x + w and y <= b + d / 2 < y + h for a, b, c, d in self.wins)]+ rects = [(max(x, 0), max(y, 0), min(x + w, W), min(y + h, H)) for x, y, w, h in self.wins + bare]+ return [Page(np.asarray(shot.crop(r)), r[:2]) for r in rects if r[2] > r[0] and r[3] > r[1]]+ return self.per_frame('pages', make)++ @property+ def shots(self):+ """What Claude sees: one shrunk PNG per monitor, with your boxes (numbered when several).+ Built on the worker thread (0.2 s), so the pill shows at once."""+ boxes = list(enumerate(self.region or [], 1))+ return self.per_frame('shots', lambda shot: [+ prepare(shot.crop((x, y, x + w, y + h)), [(n if len(boxes) > 1 else None, (a - x, b - y, c - x, d - y))+ for n, (a, b, c, d) in boxes if a < x + w and c > x and b < y + h and d > y])+ for x, y, w, h in self.screens])++ def top_geom(self):+ x, y, w, h = self.screens[self.main]+ return self.geom[0] + x, self.geom[1] + y, w, h++ def page_for(self, r):+ """The page under the middle of r (desktop coords), else the nearest one."""+ cx, cy = (r[0] + r[2]) / 2, (r[1] + r[3]) / 2+ return min(self.pages, key=lambda p: math.dist((cx, cy), (min(max(cx, p.ox), p.ox + p.w), min(max(cy, p.oy), p.oy + p.h))))++ # --- talking to Claude ---+ def request(self, text, new_shot=True):+ self.busy, self.error, self.busy_t0 = True, None, time.monotonic()+ set_state('busy')+ if self.want_plot:+ screen = show.monitor(self.screens, self.main, self.geom)+ spot = show.rect(screen)+ show.open_window(spot) # now, so its loading animation runs while Claude thinks+ # the frozen frame mustn't cover it: leave its whole monitor live (so you can move it or make it fullscreen);+ # with one monitor, just the window and i3's frame round it+ hole = QRect(*screen) if len(self.screens) > 1 else QRect(*spot).adjusted(-4, -30, 4, 4)+ self.setMask(QRegion(self.rect()).subtracted(QRegion(hole.translated(-self.geom[0], -self.geom[1]))))+ if self.isVisible():+ self.tick.start()+ else:+ self.pill = Pill(self.shot, self.top_geom())+ self.pill.show()+ page = self.page_req if new_shot else None++ def work():+ try:+ r = ask(self.shots, text, self.main, new_shot, page=page and page.result())+ except Exception as ex:+ r = {'error': str(ex)[:300]}+ self.done.emit(r)+ threading.Thread(target=work, daemon=True).start()++ def followup(self, text):+ self.request(text, new_shot=self.result is None) # Claude already has this screenshot once it has answered++ def on_done(self, r):+ self.busy = False+ if self.want_plot:+ self.want_plot = False+ show.send(spec=r['plot']) if r.get('plot') else show.send(error=r.get('error') or "Claude didn't send an animation this time.")+ if 'error' in r:+ if self.isVisible():+ self.error = r['error']+ self.update()+ else:+ self.pill.fail(r['error'])+ return+ if self.pill:+ self.pill.close()+ self.pill = None+ save_last(self, r)+ self.set_result(r)+ if not self.isVisible():+ self.present()++ def present(self):+ self.show()+ self.raise_()+ QTimer.singleShot(80, lambda: (self.activateWindow(), self.grabKeyboard()))++ # --- turning the answer into drawables ---+ def set_result(self, r):+ self.result, self.read_imgs, self.pinned, self.hover = r, None, None, None+ self.pal = PALETTE['dark' if self.page_for(tup(self.M)).dark else 'light']+ typeset(tex_jobs(r))+ self.head_img = shrink(tex(r.get('headline', ''), 'white', HEAD), self.M.width() * .7)+ marks = r.get('marks', [])+ boxes, pgs = [], []+ for m in marks:+ k = m.get('screen')+ k = k if isinstance(k, int) and 0 <= k < len(self.screens) else self.main+ (x, y, w, _), s = self.screens[k], self.screens[k][2] / self.shots[k][1][0]+ b = [x + m['box'][0] * s, y + m['box'][1] * s, x + m['box'][2] * s, y + m['box'][3] * s]+ pgs.append(page := self.page_for(b))+ boxes.append(qrect(page.clip(b) if m['shape'] == 'ghost' else page.snap(b)))+ pals = [PALETTE['dark' if pg.dark else 'light'] for pg in pgs]+ outer = [ring_rect(b) if m['shape'] == 'circle' else b.adjusted(-6, -6, 46 if m['shape'] == 'check' else 6, 6)+ for m, b in zip(marks, boxes)]+ taken = [tup(o.adjusted(-6, -6, 6, 6)) for m, o in zip(marks, outer) if m['shape'] != 'ghost']+ self.legend = self.legend_rows(marks)+ if self.legend:+ taken.append(tup(self.legend[0].adjusted(-8, -8, 8, 8)))+ if CONF['stats']:+ taken.append(tup(self.stats()[0].adjusted(-8, -8, 8, 8)))+ self.drill = self.make_drill(r['drill']) if isinstance(r.get('drill'), dict) else None+ self.head = self.head_spot(r, taken)+ taken.append(tup(self.head.adjusted(-10, -10, 10, 10)))+ writes = {i: as_math(m['write']) for i, m in enumerate(marks)+ if m.get('write') and m['shape'] in ('strike', 'ghost')}+ ghosts = {i: tex(w, pals[i]['ghost'], GHOST) for i, w in writes.items() if marks[i]['shape'] == 'ghost'}+ gf = min([1] + [(pgs[i].w - 12) / max(g.width(), 1) for i, g in ghosts.items()]) # one size; only shrinks to fit the window+ written = {} # ghosts and corrections claim their space before any note bubble does+ for i, w in writes.items():+ m, b, page = marks[i], boxes[i], pgs[i]+ if i in ghosts:+ img = ghosts[i]+ size = (img.width() * gf, img.height() * gf)+ spot = (b.left(), b.top(), b.left() + size[0], b.top() + size[1])+ else: # correction written just above the crossed-out part+ img = shrink(tex(w, pals[i]['fix'], FIX), page.w - 12)+ size = (img.width(), img.height())+ spot = (b.center().x() - size[0] / 2, b.top() - size[1] - 6, b.center().x() + size[0] / 2, b.top() - 6)+ if page.busy(spot, taken):+ spot = page.place(size, tup(b), taken)+ taken.append(spot)+ written[i] = (img, qrect(spot))+ if m['shape'] == 'ghost':+ outer[i] = qrect(spot).adjusted(-4, -4, 4, 4)+ items = []+ order = sorted(range(len(marks)), key=lambda i: (marks[i].get('step') or i + 1, i))+ for k, i in enumerate(order):+ m, b, o, page, pal = marks[i], boxes[i], outer[i], pgs[i], pals[i]+ col, T = pal.get(m['role'], pal['a']), .25 + k * .5+ dashed = m['role'] in ('carry', 'unsure')+ sh_ = m['shape']+ stroke = lambda pts, w=3.2, t=T, d=.4, head=False, c=col, dash=dashed: items.append(+ dict(kind='stroke', pts=pts, pen=pen(c, w, dash), t=t, dur=d, head=head, layer=1))+ if sh_ == 'circle':+ stroke(ring(b, i))+ elif sh_ == 'mark':+ items.append(dict(kind='fill', rect=b.adjusted(-6, -4, 6, 4), color=col, t=T, dur=.3, layer=0, page=page))+ elif sh_ == 'underline':+ y = b.bottom() + 6+ stroke(line_pts((b.left() - 3, y), (b.right() + 3, y + 1)))+ elif sh_ == 'wavy':+ y, x0, n = b.bottom() + 7, b.left() - 3, max(8, int(b.width() / 3))+ stroke([QPointF(x0 + (b.width() + 6) * j / n, y + 3.5 * math.sin(j / n * (b.width() + 6) / 14 * 2 * math.pi))+ for j in range(n + 1)])+ elif sh_ == 'strike':+ stroke(line_pts((b.left() - 4, b.center().y() + 4), (b.right() + 4, b.center().y() - 4)))+ elif sh_ == 'check':+ x, y = min(b.right() + 16, page.ox + page.w - 30), b.center().y()+ stroke(line_pts((x, y), (x + 7, y + 9), (x + 24, y - 14)), w=3.6, d=.3)+ elif sh_ == 'box':+ path = QPainterPath()+ path.addRoundedRect(b.adjusted(-6, -5, 6, 5), 7, 7)+ stroke([path.pointAtPercent(j / 60) for j in range(61)])+ if i in written:+ img, spot = written[i]+ ghost = sh_ == 'ghost'+ items.append(dict(kind='image', img=img, rect=spot, t=T if ghost else T + .35, dur=.5 if ghost else .3,+ layer=2, alpha=.8 if ghost else 1))+ if m.get('note'):+ img = shrink(tex_lines(m['note'], col, NOTE, NOTE_CH), page.w - 40)+ spot = qrect(page.place((img.width() + 22, img.height() + 14), tup(o), taken))+ taken.append(tup(spot))+ a = edge(spot, o.center(), 2)+ stroke(curve(a, edge(o, a, 3)), w=2.4, t=T + .35, d=.3, head=True, dash=False)+ items.append(dict(kind='bubble', img=img, rect=spot, color=col, t=T + .55, dur=.25, layer=2, why=m.get('why'), page=page))+ j = m.get('link')+ if isinstance(j, int) and 0 <= j < len(marks) and j != i:+ a = edge(o, outer[j].center())+ z = edge(outer[j], a)+ if math.dist((a.x(), a.y()), (z.x(), z.y())) < 40:+ continue # neighbours: a stub arrow reads as noise+ stroke(curve(a, z, .25), w=2.6, t=T + .4, d=.4, head=True,+ dash=marks[j]['role'] == 'carry')+ self.hits = [(o, m.get('why')) for o, m in zip(outer, marks) if m.get('why')]+ self.items = sorted(items, key=lambda d: d['layer'])+ self.end = max([d['t'] + d['dur'] for d in items], default=0) + .1+ self.replay()++ def replay(self):+ self.t0 = time.monotonic()+ self.tick.start()++ # --- painting ---+ def paintEvent(self, e):+ p = QPainter(self)+ p.setRenderHint(QPainter.RenderHint.Antialiasing)+ p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)+ p.drawImage(0, 0, self.shot)+ now = time.monotonic() - self.t0+ if now > self.end and not self.busy:+ self.tick.stop()+ dim = .3 if self.busy else 1+ for d in self.items:+ k = min(1, max(0, (now - d['t']) / d['dur']))+ if k > 0:+ self.draw(p, d, k, dim)+ p.setOpacity(1)+ if self.legend and self.result:+ self.draw_legend(p)+ if self.drill:+ self.draw_drill(p)+ self.draw_headline(p)+ why = self.pinned or self.hover+ if why:+ self.draw_tip(p, why)+ if CONF['read']:+ self.draw_read(p)++ def draw(self, p, d, k, dim):+ kind = d['kind']+ p.setOpacity(dim * d.get('alpha', 1) * (1 if kind == 'stroke' else k))+ if kind == 'fill': # highlighter that keeps the ink crisp, on dark or light paper+ c = QColor(d['color'])+ c.setAlphaF(.42 if d['page'].dark else .45)+ p.setCompositionMode(QPainter.CompositionMode.CompositionMode_Screen if d['page'].dark+ else QPainter.CompositionMode.CompositionMode_Multiply)+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(c)+ p.drawRoundedRect(d['rect'], 6, 6)+ p.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceOver)+ elif kind == 'stroke':+ pts = d['pts']+ n = max(2, round(len(pts) * k))+ p.setPen(d['pen'])+ p.setBrush(Qt.BrushStyle.NoBrush)+ p.drawPolyline(QPolygonF(pts[:n]))+ if d['head']:+ arrowhead(p, pts[n - 2], pts[n - 1], d['pen'].color())+ elif kind == 'image':+ p.drawImage(d['rect'], d['img'])+ elif kind == 'bubble':+ bg = QColor(*d['page'].bg.tolist(), 235)+ p.setPen(pen(d['color'], 2))+ p.setBrush(bg)+ p.drawRoundedRect(d['rect'], 10, 10)+ p.drawImage(d['rect'].topLeft() + QPointF(11, 7), d['img'])++ def headline(self):+ r = self.result or {}+ if self.error:+ icon, col, img = '!', '#FF6B4A', text_img(self.error[:90], 'white', 19)+ elif self.busy:+ icon, col, img = '◌', SPIN, text_img('Thinking', '#E6E6E6', 19) # spin() draws over the ◌ slot+ else:+ icon, role = VERDICT.get(r.get('verdict'), ('•', 'a'))+ icon, col, img = icon, self.pal[role], self.head_img+ f = ui_font(19)+ return icon, col, img, f, QFontMetrics(f).horizontalAdvance(f'{icon} ') + img.width() + 44++ def legend_rows(self, marks):+ """Legend for the colours this answer uses: (rect, [(colours, dashed, label)])."""+ keys = list(dict.fromkeys('ghost' if m['shape'] == 'ghost' else 'abc' if m['role'] in 'abc' else m['role']+ for m in marks))+ abc = [self.pal[x] for x in 'abc' if any(m['role'] == x and m['shape'] != 'ghost' for m in marks)]+ rows = [(abc if k == 'abc' else [self.pal[k]], k in ('carry', 'unsure'), LEGEND[k]) for k in keys]+ if not rows:+ return None+ w = 66 + max(QFontMetrics(ui_font(16)).horizontalAdvance(l) for *_, l in rows)+ h = 14 + 26 * len(rows)+ return QRectF(self.M.right() - w - 12, self.M.bottom() - 46 - h, w, h), rows++ def draw_legend(self, p):+ r, rows = self.legend+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(18, 18, 22, 215))+ p.drawRoundedRect(r, 10, 10)+ p.setFont(ui_font(16))+ y = r.top() + 7+ for cols, dashed, label in rows:+ seg = 30 / len(cols)+ for j, c in enumerate(cols): # a line sample per colour, drawn like the marks+ x = r.left() + 14 + j * seg+ p.setPen(pen(c, 3.6, dashed))+ p.drawLine(QPointF(x, y + 13), QPointF(x + seg - 6, y + 13))+ p.setPen(QColor(215, 215, 222))+ p.drawText(QRectF(r.left() + 54, y, r.width() - 60, 26), Qt.AlignmentFlag.AlignVCenter, label)+ y += 26++ def head_spot(self, r, taken):+ """Headline pill goes where it hides no handwriting: top, below the toolbars, bottom, corners."""+ w, (X, Y, W, H) = self.headline()[4], self.screens[self.main]+ spots = () if self.drill else ( # a drill card sits right under the top spot+ (X + (W - w) / 2, Y + TOP), (X + (W - w) / 2, Y + TOP + 56), (X + (W - w) / 2, Y + H - 92), (X + W - w - 16, Y + TOP), (X + 16, Y + TOP))+ for x, y in spots:+ spot = (x, y, x + w, y + 42)+ if not self.page_for(spot).on_writing(spot) and not any(+ spot[0] < t[2] and t[0] < spot[2] and spot[1] < t[3] and t[1] < spot[3] for t in taken):+ return qrect(spot)+ return qrect((X + (W - w) / 2, Y + TOP, X + (W + w) / 2, Y + TOP + 42))++ def draw_headline(self, p):+ icon, col, img, f, w = self.headline()+ head = self.head or QRectF(self.M.center().x(), self.M.top() + TOP, 0, 42)+ h = max(42, img.height() + 14)+ box = self.head_box = QRectF(head.center().x() - w / 2, head.top(), w, h)+ p.setFont(f)+ fm = QFontMetrics(f)+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(18, 18, 22, 228))+ p.drawRoundedRect(box, 21, 21)+ p.setPen(QColor(col))+ if self.busy and not self.error:+ spin(p, QPointF(box.left() + 22 + fm.horizontalAdvance(icon) / 2, box.center().y()), self.busy_t0)+ else:+ p.drawText(box.adjusted(22, 0, 0, 0), Qt.AlignmentFlag.AlignVCenter, icon)+ p.drawImage(QPointF(box.left() + 22 + fm.horizontalAdvance(icon + ' '), box.center().y() - img.height() / 2), img)+ f.setPixelSize(15)+ p.setFont(f)+ self.draw_bar(p, f, self.keys(), right=True)+ if CONF['stats']:+ self.draw_stats(p)++ def stats(self):+ """Bottom-left panel: (rect, label column width, rows). A row is (label, text, bar fraction or None); None is a gap."""+ r = self.result or {}+ rows = [('model', CONF['model'], None), ('effort', CONF['effort'], None), ('context', CONF['context'], None)]+ n, cached, *total = r.get('_tokens') or [None, None]+ run = [('took', f"{r['_secs']:.1f} s", None)] if '_secs' in r else []+ if n is not None:+ run.append(('question', f'{n / 1000:.1f}k tokens ({cached / 1000:.1f}k cached)', None))+ run += [('session', f'{total[0] / 1000:.1f}k tokens', None)] if total else []+ rows += [None, *run] if run else []+ lim = r.get('_limits') or {}+ lims = [(label, f"{w['utilization']:.0%} · resets {time.strftime(fmt, time.localtime(w['resetsAt']))}", w['utilization'])+ for key, label, fmt in (('five_hour', '5 hours', '%H:%M'), ('seven_day', 'week', '%a %H:%M'))+ if (w := lim.get(key)) and 'utilization' in w]+ rows += [None, *lims] if lims else []+ fm = QFontMetrics(ui_font(15))+ lw = max(fm.horizontalAdvance(x[0]) for x in rows if x) + 14+ vw = max(fm.horizontalAdvance(t) + (0 if f is None else BAR + 10) for x in rows if x for _, t, f in [x])+ h = 12 + sum(22 if x else 8 for x in rows)+ return QRectF(self.M.left() + 12, self.M.bottom() - 8 - h, 24 + lw + vw, h), lw, rows++ def draw_stats(self, p):+ r, lw, rows = self.stats()+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(18, 18, 22, 240)) # xournal's sidebar sits under it+ p.drawRoundedRect(r, 10, 10)+ p.setFont(ui_font(15))+ y = r.top() + 6+ for row in rows:+ if not row:+ y += 8+ continue+ label, text, frac = row+ p.setPen(QColor(120, 120, 132))+ p.drawText(QRectF(r.left() + 12, y, lw, 22), Qt.AlignmentFlag.AlignVCenter, label)+ x = r.left() + 12 + lw+ if frac is not None:+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(58, 58, 66))+ p.drawRoundedRect(QRectF(x, y + 8, BAR, 6), 3, 3)+ p.setBrush(QColor(self.pal['error' if frac >= .9 else 'unsure' if frac >= .7 else 'ok']))+ p.drawRoundedRect(QRectF(x, y + 8, max(6, BAR * min(frac, 1)), 6), 3, 3)+ x += BAR + 10+ p.setPen(QColor(200, 200, 208))+ p.drawText(QRectF(x, y, r.right() - x, 22), Qt.AlignmentFlag.AlignVCenter, text)+ y += 22++ def draw_bar(self, p, f, text, right):+ w = QFontMetrics(f).horizontalAdvance(text) + 24+ r = QRectF(self.M.right() - w - 12 if right else self.M.left() + 12, self.M.bottom() - 36, w, 28)+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(18, 18, 22, 210))+ p.drawRoundedRect(r, 14, 14)+ p.setPen(QColor(170, 170, 180))+ p.drawText(r, Qt.AlignmentFlag.AlignCenter, text)++ def tip_rect(self, text, pos):+ if text not in self.tips:+ self.tips[text] = shrink(tex_lines(text, 'white', TIP, TIP_CH), self.width() - 48)+ img = self.tips[text]+ r = QRectF(pos.x() + 18, pos.y() + 18, img.width() + 24, img.height() + 16)+ if r.right() > self.width():+ r.moveRight(pos.x() - 12)+ if r.bottom() > self.height():+ r.moveBottom(pos.y() - 12)+ r.moveTo(max(r.left(), 4), max(r.top(), 4))+ return r, img++ def draw_tip(self, p, text):+ r, img = self.tip_rect(text, self.pin_pos if self.pinned else self.tip_pos) # a pinned tip stays where you tapped+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(18, 18, 22, 240))+ p.drawRoundedRect(r, 9, 9)+ p.drawImage(r.topLeft() + QPointF(12, 8), img)++ def draw_read(self, p):+ if self.read_imgs is None:+ self.read_imgs = [shrink(tex(read_line(l), '#E8E8EC', READ), self.M.width() - 64)+ for l in (self.result or {}).get('read_as', [])]+ w = max([i.width() for i in self.read_imgs] + [260]) + 32+ h = sum(i.height() + 10 for i in self.read_imgs) + 54+ r = QRectF(self.M.right() - w - 16, self.M.top() + TOP + 56, w, h)+ p.setPen(Qt.PenStyle.NoPen)+ p.setBrush(QColor(18, 18, 22, 235))+ p.drawRoundedRect(r, 12, 12)+ p.drawImage(r.topLeft() + QPointF(16, 12), text_img('What I read:', '#9A9AA5', 14))+ y = r.top() + 42+ for img in self.read_imgs:+ p.drawImage(QPointF(r.left() + 16, y), img)+ y += img.height() + 10++ # --- input ---+ def mouseMoveEvent(self, e):+ old, self.tip_pos = self.tip_pos, e.position()+ if self.drill:+ if (row := self.drill_row(self.tip_pos)) != self.drill['hover']:+ self.drill['hover'] = row+ self.update()+ return+ hit = next((why for o, why in self.hits if o.contains(self.tip_pos)), None) if self.result else None+ hit = hit or next((d['why'] for d in self.items if d['kind'] == 'bubble' and d.get('why')+ and d['rect'].contains(self.tip_pos)), None)+ if hit != self.hover:+ self.hover = hit+ self.update()+ elif hit and not self.pinned: # the tip follows the cursor: repaint only where it was and where it goes+ for pos in (old, self.tip_pos):+ self.update(self.tip_rect(hit, pos)[0].toAlignedRect().adjusted(-2, -2, 2, 2))++ def mousePressEvent(self, e):+ self.tip_pos = e.position()+ if e.button() == Qt.MouseButton.RightButton:+ self.close()+ elif self.drill: # pen taps miss: in a drill only Esc or right-click closes+ if (row := self.drill_row(self.tip_pos)) is not None:+ self.pick_line(row)+ elif self.mode == 'technique' and not self.busy and self.head_box and self.head_box.contains(self.tip_pos):+ self.pick_technique()+ elif not self.hover:+ self.close()+ else: # tap a mark to pin its "why" (pens don't hover well)+ self.pinned, self.pin_pos = None if self.pinned == self.hover else self.hover, self.tip_pos+ self.update()++ def keyPressEvent(self, e):+ t = e.text()+ hyper = Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier+ pad = {Qt.Key.Key_M: 'check', Qt.Key.Key_S: 'final'}.get(e.key()) if e.modifiers() & hyper == hyper else None+ if e.key() in (Qt.Key.Key_Escape, Qt.Key.Key_Q):+ self.close()+ elif self.busy:+ return+ elif pad: # a tablet button while this is open: we hold the keyboard, so i3 never sees it; ask here+ self.followup(TASKS[pad])+ elif t == 'h':+ self.followup(MORE)+ elif t == '?':+ self.ask_rofi(FOLLOWUPS, 'follow-up')+ elif t == 'p' and self.mode == 'technique':+ self.pick_technique()+ elif t == 'n' and self.drill:+ self.followup(TASKS['drill_more'])+ elif t == 'g':+ self.pick_then_show()+ elif t == 'a' and self.mode == 'why':+ self.ask_rofi([], 'your answer', TASKS['why_typed'])+ elif t == 'w':+ self.write_then(TASKS['why_written' if self.mode == 'why' else 'written'])+ elif t == 'r':+ self.replay()+ elif t in ('s', 't'):+ key = 'stats' if t == 's' else 'read'+ save(**{key: not CONF[key]})+ self.update()++ def on_asked(self, q):+ if q is None: # Esc in rofi stops penmentor, like Esc anywhere else+ return self.close()+ self.activateWindow()+ self.grabKeyboard()+ if q:+ self.followup(q)++ def closeEvent(self, e):+ activate(self.app_window)+ QApplication.quit()++ # --- the modes ---+ def keys(self):+ if self.drill:+ return 'tap the wrong line · n new drill · esc close'+ k = {'technique': ['p pick the technique'], 'why': ['a type answer', 'w write answer']}.get(self.mode, ['w write more'])+ return ' · '.join(k + ['h more help', '? ask', 'g show me', 't what I read', 's stats', 'r replay', 'esc close'])++ def pick_then_show(self):+ """g: box what to show on this frame, then Claude animates it (no boxes: what the problem is about)."""+ self.releaseKeyboard()++ def chosen(boxes):+ self.activateWindow()+ self.grabKeyboard()+ self.region, self.want_plot = boxes, True+ self.cache.pop('shots', None) # redraw what Claude sees, with the boxes+ self.request(TASKS['show_boxes' if boxes else 'show'], new_shot=bool(boxes) or self.result is None)+ self.picker = BoxPicker(self.shot, self.geom, self.screens[self.main], chosen)+ self.picker.present()++ def ask_rofi(self, rows, prompt, template='{}'):+ """A rofi pick (or typed text) turned into a follow-up. No rows: just a text box."""+ self.releaseKeyboard() # only reaches X once we are back in the event loop, so rofi runs on a thread+ def pick():+ c = rofi(rows, prompt)+ self.asked.emit(None if c is None else c and template.format(c)) # None: Esc+ threading.Thread(target=pick, daemon=True).start()++ def pick_technique(self):+ self.ask_rofi(TECHNIQUES, 'technique', TASKS['pick'])++ def write_then(self, task):+ """Step aside so you can write on the real page; ask `task` about the new screen once you tap the badge."""+ self.pending = task+ self.releaseKeyboard()+ self.hide()+ activate(self.app_window) # so your keys reach xournal again, and so does the page-export shortcut+ self.pill = Pill(self.shot, self.top_geom(), 'Done writing? Tap here', self.retake, busy=False)+ self.pill.show()+ set_state(f'waiting {os.getpid()}')+ signal.signal(signal.SIGUSR1, lambda *a: QTimer.singleShot(0, self.retake)) # pressing an penmentor key again = done too+ QTimer.singleShot(30 * 60 * 1000, lambda: self.pending and QApplication.quit()) # nobody came back++ def retake(self):+ if not self.pending or not self.pill:+ return+ task, self.pending = self.pending, None+ signal.signal(signal.SIGUSR1, signal.SIG_IGN)+ self.pill.close()+ self.pill = None+ QTimer.singleShot(150, lambda: self.reshoot(task)) # let X repaint under the badge before the screenshot++ def reshoot(self, task):+ try:+ shot, screens, main, wins = capture()+ except Oops as ex:+ self.pill = Pill(self.shot, self.top_geom())+ self.pill.show()+ return self.pill.fail(str(ex))+ self.page_req, self.region, self.result = xournal.PageRequest(), None, None+ self.load(shot, screens, main, wins)+ self.request(task, new_shot=True)++ # --- find-the-error drill ---+ def make_drill(self, d):+ lines = [l for l in d.get('lines') or [] if isinstance(l, str)]+ wrong = d.get('wrong') if isinstance(d.get('wrong'), int) and 0 <= d['wrong'] < len(lines) else None+ maxw = self.M.width() * .6+ prob = shrink(tex_lines(display(d.get('problem')), '#E8E8EC', DRILL, 60), maxw)+ imgs = [shrink(tex(display(l), 'white', DRILL), maxw) for l in lines]+ fix = shrink(tex(display(d.get('fix')), self.pal['fix'], DRILL), maxw - 40)+ why = shrink(tex_lines(d.get('why') or '', '#C8C8D0', TIP, TIP_CH), maxw)+ said = text_img(f'line {(wrong or 0) + 1} should be', '#9A9AA5', 15)+ hint = text_img('One line has a mistake. Tap it.', '#7A7A86', 16)+ pad, num = 22, 40+ heights = [max(i.height(), 28) + 16 for i in imgs]+ W = max([prob.width(), said.width() + 12 + fix.width(), why.width(), *(i.width() for i in imgs)]) + num + 2 * pad+ reveal = max(said.height(), fix.height()) + why.height() + 34 # always reserved, so the card's size gives nothing away+ card = QRectF(self.M.center().x() - W / 2, self.M.top() + TOP + 62, W, pad + prob.height() + 18 + sum(heights) + reveal + pad)+ rows, y = [], card.top() + pad + prob.height() + 18+ for h, img in zip(heights, imgs):+ rows.append((QRectF(card.left() + 10, y, W - 20, h), img))+ y += h+ return dict(card=card, prob=prob, rows=rows, wrong=wrong, fix=fix, why=why, said=said, hint=hint, pad=pad, num=num, y=y,+ hover=None, picked=set(), revealed=False, found=False)++ def drill_row(self, pos):+ return next((i for i, (r, _) in enumerate(self.drill['rows']) if r.contains(pos)), None)++ def pick_line(self, i):+ d = self.drill+ if d['revealed'] or i in d['picked']:+ return+ d['found'] = i == d['wrong']+ if not d['found']:+ d['picked'].add(i)+ d['revealed'] = d['found'] or d['wrong'] is None or len(d['picked']) >= 2 # two misses: show it+ if d['revealed']:+ text = 'Found it' if d['found'] else f"It was line {(d['wrong'] or 0) + 1}"+ self.result = dict(self.result, headline=text, verdict='correct' if d['found'] else 'mistake')+ self.head_img = tex(text, 'white', HEAD)+ self.update()++ def draw_drill(self, p):+ d, pal = self.drill, self.pal+ p.fillRect(self.rect(), QColor(0, 0, 0, 150)) # the drill is not your page: push the page back+ c = d['card']+ panel(p, c, 14, 255)+ p.drawImage(QPointF(c.left() + d['pad'], c.top() + d['pad']), d['prob'])+ y = c.top() + d['pad'] + d['prob'].height() + 9+ p.setPen(pen('#3a3a44', 1.2))+ p.drawLine(QPointF(c.left() + d['pad'], y), QPointF(c.right() - d['pad'], y))+ p.setFont(ui_font(16))+ for i, (r, img) in enumerate(d['rows']):+ miss, hit = i in d['picked'], d['revealed'] and i == d['wrong']+ if hit or miss or (i == d['hover'] and not d['revealed']):+ p.setPen(pen(pal['error'], 2.2) if hit else Qt.PenStyle.NoPen)+ p.setBrush(QColor(255, 178, 36, 30) if miss else QColor(255, 255, 255, 16 if not hit else 0))+ p.drawRoundedRect(r, 8, 8)+ p.setPen(QColor(120, 120, 132))+ p.drawText(QRectF(r.left(), r.top(), d['num'], r.height()), Qt.AlignmentFlag.AlignCenter, str(i + 1))+ p.drawImage(QPointF(r.left() + d['num'], r.center().y() - img.height() / 2), img)+ if miss:+ p.setPen(QColor(pal['unsure']))+ p.drawText(r.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignRight, 'this line is fine')+ x, y = c.left() + d['pad'], d['y'] + 18+ if not d['revealed']:+ p.drawImage(QPointF(x, y), d['hint'])+ elif d['wrong'] is not None:+ p.drawImage(QPointF(x, y + (d['fix'].height() - d['said'].height()) / 2), d['said'])+ p.drawImage(QPointF(x + d['said'].width() + 12, y), d['fix'])+ p.drawImage(QPointF(x, y + max(d['fix'].height(), d['said'].height()) + 10), d['why'])diff --git a/src/penmentor/page.py b/src/penmentor/page.pynew file mode 100644index 0000000..4709736--- /dev/null+++ b/src/penmentor/page.py@@ -0,0 +1,100 @@+"""Where the ink is: snap Claude's rough boxes onto the handwriting, and find empty space for notes."""+import math++import numpy as np+++class Page:+ """One window (or bare monitor) of the screenshot. Every method takes and returns desktop coordinates."""++ def __init__(self, rgb, origin=(0, 0)):+ from scipy import ndimage # slow import (0.2 s): only pages need it, and they are built while Claude thinks+ self.ox, self.oy = origin # where this window sits on the desktop+ h, w = rgb.shape[:2] # paper colour = most common colour mid-window (edges are toolbars, margins)+ vals, counts = np.unique(rgb[h // 4:3 * h // 4:4, w // 4:3 * w // 4:4].reshape(-1, 3), axis=0, return_counts=True)+ self.bg = vals[counts.argmax()]+ self.dark = self.bg.mean() < 128+ occ = np.abs(rgb.astype(np.int16) - self.bg).sum(2) > 90+ f = occ.astype(np.float32)+ # long straight runs are ruling, page edges or app chrome, not handwriting+ hrun, vrun = (ndimage.uniform_filter1d(f, 121, axis=ax) > .97 for ax in (1, 0))+ self.ink = occ & ~(hrun | vrun)+ self.paper = ~occ+ self.h, self.w = occ.shape+ # app chrome = thick long bands (toolbars, status bar, panel frames); the page is the open area around+ # the window centre, and whatever the chrome walls off from it (a sidebar) is off-limits too+ solid = ndimage.binary_opening(occ, np.ones((9, 9), bool)) & (hrun | vrun)+ lab, _ = ndimage.label(~solid)+ mid = lab[h // 2, w // 2]+ chrome = (lab != mid) if mid else solid+ # notes may cover ruled lines, never handwriting or chrome+ integral = lambda m: np.pad(m.cumsum(0).cumsum(1), ((1, 0), (1, 0)))+ self.sum, self.chrome_sum = integral(ndimage.binary_dilation(self.ink, iterations=8) | chrome), integral(chrome)++ def local(self, r):+ return r[0] - self.ox, r[1] - self.oy, r[2] - self.ox, r[3] - self.oy++ def desk(self, r):+ return r[0] + self.ox, r[1] + self.oy, r[2] + self.ox, r[3] + self.oy++ def clip(self, b):+ return self.desk(self._clip(self.local(b)))++ def _clip(self, b):+ x0, y0, x1, y1 = (int(round(v)) for v in b)+ x0, x1 = sorted((min(max(x0, 0), self.w - 1), min(max(x1, 1), self.w)))+ y0, y1 = sorted((min(max(y0, 0), self.h - 1), min(max(y1, 1), self.h)))+ return x0, y0, max(x1, x0 + 1), max(y1, y0 + 1)++ def snap(self, box, pad=14):+ """Tight box around the ink strokes that lie mostly inside `box`."""+ from scipy import ndimage+ x0, y0, x1, y1 = self._clip(self.local(box))+ X0, Y0, X1, Y1 = self._clip((x0 - pad, y0 - pad, x1 + pad, y1 + pad))+ win = self.ink[Y0:Y1, X0:X1]+ lab, n = ndimage.label(ndimage.binary_dilation(win, iterations=3))+ lab = lab * win+ inside = np.zeros_like(win)+ inside[y0 - Y0:y1 - Y0, x0 - X0:x1 - X0] = True+ tot = np.bincount(lab.ravel(), minlength=n + 1)+ ins = np.bincount(lab[inside].ravel(), minlength=n + 1)+ keep = [i for i in range(1, n + 1) if ins[i] and ins[i] >= .3 * tot[i]]+ if not keep:+ return self.desk((x0, y0, x1, y1))+ ys, xs = np.nonzero(np.isin(lab, keep))+ return self.desk((X0 + xs.min(), Y0 + ys.min(), X0 + xs.max() + 1, Y0 + ys.max() + 1))++ def busy(self, r, taken, ink=True):+ x0, y0, x1, y1 = (int(v) for v in self.local(r))+ if x0 < 0 or y0 < 0 or x1 > self.w or y1 > self.h:+ return True+ S = self.sum if ink else self.chrome_sum+ if S[y1, x1] - S[y0, x1] - S[y1, x0] + S[y0, x0]:+ return True+ return any(r[0] < t[2] and t[0] < r[2] and r[1] < t[3] and t[1] < r[3] for t in taken)++ def fit(self, r, m=6):+ """r moved fully inside the window (left edge wins if it is too wide)."""+ x0, y0, x1, y1 = self.local(r)+ dx = max(min(0, self.w - m - x1), m - x0)+ dy = max(min(0, self.h - m - y1), m - y0)+ return self.desk((x0 + dx, y0 + dy, x1 + dx, y1 + dy))++ def place(self, size, target, taken):+ """Nearest empty spot for a w×h note on rings around target; right, below, above, left first."""+ w, h = size+ tx0, ty0, tx1, ty1 = target+ cx, cy, rx, ry = (tx0 + tx1) / 2, (ty0 + ty1) / 2, (tx1 - tx0 + w) / 2, (ty1 - ty0 + h) / 2+ for ink in (True, False): # no empty paper left: cover ink rather than leave the page+ for d in (24, 50, 90, 140, 210, 300, 420, 580):+ for deg in (0, 90, -90, 180, 30, -30, 60, -60, 120, -120, 150, -150):+ x = cx + math.cos(math.radians(deg)) * (rx + d) - w / 2+ y = cy + math.sin(math.radians(deg)) * (ry + d) - h / 2+ if not self.busy((x, y, x + w, y + h), taken, ink):+ return x, y, x + w, y + h+ return self.fit((tx1 + 24, cy - h / 2, tx1 + 24 + w, cy + h / 2))++ def on_writing(self, r, pad=8):+ """Does r cover handwriting on the page? (covering app chrome is fine)"""+ x0, y0, x1, y1 = self._clip(self.local((r[0] - pad, r[1] - pad, r[2] + pad, r[3] + pad)))+ return self.paper[y0:y1, x0:x1].mean() > .5 and self.ink[y0:y1, x0:x1].any()diff --git a/src/penmentor/plot.py b/src/penmentor/plot.pynew file mode 100644index 0000000..1326501--- /dev/null+++ b/src/penmentor/plot.py@@ -0,0 +1,1147 @@+"""Show me: a 3Blue1Brown-style animation of the maths on screen, made with 3b1b's own manim (manimgl), in a window+you can play with: drag to move the bound, the number of rectangles, the point on the curve...++ python -m penmentor.plot JOB.json the window. JOB = {"rect": [x, y, w, h], "parent": pid}. It opens at once+ with a loading animation; the maths comes in JOB.spec.json:+ {"spec": Claude's plot} or {"error": "..."}. Only q closes it, not Esc.+ python -m penmentor.plot --png SPEC.json OUT.png the last frame as an image (no window)+ python -m penmentor.plot --check build every kind once (penmentor --selftest)++Each kind below turns Claude's spec (see prompts.PLOT_KINDS) into mobjects, an intro animation, and a knob.+Runs in the Python that has manimgl (see README), not necessarily penmentor's own.+"""+import json+import math+import os+import re+import subprocess+import sys+import time+from pathlib import Path++_argv, sys.argv = sys.argv, ['manimgl'] # manimlib parses the command line when it is imported+from manimlib import * # noqa: E402,F403 (manim's own idiom)+from manimlib.window import Window # noqa: E402+from moderngl_window.context.pyglet.window import Window as PygletWindow # noqa: E402+sys.argv = _argv++from .expr import formula, number # noqa: E402++# 3Blue1Brown's settings, from github.com/3b1b/videos custom_config.yml; everything else (letter and line spacing,+# Tex, sizes) stays at manim's defaults, as in his videos+manim_config.camera.background_color = '#000000'+manim_config.text.font, manim_config.text.alignment = 'CMU Serif', 'CENTER'+SPIN = '#4EA8FF' # style.SPIN: the loader's blue+MONO = 'CMU Typewriter Text' # 3b1b's typewriter face, fixed width: for the values you type+HINT = 'drag to explore · click a value to change it · scroll to zoom · space replay · q close'+FIELDS = ('f', 'g', 'a', 'b', 'n') # the values you can click and retype+NAMES = {'series': {'f': 'a_n'}, 'polar': {'f': r'r(\theta)'}, 'parametric': {'f': 'x(t)', 'g': 'y(t)'},+ 'substitution': {'f': 'f(u)', 'g': 'u'}, 'taylor': {'g': r'\text{term}_k'}}+VARS = {'series': {'f': ('n',)}, 'polar': {'f': ('t',)}, 'parametric': {'f': ('t',), 'g': ('t',)},+ 'substitution': {'f': ('u', 'x')}, 'taylor': {'g': ('k', 'x')}} # the variables each formula is in (default x)+WAIT = 600 # s: give up on Claude after this+++def cmu_serif():+ """CMU Serif (words) and CMU Typewriter (what you type) ship with TeX Live; Pango only needs to be told where."""+ import manimpango+ for name in ('cmunrm.otf', 'cmuntt.otf'):+ if p := subprocess.run(['kpsewhich', name], capture_output=True, text=True).stdout.strip():+ manimpango.register_font(p)+++# ---------- helpers ----------++def fn(s, key, names=('x',), default=None):+ src = s.get(key) or default+ if not src:+ raise ValueError(f'the plot needs "{key}"')+ f = formula(src, names)+ return lambda **kw: np.broadcast_to(np.asarray(f(**kw), float), np.shape(next(iter(kw.values()))))+++def bounds(s, a=0., b=1.):+ a, b = number(s.get('a'), a), number(s.get('b'), b)+ return (a, b) if a <= b else (b, a)+++def around(a, b, m=.15):+ d = (b - a) * m or 1+ return a - d, b + d+++def integral(y, x):+ from scipy.integrate import cumulative_trapezoid+ return cumulative_trapezoid(np.nan_to_num(y), x, initial=0)+++def step_for(span):+ """A round tick step giving about 8 ticks."""+ raw = span / 8 or 1+ mag = 10 ** math.floor(math.log10(raw))+ return next(m * mag for m in (1, 2, 5, 10) if m * mag >= raw)+++def spread(*ys, pad=.12):+ """y from the curves (ignoring blow-ups) and 0."""+ v = np.concatenate([np.ravel(np.asarray(y, float)) for y in ys] + [np.zeros(1)])+ v = v[np.isfinite(v)]+ lo, hi = np.percentile(v, [1, 99]) if v.size > 2 else (-1, 1)+ lo, hi = min(lo, 0), max(hi, 0)+ hi = hi if hi - lo > 1e-9 else lo + 1+ return lo - (hi - lo) * pad, hi + (hi - lo) * pad+++def plot_axes(x0, x1, y0, y1, width=12, height=4.8, labels=True):+ """Axes through the origin (manim draws them there), with round ticks."""+ x0, x1, y0, y1 = min(x0, 0), max(x1, 0), min(y0, 0), max(y1, 0) # ponytail: far-off ranges get squashed; shift the origin if that matters+ sx, sy = step_for(x1 - x0), step_for(y1 - y0)+ xr = (math.floor(x0 / sx) * sx, math.ceil(x1 / sx) * sx, sx)+ yr = (math.floor(y0 / sy) * sy, math.ceil(y1 / sy) * sy, sy)+ axes = Axes(xr, yr, width=width, height=height)+ if labels:+ for axis, step in ((axes.x_axis, sx), (axes.y_axis, sy)):+ axis.add_numbers(font_size=20, excluding=[0], num_decimal_places=max(0, -math.floor(math.log10(step)))).set_opacity(.8)+ return axes+++def curve(axes, xs, ys, color=BLUE, width=4):+ """The graph through (xs, ys), broken where it is undefined or leaves the axes."""+ y0, y1 = axes.y_range[:2]+ xs, ys = np.asarray(xs, float), np.asarray(ys, float)+ ok = np.isfinite(ys) & (ys > y0 - (y1 - y0) * .02) & (ys < y1 + (y1 - y0) * .02)+ pts = axes.c2p(xs, np.clip(np.nan_to_num(ys), y0, y1))+ ends = np.flatnonzero(np.diff(np.r_[0, ok.astype(int), 0])) # where the defined stretches start and stop+ return VGroup(*[VMobject().set_points_as_corners(pts[a:b]) for a, b in zip(ends[::2], ends[1::2]) if b - a > 1]).set_stroke(color, width)+++def region(axes, xs, top, bottom, color=BLUE, opacity=.4):+ """Shade between two curves: blue where top is above, red where it is below (signed area)."""+ y0, y1 = axes.y_range[:2]+ top, bottom = np.clip(np.nan_to_num(top), y0, y1), np.clip(np.nan_to_num(bottom), y0, y1)+ out = VGroup()+ for hi, lo, c in ((np.maximum(top, bottom), bottom, color), (bottom, np.minimum(top, bottom), RED)):+ if len(xs) > 1 and np.any(hi - lo > 1e-12):+ pts = np.vstack([axes.c2p(xs, hi), axes.c2p(xs[::-1], lo[::-1])])+ out.add(Polygon(*pts, stroke_width=0, fill_color=c, fill_opacity=opacity))+ return out+++def num(v, places=2, size=24):+ """A number as manim shows changing numbers: DecimalNumber reuses typeset digits, where Tex would run LaTeX+ (half a second) for every new value."""+ return DecimalNumber(v + 0, num_decimal_places=places, font_size=size)+++def coords(x, y):+ """(x, y) the 3b1b way: Tex for the brackets (typeset once), DecimalNumbers for the values."""+ places = lambda v: 0 if abs(v - round(v)) < 5e-4 else 2+ out = VGroup(Tex('(', font_size=24), num(x, places(x)), Tex(r',', font_size=24), num(y, places(y)),+ Tex(')', font_size=24)).arrange(RIGHT, buff=.05, aligned_edge=DOWN)+ out[3:].shift(RIGHT * .1) # a thin space after the comma, as LaTeX sets "(x,\ y)"+ return out+++def point_mark(axes, x, y, guide=True):+ """A point that matters, on top of everything: dashed guide down to the x-axis, dot, and its coordinates on a dark+ backing (3b1b style) so they read over the curves."""+ dot = Dot(axes.c2p(x, y), radius=.07, fill_color=WHITE)+ label = coords(x, y).next_to(dot, UR, buff=.08)+ line = DashedLine(axes.c2p(x, 0), axes.c2p(x, y), dash_length=.06).set_stroke(GREY_A, 2) if guide and abs(y) > 1e-9 else VGroup()+ return VGroup(line, dot, BackgroundRectangle(label, fill_opacity=.9, buff=.06), label).set_z_index(10)+++def bound_marks(sc, axes, f, g, a, b):+ """The vertical lines x = a and x = b, up to the curve(s), with where they meet them; drag one to move the bound."""+ sc.live, sc.handles = {'a': a, 'b': b}, [('a', axes), ('b', axes)]++ def mark(key):+ x = sc.live[key]+ y = float(np.nan_to_num(f(x=np.array([x]))[0]))+ out = point_mark(axes, x, y)+ if g is not None:+ yg = float(np.nan_to_num(g(x=np.array([x]))[0]))+ out.add(Line(axes.c2p(x, 0), axes.c2p(x, yg)).set_stroke(GREY_A, 2), point_mark(axes, x, yg, guide=False))+ tag = Tex(key, font_size=28).set_color(YELLOW).next_to(axes.c2p(x, 0), DOWN if y >= 0 else UP, buff=.52) # past the tick numbers+ if abs(axes.c2p(x, 0)[0] - axes.c2p(0, 0)[0]) < .3: # on the y-axis: beside its numbers, not on them+ tag.shift(RIGHT * .3)+ return out.add(tag).set_z_index(10)+ return VGroup(*[redraw(lambda key=key: mark(key), lambda key=key: sc.live[key]) for key in ('a', 'b')])+++def crossings(axes, xs, F, G, most=6, skip=()):+ """Where F and G cross (G = 0: where F meets the x-axis), marked with point_mark. Jumps (asymptotes) are not+ crossings; x's in skip already have a mark (a bound)."""+ d = np.asarray(F, float) - np.asarray(G, float)+ span = axes.y_range[1] - axes.y_range[0]+ out = VGroup()+ for i in range(len(xs) - 1):+ a, b = d[i], d[i + 1]+ if not (np.isfinite(a) and np.isfinite(b)) or a * b > 0 or a == b or abs(a - b) > span / 2:+ continue+ if a == 0 and i and d[i - 1] == 0: # touching along a stretch: one dot is enough+ continue+ x = xs[i] - a * (xs[i + 1] - xs[i]) / (b - a)+ y = float(np.interp(x, xs, np.asarray(G, float)))+ near = (xs[-1] - xs[0]) / 60+ if out and abs(x - out[-1].x) < near or any(abs(x - v) < near for v in skip) or not axes.y_range[0] <= y <= axes.y_range[1]:+ continue+ mark = point_mark(axes, x, y)+ mark.x = x+ out.add(mark)+ if len(out) == most:+ break+ return out+++def reveal(marks):+ """The marks, one after another, each settling into place. Each is animated whole: animating a part of a group+ makes manim break the group up in the scene, and a bound mark's updater (it follows your drag) would be lost."""+ return LaggedStart(*[FadeIn(m, shift=DOWN * .15, scale=1.15) for m in marks], lag_ratio=.35, run_time=.6 + .3 * len(marks))+++def follow(mob, ends):+ """Keep a line (or arrow) on ends() = (start, end): moved each frame it changes, not rebuilt."""+ last = [None]++ def update(m):+ p, q = ends()+ if last[0] is None or not (np.allclose(p, last[0][0]) and np.allclose(q, last[0][1])):+ last[0] = (p, q)+ m.put_start_and_end_on(p, q + (UP * 1e-4 if np.allclose(p, q) else 0))+ return mob.add_updater(update)+++def redraw(make, key):+ """Like always_redraw, but rebuilt only when key() changes (while you drag or it animates), not every frame."""+ mob, last = make(), [key()]++ def update(m):+ if (k := key()) != last[0]:+ last[0] = k+ m.become(make())+ return mob.add_updater(update)+++def ticker(get, places, rate=20):+ """A DecimalNumber updater: retypesetting a number costs ~3 ms, so it changes at most `rate` times a second+ (faster than anyone reads it) and only when what it shows changes; the motion around it stays at 60 fps."""+ since = [1.]++ def update(m, dt):+ since[0] += dt+ if since[0] >= 1 / rate and round(v := float(np.nan_to_num(get())), places) != round(m.get_value(), places):+ m.set_value(v)+ since[0] = 0+ return update+++def readout(*rows):+ """Live numbers in a row under the title: (tex label, getter[, decimals]), or any mobject (a coloured name)."""+ out = VGroup()+ for row in rows:+ if isinstance(row, Mobject):+ out.add(row)+ continue+ label, get, *places = row+ d = DecimalNumber(get(), num_decimal_places=places[0] if places else 3, font_size=32)+ d.add_updater(ticker(get, d.num_decimal_places))+ out.add(VGroup(Tex(label, font_size=32), d).arrange(RIGHT, buff=.15))+ return out.arrange(RIGHT, buff=.9).move_to(UP * 2.75).fix_in_frame()+++def inside(m, p):+ """p within m's bounding box (on screen: x and y)."""+ (x0, y0, _), (x1, y1, _) = m.get_corner(DL), m.get_corner(UR)+ return x0 <= p[0] <= x1 and y0 <= p[1] <= y1+++def frac_x(axes, p):+ return (p[0] - axes.get_left()[0]) / max(axes.get_width(), 1e-9)+++def pretty(src):+ """A Python formula as LaTeX for a label: x**2/(1+x) -> x^{2}/(1+x)."""+ import re+ t = re.sub(r'\*\*\(([^()]*)\)|\*\*([\w.]+)', lambda m: '^{' + (m[1] or m[2]) + '}', src).replace('*', r'\,')+ t = re.sub(r'\bsqrt\(([^()]*)\)', r'\\sqrt{\1}', t)+ t = re.sub(r'\bfactorial\(([^()]*)\)', r'(\1)!', t)+ t = re.sub(r'\binf\b', r'\\infty', t)+ return re.sub(r'\b(exp|log|ln|sin|cos|tan|arctan|arcsin|arccos|sinh|cosh|tanh|pi)\b', r'\\\1', t)+++def nonzero(src):+ return (src or '0').strip() not in ('0', '0.0')+++def tex_or_text(tex, plain, **kw):+ try:+ return Tex(tex, **kw)+ except Exception: # LaTeX choked on it+ return Text(plain, **kw)+++# ---------- the kinds: each adds its mobjects, plays its intro, and sets sc.knob (ValueTracker, lo, hi, drag) ----------++def area(sc, s):+ f, g = fn(s, 'f'), fn(s, 'g', default='0')+ a, b = bounds(s)+ lo, hi = around(a, b)+ xs = np.linspace(lo, hi, 600)+ axes = plot_axes(lo, hi, *spread(f(x=xs), g(x=xs))).shift(DOWN * .4)+ graphs = VGroup(curve(axes, xs, f(x=xs)), *([curve(axes, xs, g(x=xs), YELLOW)] if nonzero(s.get('g')) else []))+ xi = np.linspace(a, b, 240)+ fi, gi = f(x=xi), g(x=xi)+ total = integral(fi - gi, xi)+ k = ValueTracker(a)+ upto = lambda: max(2, int(np.searchsorted(xi, k.get_value())) + 1)+ shade = redraw(lambda: region(axes, xi[:upto()], fi[:upto()], gi[:upto()]), upto)+ edge = follow(Line(UP, DOWN).set_stroke(YELLOW, 2.5, .9).set_z_index(8), lambda: (+ axes.c2p(k.get_value(), 0), axes.c2p(k.get_value(), float(np.nan_to_num(f(x=np.array([k.get_value()]))[0])))))+ nums = readout(('x =', k.get_value), (r'\text{area} \approx', lambda: np.interp(k.get_value(), xi, total)))+ meets = crossings(axes, xs, f(x=xs), g(x=xs), skip=(a, b))+ ends = bound_marks(sc, axes, f, g if nonzero(s.get('g')) else None, a, b)+ sc.play(ShowCreation(axes), run_time=1)+ sc.play(*map(ShowCreation, graphs), run_time=1.5)+ sc.add(shade, edge, graphs, ends) # ends itself too: its updater moves the lines while you drag a bound+ sc.play(reveal(ends))+ sc.play(reveal(meets)) if meets else None+ sc.play(FadeIn(nums, shift=DOWN * .1))+ sc.knob, sc.zone = (k, a, b, lambda p: axes.p2c(p)[0]), axes+ sc.wait(.3)+ sc.play(k.animate.set_value(b), run_time=3)+++def riemann(sc, s):+ f = fn(s, 'f')+ a, b = bounds(s)+ most = min(max(int(s.get('n') or 32), 2), 256)+ lo, hi = around(a, b, .08)+ xs = np.linspace(lo, hi, 600)+ axes = plot_axes(lo, hi, *spread(f(x=xs))).shift(DOWN * .4)+ graph = curve(axes, xs, f(x=xs))+ xi = np.linspace(a, b, 4000)+ exact = integral(f(x=xi), xi)[-1]+ k = ValueTracker(0) # log2 of n+ n_now = lambda: max(1, round(2 ** k.get_value()))++ def bars(n=None):+ n = n or n_now()+ w = (b - a) / n+ left = a + w * np.arange(n)+ h = np.nan_to_num(f(x=left + w / 2))+ y0, y1 = axes.y_range[:2]+ out = VGroup(*[Polygon(axes.c2p(x, 0), axes.c2p(x + w, 0), axes.c2p(x + w, min(max(v, y0), y1)),+ axes.c2p(x, min(max(v, y0), y1))) for x, v in zip(left, h)])+ out.set_submobject_colors_by_gradient(BLUE, GREEN) # manim's own Riemann rectangles+ out.set_style(stroke_color=BLACK, stroke_width=1 if n < 64 else 0, fill_opacity=.75)+ for r_, v in zip(out, h):+ r_.set_fill(RED) if v < 0 else None+ return out+ rects = redraw(bars, n_now)+ rects.suspend_updating()+ sum_now = lambda: float(np.nan_to_num(f(x=a + (b - a) / n_now() * (np.arange(n_now()) + .5))).sum() * (b - a) / n_now())+ nums = readout(('n =', n_now, 0), (r'\text{sum} \approx', sum_now), (r'\text{exact} \approx', lambda: exact))+ meets = crossings(axes, xs, f(x=xs), 0 * xs, skip=(a, b))+ ends = bound_marks(sc, axes, f, None, a, b)+ sc.play(ShowCreation(axes), run_time=1)+ sc.play(ShowCreation(graph), run_time=1.5)+ sc.add(rects, graph, meets, ends)+ sc.play(reveal(ends))+ sc.play(reveal(meets)) if meets else None+ sc.play(FadeIn(rects, lag_ratio=.1), FadeIn(nums, shift=DOWN * .1))+ top = math.log2(most)+ for n in sorted({min(2 ** i, most) for i in range(1, math.ceil(top) + 1)}) if not sc.quick else [most]: # each rectangle splits in two+ sc.wait(.25)+ sc.play(Transform(rects, bars(n)), k.animate.set_value(math.log2(n)), run_time=.9)+ rects.resume_updating()+ sc.knob, sc.zone = (k, 0, top, lambda p: frac_x(axes, p) * top), axes+++def improper(sc, s):+ from scipy.integrate import quad+ f = fn(s, 'f')+ a, b = number(s.get('a'), 0), number(s.get('b'), np.inf)+ toward = s.get('toward') or ('a' if np.isinf(a) and not np.isinf(b) else 'b')+ if toward == 'b':+ start = a+ path = (lambda u: a + 10 ** (3 * u) - 1) if np.isinf(b) else (lambda u: b - (b - a) / 2 * 10 ** (-4 * u))+ view = (a, a + 12) if np.isinf(b) else (a, b)+ else:+ start = b+ path = (lambda u: b - 10 ** (3 * u) + 1) if np.isinf(a) else (lambda u: a + (b - a) / 2 * 10 ** (-4 * u))+ view = (b - 12, b) if np.isinf(a) else (a, b)+ point = lambda x: float(np.nan_to_num(f(x=np.array([x]))[0], posinf=0, neginf=0))+ us = np.linspace(0, 1, 160)+ ts = np.array([path(u) for u in us])+ vals = np.array([quad(point, min(start, t), max(start, t), limit=200)[0] for t in ts])+ lo, hi = around(*view, .04)+ xs = np.linspace(lo, hi, 600)+ axes = plot_axes(lo, hi, *spread(f(x=xs)), width=7.6, height=4.8).to_edge(LEFT, buff=.7).shift(DOWN * .4)+ graph = curve(axes, xs, f(x=xs))+ side = plot_axes(0, 1, *spread(vals), width=4, height=3, labels=False).to_edge(RIGHT, buff=.8).shift(DOWN * .4)+ side_title = Text('area so far', font_size=24).next_to(side, UP)+ k = ValueTracker(0)+ t_now = lambda: float(np.interp(k.get_value(), us, ts))+ upto = lambda: round(k.get_value() * 200)+ seen = lambda: min(max(t_now(), lo), hi)+ shade = redraw(lambda: region(axes, (X := np.linspace(min(start, seen()), max(start, seen()), 200)),+ np.clip(f(x=X), *axes.y_range[:2]), 0 * X), upto)+ trail = redraw(lambda: curve(side, us[:max(2, int(k.get_value() * 159) + 1)], vals[:max(2, int(k.get_value() * 159) + 1)],+ YELLOW, 3), upto)+ limit = DashedLine(side.c2p(0, vals[-1]), side.c2p(1, vals[-1]), stroke_color=GREY_B, stroke_width=1.5)+ nums = readout(('t =', t_now, 2), (r'\text{area} \approx', lambda: np.interp(k.get_value(), us, vals)))+ sc.play(ShowCreation(axes), ShowCreation(side), FadeIn(side_title), run_time=1)+ sc.play(ShowCreation(graph), ShowCreation(limit), run_time=1.5)+ sc.add(shade, graph, trail)+ sc.play(FadeIn(nums, shift=DOWN * .1))+ sc.knob, sc.zone = (k, 0, 1, lambda p: frac_x(axes, p)), axes+ sc.wait(.3)+ sc.play(k.animate.set_value(1), run_time=4.5)+++def substitution(sc, s):+ f, g = fn(s, 'f', ('u', 'x')), fn(s, 'g')+ a, b = bounds(s)+ x = np.linspace(a, b, 300)+ u = g(x=x)+ h = (b - a) * 1e-5+ y0 = f(u=u, x=x) * (g(x=x + h) - g(x=x - h)) / (2 * h) # f(g(x)) g'(x)+ y1 = f(u=u, x=x)+ both = np.concatenate([x, u])+ lo, hi = around(np.nanmin(both), np.nanmax(both), .08)+ axes = plot_axes(lo, hi, *spread(y0, y1)).shift(DOWN * .4)+ k = ValueTracker(0)+ shape = lambda: ((1 - k.get_value()) * x + k.get_value() * u, (1 - k.get_value()) * y0 + k.get_value() * y1)+ colour = lambda: interpolate_color(BLUE, YELLOW, k.get_value())+ key = lambda: round(k.get_value(), 3)+ line = redraw(lambda: curve(axes, *shape(), colour()), key)+ shade = redraw(lambda: region(axes, *shape(), 0 * x, colour(), .3), key)+ value = integral(y0, x)[-1]+ before = Tex(r"\int f(g(x))\,g'(x)\,dx", font_size=36)+ after = Tex(r'\int f(u)\,du', font_size=36)+ for t in (before, after):+ t.move_to(UP * 2.75 + LEFT * 1.6).fix_in_frame()+ before.add_updater(lambda m: m.set_opacity(1 - k.get_value()))+ after.add_updater(lambda m: m.set_opacity(k.get_value()))+ nums = readout((r'\text{area} \approx', lambda: value)).next_to(before, RIGHT, buff=.9)+ sc.play(ShowCreation(axes), run_time=1)+ sc.add(shade, line)+ sc.play(FadeIn(shade), ShowCreation(line), FadeIn(before), FadeIn(nums), run_time=1.5)+ sc.add(after)+ sc.knob, sc.zone = (k, 0, 1, lambda p: frac_x(axes, p)), axes+ sc.wait(.5)+ sc.play(k.animate.set_value(1), run_time=3.5)+++def revolution(sc, s):+ f, g = fn(s, 'f'), fn(s, 'g', default='0')+ a, b = bounds(s)+ spin_y = s.get('axis') == 'y'+ x = np.linspace(a, b, 200)+ F, G = np.nan_to_num(f(x=x)), np.nan_to_num(g(x=x))+ if spin_y: # shells: the region between the curves, at distance |x| from the axis+ vol = 2 * np.pi * integral(np.abs(x) * np.abs(F - G), x)[-1]+ else: # washers+ vol = np.pi * integral(F ** 2 - G ** 2, x)[-1]+ m = max(np.max(np.abs(F)), np.max(np.abs(G)), np.max(np.abs(x)) if spin_y else 0, 1e-9) * 1.1+ rng = lambda lo_, hi_: (lo_, hi_, step_for(hi_ - lo_))+ axes = ThreeDAxes(rng(-m, m) if spin_y else rng(min(a, 0), max(b, 0)), rng(-m, m), rng(min(0, F.min()), m) if spin_y else rng(-m, m),+ width=5, height=4, depth=4)+ R = lambda v: float(np.interp(v, x, F))+ r = lambda v: float(np.interp(v, x, G))+ if spin_y:+ sheet = lambda h, frac: ParametricSurface(lambda uu, vv: axes.c2p(uu * math.cos(vv), uu * math.sin(vv), h(uu)),+ u_range=(a, b), v_range=(0, TAU * frac), resolution=(64, 64))+ profile = curve(axes, x, F, YELLOW).rotate(PI / 2, RIGHT, about_point=axes.c2p(0, 0, 0))+ else:+ sheet = lambda h, frac: ParametricSurface(lambda uu, vv: axes.c2p(uu, h(uu) * math.cos(vv), h(uu) * math.sin(vv)),+ u_range=(a, b), v_range=(0, TAU * frac), resolution=(64, 64))+ profile = curve(axes, x, F, YELLOW)+ k = ValueTracker(.02)+ surfaces = redraw(lambda: Group(sheet(R, k.get_value()).set_color(BLUE, .55),+ *([sheet(r, k.get_value()).set_color(TEAL, .55)] if s.get('g') else [])),+ lambda: round(k.get_value(), 3))+ nums = readout((r'V \approx', lambda: vol))+ sc.frame.reorient(-50, 65, 0, (0, 0, .4), 9.5)+ sc.play(ShowCreation(axes), ShowCreation(profile), FadeIn(nums), run_time=1.5)+ sc.add(surfaces)+ sc.bring_to_front(*[m for m in sc.mobjects if m.is_fixed_in_frame()]) # the title stays over the solid+ sc.knob, sc.zone = (k, .02, 1, None), None # dragging turns the view instead, anywhere+ turn = lambda fr, dt: fr.increment_theta(dt * .1)+ sc.frame.add_updater(turn)+ sc.play(k.animate.set_value(1), run_time=4)+ sc.wait(1)+ sc.frame.remove_updater(turn)+++def series(sc, s):+ t = fn(s, 'f', ('n',))+ start = int(number(s.get('a'), 1))+ count = min(max(int(s.get('n') or 25), 2), 300)+ n = np.arange(start, start + count, dtype=float)+ an = t(n=n)+ S = np.nancumsum(an)+ far = [(k_, np.nansum(t(n=np.arange(start, start + k_, dtype=float)))) for k_ in (10 ** 3, 10 ** 5)]+ top = plot_axes(n[0] - 1, n[-1] + 1, *spread(an), height=2).shift(UP * .9)+ bottom = plot_axes(n[0] - 1, n[-1] + 1, *spread(S), height=2).shift(DOWN * 1.8)+ labels = VGroup(*[Tex(t_, font_size=30).next_to(ax.y_axis.get_top(), RIGHT) for t_, ax in (('a_n', top), ('S_n', bottom))])+ k = ValueTracker(1)+ shown = lambda: int(min(max(k.get_value(), 1), count))+ bars = redraw(lambda: VGroup(*[Line(top.c2p(v, 0), top.c2p(v, np.clip(np.nan_to_num(y), *top.y_range[:2])),+ stroke_color=BLUE, stroke_width=6) for v, y in zip(n[:shown()], an[:shown()])]), shown)+ dots = redraw(lambda: VGroup(*[Dot(bottom.c2p(v, np.clip(np.nan_to_num(y), *bottom.y_range[:2])), radius=.05, fill_color=YELLOW)+ for v, y in zip(n[:shown()], S[:shown()])]), shown)+ nums = readout(('n =', lambda: n[shown() - 1], 0), (r'S_n =', lambda: S[shown() - 1]))+ tail = readout(*[(rf'S_{{{k_}}} \approx', lambda v=v: v, 5) for k_, v in far]).set_color(GREY_B).next_to(nums, DOWN, buff=.15)+ sc.play(ShowCreation(top), ShowCreation(bottom), FadeIn(labels), FadeIn(nums, shift=DOWN * .1), run_time=1.2)+ sc.add(bars, dots)+ sc.knob, sc.zone = (k, 1, count, lambda p: 1 + frac_x(top, p) * count), VGroup(top, bottom)+ sc.wait(.3)+ sc.play(k.animate.set_value(count), run_time=4.5)+ sc.play(FadeIn(tail, shift=DOWN * .1))+++def taylor(sc, s):+ f, term = fn(s, 'f'), fn(s, 'g', ('k', 'x'))+ a, b = bounds(s, -3, 3)+ count = min(max(int(s.get('n') or 8), 1), 40)+ x = np.linspace(a, b, 500)+ F = f(x=x)+ P = np.nancumsum([np.nan_to_num(term(k=np.full_like(x, k_), x=x)) for k_ in range(count)], axis=0)+ axes = plot_axes(a, b, *spread(F, pad=.5)).shift(DOWN * .4)+ graph = curve(axes, x, F, BLUE, 6)+ k = ValueTracker(1)+ m_now = lambda: int(min(max(round(k.get_value()), 1), count))+ poly = lambda m: curve(axes, x, P[m - 1], YELLOW, 4)+ approx = redraw(lambda: poly(m_now()), m_now)+ approx.suspend_updating()+ nums = readout((r'\text{terms} =', m_now, 0))+ sc.play(ShowCreation(axes), run_time=1)+ sc.play(ShowCreation(graph), run_time=1.5)+ sc.add(approx)+ sc.play(ShowCreation(approx), FadeIn(nums, shift=DOWN * .1))+ for m in sorted({round(v) for v in np.linspace(1, count, 12)} - {1}): # more terms: it bends further along the curve+ sc.wait(.2)+ sc.play(Transform(approx, poly(m)), k.animate.set_value(m), run_time=.8)+ approx.resume_updating()+ sc.knob, sc.zone = (k, 1, count, lambda p: 1 + frac_x(axes, p) * (count - 1)), axes+++def trace(sc, s, xy, polar_):+ a, b = bounds(s, 0, 2 * np.pi)+ t = np.linspace(a, b, 600)+ X, Y = xy(t)+ ok = np.isfinite(X) & np.isfinite(Y)+ m = max(np.max(np.abs(X[ok])) if ok.any() else 1, np.max(np.abs(Y[ok])) if ok.any() else 1) * 1.15+ unit = min(12 / (2 * m), 5.4 / (2 * m)) # equal scales: a circle stays round+ axes = plot_axes(-m, m, -m, m, width=2 * m * unit, height=2 * m * unit).shift(DOWN * .4)+ ghost = curve(axes, X, Y, GREY_D, 2)+ swept = integral(.5 * (X ** 2 + Y ** 2), t) if polar_ else integral(np.hypot(np.gradient(X, t), np.gradient(Y, t)), t)+ k = ValueTracker(0)+ i_now = lambda: int(min(max(k.get_value(), 0), 1) * (len(t) - 1))+ path = redraw(lambda: curve(axes, X[:i_now() + 2], Y[:i_now() + 2], BLUE, 4), i_now)+ head = lambda: axes.c2p(np.nan_to_num(X[i_now()]), np.nan_to_num(Y[i_now()]))+ dot = Dot(head(), radius=.08, fill_color=YELLOW).set_z_index(8).add_updater(lambda m: m.move_to(head()))+ if polar_:+ arm = follow(Line(LEFT, RIGHT).set_stroke(YELLOW, 3), lambda: (axes.c2p(0, 0), head()))+ fan = redraw(lambda: Polygon(axes.c2p(0, 0), *axes.c2p(np.nan_to_num(X[:i_now() + 2]), np.nan_to_num(Y[:i_now() + 2])),+ stroke_width=0, fill_color=BLUE, fill_opacity=.25), i_now)+ nums = readout((r'\theta =', lambda: t[i_now()]), (r'\text{area} \approx', lambda: swept[i_now()]))+ else:+ dX, dY = np.gradient(X, t), np.gradient(Y, t)+ sc_ = lambda i: m * .25 / (math.hypot(dX[i], dY[i]) or 1)+ arm = follow(Arrow(LEFT, RIGHT, buff=0).set_color(YELLOW), lambda: (+ head(), axes.c2p(X[i_now()] + dX[i_now()] * sc_(i_now()), Y[i_now()] + dY[i_now()] * sc_(i_now()))))+ fan = VGroup()+ nums = readout(('t =', lambda: t[i_now()]), (r'\text{length} \approx', lambda: swept[i_now()]))++ def nearest(p): # drag the point along the curve+ px, py = axes.p2c(p)[:2]+ return float(np.nanargmin((X - px) ** 2 + (Y - py) ** 2)) / (len(t) - 1)+ sc.play(ShowCreation(axes), ShowCreation(ghost), run_time=1.2)+ sc.add(fan, path, arm, dot)+ sc.play(FadeIn(nums, shift=DOWN * .1), GrowFromCenter(dot))+ sc.knob, sc.zone = (k, 0, 1, nearest), axes+ sc.wait(.3)+ sc.play(k.animate.set_value(1), run_time=5)+++def polar(sc, s):+ r = fn(s, 'f', ('t',))+ return trace(sc, s, lambda t: (r(t=t) * np.cos(t), r(t=t) * np.sin(t)), True)+++def parametric(sc, s):+ fx, fy = fn(s, 'f', ('t',)), fn(s, 'g', ('t',))+ return trace(sc, s, lambda t: (fx(t=t), fy(t=t)), False)+++def curves(sc, s):+ f, g = fn(s, 'f'), fn(s, 'g', default='0')+ a, b = bounds(s)+ x = np.linspace(a, b, 600)+ F, G = f(x=x), g(x=x)+ axes = plot_axes(a, b, *spread(F, G)).shift(DOWN * .4)+ cf, cg = curve(axes, x, F), curve(axes, x, G, YELLOW)+ names = VGroup(tex_or_text(pretty(s['f']), s['f'], font_size=30).set_color(BLUE),+ tex_or_text(pretty(s.get('g') or '0'), s.get('g') or '0', font_size=30).set_color(YELLOW))+ between = region(axes, x[::3], F[::3], G[::3], BLUE, .15)+ k = ValueTracker(a)+ at = lambda: (k.get_value(), float(np.interp(k.get_value(), x, np.nan_to_num(F))), float(np.interp(k.get_value(), x, np.nan_to_num(G))))+ cut = follow(Line(UP, DOWN).set_stroke(WHITE, 3).set_z_index(8), lambda: (axes.c2p(at()[0], at()[2]), axes.c2p(at()[0], at()[1])))+ nums = readout(*names, ('x =', lambda: at()[0]), (r'f(x) - g(x) =', lambda: at()[1] - at()[2]))+ meets = crossings(axes, x, F, G)+ sc.play(ShowCreation(axes), run_time=1)+ sc.play(ShowCreation(cf), ShowCreation(cg), run_time=2)+ sc.add(between, cf, cg, meets)+ sc.play(FadeIn(between), FadeIn(nums, shift=DOWN * .1))+ sc.play(reveal(meets)) if meets else None+ sc.play(ShowCreation(cut))+ sc.knob, sc.zone = (k, a, b, lambda p: axes.p2c(p)[0]), axes+ sc.wait(.3)+ sc.play(k.animate.set_value(b), run_time=3.5)+++KINDS = dict(area=area, riemann=riemann, improper=improper, substitution=substitution, revolution=revolution,+ series=series, taylor=taylor, polar=polar, parametric=parametric, curves=curves)+++class Field:+ """The value you are typing: its text, the caret and the selection (anchor..caret), edited like any text box."""++ def __init__(self, key, text, now):+ self.key, self.text = key, text+ self.anchor, self.caret = 0, len(text) # all selected at first: typing replaces it, an arrow keeps it+ self.touched, self.clicked, self.geom = now, -1, (0, 1)++ def span(self):+ return None if self.anchor is None or self.anchor == self.caret else tuple(sorted((self.anchor, self.caret)))++ def selected(self):+ lo, hi = self.span()+ return self.text[lo:hi]++ def insert(self, t):+ if sel := self.span():+ self.text, self.caret = self.text[:sel[0]] + self.text[sel[1]:], sel[0]+ self.text = self.text[:self.caret] + t + self.text[self.caret:]+ self.caret, self.anchor = self.caret + len(t), None++ def move(self, motion, select):+ """A pyglet text motion: arrows, Ctrl+arrows (a word), Home/End, Backspace/Delete; select: with Shift."""+ import re+ from pyglet.window import key+ if motion in (key.MOTION_BACKSPACE, key.MOTION_DELETE):+ if not self.span():+ c = self.caret+ self.anchor, self.caret = (c, max(c - 1, 0)) if motion == key.MOTION_BACKSPACE else (c, min(c + 1, len(self.text)))+ return self.insert('')+ sel = self.span()+ if select and self.anchor is None:+ self.anchor = self.caret+ c, n = self.caret, len(self.text)+ words = [m.start() for m in re.finditer(r'\w+', self.text)] + [n]+ if not select and sel and motion in (key.MOTION_LEFT, key.MOTION_RIGHT):+ c = sel[0] if motion == key.MOTION_LEFT else sel[1] # an arrow on a selection lands at its end+ else:+ c = {key.MOTION_LEFT: c - 1, key.MOTION_RIGHT: c + 1, key.MOTION_BEGINNING_OF_LINE: 0, key.MOTION_END_OF_LINE: n,+ key.MOTION_BEGINNING_OF_FILE: 0, key.MOTION_END_OF_FILE: n,+ key.MOTION_PREVIOUS_WORD: max([w for w in words if w < c] or [0]),+ key.MOTION_NEXT_WORD: min([w for w in words if w > c] or [n])}.get(motion, c)+ self.caret = min(max(c, 0), n)+ if not select:+ self.anchor = None+++# ---------- the scene and its window ----------++class Show(Scene):+ """Loading animation until the maths arrives, then the kind's intro, then yours to play with."""+ drag_to_pan = False # dragging moves the knob; scroll still zooms++ def __str__(self):+ return 'penmentor · show me' # the window title++ def __init__(self, spec=None, job=None, **kw):+ self.spec, self.job, self.knob, self.again, self.goal = spec, job, None, False, None+ self.zone, self.handles, self.live, self.values = None, [], {}, VGroup()+ self.editing, self.dragging, self.hand, self.quick, self.reopen, self.selecting = None, None, False, False, None, False+ super().__init__(**kw)+ self.preview_while_skipping = False # a redraw after you change a value shows only when it is complete+ if self.window:+ self.camera.fps = 60 # manimgl caps its window at 30+ # manimgl measures its window once (as 1280x720) and sizes line edges by that: use the real size+ c = self.camera+ c.get_pixel_shape = lambda: tuple(c.window_fbo.viewport[2:]) if c.fbo is c.window_fbo else c.fbo.size++ def construct(self):+ if self.spec is None:+ self.spec = self.wait_for_maths()+ self.build()++ def wait_for_maths(self):+ # the same loader as penmentor's top badge: a faint ring, and a blue arc turning round its centre as it stretches and shrinks+ centre, t0 = UP * .5, self.time+ ring = Circle(radius=.4).move_to(centre).set_stroke(WHITE, 5, opacity=.15)+ arc = always_redraw(lambda: Arc(-(self.time - t0) * 330 * DEG, (40 + 230 * (.5 - .5 * math.cos((self.time - t0) * 4))) * DEG,+ radius=.4, arc_center=centre).set_stroke(SPIN, 5))+ word = Text('Drawing your animation', font_size=36).set_color(GREY_A).next_to(ring, DOWN, buff=.6)+ self.add(ring, arc)+ self.play(FadeIn(word), run_time=.4)+ spec_file, parent, end = Path(self.job['path']).with_suffix('.spec.json'), self.job.get('parent'), time.monotonic() + WAIT+ while not spec_file.exists():+ if (parent and os.getppid() != parent) or time.monotonic() > end: # penmentor stopped (Esc) before Claude answered+ break+ self.wait(.1)+ got = json.loads(spec_file.read_text()) if spec_file.exists() else {'error': 'Stopped before Claude answered.'}+ arc.clear_updaters()+ self.play(FadeOut(VGroup(ring, arc, word)), run_time=.4)+ return got.get('spec') or {'error': got.get('error') or 'no animation this time'}++ def build(self):+ """Title, the kind (its intro unless self.quick: after you change a value it just redraws), values row, hint."""+ self.knob, self.zone, self.handles, s = None, None, [], self.spec+ skipping = self.skip_animations+ self.skip_animations = skipping or self.quick+ try:+ if 'error' in s:+ raise ValueError(s['error'])+ if s.get('title'):+ try:+ title = TexText(s['title'])+ except Exception: # LaTeX choked on Claude's title+ title = Text(s['title'].replace('$', ''))+ title.set_max_width(FRAME_WIDTH - 1).to_edge(UP, buff=.35).fix_in_frame()+ # written on slowly, in the background, while the plot draws itself+ self.add(title if self.skip_animations else turn_animation_into_updater(Write(title, run_time=3.5, lag_ratio=.15)))+ KINDS[s.get('kind')](self, s)+ self.goal = self.knob[0].get_value() if self.knob else None+ self.values = self.values_row(s)+ self.place_row()+ self.play(FadeIn(self.values, shift=UP * .1), FadeIn(Text(HINT, font_size=20).set_color(GREY_B).to_edge(DOWN, buff=.2).fix_in_frame()))+ self.reopen_now() # you were stepping or tabbing: the field stays open+ except EndScene:+ raise+ except Exception as ex:+ self.clear().add(self.frame)+ self.values = VGroup()+ self.add(VGroup(Text("Couldn't draw this one"), Text(str(ex)[:120], font_size=24).set_color(GREY_B))+ .arrange(DOWN, buff=.4).fix_in_frame(), Text('q close', font_size=20).set_color(GREY_B).to_edge(DOWN, buff=.2))+ finally:+ self.skip_animations, self.quick = skipping, False++ @property+ def char_w(self):+ """Width of one character of the typewriter face."""+ if not hasattr(self, '_char_w'):+ self._char_w = Text('0' * 40, font=MONO, font_size=24).get_width() / 40+ return self._char_w++ def chip(self, key):+ """One value in the row, as maths: "a = 0", "f(x) = x e^{-x}"."""+ s = self.spec+ name = NAMES.get(s.get('kind'), {}).get(key, {'f': 'f(x)', 'g': 'g(x)'}.get(key, key))+ text = str(s[key])+ if re.fullmatch(r'-?\d+(\.\d+)?', text): # a plain number: digits that are typeset already, no LaTeX run+ body = VGroup(Tex(f'{name} =', font_size=26), num(float(text), len(text.partition('.')[2]), 26)).arrange(RIGHT, buff=.12)+ else:+ body = tex_or_text(rf'{name} = {pretty(text)}', f'{key} = {text}', font_size=26)+ box = RoundedRectangle(width=body.get_width() + .36, height=max(body.get_height(), .3) + .22, corner_radius=.1)+ chip = VGroup(box.set_stroke(GREY_C, 1.5).set_fill(BLACK, .85).move_to(body), body)+ chip.key = key+ return chip.set_z_index(12).fix_in_frame()++ def field_chip(self, colour=YELLOW):+ """The value you are typing, in CMU Typewriter (fixed width, so the caret and selection line up exactly):+ "b = 2.5" with a blinking caret and the selection shaded."""+ f, cw = self.editing, self.char_w+ prefix = f'{f.key} = '+ text = Text(prefix + f.text, font=MONO, font_size=24)+ left, y = text.get_left()[0], text.get_center()[1]+ at = lambda i: left + (len(prefix) + i) * cw+ f.geom = (left + len(prefix) * cw, cw) # where the text starts, for clicks+ width = (len(prefix) + len(f.text) + 1) * cw+ box = RoundedRectangle(width=width + .36, height=.52, corner_radius=.1).set_stroke(colour, 2).set_fill(BLACK, .9)+ box.move_to([left + width / 2, y, 0])+ chip = VGroup(box)+ if sel := f.span():+ chip.add(Rectangle(width=(sel[1] - sel[0]) * cw, height=.36).set_stroke(width=0).set_fill(BLUE_D, .85)+ .move_to([(at(sel[0]) + at(sel[1])) / 2, y, 0]))+ caret = Line(UP * .17, DOWN * .17).set_stroke(WHITE, 2).move_to([at(f.caret), y, 0])+ caret.add_updater(lambda m: m.set_opacity(1 if (self.time - f.touched) % 1.06 < .6 else 0)) # blinks, steady while typing+ chip.add(text, caret)+ chip.key = f.key+ return chip.set_z_index(12).fix_in_frame()++ def values_row(self, s):+ keys = [k for k in FIELDS if s.get(k) not in (None, '') and not (k == 'g' and s.get('kind') == 'area' and not nonzero(s[k]))]+ return VGroup(*[self.chip(k) for k in keys])++ def place_row(self):+ self.values.arrange(RIGHT, buff=.3).move_to(DOWN * 3.3)++ def play(self, *animations, **kw):+ """After you change a value the plot is rebuilt with no intro: every animation lands on its end at once,+ without manim copying each shape to animate it (60% of a rebuild)."""+ if not self.quick:+ return super().play(*animations, **kw)+ for a in animations:+ self.land(a)++ def land(self, a):+ from manimlib.mobject.mobject import _AnimationBuilder+ if isinstance(a, _AnimationBuilder): # tracker.animate.set_value(...): cheap, let manim do it+ super().play(a)+ elif isinstance(a, AnimationGroup):+ for part in a.animations:+ self.land(part)+ elif type(a) in (Transform, ReplacementTransform):+ a.mobject.become(a.target_mobject)+ self.add(a.mobject)+ elif isinstance(a, FadeOut):+ self.remove(a.mobject)+ else: # ShowCreation, FadeIn, Write, GrowFromCenter...: the mobject as built is the end state+ self.add(a.mobject)++ def wait(self, *args, **kw):+ return None if self.quick else super().wait(*args, **kw)++ def interact(self):+ self.skip_animations = False+ while not self.is_window_closing():+ if self.again:+ self.again = False+ self.clear().add(self.frame)+ if not self.quick:+ self.frame.to_default_state()+ self.build()+ if self.knob and self.goal is not None: # glide toward where you put it, quick then settling, like a hand+ k = self.knob[0]+ k.set_value(k.get_value() + (self.goal - k.get_value()) * (1 - math.exp(-14 / self.camera.fps)))+ self.update_frame(1 / self.camera.fps)++ # --- changing a value: retype it, step it, or drag a bound line ---+ def chip_at(self, point):+ fixed = self.frame.to_fixed_frame_point(point) # the row is fixed in the frame (it stays put in 3D)+ return next((c for c in self.values if inside(c, fixed)), None)++ def handle_at(self, point):+ return next((key for key, axes in self.handles+ if abs(point[0] - axes.c2p(self.live[key], 0)[0]) < .22 and inside(axes, point)), None)++ def change(self, key, text):+ """The spec with key = text, if it makes sense (a formula in the right variables, a number), else None."""+ try:+ if key in ('f', 'g'):+ formula(text, VARS.get(self.spec.get('kind'), {}).get(key, ('x',)))+ elif key == 'n':+ text = max(1, int(float(text)))+ else:+ number(text)+ except (ValueError, SyntaxError, TypeError, OverflowError):+ return None+ return dict(self.spec, **{key: text})++ def redraw_with(self, spec, keep_typing=False):+ """Your change: draw it at once (no intro) and keep it in the history. keep_typing: the field stays open."""+ self.spec, self.quick, self.again = spec, True, True+ self.reopen = self.editing if keep_typing else None+ try:+ from .show import remember+ remember(spec)+ except Exception: # the history is a nicety+ pass++ def edit(self, key):+ self.editing = Field(key, str(self.spec[key]), self.time)+ self.show_edit()++ def show_edit(self, colour=YELLOW):+ self.editing.touched = self.time+ i = next(i for i, c in enumerate(self.values) if c.key == self.editing.key)+ self.remove(self.values)+ self.values.replace_submobject(i, self.field_chip(colour))+ self.place_row()+ self.add(self.values)++ def end_edit(self, commit, then=None):+ """commit: use the value (Enter, Tab, clicking elsewhere); one that makes no sense turns red and stays open.+ Not commit: Esc, back as it was. then: the key to type in next (Tab)."""+ f = self.editing+ spec = self.change(f.key, f.text.strip()) if commit else self.spec+ if spec is None:+ self.show_edit(RED)+ return False+ self.editing = None+ i = next(i for i, c in enumerate(self.values) if c.key == f.key)+ self.remove(self.values)+ self.values.replace_submobject(i, self.chip(f.key)) # back to maths+ self.place_row()+ self.add(self.values)+ if spec != self.spec:+ self.redraw_with(spec)+ if then:+ self.reopen = Field(then, str(spec[then]), self.time)+ if spec == self.spec:+ self.reopen_now()+ return True++ def reopen_now(self):+ """After a redraw: the field you were in (stepping, Tab) is open again, caret where it was."""+ if self.reopen:+ self.editing, self.reopen = self.reopen, None+ if self.editing and any(c.key == self.editing.key for c in self.values):+ self.show_edit()+ else:+ self.editing = None++ def step(self, direction, big):+ """Up/Down on a number: one step up or down (Shift: ten), redrawn at once."""+ f = self.editing+ if f.key not in ('a', 'b', 'n'):+ return+ try:+ v = number(f.text)+ except ValueError:+ return+ d = (1 if f.key == 'n' else .1) * (10 if big else 1) * direction+ f.text = str(int(max(1, v + d))) if f.key == 'n' else f'{v + d:.10g}'+ f.caret, f.anchor = len(f.text), None+ if spec := self.change(f.key, f.text):+ self.redraw_with(spec, keep_typing=True)+ self.show_edit()++ def on_text(self, text):+ if self.editing and text.isprintable():+ self.editing.insert(text)+ self.show_edit()++ def on_text_motion(self, motion, select=False):+ from pyglet.window import key+ f = self.editing+ if not f:+ return+ if motion in (key.MOTION_UP, key.MOTION_DOWN):+ return self.step(1 if motion == key.MOTION_UP else -1, select)+ if motion == key.MOTION_COPY:+ return f.span() and self.window._window.set_clipboard_text(f.selected())+ if motion == key.MOTION_PASTE:+ f.insert(' '.join(self.window._window.get_clipboard_text().split()))+ else:+ f.move(motion, select)+ self.show_edit()++ def on_escape(self):+ if self.editing:+ self.end_edit(False)++ # --- the pen and the keys ---+ def turn(self, point):+ if self.knob and self.knob[3]:+ k, lo, hi, at = self.knob+ self.goal = min(max(at(point), lo), hi)++ def on_mouse_motion(self, point, d_point):+ super().on_mouse_motion(point, d_point)+ grab = self.chip_at(point) or self.handle_at(point) or self.dragging or (+ self.knob and (self.zone is None or inside(self.zone, point)))+ if bool(grab) != self.hand and self.window: # a hand wherever you can drag or click+ w = self.window._window+ w.set_mouse_cursor(w.get_system_mouse_cursor(w.CURSOR_HAND) if grab else None)+ self.hand = bool(grab)++ def on_mouse_press(self, point, button, mods):+ super().on_mouse_press(point, button, mods)+ chip = self.chip_at(point)+ if self.editing and chip and chip.key == self.editing.key: # in the field: place the caret, double-click selects all+ f, x = self.editing, self.frame.to_fixed_frame_point(point)[0]+ again = self.time - f.clicked < .4+ f.clicked = self.time+ f.caret = f.anchor = min(max(round((x - f.geom[0]) / f.geom[1]), 0), len(f.text))+ if again:+ f.anchor, f.caret = 0, len(f.text)+ self.selecting = True+ return self.show_edit()+ if self.editing and not self.end_edit(True) and self.editing: # clicking elsewhere uses the value; nonsense stays+ return+ if chip:+ return self.edit(chip.key)+ if key := self.handle_at(point):+ self.dragging = key+ return+ self.turn(point)++ def on_mouse_drag(self, point, d_point, buttons, modifiers):+ super().on_mouse_drag(point, d_point, buttons, modifiers)+ if self.selecting and self.editing: # drag across the text to select+ f = self.editing+ f.caret = min(max(round((self.frame.to_fixed_frame_point(point)[0] - f.geom[0]) / f.geom[1]), 0), len(f.text))+ self.show_edit()+ elif self.dragging:+ axes = dict(self.handles)[self.dragging]+ lo, hi = axes.x_range[:2]+ if self.dragging == 'a':+ hi = self.live['b'] - (hi - lo) / 100+ else:+ lo = self.live['a'] + (hi - lo) / 100+ self.live[self.dragging] = min(max(axes.p2c(point)[0], lo), hi)+ elif self.knob and self.knob[3] is None: # 3D: drag turns the view+ self.frame.increment_theta(-d_point[0] * .4)+ self.frame.increment_phi(d_point[1] * .4)+ else:+ self.turn(point)++ def on_mouse_release(self, point, button, mods):+ super().on_mouse_release(point, button, mods)+ self.selecting = False+ if key := self.dragging:+ self.dragging = None+ self.redraw_with(dict(self.spec, **{key: f'{self.live[key]:.3g}'}))++ def on_mouse_scroll(self, point, offset, x_pixel_offset, y_pixel_offset):+ """Over a number: scroll steps it. Elsewhere: zoom."""+ chip = self.chip_at(point)+ if chip and chip.key in ('a', 'b', 'n'):+ if not (self.editing and self.editing.key == chip.key):+ if self.editing and not self.end_edit(True):+ return+ self.edit(chip.key)+ return self.step(1 if y_pixel_offset > 0 else -1, False)+ super().on_mouse_scroll(point, offset, x_pixel_offset, y_pixel_offset)++ def on_key_press(self, symbol, modifiers):+ from pyglet.window import key+ if self.editing: # typing a value: keys are for the text (motions, Esc and characters come separately)+ f, ctrl = self.editing, modifiers & key.MOD_CTRL+ if symbol in (key.RETURN, key.ENTER):+ self.end_edit(True)+ elif symbol == key.TAB: # the next value (Shift: the previous one)+ keys = [c.key for c in self.values]+ self.end_edit(True, then=keys[(keys.index(f.key) + (-1 if modifiers & key.MOD_SHIFT else 1)) % len(keys)])+ elif ctrl and symbol == key.A:+ f.anchor, f.caret = 0, len(f.text)+ self.show_edit()+ elif ctrl and symbol == key.X and f.span():+ self.window._window.set_clipboard_text(f.selected())+ f.insert('')+ self.show_edit()+ elif symbol == key.SPACE:+ self.again = True+ elif symbol == key.Q: # not Esc: Esc is for penmentor, and this stays until you are done with it+ self.quit_interaction = True+ elif symbol in (key.LEFT, key.RIGHT) and self.knob:+ k, lo, hi, _ = self.knob+ self.goal = min(max((self.goal if self.goal is not None else k.get_value()) + (hi - lo) / 40 * (1 if symbol == key.RIGHT else -1), lo), hi)+ else:+ super().on_key_press(symbol, modifiers)+++class QuietWindow(Window):+ """manimgl's window, opened as a floating dialog that doesn't take the focus (your pen stays in xournal),+ where penmentor put it (the overlay leaves that spot uncovered)."""++ def __init__(self, rect):+ x, y, w, h = rect+ self.scene, self.pressed_keys = None, set()+ self.default_size, self.default_position = (w, h), (x, y)+ # 4x multisampling: smooth edges, 3D too. aspect_ratio: resizing never squashes the picture, it stays 16:9 in the+ # middle (the bars are black, like the background). Invisible at first, so the hints are set before i3 sees it.+ PygletWindow.__init__(self, samples=4, visible=False, aspect_ratio=16 / 9)+ self.exit_key = None # moderngl_window closes on Esc by default, and so does pyglet underneath it: stop Esc here+ from pyglet.window import key # (it only cancels typing a value), and pass typed text to the scene++ def esc(symbol, mods):+ if symbol == key.ESCAPE:+ self.scene and self.scene.on_escape()+ return True+ self._window.push_handlers(on_key_press=esc, on_text=lambda text: self.scene and self.scene.on_text(text),+ on_text_motion=lambda m: self.scene and self.scene.on_text_motion(m),+ on_text_motion_select=lambda m: self.scene and self.scene.on_text_motion(m, True))+ win = self._window+ win.set_caption('penmentor · show me')+ win._set_atoms_property('_NET_WM_WINDOW_TYPE', ('_NET_WM_WINDOW_TYPE_DIALOG',)) # i3 floats dialogs+ from ctypes import POINTER, byref, c_ubyte, c_ulong, cast+ from pyglet.libs.x11 import xlib+ atom = lambda name: xlib.XInternAtom(win._x_display, name.encode(), False)+ zero = c_ulong(0) # user time 0: don't focus it+ xlib.XChangeProperty(win._x_display, win._window, atom('_NET_WM_USER_TIME'), atom('CARDINAL'), 32,+ xlib.PropModeReplace, cast(byref(zero), POINTER(c_ubyte)), 1)+ self.to_default_position()+ win.set_visible(True)+ # i3 opens floating windows on the focused screen: move it to the one we want (no-op elsewhere)+ subprocess.run(['i3-msg', f'[id={win._window}] move absolute position {self.default_position[0]} {self.default_position[1]}'],+ capture_output=True)++ def pixel_coords_to_space_coords(self, px, py, relative=False):+ """Window pixels to scene coordinates, through the 16:9 area (manimgl's own version assumes the whole window)."""+ if self.scene is None or not hasattr(self.scene, 'frame'):+ return np.zeros(3)+ vx, vy, vw, vh = self.viewport+ coords = np.zeros(3)+ coords[:2] = np.array(FRAME_SHAPE) / (vw, vh) * ((px, py) if relative else (px - vx, py - vy))+ if not relative:+ coords[:2] -= .5 * np.array(FRAME_SHAPE)+ return self.scene.frame.from_fixed_frame_point(coords, relative)+++def render(spec, out=None):+ """Build spec with no window; the last frame to out (a PNG)."""+ scene = Show(spec=spec, skip_animations=True)+ scene.setup()+ scene.construct()+ scene.update_frame(force_draw=True) # skipping animations draws nothing by itself+ if out:+ scene.get_image().save(out)+ return scene+++def check():+ """Every kind builds without errors, and a hostile formula is refused (shown as a message, not run)."""+ specs = [dict(kind='area', f='x*exp(-x)', g='0', a='0', b='4'), dict(kind='riemann', f='sin(x)', a='0', b='pi', n=20),+ dict(kind='improper', f='1/x**2', a='1', b='inf'), dict(kind='improper', f='1/sqrt(x)', a='0', b='1', toward='a'),+ dict(kind='substitution', f='cos(u)', g='x**2', a='0', b='1'), dict(kind='revolution', f='sqrt(x)', a='0', b='4'),+ dict(kind='revolution', f='x*(2-x)', a='0', b='2', axis='y'), dict(kind='series', f='1/n**2', a='1', n=20),+ dict(kind='taylor', f='exp(x)', g='x**k/factorial(k)', a='-2', b='2', n=6), dict(kind='polar', f='1+cos(t)', a='0', b='2*pi'),+ dict(kind='parametric', f='cos(t)', g='sin(2*t)', a='0', b='2*pi'), dict(kind='curves', f='1/x**2', g='1/(x**2+1)', a='1', b='5', title='Two $1/x$ curves')]+ assert {s['kind'] for s in specs} == set(KINDS)+ for spec in specs + [dict(kind='area', f="__import__('os')", a='0', b='1')]:+ scene = render(spec)+ failed = any(isinstance(m, VGroup) and len(m) == 2 and isinstance(m[0], Text) and m[0].text == "Couldn't draw this one"+ for m in scene.mobjects)+ assert failed == spec['f'].startswith('__'), spec+ assert spec['f'].startswith('__') or scene.knob, spec+ # retyping a value: sensible text gives a new spec, nonsense (or code) gives none+ scene = render(specs[0])+ assert scene.change('b', 'pi')['b'] == 'pi' and scene.change('n', '12') and scene.change('f', 'x**2 + 1')+ assert not scene.change('a', 'zero') and not scene.change('f', "__import__('os')") and not scene.change('f', 'y + 1')+ assert [c.key for c in scene.values] == ['f', 'a', 'b'] # g = 0 is not worth a chip+ from pyglet.window import key+ f = Field('f', 'x*exp(-x)', 0)+ f.insert('sin(x)') # all selected at first: typing replaces it+ assert (f.text, f.caret) == ('sin(x)', 6)+ f.move(key.MOTION_LEFT, False), f.move(key.MOTION_LEFT, True), f.move(key.MOTION_LEFT, True) # Shift+Left twice: '(x'+ assert f.selected() == '(x'+ f.insert('^2(x')+ f.move(key.MOTION_BEGINNING_OF_LINE, False), f.move(key.MOTION_DELETE, False), f.move(key.MOTION_NEXT_WORD, False)+ assert (f.text, f.caret) == ('in^2(x)', 3), (f.text, f.caret) # Ctrl+Right: the start of the next word+ f.move(key.MOTION_END_OF_LINE, False), f.move(key.MOTION_BACKSPACE, False)+ assert f.text == 'in^2(x'+ scene.edit('b') # Up on a number steps it and redraws, the field stays open+ scene.step(1, False)+ assert scene.spec['b'] == '4.1' and scene.reopen is scene.editing+ print('plots ok')+++def main(argv):+ cmu_serif()+ if argv[:1] == ['--check']:+ return check()+ if argv[:1] == ['--png']:+ return render(json.loads(Path(argv[1]).read_text()), argv[2])+ job = dict(json.loads(Path(argv[0]).read_text()), path=argv[0])+ Show(job=job, window=QuietWindow(job.get('rect') or (160, 90, 1600, 900))).run()+++if __name__ == '__main__':+ main(sys.argv[1:])diff --git a/src/penmentor/prompts.py b/src/penmentor/prompts.pynew file mode 100644index 0000000..27a69a2--- /dev/null+++ b/src/penmentor/prompts.py@@ -0,0 +1,157 @@+"""What penmentor asks Claude, and the JSON shape Claude answers in."""++PRESETS = [ # rofi menu: (label, mode)+ ('✓ Did I make any mistakes?', 'check'),+ ('☑ Solution check', 'final'),+ ('→ Give me a hint', 'nudge'),+ ('◇ Which technique?', 'technique'),+ ('✎ Quiz me on my steps', 'why'),+ ('✗ Find-the-error drill', 'drill'),+ ('∿ Show me (animation)', 'show'),+ ('◎ Ask about a box… (drag one)', 'box'),+]+BOX_QS = ['Explain this step', 'Is this part right?']+FOLLOWUPS = ['Why is that wrong?', 'Show me the next step', 'Explain it differently', 'Show the full fix']+TECHNIQUES = ['u-substitution', 'integration by parts', 'trig identities (powers of sin and cos)', 'trig substitution',+ 'partial fractions', 'improper integral: take a limit', 'algebra first (expand, simplify, split)',+ "L'Hôpital's rule", 'geometric series', 'p-series', 'divergence test (n-th term)', 'integral test',+ 'direct comparison', 'limit comparison', 'alternating series test', 'ratio test', 'root test',+ 'telescoping series', 'power / Taylor series']+MORE = ('That was not enough. Give one level more help than your previous answer, on this ladder: '+ 'nudge → name the technique and colour-code the parts → ghost the next line → show the full fix.')++SYSTEM = r"""You are a calculus tutor looking over a student's shoulder at a screenshot of their handwritten work (usually xournal++). You answer by drawing on their screen, the way a teacher marks work with coloured pens. The student learns by seeing, not by reading, so words are a last resort.+You get one screenshot per monitor. The focused one usually holds the student's work; the others may show a tutorial, lecture or problem sheet. Use them, and mark them too when it helps (e.g. circle the matching step in the tutorial).+You may also get the whole current page of their xournal notes. The screen often shows only part of it, so use the page for context (the problem statement may be scrolled away), but put your marks on the screenshots only.+This is one long tutoring conversation: earlier messages hold earlier screenshots, questions and your answers, so use them to follow the student's work. Always answer about the newest screenshots.++Answer as JSON:+- read_as: first transcribe every handwritten line on the screens, top to bottom, as LaTeX (no $). Read carefully; handwriting is messy. Use the maths around a symbol to resolve what it is.+- verdict: correct | mistake | unsure | hint | answer.+- headline: at most 5 words, e.g. "Sign slip in line 4", "All correct", "Try integration by parts".+- marks: at most 6, fewer is better. Each mark:+ - screen: which screenshot the box is on (0-based, left to right).+ - box: [x0, y0, x1, y1] in that screenshot's pixels, tight around exactly the symbols you mean (one term, not the whole line, unless the whole line is meant).+ - shape: circle (ring around a term), mark (highlighter), underline, wavy (wavy underline), strike (cross out; correction goes in "write"), check (tick after a correct line; box = that line), box (rectangle), ghost (faint suggested writing placed in EMPTY space; box = where it goes, "write" = the LaTeX).+ - role: error (wrong), fix (the correction), carry (only wrong because of an earlier error), unsure (can't read it / suspicious), ok (correct), a / b / c (neutral hint colours; things that belong together get the same letter, e.g. u and du both a), ask (a question for the student; the note is the question).+ - note: optional, at most 6 words, shown in a bubble with an arrow to the mark. Prefer maths over words: "$-\frac{7}{64}$" beats "the coefficient should be negative".+ - write: what to write for strike corrections and ghosts, e.g. "$\frac{3}{4}\sin 2\theta$".+ - why: optional, one short plain-language sentence, shown only when the student hovers the mark.+ - link: optional 0-based index of another mark; draws an arrow from this mark to that one (cause → effect, "this becomes that").+ - step: drawing order 1, 2, 3, ... (marks appear one at a time).+- drill, plot: only when the task asks for them.++Text format for headline, note, write, why and drill texts: plain words, with every bit of maths inside $...$, e.g. "which angle has $\sin\theta=1$?". Never leave maths bare: not x^2, sqrt(x), pi/2, ->, <= but $x^2$, $\sqrt{x}$, $\frac{\pi}{2}$, $\to$, $\leq$. Words go outside the $...$ (or in \text{...}). It is typeset with LaTeX (amsmath, amssymb, cancel) on one line: no line breaks, no display environments other than cases.++Rules:+- Never invent a mistake. Many pages are correct; then say so (verdict correct, a check after each line).+- If you are not sure you read a symbol right, use role unsure instead of error.+- Don't do the student's work for them: a hint should make them think, unless they ask for the solution.+- Ignore app toolbars and anything that is not maths."""++TASKS = {+ 'check': 'Check this work for mistakes. Circle the first real error (role error) with a note that shows the fix. '+ 'Give later lines that inherit it a dashed underline (shape underline, role carry) and link the error to them. '+ 'Tick (check, role ok) each line that is right before the error. Include the final answer. '+ 'If everything is right, tick every line and say so in the headline (verdict correct). '+ 'If the error comes from misusing something in an earlier line, highlight that source (role a) and link it to the error.',+ 'nudge': 'I am stuck. Give the smallest possible hint: highlight the one thing I should look at (role a) '+ 'with a note of at most 4 words. Do not give the next step.',+ 'explain': 'I drew a cyan rectangle around a step I do not understand. Show how it follows from the line before it: '+ 'highlight matching pieces in both lines with the same role letter and link each source to its result.',+ 'final': 'I think I am done. Check my solution as a whole: is the final answer correct, and is anything missing '+ '(e.g. +C, absolute values, evaluating the bounds, cases, domain, simplifying, or not answering what was asked)? '+ 'Tick the final answer if right; if wrong, circle it and put the correct answer in a note. '+ 'Ghost each missing piece where it belongs (role fix). If it is complete and correct, say so in the headline (verdict correct).',+ 'box': 'I drew a cyan rectangle around part of my work. Answer only about that part: ',+ 'technique': 'Which technique fits the integral, limit or series I am working on (or about to start)? Do not solve it and do not '+ 'name any method. Colour the features that point to the method (shape mark or circle, roles a, b, c; pieces that '+ 'work together share a letter), each with a note of at most 5 words naming the feature, e.g. "root of $a^2-x^2$", '+ '"polynomial times $e^x$", "factorials", "top degree $\\geq$ bottom degree". Headline: "Which technique fits?", '+ 'verdict hint. I will pick a method next.',+ 'pick': 'I pick: {}. Is that a good method here? Verdict correct if it works well, hint if it works but another is clearly '+ 'easier (name that one), mistake if it does not work. The headline says so, e.g. "Yes: integration by parts". '+ 'Mark the deciding feature with a note on why, at most 6 words. Do not solve the problem.',+ 'why': 'Quiz me on my reasoning. Pick the 1 or 2 steps where understanding matters most (a substitution choice, an identity, '+ 'a sign, a change of bounds, why a test applies). At each, put a mark (shape box, role ask) whose note is a short question, '+ 'e.g. "Why $u=\\sin\\theta$ here?", "Where did the $\\frac{1}{2}$ go?". Do not hint at the answer. '+ 'Headline: "Explain these steps", verdict hint.',+ 'why_typed': 'My answer to your question(s): "{}". Grade my understanding: verdict correct if I got the key idea, mistake if not. '+ 'Tick the step (check, role ok) if I understood it; otherwise put the key idea in a note at the step, at most 6 words. '+ 'Ask nothing new.',+ 'why_written': 'I wrote my answer(s) to your question(s) on the page, next to the steps. Grade them: verdict correct if I got the '+ 'key idea, mistake if not. Tick each answer I got right (check, role ok); otherwise put the key idea in a note next '+ 'to my answer, at most 6 words. Ask nothing new.',+ 'written': 'I wrote more after your last answer. Check the new part only: circle the first real error (role error) with a note '+ 'that shows the fix, and tick each new line that is right. If it is all right, say so in the headline (verdict correct).',+ 'drill': 'Find-the-error drill. Write a short worked solution (4 to 8 lines) to a NEW problem of the same kind as mine on screen: '+ 'same technique, a different function or different numbers. Plant exactly one realistic mistake, the kind students really '+ 'make (if I made a mistake earlier in this conversation, plant that kind). Lines before it are right; lines after it carry '+ 'the mistake on consistently, the way a student would. Put it all in drill. Headline "Find the mistake", verdict hint, '+ 'no marks, read_as empty.',+ 'drill_more': 'Another drill like that: a new problem of the same kind, with a different planted mistake.',+ 'show': 'Show me visually what is going on, 3Blue1Brown style: put one animation in plot, with the actual function from my '+ 'work. Pick the kind that matches what the problem is about, not the fanciest one: a definite integral is an area '+ '(area, or riemann to see it as a sum); revolution only when the problem itself asks for a volume or a solid of '+ 'revolution. Circle (role a) the part of my work it shows. Headline: what to watch, e.g. "Watch the rectangles fill '+ 'the area", verdict hint.',+ 'show_boxes': 'I drew numbered cyan boxes round exactly what I want to see. Show me that, 3Blue1Brown style: put one '+ 'animation in plot, built from what is inside the boxes and nothing else (several boxes: one picture that uses '+ 'them together, e.g. two functions: curves; a function and its bounds: area). Pick the kind that matches what '+ 'is boxed: a definite integral is an area (area or riemann); revolution only if the boxed problem asks for a '+ 'volume or a solid of revolution. Circle (role a) each boxed part. Headline: what to watch, verdict hint.',+}++FMT = 'Plain words; EVERY bit of maths, even a lone x or arcsin(1), inside $...$ as LaTeX.'+EXPR = ('A formula in Python syntax with explicit *: x**2, 3*x, sqrt(x), exp(-x), log(x) for ln, abs(x), sin(x), arctan(x), '+ 'factorial(n), pi, e. No $ and no LaTeX.')+PLOT_KINDS = { # kind: what its fields mean (also tells Claude how to fill them)+ 'area': 'area under f(x) from a to b, filling up; g(x) = lower curve for the area between two curves',+ 'riemann': 'rectangles under f(x) on [a, b], doubling up to n of them, closing in on the integral',+ 'improper': 'f(x) on [a, b] with b = "inf" (or f blowing up at an end): the bound moves out and the area converges or not; toward = which end moves',+ 'substitution': 'u = g(x) as a stretch of the x-axis: f(g(x))g\'(x) on [a, b] morphs into f(u) on [g(a), g(b)]; f is in u',+ 'revolution': 'ONLY for volumes / solids of revolution: the region under f(x) on [a, b] spun around the axis into a solid; g(x) = inner radius (washers)',+ 'series': 'terms f(n) and partial sums from n = a, n terms',+ 'taylor': 'f(x) and its Taylor polynomials adding one term at a time; g = the k-th term in k and x; x from a to b; n terms',+ 'polar': 'r = f(t) (t is θ) traced from t = a to b, sweeping out its area',+ 'parametric': 'x = f(t), y = g(t) traced from t = a to b',+ 'curves': 'f(x) and g(x) on [a, b] drawn together, e.g. for a comparison test',+}+DRILL = {+ 'type': 'object', 'additionalProperties': False, 'required': ['problem', 'lines', 'wrong', 'fix', 'why'],+ 'properties': {+ 'problem': {'type': 'string', 'description': 'the task, one line. ' + FMT},+ 'lines': {'type': 'array', 'items': {'type': 'string'}, 'description': 'the worked solution, one step a line. ' + FMT},+ 'wrong': {'type': 'integer', 'description': '0-based index of the line with the planted mistake'},+ 'fix': {'type': 'string', 'description': 'that line done right. ' + FMT},+ 'why': {'type': 'string', 'description': 'what went wrong, one short sentence. ' + FMT}}}+PLOT = {+ 'type': 'object', 'additionalProperties': False, 'required': ['kind', 'f', 'a', 'b'],+ 'properties': {+ 'kind': {'enum': list(PLOT_KINDS), 'description': '; '.join(f'{k}: {v}' for k, v in PLOT_KINDS.items())},+ 'title': {'type': 'string', 'description': 'shown above the animation, e.g. "$\\int_0^2 x e^{-x}\\,dx$". ' + FMT},+ 'f': {'type': 'string', 'description': 'the main formula (in x; n for series; t for polar and parametric). ' + EXPR},+ 'g': {'type': 'string', 'description': 'the second formula, if the kind uses one. ' + EXPR},+ 'a': {'type': 'string', 'description': 'start, a number or constant formula, e.g. "0", "pi/2", "-inf"'},+ 'b': {'type': 'string', 'description': 'end, e.g. "1", "2*pi", "inf"'},+ 'n': {'type': 'integer', 'description': 'how many rectangles, terms or Taylor terms at most'},+ 'axis': {'enum': ['x', 'y'], 'description': 'revolution: the axis it spins around'},+ 'toward': {'enum': ['a', 'b'], 'description': 'improper: the end that moves'}}}+SCHEMA = {+ 'type': 'object', 'additionalProperties': False, 'required': ['read_as', 'verdict', 'headline', 'marks'],+ 'properties': {+ 'read_as': {'type': 'array', 'items': {'type': 'string'}},+ 'verdict': {'enum': ['correct', 'mistake', 'unsure', 'hint', 'answer']},+ 'headline': {'type': 'string', 'description': FMT},+ 'marks': {'type': 'array', 'items': {+ 'type': 'object', 'additionalProperties': False, 'required': ['shape', 'role', 'screen', 'box'],+ 'properties': {+ 'screen': {'type': 'integer', 'description': 'index of the screenshot the box is on'},+ 'shape': {'enum': ['circle', 'mark', 'underline', 'wavy', 'strike', 'check', 'box', 'ghost']},+ 'role': {'enum': ['error', 'fix', 'carry', 'unsure', 'ok', 'a', 'b', 'c', 'ask']},+ 'box': {'type': 'array', 'items': {'type': 'number'}, 'minItems': 4, 'maxItems': 4},+ 'note': {'type': 'string', 'description': FMT}, 'write': {'type': 'string', 'description': FMT},+ 'why': {'type': 'string', 'description': FMT},+ 'link': {'type': 'integer'}, 'step': {'type': 'integer'}}}},+ 'drill': DRILL,+ 'plot': PLOT}}diff --git a/src/penmentor/selftest.py b/src/penmentor/selftest.pynew file mode 100644index 0000000..63b704b--- /dev/null+++ b/src/penmentor/selftest.py@@ -0,0 +1,224 @@+"""penmentor --selftest: the logic that is easy to break, checked without Claude or a real screen."""+import json+import os+import tempfile+import time+from pathlib import Path++import numpy as np+++def pages():+ from .page import Page+ rgb = np.zeros((300, 600, 3), np.uint8)+ rgb[100:140, 200:230] = 255 # a symbol+ rgb[100:140, 300:330] = 255 # its neighbour+ pg = Page(rgb)+ assert pg.dark+ assert pg.snap((190, 95, 240, 150)) == (200, 100, 230, 140) # loose box tightens+ assert pg.snap((205, 104, 236, 138)) == (200, 100, 230, 140) # offset box still finds the whole symbol+ assert pg.snap((150, 200, 180, 230)) == (150, 200, 180, 230) # no ink: box kept+ r = pg.place((80, 30), (200, 100, 230, 140), [])+ assert not pg.busy(r, []), r+ assert pg.busy((290, 110, 320, 120), []) # on ink+ side = np.zeros((300, 600, 3), np.uint8)+ side[:, 100:115] = 53 # a sidebar frame: black inside, like the paper+ side[:20] = 53 # a toolbar+ ps = Page(side)+ assert ps.busy((10, 100, 60, 130), [], ink=False) # inside the sidebar+ assert ps.busy((200, 5, 260, 30), [], ink=False) # on the toolbar+ assert not ps.busy((200, 100, 260, 130), [], ink=False) # on the page+ x0, y0, x1, y1 = ps.place((60, 30), (120, 100, 140, 130), [])+ assert x0 >= 115 and y0 >= 20, (x0, y0)+ full = [(0, 0, 600, 300)] # no room anywhere: the note still lands on screen+ for target in ((560, 10, 598, 40), (2, 260, 40, 298)):+ x0, y0, x1, y1 = pg.place((200, 40), target, full)+ assert 0 <= x0 and x1 <= 600 and 0 <= y0 and y1 <= 300, (target, x0, y0, x1, y1)+ po = Page(rgb, (1000, 50)) # same page, placed further along the desktop+ assert po.snap((1190, 145, 1240, 200)) == (1200, 150, 1230, 190)+ assert po.busy((1290, 160, 1320, 170), []) and not po.busy(po.place((80, 30), (1200, 150, 1230, 190), []), [])+ assert po.fit((900, 0, 960, 30)) == (1006, 56, 1066, 86)+++def text():+ from . import typeset+ from .typeset import latex_source, plain, tex_source, typeset as run_latex+ for raw, want in ((r'$a \iff b \le c \ge d$', r'$a \Leftrightarrow b \leq c \geq d$'),+ (r'$\frac{3}{2}\left[$', r'$\dfrac{3}{2}[$'),+ (r'$\left(\tfrac{1}{2}\right)$', r'$\left(\dfrac{1}{2}\right)$'),+ (r'use x^2 and \sqrt{x} here', r'use $x^2$ and $\sqrt{x}$ here'),+ (r'angle with $\sin\theta=1$?', r'angle with $\sin\theta=1$?'),+ ('odd $ count x^2', 'odd count $x^2$'), ('plain words', 'plain words'),+ ('arcsin(y) is the angle whose sine is y.', r'$\arcsin(y)$ is the angle whose sine is $y$.'),+ ('take ln of both sides, then dx', r'take $\ln$ of both sides, then $dx$'),+ ('e.g. a sign slip (not yours)', 'e.g. a sign slip (not yours)'),+ ('so arcsin(1) = ?', r'so $\arcsin(1) =$ ?'), (r'$\theta=arcsin(x)$', r'$\theta=\arcsin(x)$')):+ assert tex_source(raw) == want, (raw, tex_source(raw))+ assert plain(r'$\dfrac{\pi}{2} \cdot x$') == '(π)/(2) ⋅ x', plain(r'$\dfrac{\pi}{2} \cdot x$')+ assert latex_source('θ ≤ 1, 50% done') == r'$\theta \leq 1$, $50\%$ done', latex_source('θ ≤ 1, 50% done')+ if typeset.LATEX:+ ks = [(r'$\iff$ ok', 19), (r'$\nosuchcmd x$', 19), (r'$\frac{1}{2$', 19), (r'$|x|=\begin{cases}x\\-x\end{cases}$', 19)]+ run_latex(ks)+ assert [typeset._typeset[k] is not None for k in ks] == [True, False, False, True], [typeset._typeset[k] for k in ks]+ assert typeset._typeset[ks[3]].height() > typeset._typeset[ks[0]].height() # the cases page really is the cases page+++def desktop():+ from .desktop import windows+ tree = {'type': 'root', 'nodes': [{'type': 'output', 'nodes': [+ {'type': 'con', 'name': 'content', 'rect': {'x': 0, 'y': 0, 'width': 199, 'height': 90}},+ {'type': 'workspace', 'name': '1', 'rect': {'x': 0, 'y': 0, 'width': 99, 'height': 99}, 'nodes': [+ {'window': 7, 'focused': True, 'rect': {'x': 0, 'y': 0, 'width': 50, 'height': 99}},+ {'window': 8, 'rect': {'x': 50, 'y': 0, 'width': 49, 'height': 99}}]},+ {'type': 'workspace', 'name': '2', 'nodes': [{'window': 9, 'rect': {'x': 0, 'y': 0, 'width': 99, 'height': 99}}]},+ {'type': 'workspace', 'name': '3', 'focused': True, 'rect': {'x': 100, 'y': 0, 'width': 99, 'height': 99}}]}]}+ assert windows(tree, {'1', '3'}) == ([(0, 0, 50, 99), (50, 0, 49, 99)], (100, 0, 99, 99), [(0, 0, 199, 90)]) # hidden ws 2 skipped; empty ws 3 focused+++def menus():+ from . import cli, config, show+ real, saved, conf, past = cli.rofi, config.SETTINGS, dict(config.CONF), show.HISTORY+ with tempfile.TemporaryDirectory() as d:+ config.SETTINGS, show.HISTORY = Path(d) / 'settings.json', Path(d) / 'history.jsonl'+ # settings page → effort → 3rd row (high) → model → typed id → effort → typo (ignored) → esc+ answers = iter([lambda r: r[1], lambda r: r[2], lambda r: r[0], lambda r: 'claude-sonnet-5-5',+ lambda r: r[1], lambda r: 'hgih', lambda r: None])+ cli.rofi = lambda rows, *a: next(answers)(rows)+ try:+ cli.settings(None)+ assert config.CONF['effort'] == 'high' and config.CONF['model'] == 'claude-sonnet-5-5', config.CONF+ assert json.loads(config.SETTINGS.read_text()) == config.CONF+ # two animations shown → settings → history → the older one plays again+ for title in ('Area under $e^{-x}$', 'Riemann sums'):+ show.HISTORY.write_text((show.HISTORY.read_text() if show.HISTORY.exists() else '') ++ json.dumps({'t': time.time(), 'spec': {'kind': 'area', 'title': title}}) + '\n')+ answers, reopened = iter([lambda r: r[-1], lambda r: r[1]]), []+ cli.settings(reopened.append)+ assert reopened == [{'kind': 'area', 'title': 'Area under $e^{-x}$'}], reopened+ finally:+ cli.rofi, config.SETTINGS, show.HISTORY = real, saved, past+ config.CONF.clear(), config.CONF.update(conf)+++def formulas():+ from .expr import formula, number+ x = np.array([0., 1, 2])+ assert np.allclose(formula('x^2*exp(-x) + 2x')(x=x), x ** 2 * np.exp(-x) + 2 * x)+ assert np.allclose(formula('(-1)**k*x**(2*k+1)/factorial(2*k+1)', ('k', 'x'))(k=np.arange(3.), x=1.), [1, -1 / 6, 1 / 120])+ assert np.isnan(formula('1/x')(x=0.)) and formula('log10(x)')(x=100.) == 2 and formula('sqrt(1-theta)', ('t',))(t=0.) == 1+ assert (number('pi/2'), number('-inf'), number('1e-5')) == (np.pi / 2, -np.inf, 1e-5)+ for bad in ["__import__('os').system('true')", 'x.__class__', '(lambda: 1)()', '[x for x in ()]', "open('f')",+ 'x[0]', "'a'", 'y+1', 'sin(x, out=x)', 'True', 'exec("1")', 'globals()']:+ try:+ formula(bad)+ raise AssertionError(f'formula let through: {bad}')+ except ValueError:+ pass+ t = time.monotonic()+ formula('9**9**9')() # float powers: overflow, not a hang building a giant int+ assert time.monotonic() - t < 1+++def plots():+ """Every Show-me kind builds in manim, and a hostile formula is refused: run in the Python that has manimgl."""+ import subprocess+ import sys+ from .config import CACHE, MANIM+ python = str(MANIM) if MANIM.exists() else sys.executable+ src = str(Path(__file__).resolve().parent.parent)+ CACHE.mkdir(parents=True, exist_ok=True)+ p = subprocess.run([python, '-c', 'import manimlib'], capture_output=True)+ if p.returncode:+ return print('plots skipped: no manimgl (see README)')+ p = subprocess.run([python, '-m', 'penmentor.plot', '--check'], capture_output=True, text=True, cwd=CACHE,+ env=dict(os.environ, PYTHONPATH=src), timeout=600)+ assert p.returncode == 0 and 'plots ok' in p.stdout, (p.stdout + p.stderr)[-2000:]+++def overlay():+ """Drill, technique and Pill wiring, on an offscreen Qt."""+ os.environ['QT_QPA_PLATFORM'] = 'offscreen'+ from PIL import Image+ from PyQt6.QtCore import QPointF+ from PyQt6.QtWidgets import QApplication+ from .overlay import Overlay, Pill, display, tex_jobs+ app = QApplication.instance() or QApplication([])+ shot = Image.new('RGB', (1200, 800), (20, 20, 24))+ ov = Overlay(shot, (0, 0, 1200, 800), mode='drill')+ drill = dict(problem=r'Find $\int x e^x\,dx$', lines=[r'$u = x,\ dv = e^x dx$', r'$du = dx,\ v = e^x$', r'$= x e^x + \int e^x\,dx$', r'$= x e^x + e^x + C$'],+ wrong=2, fix=r'$= x e^x - \int e^x\,dx$', why='Integration by parts subtracts: $uv - \\int v\\,du$.')+ r = dict(read_as=[], verdict='hint', headline='Find the mistake', marks=[], drill=drill)+ assert (display(drill['fix']), 19) in tex_jobs(r)+ ov.set_result(r)+ d = ov.drill+ assert len(d['rows']) == 4 and 'tap the wrong line' in ov.keys()+ centre = lambda i: d['rows'][i][0].center()+ assert ov.drill_row(centre(1)) == 1 and ov.drill_row(QPointF(-5, -5)) is None+ ov.pick_line(0)+ assert d['picked'] == {0} and not d['revealed']+ ov.pick_line(2)+ assert d['revealed'] and d['found'] and ov.result['verdict'] == 'correct'+ ov.grab() # paints the card without errors+ ov.set_result(dict(r, drill=dict(drill)))+ ov.pick_line(0), ov.pick_line(1) # two misses: the answer shows+ assert ov.drill['revealed'] and not ov.drill['found'] and ov.result['headline'] == 'It was line 3'+ tech = Overlay(shot, (0, 0, 1200, 800), mode='technique')+ tech.set_result(dict(read_as=[], verdict='hint', headline='Which technique fits?', marks=[]))+ tech.grab()+ assert tech.drill is None and tech.keys().startswith('p pick') and tech.head_box is not None+ pill = Pill(tech.shot, (0, 0, 1200, 800))+ assert not pill.grab().isNull()+++def page_export():+ """A xournal++ that never answers (started before the plugin was installed) costs one wait, not one per question."""+ from . import xournal as X+ saved = X.PLUGIN, X.PAGE, X.INFO, X.MISS, X.focused, X.PageRequest.poke+ with tempfile.TemporaryDirectory() as d:+ X.PLUGIN, X.PAGE, X.INFO, X.MISS = Path(d), Path(d, 'page.png'), Path(d, 'page.txt'), Path(d, 'page.miss')+ pid, pokes = ['123'], []+ X.focused, X.PageRequest.poke = lambda: pid[0], staticmethod(lambda: pokes.append(1))+ try:+ assert X.PageRequest().result(wait=.1) is None and len(pokes) == 2 # asked twice, then gave up+ assert not X.PageRequest().on # same xournal: not asked again+ pid[0] = '456' # restarted, plugin loaded now+ r = X.PageRequest()+ X.INFO.write_text('3 5')+ X.PAGE.write_bytes(b'png')+ assert r.on and r.result() == (b'png', 'page 3 of 5') and not X.MISS.exists()+ finally:+ X.PLUGIN, X.PAGE, X.INFO, X.MISS, X.focused, X.PageRequest.poke = saved+++def stopping():+ """Esc kills a claude that is still answering instead of leaving it running on your plan."""+ import threading+ from . import claude+ with tempfile.TemporaryDirectory() as d:+ stub, saved, failed = Path(d) / 'claude', claude.CLAUDE, []+ stub.write_text('#!/bin/sh\nexec sleep 30\n')+ stub.chmod(0o755)+ claude.CLAUDE = str(stub)+ def ask():+ try:+ claude.ask([], 'hi', keep=False)+ except RuntimeError:+ failed.append(True)+ try:+ t = threading.Thread(target=ask)+ t.start()+ for _ in range(300):+ if claude.RUNNING:+ break+ time.sleep(.01)+ claude.stop()+ t.join(5)+ assert not t.is_alive() and failed and not claude.RUNNING+ finally:+ claude.CLAUDE = saved+++def selftest():+ for check in (pages, text, desktop, menus, formulas, plots, overlay, page_export, stopping):+ check()+ print('selftest ok')diff --git a/src/penmentor/show.py b/src/penmentor/show.pynew file mode 100644index 0000000..a43723e--- /dev/null+++ b/src/penmentor/show.py@@ -0,0 +1,85 @@+"""The Show-me window (plot.py, run by the Python that has manimgl): where it opens, starting it, feeding it the+maths, and the history of every animation, which Settings → History brings back."""+import importlib.util+import json+import os+import signal+import subprocess+import sys+import time+from pathlib import Path++from .config import CACHE, DATA, MANIM+from .desktop import notify++JOB = CACHE / 'plot.json' # the window's job; the maths follows in plot.spec.json+HISTORY = DATA / 'history.jsonl' # one {"t": unix time, "spec": Claude's plot} per line, oldest first+KEEP = 300+++def monitor(screens, main, geom):+ """The monitor Show me opens on (desktop pixels): the biggest other one, the nearest of those."""+ mx = screens[main][0]+ others = [r for i, r in enumerate(screens) if i != main] or screens+ x, y, w, h = max(others, key=lambda r: (r[2] * r[3], -abs(r[0] - mx)))+ return geom[0] + x, geom[1] + y, w, h+++def rect(screen):+ """The window on it: 16:9, centred."""+ x, y, w, h = screen+ W = min(int(w * .7), int(h * .8 * 16 / 9))+ H = W * 9 // 16+ return x + (w - W) // 2, y + (h - H) // 2, W, H+++def open_window(where, spec=None):+ """Open the window now, replacing the last one; it shows a loading animation until send() gives it the maths+ (or plays spec at once, from the history). Its own process, so it outlives penmentor: only q closes it."""+ python = str(MANIM) if MANIM.exists() else sys.executable+ if python == sys.executable and not importlib.util.find_spec('manimlib'):+ notify('Show me needs manimgl: see the README', ms=6000)+ return+ JOB.with_suffix('.spec.json').unlink(missing_ok=True)+ if spec:+ send(spec=spec, keep=False)+ JOB.write_text(json.dumps({'rect': list(where), 'parent': os.getpid()}))+ pid = CACHE / 'plot.pid'+ try:+ old = int(pid.read_text())+ if b'penmentor.plot' in Path(f'/proc/{old}/cmdline').read_bytes(): # never signal a stranger that reused the pid+ os.kill(old, signal.SIGTERM)+ except (OSError, ValueError):+ pass+ src = str(Path(__file__).resolve().parent.parent) # works from a checkout too, not only when installed+ env = dict(os.environ, PYTHONPATH=os.pathsep.join(filter(None, [src, os.environ.get('PYTHONPATH')])))+ with open(CACHE / 'plot.log', 'w') as log:+ p = subprocess.Popen([python, '-m', 'penmentor.plot', str(JOB)], env=env, stdout=log, stderr=log, start_new_session=True, cwd=CACHE)+ pid.write_text(str(p.pid))+++def send(keep=True, **msg):+ """spec=Claude's plot (kept in the history), or error=why there is none, for the window open_window opened."""+ tmp = JOB.with_suffix('.tmp')+ tmp.write_text(json.dumps(msg))+ tmp.replace(JOB.with_suffix('.spec.json')) # whole or not at all: the window polls for it+ if keep and msg.get('spec'):+ remember(msg['spec'])+++def remember(spec):+ """Add an animation to the history (Claude's, or one you changed in the window)."""+ DATA.mkdir(parents=True, exist_ok=True)+ lines = HISTORY.read_text().splitlines()[-(KEEP - 1):] if HISTORY.exists() else []+ HISTORY.write_text('\n'.join(lines + [json.dumps({'t': time.time(), 'spec': spec})]) + '\n')+++def history():+ """Every animation shown, newest first."""+ out = []+ for line in reversed(HISTORY.read_text().splitlines() if HISTORY.exists() else []):+ try:+ out.append(json.loads(line))+ except ValueError:+ pass+ return outdiff --git a/src/penmentor/style.py b/src/penmentor/style.pynew file mode 100644index 0000000..dac47df--- /dev/null+++ b/src/penmentor/style.py@@ -0,0 +1,20 @@+"""Look of the overlay: colours, text sizes, fonts, spacing."""++PALETTE = { # Okabe-Ito based so it survives colour blindness; shapes carry the meaning too+ 'light': dict(error='#D55E00', fix='#009E73', ok='#009E73', carry='#E69F00', unsure='#E69F00',+ a='#0072B2', b='#CC79A7', c='#1E9BD7', ask='#6A4CC2', ghost='#7A7F87'),+ 'dark': dict(error='#FF6B4A', fix='#35D69B', ok='#35D69B', carry='#FFB224', unsure='#FFB224',+ a='#4EA8FF', b='#F27BC9', c='#6FE0FF', ask='#B39DFF', ghost='#A3A9B3'),+}+LEGEND = {'error': 'mistake', 'fix': 'correction', 'ok': 'correct', 'carry': 'follows from the mistake',+ 'unsure': 'unsure: check this', 'abc': 'same colour = same thing', 'ask': 'question for you',+ 'ghost': 'suggested writing'}+VERDICT = {'correct': ('✓', 'ok'), 'mistake': ('✗', 'error'), 'unsure': ('?', 'unsure'), 'hint': ('→', 'a'), 'answer': ('•', 'a')}++UI_FONT = 'CMU Serif' # 3Blue1Brown's look: CMU Serif words (his manim config), Computer Modern maths (his LaTeX)+HEAD, NOTE, GHOST, FIX, TIP, READ, DRILL = 17, 21, 22, 21, 16, 15, 19 # text sizes in pt; Computer Modern's thin serifs get grainy below ~16+NOTE_CH, TIP_CH = 34, 44 # wrap notes / hover tips at about this many characters+TOP = 36 # top bar's distance from the monitor top: clears i3's 22 px title/tab bar+BAR = 84 # usage-limit bar width in the stats panel, px+SPIN = '#4EA8FF' # loading arc colour+PANEL = (18, 18, 22) # panel backgrounddiff --git a/src/penmentor/typeset.py b/src/penmentor/typeset.pynew file mode 100644index 0000000..9d915b2--- /dev/null+++ b/src/penmentor/typeset.py@@ -0,0 +1,263 @@+"""Text with maths as images: real LaTeX when installed (Computer Modern via latex + dvipng), else matplotlib's mathtext."""+import functools+import io+import re+import shutil+import subprocess+import tempfile+from pathlib import Path++from PyQt6.QtCore import QRect, QRectF, Qt+from PyQt6.QtGui import QColor, QFont, QFontDatabase, QFontMetrics, QImage, QPainter++from .style import DRILL, FIX, GHOST, HEAD, NOTE, READ, TIP, UI_FONT++LATEX = bool(shutil.which('latex') and shutil.which('dvipng')) # real LaTeX if installed, else matplotlib's imitation++W_ = r'(?![a-zA-Z])' # end of a command name+TEX_FIXES = [ # LaTeX that matplotlib's mathtext lacks -> the nearest thing it has+ (r'\\(iff|Longleftrightarrow)' + W_, r'\\Leftrightarrow'), (r'\\implies' + W_, r'\\Rightarrow'),+ (r'\\impliedby' + W_, r'\\Leftarrow'), (r'\\le' + W_, r'\\leq'), (r'\\ge' + W_, r'\\geq'),+ (r'\\[lr]vert' + W_, '|'), (r'\\[lr]Vert' + W_, r'\\Vert'), (r'\\text(bf|it)' + W_, r'\\math\1'),+ (r'\\dd' + W_, 'd'), (r'\\color\{[^}]*\}', ''), (r'\\(begin|end)\{[^}]*\}', ''), (r'\\\\', r'\\;'), (r'(?<!\\)&', ''),+ (r'\\(displaystyle|textstyle|limits|nolimits|[bB]igg?[lr]?|boxed|cancel)' + W_, ''),+]+++FN = r'(?<![\\a-zA-Z])(arcsin|arccos|arctan|sinh|cosh|tanh|sin|cos|tan|sec|csc|cot|ln|log|exp|lim)' + W_+++def mathy(w):+ """Is this word really maths: x, -1, arcsin(y), x^2, dx, sin?"""+ if w in ('a', 'A', 'I'):+ return False+ core = re.sub(FN + r'|\\[a-zA-Z]+|^d[a-zθ]$', '', w)+ return not re.search('[A-Za-z]{2}', core) and (core != w or len(w) == 1 or bool(re.search(r'[\\^_={}<>+*/()\[\]\d−-]', w)))+++def bare_math(t):+ """Wrap maths written without $ (arcsin(y), x^2, \\sqrt{x}) so it renders like the rest."""+ out, run = [], []+ for w in t.split(' '):+ core, tail = re.fullmatch(r'(.*?)([.,;:!?]*)', w).groups()+ if core and mathy(core):+ run.append(core)+ if tail: # sentence punctuation stays outside the maths+ out.append(f"${' '.join(run)}${tail}")+ run = []+ continue+ if run:+ out.append(f"${' '.join(run)}$")+ run = []+ out.append(w)+ if run:+ out.append(f"${' '.join(run)}$")+ return ' '.join(out)+++def tex_source(s, mathtext=True):+ """Claude's text -> maths in $...$; for mathtext also swap out what it lacks."""+ parts = s.split('$')+ if len(parts) % 2 == 0: # unpaired $: guess where the maths is+ parts = [''.join(parts)]+ parts = '$'.join(p if i % 2 else bare_math(p) for i, p in enumerate(parts)).split('$')+ for i in range(1, len(parts), 2):+ m = re.sub(r'\\[tdc]?frac' + W_, r'\\dfrac', parts[i]) # full-size fractions read better on screen+ for a, b in TEX_FIXES if mathtext else ():+ m = re.sub(a, b, m)+ m = re.sub(FN, r'\\\1', m) # arcsin -> \arcsin, upright like in print+ if len(re.findall(r'\\left' + W_, m)) != len(re.findall(r'\\right' + W_, m)):+ m = re.sub(r'\\(left|right)(\.|' + W_ + ')', '', m)+ parts[i] = f'${m}$' if m.strip() else ''+ return ''.join(parts)+++def plain(s):+ """Last resort: LaTeX as readable unicode text."""+ from matplotlib._mathtext_data import tex2uni+ s = re.sub(r'\\dfrac\{([^{}]*)\}\{([^{}]*)\}', r'(\1)/(\2)', s)+ s = re.sub(r'\\(left|right|quad|qquad|mathrm|text|[,;:! ])' + W_, ' ', s)+ s = re.sub(r'\\([a-zA-Z]+)', lambda m: chr(tex2uni[m[1]]) if m[1] in tex2uni else m[1], s)+ return re.sub(r'[{}$\\]', '', s)+++UNI = {'θ': r'\theta', 'π': r'\pi', 'α': r'\alpha', 'β': r'\beta', 'γ': r'\gamma', 'δ': r'\delta', 'ε': r'\varepsilon',+ 'λ': r'\lambda', 'μ': r'\mu', 'σ': r'\sigma', 'φ': r'\varphi', 'ω': r'\omega', 'Δ': r'\Delta', 'Σ': r'\Sigma',+ '∞': r'\infty', '≤': r'\leq', '≥': r'\geq', '≠': r'\neq', '≈': r'\approx', '→': r'\to', '⇒': r'\Rightarrow',+ '⇔': r'\Leftrightarrow', '∫': r'\int', '√': r'\surd', '·': r'\cdot', '⋅': r'\cdot', '×': r'\times', '±': r'\pm',+ '−': '-', '∈': r'\in', '∑': r'\sum', '°': r'^\circ', '²': '^2', '³': '^3'}+UNI_RE = '[' + ''.join(map(re.escape, UNI)) + ']'+PREAMBLE = r"""\documentclass{article}+\usepackage[T1]{fontenc}\usepackage{lmodern}\usepackage{amsmath,amssymb,cancel}+\pagestyle{empty}""" + ''.join(rf'\DeclareMathSizes{{{z}}}{{{z * 1.05:.1f}}}{{{z * .8:.1f}}}{{{z * .6:.1f}}}'+ for z in sorted({HEAD, NOTE, GHOST, FIX, TIP, READ, DRILL})) + r"\begin{document}"+SS, GAMMA = 3, '1.6' # LaTeX supersampling factor, dvipng gamma+_typeset = {} # (text, size) -> alpha mask from LaTeX, None if LaTeX choked on it+++def latex_source(s):+ """Claude's text -> LaTeX source: unicode maths to commands, text-mode specials escaped."""+ parts = tex_source(s, mathtext=False).split('$')+ for i, p in enumerate(parts):+ parts[i] = (re.sub(UNI_RE, lambda m: UNI[m[0]] + ' ', re.sub(r'(?<!\\)([%#])', r'\\\1', p)) if i % 2 else+ re.sub(UNI_RE, lambda m: f'${UNI[m[0]]}$', re.sub(r'(?<!\\)([%#&])', r'\\\1', p)))+ return '$'.join(parts)+++def latex_ok(s):+ """Balanced braces and environments, so one bad string can't swallow the pages after it."""+ d = 0+ for c in re.sub(r'\\[{}]', '', s):+ d += (c == '{') - (c == '}')+ if d < 0:+ return False+ return d == 0 and s.count('\\begin{') == s.count('\\end{')+++def typeset(keys):+ """One LaTeX run for many (text, size): a page each, cropped tight by dvipng into alpha masks."""+ todo = [k for k in dict.fromkeys(keys) if k not in _typeset]+ if not LATEX or not todo:+ return+ src = ['\n'.join(map(latex_source, t.split('\n'))) for t, _ in todo]+ line = lambda t: rf'\strut {t if latex_ok(t) else "x"}'+ box = lambda t: line(t) if '\n' not in t else r'\vbox{' + ''.join(rf'\hbox{{{line(l)}}}' for l in t.split('\n')) + '}'+ # several lines: one vbox, so TeX spaces them itself (\baselineskip = 1.2 x the size, as in print)+ body = [rf'\newpage\hbox{{\fontsize{{{z}}}{{{z * 1.2:.1f}}}\selectfont {box(t)}}}' for t, (_, z) in zip(src, todo)]+ first = PREAMBLE.count('\n') + 2 # source line of the first page+ try:+ with tempfile.TemporaryDirectory() as d:+ Path(d, 'x.tex').write_text(PREAMBLE + '\n' + '\n'.join(body) + '\n\\end{document}\n')+ subprocess.run(['latex', '-interaction=nonstopmode', '-no-shell-escape', 'x.tex'], cwd=d, capture_output=True, timeout=30)+ # 115 dpi matches the handwriting. dvipng anti-aliases with only 15 alpha levels (jagged edges), so render 3x+ # and scale down smoothly; gamma thickens Computer Modern's thin strokes a little so they read on screen+ subprocess.run(['dvipng', '-T', 'tight', '-D', str(115 * SS), '-bg', 'Transparent', '--gamma', GAMMA, '-q', '-o', 'p%d.png', 'x.dvi'],+ cwd=d, capture_output=True, timeout=30)+ log = Path(d, 'x.log').read_text(errors='replace')+ bad = {int(n) - first for n in re.findall(r'^!.*?^l\.(\d+)', log, re.M | re.S)}+ aligned = len(list(Path(d).glob('p*.png'))) == len(todo)+ for i, k in enumerate(todo):+ img = QImage(str(Path(d, f'p{i + 1}.png'))) if aligned and i not in bad and latex_ok(src[i]) else None+ _typeset[k] = None if img is None or img.isNull() else img.convertToFormat(QImage.Format.Format_ARGB32_Premultiplied).scaled(+ round(img.width() / SS), round(img.height() / SS), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)+ except Exception:+ _typeset.update(dict.fromkeys(todo))+++def tint(mask, color):+ img = mask.convertToFormat(QImage.Format.Format_ARGB32_Premultiplied)+ p = QPainter(img)+ p.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceIn)+ p.fillRect(img.rect(), QColor(color))+ p.end()+ return img+++def tex(s, color, size=15):+ """Text with $maths$ as a QImage: real LaTeX (Latin Modern), else matplotlib mathtext, else plain text."""+ typeset([(s, size)])+ if _typeset.get((s, size)) is not None:+ return tint(_typeset[(s, size)], color)+ import matplotlib+ from matplotlib import mathtext+ from matplotlib.font_manager import FontProperties+ matplotlib.rcParams['savefig.transparent'] = True+ matplotlib.rcParams['mathtext.fontset'] = 'cm' # Computer Modern, the LaTeX look+ for f in font_paths():+ matplotlib.font_manager.fontManager.addfont(f)+ s = tex_source(s)+ for _ in range(6):+ buf = io.BytesIO()+ try:+ mathtext.math_to_image(s, buf, prop=FontProperties(family=[UI_FONT, 'sans-serif'], size=size),+ dpi=100, format='png', color=color)+ return QImage.fromData(buf.getvalue())+ except Exception as e:+ bad = re.search(r'Unknown symbol: (\\[a-zA-Z]+)', str(e))+ if not bad:+ break+ s = tex_source(re.sub(re.escape(bad[1]) + W_, ' ', s))+ return text_img(plain(s), color, round(size * 100 / 72))+++def wrap(s, chars):+ """Lines of about `chars` visible characters; never breaks inside $...$."""+ lines, cur, n = [], [], 0+ for w in re.findall(r'(?:[^\s$]|\$[^$]*\$)+', tex_source(s or '', mathtext=False)):+ k = len(re.sub(r'[{}^_$]', '', re.sub(r'\\[a-zA-Z]+', 'x', w)))+ if cur and n + k > chars:+ lines.append(' '.join(cur))+ cur, n = [], 0+ cur.append(w)+ n += k + 1+ return [l for l in lines + [' '.join(cur)] if l]+++def as_math(w):+ return w if '$' in w else f'${w}$'+++def read_line(l):+ return f"${l.replace('$', '')}$"+++def lines_key(s, size, chars):+ """(text, size) for s wrapped at about `chars`: the key tex_lines typesets, so callers can batch it."""+ return '\n'.join(wrap(s, chars)) or s or '', size+++def tex_lines(s, color, size=15, chars=40):+ """tex() wrapped over several lines: with LaTeX one box whose line spacing is TeX's own, else stacked lines."""+ text, _ = lines_key(s, size, chars)+ typeset([(text, size)])+ if '\n' not in text or _typeset.get((text, size)) is not None:+ return tex(text, color, size)+ imgs = [tex(l, color, size) for l in text.split('\n')]+ gap = 4+ out = QImage(max(i.width() for i in imgs), sum(i.height() + gap for i in imgs) - gap, QImage.Format.Format_ARGB32_Premultiplied)+ out.fill(0)+ p, y = QPainter(out), 0+ for i in imgs:+ p.drawImage(0, y, i)+ y += i.height() + gap+ p.end()+ return out+++def shrink(img, maxw):+ return img.scaledToWidth(int(maxw), Qt.TransformationMode.SmoothTransformation) if img.width() > maxw else img+++def font_paths():+ """CMU Serif ships with TeX Live (cm-unicode), so nothing needs a system-wide install."""+ return subprocess.run(['kpsewhich', 'cmunrm.otf'], capture_output=True, text=True).stdout.split() if shutil.which('kpsewhich') else []+++def font_files():+ """CMU Serif registered with Qt (needs the QApplication)."""+ for f in font_paths():+ QFontDatabase.addApplicationFont(f)+ return font_paths()+++def ui_font(px):+ font_files()+ f = QFont(UI_FONT)+ f.setPixelSize(px)+ f.setHintingPreference(QFont.HintingPreference.PreferNoHinting) # the font's own letter spacing, as TeX and manim draw it+ return f+++def text_img(s, color, px=20, width=2000):+ f = ui_font(px)+ r = QFontMetrics(f).boundingRect(QRect(0, 0, width, 4000), Qt.TextFlag.TextWordWrap, s)+ img = QImage(r.width() + 4, r.height() + 2, QImage.Format.Format_ARGB32_Premultiplied)+ img.fill(0)+ p = QPainter(img)+ p.setFont(f)+ p.setPen(QColor(color))+ p.drawText(QRectF(2, 0, r.width() + 2, r.height() + 2), Qt.TextFlag.TextWordWrap, s)+ p.end()+ return imgdiff --git a/src/penmentor/xournal.py b/src/penmentor/xournal.pynew file mode 100644index 0000000..84d26da--- /dev/null+++ b/src/penmentor/xournal.py@@ -0,0 +1,64 @@+"""The whole current xournal++ page, not just the part on screen (the problem statement is often scrolled away).++penmentor's xournal++ plugin (xournalpp-plugin/penmentor) exports the current page from memory, so unsaved strokes count,+when it gets its shortcut; penmentor sends that shortcut and waits for ~/.cache/penmentor/page.png.+"""+import os+import subprocess+import time+from pathlib import Path++from .config import CACHE++PLUGIN = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'xournalpp' / 'plugins' / 'penmentor'+PAGE, INFO = CACHE / 'page.png', CACHE / 'page.txt'+MISS = CACHE / 'page.miss' # pid of a xournal++ that didn't answer (started before the plugin was installed): don't wait on it again+KEY = 'ctrl+alt+shift+F12' # the plugin's accelerator (main.lua)+++def focused():+ """xournal++'s pid if it is the active window (only then does the shortcut reach it), else None."""+ p = subprocess.run(['xdotool', 'getactivewindow', 'getwindowclassname', 'getwindowpid'], capture_output=True, text=True)+ cls, _, pid = p.stdout.strip().partition('\n')+ return pid.strip() or '?' if 'xournal' in cls.lower() else None+++class PageRequest:+ """Ask the plugin for the page now (before rofi takes the keyboard); result() waits for it."""++ def __init__(self):+ self.pid = PLUGIN.is_dir() and focused()+ self.on = bool(self.pid) and not (MISS.exists() and MISS.read_text() == self.pid)+ if self.on:+ CACHE.mkdir(parents=True, exist_ok=True)+ PAGE.unlink(missing_ok=True)+ self.poke()++ @staticmethod+ def poke():+ subprocess.run(['xdotool', 'key', KEY], capture_output=True)++ def result(self, wait=1.5):+ """(PNG bytes, 'page 3 of 5'), or None without the plugin. Safe to call twice."""+ if not self.on:+ return None+ if not hasattr(self, '_page'):+ self._page = None+ for attempt, limit in enumerate((.5, wait)):+ end = time.monotonic() + limit+ while time.monotonic() < end and not PAGE.exists():+ time.sleep(.05)+ if PAGE.exists():+ try:+ n, total = INFO.read_text().split()+ label = f'page {n} of {total}'+ except (OSError, ValueError):+ label = 'current page'+ self._page = PAGE.read_bytes(), label+ MISS.unlink(missing_ok=True)+ break+ if attempt == 0 and focused(): # the first key is lost while i3 still holds the hotkey; rofi has closed by now+ self.poke()+ else:+ MISS.write_text(self.pid)+ return self._pagediff --git a/xournalpp-plugin/penmentor/main.lua b/xournalpp-plugin/penmentor/main.luanew file mode 100644index 0000000..d5da922--- /dev/null+++ b/xournalpp-plugin/penmentor/main.lua@@ -0,0 +1,19 @@+-- penmentor sends this plugin's shortcut when you ask a question; the plugin exports the current page as a PNG+-- (from memory, so unsaved strokes count) to ~/.cache/penmentor/page.png, plus "page pages" in page.txt.++function initUi()+ app.registerUi({menu = "penmentor: share the current page", callback = "penmentorSharePage", accelerator = "<Control><Alt><Shift>F12"})+end++function penmentorSharePage()+ local dir = (os.getenv("XDG_CACHE_HOME") or (os.getenv("HOME") .. "/.cache")) .. "/penmentor"+ local doc = app.getDocumentStructure()+ app.export({outputFile = dir .. "/page.tmp.png", range = tostring(doc.currentPage), background = "all", pngDpi = 150})+ local f = io.open(dir .. "/page.tmp.txt", "w")+ if f then+ f:write(doc.currentPage, " ", #doc.pages)+ f:close()+ os.rename(dir .. "/page.tmp.txt", dir .. "/page.txt")+ end+ os.rename(dir .. "/page.tmp.png", dir .. "/page.png") -- last: penmentor waits for this file+enddiff --git a/xournalpp-plugin/penmentor/plugin.ini b/xournalpp-plugin/penmentor/plugin.ininew file mode 100644index 0000000..d0c1b02--- /dev/null+++ b/xournalpp-plugin/penmentor/plugin.ini@@ -0,0 +1,10 @@+[about]+author=penmentor contributors+description=Lets penmentor see the whole current page: the parts scrolled off screen and strokes not saved yet.+version=1.0++[default]+enabled=true++[plugin]+mainfile=main.lua