Update 2026-11-16 09:40:08

multimodal
Jörn Fischer 2026-11-16 09:40:08 +01:00
parent 1fcfe039a1
commit 2f7116b954
7 changed files with 388 additions and 43 deletions

107
jcode.py
View File

@ -38,10 +38,11 @@ MODEL = DEFAULT_MODEL
_LM_STUDIO_URL = "http://localhost:1234/v1"
_OLLAMA_URL = "http://localhost:11434/v1"
def _fetch_models(url: str) -> list[str] | None:
def _fetch_models(url: str, key: str = "") -> list[str] | None:
headers = {"User-Agent": APP_NAME, **({"Authorization": f"Bearer {key}"} if key else {})}
try:
with urllib.request.urlopen(urllib.request.Request(
f"{url}/models", headers={"User-Agent": APP_NAME}), timeout=3) as r:
f"{url.rstrip('/')}/models", headers=headers), timeout=3) as r:
return [m["id"] for m in json.loads(r.read()).get("data", [])]
except Exception:
return None
@ -62,7 +63,8 @@ def _pick_model(models: list[str]) -> str:
SETTINGS_FILE = Path("settings.json")
def _load_settings() -> dict:
"""Reads settings.json: providers (OpenAI/Anthropic/Gemini via OpenAI-compatible endpoints) for '/backend <name>',
plus Claude-Code-style "autoCompactEnabled" (bool) and "autoCompactWindow" (e.g. "256k")."""
plus Claude-Code-style "autoCompactEnabled" (bool) and "autoCompactWindow" (context window
of the model, e.g. "256k"; the history is compacted at 80% of it)."""
try:
return json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) if SETTINGS_FILE.is_file() else {}
except Exception as e: # noqa: BLE001
@ -114,8 +116,8 @@ MAX_STEPS = 200
MAX_REPEATS = 3 # identical tool calls (within REPEAT_WINDOW) or same-error failures before a reflection step; twice = stop
REPEAT_WINDOW = 10 # how many recent tool calls an identical call is compared against (catches A-B-A-B cycles)
CMD_TIMEOUT = 60 # seconds per command (compiling C/C++/Java takes time)
CONTEXT_LIMIT = 256_000 # context window of the model (tokens)
COMPACT_THRESHOLD = _parse_tokens(SETTINGS.get("autoCompactWindow"), 250_000) # history is compacted from here on
CONTEXT_LIMIT = _parse_tokens(SETTINGS.get("autoCompactWindow"), 256_000) # context window of the model (tokens)
COMPACT_THRESHOLD = CONTEXT_LIMIT * 8 // 10 # history is compacted from here on (80%: headroom for the next response)
AUTO_COMPACT = bool(SETTINGS.get("autoCompactEnabled", True)) # false = never compact
INLINE_SKILLS = bool(SETTINGS.get("inlineSkills", False)) # true = full SKILL.md texts in the system prompt (models that ignore the catalog)
KEEP_RECENT = 8 # most recent messages kept uncompressed
@ -210,11 +212,10 @@ def _resolve(path: str, write: bool = False) -> Path:
parts = list(p.parts)
# Skill files: accept 'skills/<name>/file', '<name>/file' and absolute paths whose
# prefix the model garbled ('/Users/x/wrong/skills/<name>/file' - seen in logs).
if "skills" in parts and not (SANDBOX / "skills").exists():
rest = parts[parts.index("skills") + 1:]
if rest and rest[0] in SKILLS:
p = SKILLS[rest[0]]["dir"].joinpath(*rest[1:])
elif parts and parts[0] in SKILLS and not (SANDBOX / parts[0]).exists():
rest = parts[parts.index("skills") + 1:] if "skills" in parts else []
if rest and rest[0] in SKILLS and not (SANDBOX / "skills").exists():
p = SKILLS[rest[0]]["dir"].joinpath(*rest[1:])
elif not write and parts and parts[0] in SKILLS and not (SANDBOX / parts[0]).exists():
p = SKILLS[parts[0]]["dir"].joinpath(*parts[1:])
elif not p.is_absolute():
while parts and parts[0] == SANDBOX.name:
@ -254,6 +255,7 @@ def _garbled_sandbox_tail(parts: list[str]) -> list[str] | None:
SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".venv", "venv", ".ruff_cache",
".pytest_cache", ".mypy_cache", "dist", "build", ".DS_Store"}
MAX_LIST = 300
MAX_READ_LINES = 2000 # read_file returns at most this many lines per call
def _walk(base: Path):
"""Files and dirs under base, skipping SKIP_DIRS; yields (path, skipped_dir_entry_count)."""
@ -270,7 +272,7 @@ def _walk(base: Path):
def list_files(subdir: str = ".") -> str:
base = _resolve(subdir)
if not base.exists():
return f"'{subdir}' does not exist."
return f"ERROR: '{subdir}' does not exist."
in_project = _inside(base, SANDBOX)
items = []
for p, skipped in _walk(base):
@ -287,22 +289,25 @@ def list_files(subdir: str = ".") -> str:
def read_file(path: str, numbered: bool = False, start_line: int = 0, end_line: int = 0) -> str:
p = _resolve(path)
if not p.is_file():
return f"File '{path}' not found. Use list_files() to see available files."
return f"ERROR: File '{path}' not found. Use list_files() to see available files."
try:
text = p.read_text(encoding="utf-8")
except UnicodeDecodeError:
return (f"'{path}' is a binary file ({p.stat().st_size} bytes). Images: use view_image, "
return (f"ERROR: '{path}' is a binary file ({p.stat().st_size} bytes). Images: use view_image, "
"PDFs: view_pdf_page, other binaries: inspect with run_command (e.g. 'file', 'xxd | head').")
if not (start_line or end_line or numbered):
return text # verbatim (keeps trailing newline for edit_file copies)
lines = text.splitlines()
if not (start_line or end_line or numbered) and len(lines) <= MAX_READ_LINES:
return text # verbatim (keeps trailing newline for edit_file copies)
lo, hi = max(1, start_line or 1), min(len(lines), end_line or len(lines))
if lo > hi:
return f"Range {start_line}..{end_line} invalid - file has {len(lines)} lines."
return f"ERROR: Range {start_line}..{end_line} invalid - file has {len(lines)} lines."
if (capped := hi - lo >= MAX_READ_LINES):
hi = lo + MAX_READ_LINES - 1
sel = lines[lo - 1:hi]
out = "\n".join(f"{i:4d}\u2502{l}" for i, l in enumerate(sel, lo)) if numbered else "\n".join(sel)
if (lo, hi) != (1, len(lines)):
out += f"\n[lines {lo}-{hi} of {len(lines)}]"
out += (f"\n[lines {lo}-{hi} of {len(lines)}"
+ (" - capped; use outline_file, then read the region you need with start_line/end_line" if capped else "") + "]")
return out
def search_files(pattern: str, glob: str = "**/*") -> str:
@ -452,11 +457,11 @@ def outline_file(path: str) -> str:
"""Compact map of a source file: functions/classes/sections with line ranges."""
p = _resolve(path)
if not p.is_file():
return f"File '{path}' not found. Use list_files() to see available files."
return f"ERROR: File '{path}' not found. Use list_files() to see available files."
try:
text = p.read_text(encoding="utf-8")
except UnicodeDecodeError:
return f"'{path}' is a binary file - outline_file works on text/source files only."
return f"ERROR: '{path}' is a binary file - outline_file works on text/source files only."
lines = text.splitlines()
entries = None
syntax_note = ""
@ -523,6 +528,13 @@ def _print_diff(old: str, new: str, path: str) -> None:
if hidden > 0:
print(f"\u2502 {DIM}... {hidden} more diff lines hidden ...{RESET}")
def _write(p: Path, text: str) -> None:
"""Writes text; an existing file with CRLF line endings keeps them (read_text turned them into '\\n')."""
if p.is_file() and b"\r\n" in p.read_bytes():
p.write_bytes(text.replace("\r\n", "\n").replace("\n", "\r\n").encode("utf-8"))
else:
p.write_text(text, encoding="utf-8")
def write_file(path: str, content: str) -> str:
p = _resolve(path, write=True)
p.parent.mkdir(parents=True, exist_ok=True)
@ -533,7 +545,7 @@ def write_file(path: str, content: str) -> str:
print(f"│ {DIM}(no content change){RESET}")
return (f"WARNING: '{path}' already had exactly this content - nothing changed. "
"Do NOT write it again; it is done. Continue with the next step of the task.")
p.write_text(content, encoding="utf-8")
_write(p, content)
if old is None:
# New file: no full dump as a green diff, just a short note.
print(f"\u2502 {GREEN}+ new file ({len(content.splitlines())} lines){RESET}")
@ -564,17 +576,17 @@ def _find_close_match(needle: str, haystack: str) -> str:
def edit_file(path: str, old_string: str, new_string: str) -> str:
p = _resolve(path, write=True)
if not p.is_file():
return f"File '{path}' not found."
return f"ERROR: File '{path}' not found."
text = p.read_text(encoding="utf-8")
if old_string == new_string:
return "ERROR: old_string and new_string are identical - nothing to change. Re-read the file; the text may already be as you want it."
count = text.count(old_string)
if count == 0:
return "old_string not found - no change. " + _find_close_match(old_string, text)
return "ERROR: old_string not found - no change. " + _find_close_match(old_string, text)
if count > 1:
return f"old_string found {count}x - please make it unambiguous."
return f"ERROR: old_string found {count}x - please make it unambiguous."
new_text = text.replace(old_string, new_string)
p.write_text(new_text, encoding="utf-8")
_write(p, new_text)
_print_diff(text, new_text, path)
return f"'{path}' edited."
@ -582,19 +594,19 @@ def insert_lines(path: str, after_line: int, text: str) -> str:
"""Inserts text AFTER line after_line (1-based; 0 = at the beginning)."""
p = _resolve(path, write=True)
if not p.is_file():
return f"File '{path}' not found."
return f"ERROR: File '{path}' not found."
old = p.read_text(encoding="utf-8")
lines = old.splitlines(keepends=True)
n = len(lines)
if after_line < 0 or after_line > n:
return f"after_line={after_line} invalid - file has {n} lines (0..{n} allowed)."
return f"ERROR: after_line={after_line} invalid - file has {n} lines (0..{n} allowed)."
if lines and not lines[-1].endswith("\n"):
lines[-1] += "\n" # ensure that inserting at the end separates cleanly
if not text.endswith("\n"):
text += "\n"
new_lines = lines[:after_line] + [text] + lines[after_line:]
new = "".join(new_lines)
p.write_text(new, encoding="utf-8")
_write(p, new)
_print_diff(old, new, path)
ins = len(text.splitlines())
return f"{ins} line(s) inserted after line {after_line} in '{path}'. File now has {len(new.splitlines())} lines."
@ -603,24 +615,24 @@ def delete_lines(path: str, start_line: int, end_line: int) -> str:
"""Deletes lines start_line..end_line (1-based, inclusive)."""
p = _resolve(path, write=True)
if not p.is_file():
return f"File '{path}' not found."
return f"ERROR: File '{path}' not found."
old = p.read_text(encoding="utf-8")
lines = old.splitlines(keepends=True)
n = len(lines)
if not (1 <= start_line <= end_line <= n):
return f"Range {start_line}..{end_line} invalid - file has {n} lines."
return f"ERROR: Range {start_line}..{end_line} invalid - file has {n} lines."
new = "".join(lines[: start_line - 1] + lines[end_line:])
p.write_text(new, encoding="utf-8")
_write(p, new)
_print_diff(old, new, path)
return f"Lines {start_line}..{end_line} deleted from '{path}'. File now has {len(new.splitlines())} lines."
# Patterns for destructive commands that are never executed. Everything else
# (tests, compilers, package installation via pip/npm/...) is considered safe.
_DANGEROUS = re.compile(r"""(?xi)
\brm\s+(?:-\S+\s+)*(/|~|\.\.|\$HOME) # rm on root/home/parent
\brm\s+(?:[^;&|>\n]*\s)?['"]?(/|~|\.\.|\$\{?HOME) # rm with any absolute/home/parent argument
| \b(sudo|doas)\b | (^|[;&|]\s*)su\b # privilege escalation
| \b(shutdown|reboot|halt|poweroff)\b # shut down system
| \binit\s+[06]\b # runlevel halt/reboot
| (^|[;&|]\s*)(shutdown|reboot|halt|poweroff)\b # shut down system (as a command, not in 'grep shutdown')
| (^|[;&|]\s*)init\s+[06]\b # runlevel halt/reboot
| \b(mkfs|fdisk|parted)\b | \bdd\s+if= # filesystem/raw copy
| >\s*/dev/(sd|nvme|hd|disk|mmcblk|vd)\w # writing to raw device
| :\(\)\s*\{ # fork bomb
@ -649,7 +661,9 @@ def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str:
if (m := _DANGEROUS.search(command)) is not None:
return ("ERROR: command blocked - dangerous pattern "
f"{m.group(0).strip()!r}. Only safe commands are allowed.")
if str(SKILLS_DIR) in command and _SKILL_WRITE.search(command):
# judged per simple command, so 'cp <skill-dir>/x . && chmod +x x' passes; with a 'cd' the whole line counts
parts = [command] if re.search(r"\bcd\s", command) else re.split(r"[;&|\n]+", command)
if any(str(SKILLS_DIR) in c and _SKILL_WRITE.search(c) for c in parts):
return ("ERROR: the skills directory is read-only reference material. "
"Copy the file into the project (cp <skill-dir>/file .) and change the copy.")
shown = command # what the model wrote - used in messages
@ -660,18 +674,21 @@ def run_command(command: str, timeout: int = CMD_TIMEOUT) -> str:
command = "set -o pipefail; " + command
proc = subprocess.Popen(
command, shell=True, executable=_SHELL, cwd=SANDBOX, text=True,
stdin=subprocess.DEVNULL, # commands waiting for input get EOF instead of blocking until the timeout
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
start_new_session=True, # own process group: a timeout kills the whole tree (node, chrome, ...)
)
timed_out = False
try:
stdout, stderr = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
except (subprocess.TimeoutExpired, KeyboardInterrupt) as e:
timed_out = True
try:
os.killpg(proc.pid, signal.SIGKILL) if os.name != "nt" else proc.kill()
except OSError:
pass
if isinstance(e, KeyboardInterrupt):
raise # Ctrl+C: the child has its own session and would otherwise keep running
stdout, stderr = proc.communicate() # partial output is still valuable
stdout, stderr = (stdout or "").strip(), (stderr or "").strip()
out = (f"stdout:\n{stdout}\nstderr:\n{stderr}" if stdout and stderr else stdout or stderr or "(no output)")
@ -835,7 +852,7 @@ def view_image(path: str) -> str:
"""Loads an image file from the sandbox (png/jpg/gif/webp/bmp/svg) for visual analysis."""
p = _resolve(path)
if not p.is_file():
return f"File '{path}' not found. Use list_files() to see available files."
return f"ERROR: File '{path}' not found. Use list_files() to see available files."
Image = _pil()
if p.suffix.lower() == ".svg":
try:
@ -879,7 +896,7 @@ def view_pdf_page(path: str, page: int = 1, dpi: int = 110) -> str:
"""Renders one page of a PDF from the sandbox as an image for visual analysis."""
p = _resolve(path)
if not p.is_file():
return f"File '{path}' not found. Use list_files() to see available files."
return f"ERROR: File '{path}' not found. Use list_files() to see available files."
try:
try:
import pymupdf as fitz
@ -891,7 +908,7 @@ def view_pdf_page(path: str, page: int = 1, dpi: int = 110) -> str:
with fitz.open(p) as doc:
n = doc.page_count
if not 1 <= page <= n:
return f"page={page} invalid - '{path}' has {n} page(s)."
return f"ERROR: page={page} invalid - '{path}' has {n} page(s)."
pix = doc[page - 1].get_pixmap(dpi=max(50, min(int(dpi), 200)))
img = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
return _attach_image(img, f"Page {page}/{n} of '{path}'")
@ -972,11 +989,11 @@ SKILLS = _load_skills()
def load_skill(name: str, file: str = "SKILL.md") -> str:
"""Returns the instructions of a skill (SKILL.md) or one of its linked files."""
if name not in SKILLS:
return f"Unknown skill '{name}'. Available: {', '.join(SKILLS) or '(none)'}"
return f"ERROR: Unknown skill '{name}'. Available: {', '.join(SKILLS) or '(none)'}"
d = SKILLS[name]["dir"]
p = (d / (file or "SKILL.md")).resolve()
if d not in p.parents or not p.is_file():
return f"File '{file}' not found in skill '{name}'."
return f"ERROR: File '{file}' not found in skill '{name}'."
body = p.read_text(encoding="utf-8")
if p.name == "SKILL.md":
_, body = _parse_frontmatter(body)
@ -1274,7 +1291,7 @@ def _error_key(name: str, result: str) -> tuple[str, str] | None:
first = result.splitlines()[0] if result else ""
if first.startswith("WARNING: identical call") or first.startswith("WARNING: this is failure"):
first = next((l for l in result.splitlines()[1:] if l.strip()), "") # our own guard prefixes
if not (first.startswith(("ERROR", "WARNING", "TIMEOUT")) or "not found" in first):
if not first.startswith(("ERROR", "WARNING", "TIMEOUT")):
return None
masked = re.sub(r"'[^']*'|\"[^\"]*\"", "'...'", first)
masked = re.sub(r"\d+", "N", masked)[:160]
@ -1557,7 +1574,9 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
"""
global _REQ_NR, LAST_USAGE_TOKENS
_log("### Task (user)", task)
if auto_skills and (picked := _pick_skills(task)):
if auto_skills and not INLINE_SKILLS and (picked := [ # skip skills that are already in the history
n for n in _pick_skills(task)
if not any(f"Skill '{n}' (directory:" in _content_text(m.get("content")) for m in messages)]):
print(f"{DIM}\U0001f4da Skills: {', '.join(picked)}{RESET}")
task += ("\n\n[The following skill instructions apply to this task. Follow them; "
"read their linked files with load_skill(name, file).]\n\n"
@ -1668,6 +1687,7 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
while messages[-1].get("role") == "tool":
messages.pop()
messages.pop() # drop the stuck round so the history stays well-formed
_PENDING_IMAGES.clear() # ... including images queued by it
if not nudged: # first time: force a reflection step instead of more tool calls
nudged, repeats = True, 0
recent_calls.clear()
@ -1730,6 +1750,7 @@ def run(task: str, messages: list, auto_skills: bool = True) -> list:
def _discard_incomplete(messages: list) -> None:
"""After Ctrl+C: drops a trailing tool-call round whose tool results are incomplete."""
_PENDING_IMAGES.clear() # images queued by the aborted round
i = len(messages)
while i > 0 and messages[i - 1].get("role") == "tool":
i -= 1
@ -1773,7 +1794,7 @@ def main() -> None:
if manual_skill: # '/<skill> task' - inject the skill instructions directly into the task
task = load_skill(sk[0]) + "\n\nTask: " + (sk[1] if len(sk) > 1 else "Follow the skill instructions.")
if task.lower() == "/models":
print("\n".join(f" {m}" for m in (_fetch_models(BASE_URL) or ["(no models found)"]))); continue
print("\n".join(f" {m}" for m in (_fetch_models(BASE_URL, _API_KEY) or ["(no models found)"]))); continue
if task.lower().startswith("/backend"):
_switch_backend(task[8:].strip()); continue
if task.lower().startswith("/model"):

BIN
skills/.DS_Store vendored

Binary file not shown.

View File

@ -0,0 +1,126 @@
---
name: data-visualization
description: Visualize data as a chart, plot, diagram or graph - line, bar, scatter, histogram, box plot, pie, heatmap, area. Default output is a PNG made with Python/matplotlib; an interactive HTML page (Plotly) when the task asks for HTML, a web page or interactivity.
---
# Data visualization
Two output paths. Pick ONE:
| Task says | Output | How |
|---|---|---|
| nothing special, "plot", "chart", "diagram", PNG, report | `chart.png` | Python + matplotlib (section A) - the default |
| "HTML", "web page", "interactive", "browser", "dashboard" | `chart.html` | Plotly page from `template.html` (section B) |
## 1. Choose the chart type
| The data shows | Chart |
|---|---|
| change over time / ordered x | line (area if the filled quantity matters) |
| values per category | bar (horizontal if labels are long or there are > 8 categories) |
| categories split into sub-groups | grouped bar (compare groups) or stacked bar (show totals) |
| relation between two numeric variables | scatter |
| distribution of one variable | histogram |
| distributions of several groups side by side | box plot |
| parts of one whole, at most 5 parts | pie / donut (otherwise use a bar chart) |
| value for every cell of a grid / matrix / correlation | heatmap |
## 2. Rules for every chart
- Plot the real data of the task. Read files (CSV, JSON) with code; never retype or invent values.
- Title that states what is shown; axis labels WITH units; legend only if there are 2+ series.
- Labels in the language of the task.
- Bar charts start at zero. Sort bars by value unless the categories have a natural order.
- No 3D, no decoration. At most ~6 series per chart; more -> several panels.
- Dates on the x-axis must be real dates (`pd.to_datetime` / ISO strings), not arbitrary text.
## A. Python / matplotlib (default)
Write a script `plot.py`, run it, then look at the result.
```python
import matplotlib
matplotlib.use("Agg") # headless - NEVER call plt.show(), it blocks until the timeout
import matplotlib.pyplot as plt
x = [2019, 2020, 2021, 2022, 2023]
y = [12.1, 9.8, 13.4, 15.0, 16.2]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(x, y, marker="o") # <- the drawing call, see the table below
ax.set_title("Revenue per year")
ax.set_xlabel("Year")
ax.set_ylabel("Revenue (million EUR)")
ax.grid(alpha=0.3)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig("chart.png", dpi=150)
print("saved chart.png")
```
Drawing calls (replace the `ax.plot` line):
| Chart | Call |
|---|---|
| line | `ax.plot(x, y, marker="o", label="A")` - once per series, then `ax.legend()` |
| area | `ax.fill_between(x, y, alpha=0.4)`; stacked: `ax.stackplot(x, y1, y2, labels=["A", "B"])` |
| bar | `ax.bar(cats, vals)`; horizontal: `ax.barh(cats, vals)` |
| grouped bar | `import numpy as np; i = np.arange(len(cats)); w = 0.4`<br>`ax.bar(i - w/2, a, w, label="A"); ax.bar(i + w/2, b, w, label="B"); ax.set_xticks(i, cats)` |
| stacked bar | `ax.bar(cats, a, label="A"); ax.bar(cats, b, bottom=a, label="B")` |
| scatter | `ax.scatter(x, y, alpha=0.7)`; 3rd variable: `s=sizes` or `c=values, cmap="viridis"` |
| histogram | `ax.hist(values, bins=20, edgecolor="white")` |
| box plot | `ax.boxplot([a, b, c]); ax.set_xticks([1, 2, 3], ["A", "B", "C"])` |
| pie | `ax.pie(vals, labels=cats, autopct="%1.0f%%", startangle=90)`; donut: add `wedgeprops={"width": 0.4}`; no grid/axis labels |
| heatmap | `im = ax.imshow(matrix, cmap="viridis", aspect="auto"); fig.colorbar(im, label="unit")`<br>`ax.set_xticks(range(len(cols)), cols); ax.set_yticks(range(len(rows)), rows)`; no grid |
More:
- Several panels: `fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))`, then draw on `axes[0]`, `axes[1]`.
- Data from a file: `import pandas as pd; df = pd.read_csv("data.csv")`, then `df["column"]`. Print `df.head()` and `df.dtypes` once before plotting, so you use the real column names.
- Long category labels: `ax.barh` or `ax.tick_params(axis="x", rotation=45)`.
- Value labels on bars: `ax.bar_label(ax.bar(cats, vals), fmt="%.1f")`.
- Missing library: `pip install matplotlib pandas`.
Check (mandatory):
1. `run_command`: `python plot.py` must exit with 0 and print `saved chart.png`.
2. `view_image("chart.png")` and check what you SEE: all series/categories present, labels readable and not overlapping, nothing cut off, values plausible compared with the data. Fix and re-run if not.
## B. HTML / Plotly (only when asked for)
One self-contained page; the data sits in a JSON block, Plotly (loaded from a CDN, so the page needs internet) draws it.
1. Copy the template: `cp <skill-dir>/template.html chart.html`
2. Replace the JSON block `{"traces": [], "layout": {}}` in `chart.html` and the `<title>`:
- few values: with `edit_file`, write the JSON by hand;
- data from a file or more than ~30 values: with a Python script:
```python
import json, pandas as pd
df = pd.read_csv("data.csv")
spec = {"traces": [{"type": "bar", "x": df["city"].tolist(), "y": df["population"].tolist()}],
"layout": {"title": {"text": "Population per city"},
"xaxis": {"title": {"text": "City"}}, "yaxis": {"title": {"text": "Inhabitants"}}}}
html = open("chart.html", encoding="utf-8").read()
html = html.replace('{"traces": [], "layout": {}}', json.dumps(spec, ensure_ascii=False))
html = html.replace("<title>Chart</title>", "<title>Population per city</title>")
open("chart.html", "w", encoding="utf-8").write(html)
```
3. Check: `python <skill-dir>/check_html.py chart.html` must print `OK`.
Traces (each trace is one series; put several in the `traces` list):
| Chart | Trace | Layout extras |
|---|---|---|
| line | `{"type": "scatter", "mode": "lines+markers", "x": [...], "y": [...], "name": "A"}` | |
| area | line trace + `"fill": "tozeroy"`; stacked: `"stackgroup": "one"` instead | |
| bar | `{"type": "bar", "x": cats, "y": vals, "name": "A"}`; horizontal: swap x/y and add `"orientation": "h"` | |
| grouped / stacked bar | one bar trace per group | `"barmode": "group"` or `"stack"` |
| scatter | `{"type": "scatter", "mode": "markers", "x": [...], "y": [...]}` | |
| histogram | `{"type": "histogram", "x": values, "nbinsx": 20}` | |
| box plot | one `{"type": "box", "y": values, "name": "A"}` per group | |
| pie | `{"type": "pie", "labels": cats, "values": vals}`; donut: add `"hole": 0.5` | |
| heatmap | `{"type": "heatmap", "z": matrix, "x": cols, "y": rows, "colorscale": "Viridis"}` | |
Layout: `{"title": {"text": "..."}, "xaxis": {"title": {"text": "... (unit)"}}, "yaxis": {"title": {"text": "... (unit)"}}}`.
JSON only: double quotes, no trailing commas, no comments, no `NaN` (use `null`).

View File

@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Checks a chart page made from template.html: python check_html.py chart.html
Prints OK or the first problem found (exit code 1)."""
import json
import re
import sys
def fail(msg: str) -> None:
print("ERROR: " + msg); sys.exit(1)
if len(sys.argv) != 2:
fail("usage: python check_html.py chart.html")
html = open(sys.argv[1], encoding="utf-8").read()
m = re.search(r'<script id="chart-data" type="application/json">(.*?)</script>', html, re.S)
if not m:
fail('JSON block <script id="chart-data" type="application/json"> is missing - start again from template.html')
try:
spec = json.loads(m.group(1), parse_constant=lambda c: fail(f"{c} is not valid JSON - use null"))
except json.JSONDecodeError as e:
fail(f"the JSON block is not valid JSON: {e}")
traces = spec.get("traces") if isinstance(spec, dict) else None
if not isinstance(traces, list) or not traces:
fail('"traces" is empty - the template placeholder was not replaced')
for i, t in enumerate(traces):
if not isinstance(t, dict) or "type" not in t:
fail(f'trace {i} needs a "type" (scatter, bar, histogram, box, pie, heatmap)')
data = [k for k in ("x", "y", "z", "values") if isinstance(t.get(k), list) and t[k]]
if not data:
fail(f"trace {i} ({t['type']}) contains no data (x / y / z / values)")
pairs = [("labels", "values")] if t["type"] == "pie" else [] if t["type"] == "heatmap" else [("x", "y")]
for a, b in pairs:
if isinstance(t.get(a), list) and isinstance(t.get(b), list) and len(t[a]) != len(t[b]):
fail(f"trace {i}: {a} has {len(t[a])} entries but {b} has {len(t[b])}")
if not (spec.get("layout") or {}).get("title"):
fail('layout has no "title"')
if "<title>Chart</title>" in html:
fail("the page <title> is still the template default 'Chart'")
print(f"OK: {len(traces)} trace(s): " + ", ".join(t["type"] for t in traces))

View File

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chart</title>
<script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>
<style>
body { margin: 0; font-family: system-ui, sans-serif; background: #fff; }
#chart { width: 100%; max-width: 1000px; height: 560px; margin: 24px auto; }
#error { color: #b00020; text-align: center; }
</style>
</head>
<body>
<div id="chart"></div>
<p id="error"></p>
<!-- The chart: replace the JSON below. "traces" = list of Plotly traces, "layout" = Plotly layout. -->
<script id="chart-data" type="application/json">{"traces": [], "layout": {}}</script>
<script>
try {
const spec = JSON.parse(document.getElementById("chart-data").textContent);
const layout = Object.assign({margin: {t: 60, r: 30}, colorway:
["#4477AA", "#EE6677", "#228833", "#CCBB44", "#66CCEE", "#AA3377"]}, spec.layout); // colour-blind safe
Plotly.newPlot("chart", spec.traces, layout, {responsive: true, displaylogo: false});
} catch (e) {
document.getElementById("error").textContent = "Chart could not be drawn: " + e.message;
}
</script>
</body>
</html>

View File

@ -0,0 +1,49 @@
---
name: svg-translate
description: Translate the text inside SVG files (text, tspan, title, desc, aria-label) into another language while keeping markup, styling and layout intact. Use for any request to translate, localize or change the language of an .svg file.
---
# Translate text in SVG files
Never rewrite or retype an SVG: that breaks paths, gradients, IDs and styling. Extract only the strings into JSON, translate the JSON, and write the translations back into a copy of the original with the helper script `svg_text.py` (a file of this skill).
## Workflow
1. **Copy the helper** into the project (skill files are read-only, never retype it):
`run_command: cp <skill-dir>/svg_text.py .` (`<skill-dir>` is shown by load_skill).
Needs lxml: if `ModuleNotFoundError`, run `pip install lxml`.
2. **Extract**: `python svg_text.py extract input.svg strings.json`
- `WARNING: no text found` means the text was converted to paths or is a bitmap. It cannot be translated automatically: tell the user in the summary, do not guess.
3. **Translate**: `read_file strings.json`. Each entry has `id`, `text` (the fragment), `context` (the whole sentence or label it belongs to) and `where`. Write the file again with a `"translation"` field added to EVERY entry (valid UTF-8 JSON, keep `id` unchanged). Use write_file for the complete file.
- A sentence is often split over several fragments (tspans, or text before/after a tspan). Translate with the `context` in mind so that the fragments together read as one correct sentence; word order may differ, an empty string is allowed for a fragment without counterpart.
- Keep numbers, units, brand names, code, URLs and formulas unchanged.
- Keep labels short; prefer the shorter wording when two translations are equally good, the text must still fit the drawing.
- Surrounding spaces are restored by the script.
4. **Apply**: `python svg_text.py apply input.svg strings.json output.svg --lang de`
- `--lang <code>` sets `xml:lang` on the root (de, fr, es, ja, ...).
- Add `--drop-textlength` if the SVG uses `textLength`/`lengthAdjust` (fixed lengths squeeze or stretch translated text).
- Name the output by language, e.g. `diagram.de.svg`. Never overwrite the original unless asked.
5. **Check visually**, then fix and re-run step 4 from the ORIGINAL after editing `strings.json`.
6. **Summary**: output file name, number of strings translated, layout problems that remain.
## Visual check
Render original and translation to PNG, then look at both with `view_image`:
- `python -c "import cairosvg; cairosvg.svg2png(url='file.svg', write_to='file.png', output_width=1000)"` (`pip install cairosvg` if missing)
- or `rsvg-convert -w 1000 file.svg -o file.png`, or `inkscape file.svg -o file.png -w 1000`
Look for text outside its box or off the canvas, overlapping labels, truncated text, missing glyphs (boxes/blanks, typical for CJK, Arabic, Hebrew when the font lacks them) and wrong line breaks. Fixes, in order of preference:
1. A shorter translation in `strings.json`.
2. Split a long label into two lines with a second `<tspan x=".." dy="..">` (small `edit_file` on the output copy).
3. Slightly smaller `font-size` on that element, or change `text-anchor`.
4. For missing glyphs, add a fallback font to `font-family` (e.g. `Noto Sans CJK JP`, `Noto Sans Arabic`).
Right-to-left languages: the script keeps the logical text; consider `direction="rtl"` and `text-anchor="end"` on the affected `<text>` elements and re-check.
## What is and is not translated
- Translated: text of `<text>`, `<tspan>`, `<textPath>`, `<title>`, `<desc>`, `<flowPara>`/`<flowSpan>`, text in links, and `aria-label`.
- Not translated: strings with only digits/punctuation/symbols; `id`, `class`, `href`; CSS in `<style>`; JavaScript strings; `inkscape:label`, `data-*`; text inside embedded raster images or path outlines. If visible text lives in `<script>` or CSS `content:`, say so in the summary instead of editing it silently.
- Several files: run steps 2-4 per file, one `strings.json` and one language per output file.

View File

@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""svg_text.py - extract / apply translatable text of an SVG file.
python svg_text.py extract in.svg strings.json
python svg_text.py apply in.svg strings.json out.svg [--lang de] [--drop-textlength]
Needs lxml (pip install lxml)."""
import json, re, sys
from lxml import etree
TEXT_TAGS = {"text", "tspan", "textPath", "title", "desc", "flowRoot", "flowPara", "flowSpan", "a"}
ATTRS = ["aria-label"] # translatable attributes
SKIP_RX = re.compile(r"^[\W\d_]*$") # only digits/punctuation/symbols -> keep as is
def local(el):
return etree.QName(el).localname if isinstance(el.tag, str) else None
def units(root):
"""Yield (kind, element, current_string, context) in document order.
kind: 'text' (el.text), 'tail' (el.tail inside a text element), 'attr:<name>'."""
for el in root.iter():
name = local(el)
if name is None:
continue
for a in ATTRS:
if el.get(a):
yield f"attr:{a}", el, el.get(a), el.get(a)
if name not in TEXT_TAGS:
continue
in_text = name != "a" or any(local(p) in ("text", "tspan") for p in el.iterancestors())
if not in_text and name == "a":
continue
top = next((p for p in [*el.iterancestors()][::-1] if local(p) in ("text", "flowRoot")), el)
ctx = " ".join("".join(top.itertext()).split()) # whole sentence, for translation context
if el.text and el.text.strip():
yield "text", el, el.text, ctx
for child in el:
if child.tail and child.tail.strip():
yield "tail", child, child.tail, ctx
def extract(src, dst):
root = etree.parse(src).getroot()
out = []
for i, (kind, el, s, ctx) in enumerate(units(root)):
if SKIP_RX.match(s):
continue
out.append({"id": i, "text": s, "context": ctx, "where": f"{kind} of <{local(el)}>"})
json.dump(out, open(dst, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print(f"{len(out)} translatable strings -> {dst}")
if not out:
print("WARNING: no text found - the text may be converted to paths (cannot be translated).")
def apply(src, jsn, dst, lang=None, drop_tl=False):
tree = etree.parse(src); root = tree.getroot()
tr = {int(d["id"]): d["translation"] for d in json.load(open(jsn, encoding="utf-8"))
if d.get("translation") is not None}
n = 0
for i, (kind, el, s, ctx) in enumerate(units(root)):
if i not in tr:
continue
new = tr[i]
lead = s[:len(s) - len(s.lstrip())]; trail = s[len(s.rstrip()):] # keep surrounding whitespace
new = lead + new.strip() + trail
if kind == "text": el.text = new
elif kind == "tail": el.tail = new
else: el.set(kind[5:], new)
n += 1
if drop_tl:
for el in root.iter():
if isinstance(el.tag, str):
el.attrib.pop("textLength", None); el.attrib.pop("lengthAdjust", None)
if lang:
root.set("{http://www.w3.org/XML/1998/namespace}lang", lang)
tree.write(dst, xml_declaration=True, encoding="utf-8")
print(f"{n} strings applied -> {dst}")
if __name__ == "__main__":
a = sys.argv[1:]
if len(a) == 3 and a[0] == "extract": extract(a[1], a[2])
elif len(a) >= 4 and a[0] == "apply":
lang = a[a.index("--lang") + 1] if "--lang" in a else None
apply(a[1], a[2], a[3], lang, "--drop-textlength" in a)
else: print(__doc__); sys.exit(1)