mirror of
https://github.com/mankidev/antialgorithm.git
synced 2026-11-30 19:33:35 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd4c56ae82 | ||
|
|
cd0e9e4c56 | ||
|
|
e38bc879bc | ||
|
|
a671ca5253 | ||
|
|
a94c5a539d | ||
|
|
5578f7202f | ||
|
|
86b68117a0 | ||
|
|
ba63136110 | ||
|
|
a538068ce6 | ||
|
|
b7a2c7d224 | ||
|
|
75de35ef5e | ||
|
|
37ad27773e | ||
|
|
3541f7a280 | ||
|
|
e7d5d9721a | ||
|
|
d7d615ad28 | ||
|
|
71cf367192 | ||
|
|
a6c67f8cb2 | ||
|
|
95ee5116fc | ||
|
|
7623f75478 | ||
|
|
bb1105d630 | ||
|
|
f47a4aa3e3 | ||
|
|
3801e69d03 | ||
|
|
67d79fd095 | ||
|
|
8275ce3ac4 | ||
|
|
033f404957 | ||
|
|
09d1de592d | ||
|
|
f1955174a3 | ||
|
|
59fc116bc7 | ||
|
|
f9d1f05a68 | ||
|
|
9f624addd0 | ||
|
|
d3bd799ba0 | ||
|
|
57a14deca3 | ||
|
|
f5768b44b4 | ||
|
|
c4ce2ef9d5 | ||
|
|
947071bf39 | ||
|
|
947892e0b7 | ||
|
|
5923835bd2 | ||
|
|
83f0f5a2bd | ||
|
|
cd66a0eb10 | ||
|
|
df86cfc615 | ||
|
|
81bdcca43c | ||
|
|
f157372f2f | ||
|
|
73db93c590 | ||
|
|
c65de3d658 | ||
|
|
6953bcdf91 | ||
|
|
8822002a42 | ||
|
|
9e5d619a01 | ||
|
|
38623fcb29 | ||
|
|
669a37fae7 | ||
|
|
f77fb75e85 | ||
|
|
a1d6c54adc | ||
|
|
4d6f034429 | ||
|
|
f3d1b67b33 | ||
|
|
88ef36ff41 | ||
|
|
4bce7f46ac | ||
|
|
a157c67258 | ||
|
|
885f857cf7 | ||
|
|
a8dfa6bf76 | ||
|
|
af1fd3d16f | ||
|
|
199bceb6b6 | ||
|
|
9411daa610 | ||
|
|
3caf74aa65 | ||
|
|
a2519e6216 | ||
|
|
11edce7cef | ||
|
|
150b06f22a | ||
|
|
a6392c0d35 | ||
|
|
5ca280b4b7 | ||
|
|
aef169a928 | ||
|
|
1f4ae9080b | ||
|
|
aa279bbb3d | ||
|
|
21e2dca3ec |
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,49 @@
|
||||
# Contributing
|
||||
|
||||
Issues and pull requests are welcome. Small fixes can go straight to a pull request. For a new rule in `SKILL.md` or `visuals.md`, open an issue first with an example of the output that made you want it.
|
||||
|
||||
## Skill text
|
||||
|
||||
`SKILL.md` and `visuals.md` are read by the model, so the wording is the behavior. Keep it in plain English with short sentences, and name things the way a person would say them.
|
||||
|
||||
The skill has to work for anyone who installs it. Don't name other skills, tools, people or projects in the text, and keep examples general. A rule that only makes sense for your own setup belongs in your own `CLAUDE.md` or `AGENTS.md`.
|
||||
|
||||
Visual rules go in `visuals.md`, the rest in `SKILL.md`. Keep `SKILL.md` short, since it loads on any creative request.
|
||||
|
||||
## Testing a change to the skill text
|
||||
|
||||
Run the same prompt several times with the old text and with the new one, then compare the two sets side by side. A single good result proves little. If the results in a set share one look, as if made by the same hand, the skill has found a new default. The poster prompt from the README is a good start:
|
||||
|
||||
```
|
||||
Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.
|
||||
```
|
||||
|
||||
Mention in the pull request what you ran and what changed in the results. Screenshots help.
|
||||
|
||||
## Scripts
|
||||
|
||||
The scripts in `scripts/` use only the Python 3 standard library, except `check.py`, which also needs numpy, Pillow and `rsvg-convert` or cairosvg. Please don't add new dependencies.
|
||||
|
||||
They should run on Linux, macOS and Windows. Use `os.path` for paths and open text files with `encoding="utf-8"`.
|
||||
|
||||
The code has no comments or docstrings. Pick clear names instead, and put the reasoning in the pull request description.
|
||||
|
||||
Before you open a pull request, run the parts you touched. On Windows, use python or py if python3 is not found.
|
||||
|
||||
```
|
||||
python3 scripts/seed.py visual --no-log
|
||||
python3 scripts/seed.py text --no-log
|
||||
python3 scripts/seed.py idea --no-log
|
||||
python3 scripts/check.py some.svg
|
||||
python3 scripts/rough.py some.svg rough.svg
|
||||
```
|
||||
|
||||
Seed and move history is saved in `~/.local/state/antialgorithm/`, outside the repo. If you test with `ANTIALGORITHM_HISTORY` pointing somewhere else, don't commit that file.
|
||||
|
||||
## README and translations
|
||||
|
||||
The README has translations in `docs/`. If you change the English README, you don't have to update them all. Update the languages you can read, and say in the pull request which ones are now behind.
|
||||
|
||||
## License
|
||||
|
||||
By contributing you agree that your work is released under the MIT license of this project.
|
||||
@@ -1,8 +1,20 @@
|
||||
<p align="center">
|
||||
<img src=".claude-plugin/icon.png" width="140" height="140" alt="Orange bell curve with one point far out on its tail">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub>English | <a href="docs/README_TR.md">Türkçe</a> | <a href="docs/README_ZH.md">简体中文</a> | <a href="docs/README_JA.md">日本語</a> | <a href="docs/README_KO.md">한국어</a> | <a href="docs/README_ES.md">Español</a> | <a href="docs/README_PT.md">Português</a> | <a href="docs/README_DE.md">Deutsch</a> | <a href="docs/README_FR.md">Français</a> | <a href="docs/README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
Claude Code skill for creative work: names, copy, story, game ideas, posters, UI. It makes the model name its first, most average pick, then move away from it for a reason taken from the project.
|
||||
Agent skill for creative work: names, story, game ideas, posters, UI. It makes the model name its first, most average pick, then move away from it for a reason taken from the project.
|
||||
|
||||
Both rows came from the same prompt: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` The top row is one batch of six runs without the skill, none left out. The bottom row is picked from about a dozen runs made while the skill was still being written.
|
||||
|
||||
@@ -10,36 +22,29 @@ Both rows came from the same prompt: `Design a poster for a music festival as a
|
||||
|
||||
## Install
|
||||
|
||||
In Claude Code:
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Claude Code before 2.1.275 needs the marketplace added first:
|
||||
|
||||
```
|
||||
/plugin marketplace add mankidev/antialgorithm
|
||||
/plugin install antialgorithm@antialgorithm
|
||||
```
|
||||
|
||||
Or clone it into your skills folder:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm ~/.claude/skills/antialgorithm
|
||||
```
|
||||
|
||||
For Codex, Cursor, OpenCode and other agents that read `SKILL.md`, the [skills](https://github.com/vercel-labs/skills) CLI puts it in the right folder:
|
||||
The [skills](https://github.com/vercel-labs/skills) CLI puts it where your agent reads skills, for Codex, Cursor, OpenCode, Claude Code and others:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Or clone it into your agent's skills folder:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <skills folder>/antialgorithm
|
||||
```
|
||||
|
||||
In Claude Code it also installs as a plugin (on versions before 2.1.275, run `/plugin marketplace add mankidev/antialgorithm` first):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
The scripts need Python 3. `check.py` also needs numpy, Pillow and `rsvg-convert` (or the cairosvg package).
|
||||
|
||||
## Scripts
|
||||
|
||||
`seed.py` rolls a starting point when the request is thin. A visual seed gives a making method, colors, layout, type, a verb and a scale for the idea, a setting, a region and, half the time, an object. A text seed gives a voice, a way in and a register. An idea seed gives a verb, a constraint, a scale and a pressure. It draws from system randomness, so two people sending the same prompt start in different places. It also saves each seed to `~/.local/state/antialgorithm/history.jsonl` (under `$XDG_STATE_HOME` when that is set) and skips values from the last few, so your own seeds don't repeat from one session to the next. Plugin updates leave that file alone. `--keep "axis=value"` holds an axis fixed, which lets you keep a subject and roll only the look.
|
||||
`seed.py` rolls a starting point when the request is thin. A visual seed gives a making method, colors, layout, type, a verb and a scale for the idea, a setting, a region and, half the time, an object. A text seed gives a voice, a way in and a register. An idea seed gives a verb, a constraint, a scale and a pressure. Text and idea seeds also give a setting, a region and an object. It draws from system randomness, so two people sending the same prompt start in different places. It also saves each seed to `~/.local/state/antialgorithm/history.jsonl` (under `$XDG_STATE_HOME` when that is set) and skips values from the last few, so your own seeds don't repeat from one session to the next. Plugin updates leave that file alone. `--keep "axis=value"` holds an axis fixed, which lets you keep a subject and roll only the look.
|
||||
|
||||
`moves.py` keeps a short log of the main move behind each off-default answer, such as "neon tube wall, almost no type". The model reads it before showing new work, so it doesn't reuse a move that worked last time just because it worked.
|
||||
|
||||
@@ -52,3 +57,12 @@ Visual rules live in `visuals.md`, which the model reads only for visual work, s
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
name: antialgorithm
|
||||
description: 'Stops the safe, average, comfortable pick that AI reaches for first. Use when a creative choice is left open to Claude: ideas, names, story, game mechanics, visual style, color, poster or page layout, app or web interface design, composition, slogans, titles, taglines, creative copy. Not for code identifiers, bug fixes, choices the user already made, or texts whose form the user''s standing rules already set, such as a README, a store page, a commit message, release notes or license text. Also use when the user says "too generic", "boring", "typical AI", "too safe", "cliche", "average", "seen it before".'
|
||||
description: 'Stops the safe, average, comfortable pick that AI reaches for first. Use when a creative choice is left open to the agent: ideas, names, story, game mechanics, visual style, color, poster or page layout, app or web interface design, composition, slogans, titles, taglines, creative copy. Not for code identifiers, bug fixes, choices the user already made, or texts whose form the user''s standing rules already set, such as a README, a store page, a commit message, release notes or license text. Also use when the user says "too generic", "boring", "typical AI", "too safe", "cliche", "average", "seen it before".'
|
||||
---
|
||||
|
||||
# antialgorithm
|
||||
|
||||
The first answer that comes to mind is the average of all that was already made. It feels right because it is familiar, and that is the problem: the user has seen it a thousand times. This skill makes you notice that pick and move away from it on purpose.
|
||||
|
||||
The user's standing rules, in CLAUDE.md files and memory, always win over this skill, not only on language. If a rule there fixes the shape, the wording, the palette or the content of a piece, follow it and use this skill only for what is still open.
|
||||
The user's standing rules, in CLAUDE.md, AGENTS.md or similar files and memory, always win over this skill, not only on language. If a rule there fixes the shape, the wording, the palette or the content of a piece, follow it and use this skill only for what is still open.
|
||||
|
||||
## Where to start
|
||||
|
||||
@@ -15,7 +15,7 @@ The answer must differ from one user to the next, and you cannot see what others
|
||||
|
||||
1. If the request carries real context, such as a project, a place, a person, a purpose or a constraint, start from that.
|
||||
2. If the request is thin and the work is short, such as a few slogans, a name or a short text, do not stop at a question. Make the work from a seed or a stated guess, then ask one short question at the end that would make it fit better. The question asks for a fact about the case, not for leave to redo the work. If the work is long or costly, such as a full design, a long text or a game system, ask the one short question first: who it is for, where it lives or what it is about.
|
||||
3. If the request is thin and the user wants the work now, or cannot answer, roll a seed: `python3 scripts/seed.py visual`, `text` or `idea` (paths are relative to this skill's folder). Use what it gives as the starting point. The script keeps recent seeds in `history.jsonl` and avoids their values, so seeds do not repeat across sessions; `--no-log` rolls without saving. A visual seed also gives a verb and a scale: build the idea behind the piece from them, who does what, instead of a twist you think of yourself. You may roll one axis again once with `--only <axis>` if it truly fights the subject; pass the axes you keep with `--keep "axis=value"` so the new pick fits them. The region places the setting: the land, the weather and the buildings around it, and the names, jokes, habits and way of speaking of the people there, while the words stay in the language set near the end of this skill. Take what someone who lives there would know from a normal week: the brand on the bus stop, the way a neighbor greets you, what is broken and nobody fixes. Leave out what an outsider lists first, such as the national dish, the costume, the famous sight, the flag colors or the accent played for laughs. If you do not know enough real daily detail about the region, use less of it instead of filling the gap with the famous parts. Then tie the seed to the subject with a reason.
|
||||
3. If the request is thin and the user wants the work now, or cannot answer, roll a seed: `python3 scripts/seed.py visual`, `text` or `idea` (paths are relative to this skill's folder). On Windows, use python or py if python3 is not found. Use what it gives as the starting point. The script keeps recent seeds in `history.jsonl` and avoids their values, so seeds do not repeat across sessions; `--no-log` rolls without saving. A visual seed also gives a verb and a scale: build the idea behind the piece from them, who does what, instead of a twist you think of yourself. You may roll one axis again once with `--only <axis>` if it truly fights the subject; pass the axes you keep with `--keep "axis=value"` so the new pick fits them. The region places the setting: the land, the weather and the buildings around it, and the names, jokes, habits and way of speaking of the people there, while the words stay in the language set near the end of this skill. Take what someone who lives there would know from a normal week: the brand on the bus stop, the way a neighbor greets you, what is broken and nobody fixes. Leave out what an outsider lists first, such as the national dish, the costume, the famous sight, the flag colors or the accent played for laughs. If you do not know enough real daily detail about the region, use less of it instead of filling the gap with the famous parts. Then tie the seed to the subject with a reason.
|
||||
|
||||
Never pick the start point by thinking about what would be most interesting. That thought lands on the same place for all users.
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="Orange Glockenkurve mit einem Punkt weit draußen am Ende">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | Deutsch | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
Agent-Skill für kreative Arbeit: Namen, Geschichten, Spielideen, Plakate, Oberflächen. Das Modell nennt zuerst seine erste, durchschnittlichste Wahl und rückt dann mit einem Grund aus dem Projekt davon ab.
|
||||
|
||||
Beide Reihen stammen aus demselben Prompt: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` Die obere Reihe ist ein Durchgang mit sechs Läufen ohne den Skill, keiner aussortiert. Die untere Reihe ist aus etwa zwölf Läufen ausgewählt, die entstanden, während der Skill noch geschrieben wurde.
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
Die [skills](https://github.com/vercel-labs/skills)-CLI legt ihn dort ab, wo dein Agent Skills liest, für Codex, Cursor, OpenCode, Claude Code und andere:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Oder klone ihn in den Skills-Ordner deines Agenten:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <Skills-Ordner>/antialgorithm
|
||||
```
|
||||
|
||||
In Claude Code lässt er sich auch als Plugin installieren (in Versionen vor 2.1.275 zuerst `/plugin marketplace add mankidev/antialgorithm` ausführen):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Die Skripte brauchen Python 3. `check.py` braucht außerdem numpy, Pillow und `rsvg-convert` (oder das Paket cairosvg).
|
||||
|
||||
## Skripte
|
||||
|
||||
`seed.py` würfelt einen Startpunkt, wenn die Anfrage wenig hergibt. Ein visueller Seed liefert eine Herstellungsweise, Farben, Layout, Schrift, ein Verb und einen Maßstab für die Idee, einen Schauplatz, eine Region und in der Hälfte der Fälle einen Gegenstand. Ein Text-Seed liefert eine Stimme, einen Einstieg und ein Register. Ein Ideen-Seed liefert ein Verb, eine Einschränkung, einen Maßstab und einen Druck. Er nutzt den Zufall des Systems, daher starten zwei Leute mit demselben Prompt an verschiedenen Stellen. Außerdem speichert er jeden Seed in `~/.local/state/antialgorithm/history.jsonl` (unter `$XDG_STATE_HOME`, wenn das gesetzt ist) und überspringt Werte der letzten paar, damit sich deine Seeds von Sitzung zu Sitzung nicht wiederholen. Plugin-Updates lassen diese Datei in Ruhe. `--keep "axis=value"` hält eine Achse fest, so bleibt das Thema und nur der Look wird neu gewürfelt.
|
||||
|
||||
`moves.py` führt ein kurzes Protokoll über den Hauptzug jeder Antwort, die vom Naheliegenden abweicht, etwa "neon tube wall, almost no type". Das Modell liest es, bevor es neue Arbeit zeigt, und greift so nicht zu einem Zug, nur weil er beim letzten Mal funktioniert hat.
|
||||
|
||||
`rough.py` nimmt ein SVG, bringt gerade Linien, Formen und Buchstaben ins Wackeln und bricht die gleichmäßigen Abstände wiederholter Zeichen auf, damit ein in Code gezeichneter Handarbeits-Look nicht mehr wie geplottet aussieht. Es ist nur für handgemachte Verfahren wie Druck, Farbe, Stempel und Tinte gedacht; Bildschirm-, Kamera- und Render-Looks behalten ihre eigenen Spuren.
|
||||
|
||||
`check.py` rendert ein SVG in voller Größe und in Icongröße und listet Text auf, der über einen Rand läuft, unter einer Form liegt, zu wenig Kontrast hat oder zu klein ist. Die Größengrenze passt für Plakate; für einen App-Bildschirm nimm `--min-text 0.6`.
|
||||
|
||||
Die visuellen Regeln stehen in `visuals.md`. Das Modell liest die Datei nur bei visueller Arbeit, ein Name oder ein Slogan lädt sie also nicht.
|
||||
|
||||
## Lizenz
|
||||
|
||||
MIT
|
||||
|
||||
## Sterne-Verlauf
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="Curva de campana naranja con un punto lejos en la cola">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | Español | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
Skill de agente para trabajo creativo: nombres, historias, ideas de juego, carteles, interfaces. Hace que el modelo diga primero su elección más obvia y promedio, y luego se aleje de ella por una razón sacada del proyecto.
|
||||
|
||||
Las dos filas salieron del mismo prompt: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` La fila de arriba es una tanda de seis ejecuciones sin la skill, sin descartar ninguna. La de abajo está elegida entre unas doce ejecuciones hechas mientras la skill aún se estaba escribiendo.
|
||||
|
||||

|
||||
|
||||
## Instalación
|
||||
|
||||
La CLI [skills](https://github.com/vercel-labs/skills) la pone donde tu agente lee las skills, para Codex, Cursor, OpenCode, Claude Code y otros:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
O clónala en la carpeta de skills de tu agente:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <carpeta de skills>/antialgorithm
|
||||
```
|
||||
|
||||
En Claude Code también se instala como plugin (en versiones anteriores a 2.1.275, ejecuta antes `/plugin marketplace add mankidev/antialgorithm`):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Los scripts necesitan Python 3. `check.py` además necesita numpy, Pillow y `rsvg-convert` (o el paquete cairosvg).
|
||||
|
||||
## Scripts
|
||||
|
||||
`seed.py` tira un punto de partida cuando la petición trae poca información. Una semilla visual da un método de hechura, colores, composición, tipografía, un verbo y una escala para la idea, un escenario, una región y, la mitad de las veces, un objeto. Una semilla de texto da una voz, una forma de entrar y un registro. Una semilla de idea da un verbo, una restricción, una escala y una presión. Usa el azar del sistema, así que dos personas que envían el mismo prompt empiezan en sitios distintos. También guarda cada semilla en `~/.local/state/antialgorithm/history.jsonl` (dentro de `$XDG_STATE_HOME` si está definido) y evita los valores de las últimas, para que tus semillas no se repitan de una sesión a otra. Las actualizaciones del plugin no tocan ese archivo. `--keep "axis=value"` fija un eje, lo que te deja mantener el tema y volver a tirar solo el aspecto.
|
||||
|
||||
`moves.py` lleva un registro corto de la jugada principal de cada respuesta que se aleja de lo obvio, como "neon tube wall, almost no type". El modelo lo lee antes de enseñar un trabajo nuevo, así no repite una jugada solo porque funcionó la última vez.
|
||||
|
||||
`rough.py` toma un SVG, hace temblar sus líneas rectas, formas y letras, y rompe el espaciado regular de las marcas repetidas, para que un aspecto hecho a mano dibujado con código deje de parecer trazado por un plóter. Es solo para métodos hechos a mano como la impresión, la pintura, los sellos y la tinta; los aspectos de pantalla, cámara y render conservan sus propias marcas.
|
||||
|
||||
`check.py` renderiza un SVG a tamaño completo y a tamaño de icono, y lista el texto que se sale de un borde, queda bajo una forma, tiene poco contraste o es demasiado pequeño. El límite de tamaño está pensado para carteles; para una pantalla de app usa `--min-text 0.6`.
|
||||
|
||||
Las reglas visuales están en `visuals.md`, que el modelo solo lee en trabajos visuales, así que un nombre o un eslogan no las carga.
|
||||
|
||||
## Licencia
|
||||
|
||||
MIT
|
||||
|
||||
## Historial de estrellas
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="Courbe en cloche orange avec un point loin sur la queue">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | Français | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
Skill d'agent pour le travail créatif : noms, histoires, idées de jeu, affiches, interfaces. Il fait d'abord dire au modèle son premier choix, le plus moyen, puis l'en éloigne pour une raison tirée du projet.
|
||||
|
||||
Les deux rangées viennent du même prompt : `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` La rangée du haut est une série de six essais sans le skill, aucun écarté. Celle du bas a été choisie parmi une douzaine d'essais faits pendant l'écriture du skill.
|
||||
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
La CLI [skills](https://github.com/vercel-labs/skills) le place là où votre agent lit ses skills, pour Codex, Cursor, OpenCode, Claude Code et d'autres :
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Ou clonez-le dans le dossier de skills de votre agent :
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <dossier de skills>/antialgorithm
|
||||
```
|
||||
|
||||
Dans Claude Code, il s'installe aussi comme plugin (sur les versions antérieures à 2.1.275, lancez d'abord `/plugin marketplace add mankidev/antialgorithm`) :
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Les scripts demandent Python 3. `check.py` demande aussi numpy, Pillow et `rsvg-convert` (ou le paquet cairosvg).
|
||||
|
||||
## Scripts
|
||||
|
||||
`seed.py` tire un point de départ quand la demande est maigre. Une graine visuelle donne une façon de fabriquer, des couleurs, une mise en page, une typo, un verbe et une échelle pour l'idée, un décor, une région et, une fois sur deux, un objet. Une graine de texte donne une voix, une entrée en matière et un registre. Une graine d'idée donne un verbe, une contrainte, une échelle et une pression. Elle puise dans l'aléa du système, donc deux personnes qui envoient le même prompt partent de deux endroits différents. Chaque graine est aussi enregistrée dans `~/.local/state/antialgorithm/history.jsonl` (sous `$XDG_STATE_HOME` si la variable existe), et les valeurs des dernières sont évitées, pour que vos graines ne se répètent pas d'une session à l'autre. Les mises à jour du plugin ne touchent pas ce fichier. `--keep "axis=value"` bloque un axe, ce qui permet de garder un sujet et de ne retirer que l'apparence.
|
||||
|
||||
`moves.py` tient un court journal du coup principal derrière chaque réponse qui s'écarte du choix par défaut, par exemple "neon tube wall, almost no type". Le modèle le lit avant de montrer un nouveau travail, pour ne pas reprendre un coup simplement parce qu'il a marché la dernière fois.
|
||||
|
||||
`rough.py` prend un SVG, fait trembler ses lignes droites, ses formes et ses lettres, et casse l'espacement régulier des marques répétées, pour qu'un rendu fait main dessiné en code n'ait plus l'air sorti d'un traceur. Il ne sert qu'aux méthodes faites main comme l'impression, la peinture, le tampon et l'encre ; les rendus écran, photo et 3D gardent leurs propres marques.
|
||||
|
||||
`check.py` rend un SVG en taille réelle et en taille d'icône, et liste le texte qui dépasse un bord, passe sous une forme, manque de contraste ou est trop petit. La limite de taille est réglée pour les affiches ; pour un écran d'application, utilisez `--min-text 0.6`.
|
||||
|
||||
Les règles visuelles sont dans `visuals.md`, que le modèle ne lit que pour le travail visuel. Un nom ou un slogan ne les charge donc pas.
|
||||
|
||||
## Licence
|
||||
|
||||
MIT
|
||||
|
||||
## Historique des étoiles
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="尾の先に点がひとつあるオレンジの釣鐘曲線">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | 日本語 | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
クリエイティブな作業のためのエージェントスキルです。対象は名前、ストーリー、ゲームのアイデア、ポスター、UI。モデルに最初に浮かんだいちばん平均的な案をまず言わせ、プロジェクトから取った理由をもとにその案から離れさせます。
|
||||
|
||||
2段とも同じプロンプトから作りました:`Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` 上の段はスキルなしで6回実行したもので、1枚も外していません。下の段は、スキルを書いている途中に実行した十数回の中から選んだものです。
|
||||
|
||||

|
||||
|
||||
## インストール
|
||||
|
||||
[skills](https://github.com/vercel-labs/skills) CLI を使うと、Codex、Cursor、OpenCode、Claude Code などのエージェントがスキルを読み込む場所に入ります:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
または、エージェントの skills フォルダにクローンします:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <skills フォルダ>/antialgorithm
|
||||
```
|
||||
|
||||
Claude Code ではプラグインとしても入れられます(2.1.275 より前のバージョンでは、先に `/plugin marketplace add mankidev/antialgorithm` を実行してください):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
スクリプトには Python 3 が必要です。`check.py` にはさらに numpy、Pillow、`rsvg-convert`(または cairosvg パッケージ)が必要です。
|
||||
|
||||
## スクリプト
|
||||
|
||||
`seed.py` は、依頼の情報が少ないときに出発点をサイコロで決めます。ビジュアル用のシードは、制作手法、配色、レイアウト、書体、アイデアのための動詞とスケール、舞台、地域、そして2回に1回は物をひとつ出します。テキスト用のシードは、語りの声、入り方、文体を出します。アイデア用のシードは、動詞、制約、スケール、プレッシャーを出します。システムの乱数を使うので、同じプロンプトを送った2人でも出発点が変わります。各シードは `~/.local/state/antialgorithm/history.jsonl`(`$XDG_STATE_HOME` が設定されていればその下)に保存され、直近のいくつかで出た値は避けるので、自分のシードがセッションをまたいで繰り返されることもありません。プラグインを更新してもこのファイルは残ります。`--keep "axis=value"` で軸をひとつ固定でき、題材はそのままに見た目だけを振り直せます。
|
||||
|
||||
`moves.py` は、デフォルトを避けた回答ごとに、その中心になった手を短く記録します。たとえば "neon tube wall, almost no type" のようにです。モデルは新しい作品を見せる前にこれを読むので、前回うまくいったというだけで同じ手を使い回すことがなくなります。
|
||||
|
||||
`rough.py` は SVG の直線、図形、文字を揺らし、繰り返し模様の等間隔を崩して、コードで描いた手作り風の絵がプロッターで描いたように見えないようにします。印刷、絵の具、スタンプ、インクのような手作業の手法専用です。画面、カメラ、レンダーの見た目はそれぞれの痕跡をそのまま残します。
|
||||
|
||||
`check.py` は SVG を原寸とアイコンサイズでレンダリングし、端からはみ出した文字、図形の下に隠れた文字、コントラストが低い文字、小さすぎる文字を一覧にします。サイズの下限はポスター向けです。アプリ画面には `--min-text 0.6` を使ってください。
|
||||
|
||||
ビジュアルのルールは `visuals.md` にあり、モデルはビジュアルの作業のときだけ読みます。名前やスローガンを考えるときには読み込まれません。
|
||||
|
||||
## ライセンス
|
||||
|
||||
MIT
|
||||
|
||||
## スター履歴
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="꼬리 끝에 점 하나가 있는 주황색 종 모양 곡선">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | 한국어 | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
창작 작업을 위한 에이전트 스킬: 이름, 이야기, 게임 아이디어, 포스터, UI. 모델이 처음 떠올린 가장 평균적인 선택을 먼저 말하게 하고, 프로젝트에서 가져온 이유를 들어 그 선택에서 벗어나게 합니다.
|
||||
|
||||
두 줄 모두 같은 프롬프트에서 나왔습니다: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` 윗줄은 스킬 없이 한 번에 돌린 여섯 개로, 하나도 빼지 않았습니다. 아랫줄은 스킬을 아직 쓰는 중에 돌린 열두 번 정도의 결과에서 골랐습니다.
|
||||
|
||||

|
||||
|
||||
## 설치
|
||||
|
||||
[skills](https://github.com/vercel-labs/skills) CLI가 Codex, Cursor, OpenCode, Claude Code 등 에이전트가 스킬을 읽는 위치에 넣어 줍니다:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
또는 에이전트의 skills 폴더에 클론하세요:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <skills 폴더>/antialgorithm
|
||||
```
|
||||
|
||||
Claude Code에서는 플러그인으로도 설치됩니다 (2.1.275 이전 버전에서는 먼저 `/plugin marketplace add mankidev/antialgorithm`을 실행하세요):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
스크립트에는 Python 3이 필요합니다. `check.py`에는 numpy, Pillow, `rsvg-convert`(또는 cairosvg 패키지)도 필요합니다.
|
||||
|
||||
## 스크립트
|
||||
|
||||
`seed.py`는 요청에 정보가 적을 때 출발점을 굴려서 정합니다. 시각 시드는 제작 방식, 색, 레이아웃, 글꼴, 아이디어를 위한 동사와 규모, 배경, 지역, 그리고 두 번에 한 번은 사물 하나를 줍니다. 텍스트 시드는 목소리, 들어가는 방식, 말투를 줍니다. 아이디어 시드는 동사, 제약, 규모, 압박을 줍니다. 시스템 난수를 쓰기 때문에 같은 프롬프트를 보낸 두 사람도 서로 다른 곳에서 시작합니다. 시드마다 `~/.local/state/antialgorithm/history.jsonl`(`$XDG_STATE_HOME`이 설정되어 있으면 그 아래)에 저장하고 최근 몇 번의 값은 건너뛰어서, 내 시드가 세션마다 반복되지 않습니다. 플러그인을 업데이트해도 이 파일은 그대로입니다. `--keep "axis=value"`로 축 하나를 고정하면 주제는 두고 겉모습만 다시 굴릴 수 있습니다.
|
||||
|
||||
`moves.py`는 기본값을 피한 답마다 그 중심이 된 수를 짧게 기록합니다. 예: "neon tube wall, almost no type". 모델은 새 작업을 보여 주기 전에 이 기록을 읽기 때문에, 지난번에 통했다는 이유만으로 같은 수를 다시 쓰지 않습니다.
|
||||
|
||||
`rough.py`는 SVG의 직선, 도형, 글자를 흔들고 반복되는 표시의 고른 간격을 깨서, 코드로 그린 손맛이 플로터로 그린 것처럼 보이지 않게 합니다. 인쇄, 물감, 도장, 잉크처럼 손으로 만드는 방식에만 씁니다. 화면, 카메라, 렌더 느낌은 각자의 흔적을 그대로 둡니다.
|
||||
|
||||
`check.py`는 SVG를 원래 크기와 아이콘 크기로 렌더링하고, 가장자리 밖으로 나간 글자, 도형 아래 깔린 글자, 대비가 낮거나 너무 작은 글자를 알려 줍니다. 크기 기준은 포스터에 맞춰져 있으니 앱 화면에는 `--min-text 0.6`을 쓰세요.
|
||||
|
||||
시각 규칙은 `visuals.md`에 있고, 모델은 시각 작업을 할 때만 이 파일을 읽습니다. 그래서 이름이나 슬로건을 지을 때는 불러오지 않습니다.
|
||||
|
||||
## 라이선스
|
||||
|
||||
MIT
|
||||
|
||||
## 스타 기록
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="Curva de sino laranja com um ponto longe na cauda">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | Português | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
Skill de agente para trabalho criativo: nomes, histórias, ideias de jogo, pôsteres, interfaces. Faz o modelo dizer primeiro a escolha mais óbvia e mediana, e depois se afastar dela por um motivo tirado do projeto.
|
||||
|
||||
As duas fileiras saíram do mesmo prompt: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` A de cima é um lote de seis execuções sem a skill, sem nenhuma descartada. A de baixo foi escolhida entre cerca de doze execuções feitas enquanto a skill ainda estava sendo escrita.
|
||||
|
||||

|
||||
|
||||
## Instalação
|
||||
|
||||
A CLI [skills](https://github.com/vercel-labs/skills) coloca a skill onde o seu agente lê skills, para Codex, Cursor, OpenCode, Claude Code e outros:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Ou clone na pasta de skills do seu agente:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <pasta de skills>/antialgorithm
|
||||
```
|
||||
|
||||
No Claude Code ela também se instala como plugin (em versões anteriores à 2.1.275, rode antes `/plugin marketplace add mankidev/antialgorithm`):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Os scripts precisam de Python 3. O `check.py` também precisa de numpy, Pillow e `rsvg-convert` (ou do pacote cairosvg).
|
||||
|
||||
## Scripts
|
||||
|
||||
`seed.py` sorteia um ponto de partida quando o pedido traz pouca informação. Uma semente visual dá um método de feitura, cores, layout, tipografia, um verbo e uma escala para a ideia, um cenário, uma região e, em metade das vezes, um objeto. Uma semente de texto dá uma voz, uma forma de entrar e um registro. Uma semente de ideia dá um verbo, uma restrição, uma escala e uma pressão. Ela usa a aleatoriedade do sistema, então duas pessoas que mandam o mesmo prompt começam em lugares diferentes. Também salva cada semente em `~/.local/state/antialgorithm/history.jsonl` (dentro de `$XDG_STATE_HOME`, se estiver definido) e pula os valores das últimas, para que as suas sementes não se repitam de uma sessão para outra. Atualizações do plugin não mexem nesse arquivo. `--keep "axis=value"` fixa um eixo, o que permite manter o tema e sortear só a aparência.
|
||||
|
||||
`moves.py` guarda um registro curto do lance principal de cada resposta que foge do óbvio, como "neon tube wall, almost no type". O modelo lê esse registro antes de mostrar um trabalho novo, assim não repete um lance só porque ele funcionou da última vez.
|
||||
|
||||
`rough.py` pega um SVG, faz tremer suas linhas retas, formas e letras e quebra o espaçamento regular das marcas repetidas, para que um visual feito à mão desenhado em código deixe de parecer saído de uma plotter. Serve só para métodos feitos à mão, como impressão, pintura, carimbo e tinta; visuais de tela, câmera e render mantêm as próprias marcas.
|
||||
|
||||
`check.py` renderiza um SVG em tamanho cheio e em tamanho de ícone e lista o texto que passa da borda, fica sob uma forma, tem pouco contraste ou é pequeno demais. O limite de tamanho é pensado para pôsteres; para uma tela de app, use `--min-text 0.6`.
|
||||
|
||||
As regras visuais ficam em `visuals.md`, que o modelo só lê em trabalho visual, então um nome ou um slogan não as carrega.
|
||||
|
||||
## Licença
|
||||
|
||||
MIT
|
||||
|
||||
## Histórico de estrelas
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="Оранжевая колоколообразная кривая с одной точкой далеко на хвосте">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | Русский</sub></p>
|
||||
|
||||

|
||||
|
||||
Скилл для агентов для творческой работы: названия, истории, идеи для игр, постеры, интерфейсы. Он заставляет модель сначала назвать свой первый, самый усреднённый вариант, а потом уйти от него по причине, взятой из проекта.
|
||||
|
||||
Оба ряда получены из одного и того же промпта: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` Верхний ряд: шесть запусков без скилла подряд, ни один не выброшен. Нижний ряд отобран примерно из дюжины запусков, сделанных, пока скилл ещё писался.
|
||||
|
||||

|
||||
|
||||
## Установка
|
||||
|
||||
CLI [skills](https://github.com/vercel-labs/skills) кладёт его туда, откуда ваш агент читает скиллы, для Codex, Cursor, OpenCode, Claude Code и других:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Или клонируйте его в папку скиллов вашего агента:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <папка скиллов>/antialgorithm
|
||||
```
|
||||
|
||||
В Claude Code он также ставится как плагин (в версиях до 2.1.275 сначала выполните `/plugin marketplace add mankidev/antialgorithm`):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Скриптам нужен Python 3. Для `check.py` также нужны numpy, Pillow и `rsvg-convert` (или пакет cairosvg).
|
||||
|
||||
## Скрипты
|
||||
|
||||
`seed.py` выбрасывает отправную точку, когда в запросе мало данных. Визуальное зерно даёт способ изготовления, цвета, композицию, шрифт, глагол и масштаб для идеи, место действия, регион и, в половине случаев, предмет. Текстовое зерно даёт голос, способ войти в текст и регистр. Зерно идеи даёт глагол, ограничение, масштаб и давление. Случайность берётся из системы, поэтому два человека с одинаковым промптом начинают с разных мест. Каждое зерно сохраняется в `~/.local/state/antialgorithm/history.jsonl` (внутри `$XDG_STATE_HOME`, если переменная задана), а значения последних нескольких пропускаются, чтобы ваши зёрна не повторялись от сессии к сессии. Обновления плагина этот файл не трогают. `--keep "axis=value"` фиксирует одну ось: тема остаётся, а заново выпадает только внешний вид.
|
||||
|
||||
`moves.py` ведёт короткий журнал главного хода каждого ответа, который уходит от варианта по умолчанию, например "neon tube wall, almost no type". Модель читает его перед тем, как показать новую работу, и не повторяет ход только потому, что в прошлый раз он сработал.
|
||||
|
||||
`rough.py` берёт SVG, расшатывает прямые линии, фигуры и буквы и ломает ровный шаг повторяющихся элементов, чтобы нарисованный кодом «ручной» вид перестал выглядеть как вывод плоттера. Он нужен только для ручных техник: печати, краски, штампов и туши. Экранные, фото- и рендер-стили сохраняют свои собственные следы.
|
||||
|
||||
`check.py` рендерит SVG в полном размере и в размере иконки и перечисляет текст, который вылезает за край, прячется под фигурой, плохо контрастирует или слишком мелкий. Порог размера рассчитан на постеры; для экрана приложения используйте `--min-text 0.6`.
|
||||
|
||||
Визуальные правила лежат в `visuals.md`. Модель читает этот файл только при визуальной работе, так что название или слоган его не подгружают.
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT
|
||||
|
||||
## История звёзд
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="Kuyruğunda tek bir nokta olan turuncu çan eğrisi">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | Türkçe | <a href="README_ZH.md">简体中文</a> | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
Yaratıcı işler için ajan skill'i: isim, hikâye, oyun fikri, poster, arayüz. Modele önce ilk ve en ortalama seçimini söyletir, sonra projeden aldığı bir gerekçeyle o seçimden uzaklaştırır.
|
||||
|
||||
İki sıra da aynı istemden çıktı: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` Üst sıra skill olmadan yapılmış altı denemenin hepsi, hiçbiri elenmedi. Alt sıra, skill henüz yazılırken yapılan yaklaşık on iki denemeden seçildi.
|
||||
|
||||

|
||||
|
||||
## Kurulum
|
||||
|
||||
[skills](https://github.com/vercel-labs/skills) CLI'ı onu ajanının skill okuduğu yere koyar; Codex, Cursor, OpenCode, Claude Code ve diğerleri için:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Ya da ajanının skills klasörüne klonla:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <skills klasörü>/antialgorithm
|
||||
```
|
||||
|
||||
Claude Code'da plugin olarak da kurulur (2.1.275'ten eski sürümlerde önce `/plugin marketplace add mankidev/antialgorithm` çalıştır):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
Betikler Python 3 ister. `check.py` ayrıca numpy, Pillow ve `rsvg-convert` (ya da cairosvg paketi) ister.
|
||||
|
||||
## Betikler
|
||||
|
||||
`seed.py`, istekte az bilgi olduğunda bir başlangıç noktası atar. Görsel tohum bir yapım yöntemi, renkler, yerleşim, yazı tipi, fikir için bir fiil ve bir ölçek, bir mekân, bir bölge ve iki seferden birinde bir nesne verir. Metin tohumu bir ses, bir giriş yolu ve bir üslup verir. Fikir tohumu bir fiil, bir kısıt, bir ölçek ve bir baskı verir. Metin ve fikir tohumları da bir mekân, bir bölge ve bir nesne verir. Sistemin rastgeleliğinden çeker, bu yüzden aynı istemi gönderen iki kişi farklı yerlerden başlar. Her tohumu `~/.local/state/antialgorithm/history.jsonl` dosyasına kaydeder (`$XDG_STATE_HOME` tanımlıysa onun altına) ve son birkaçındaki değerleri atlar, böylece kendi tohumların oturumdan oturuma tekrar etmez. Plugin güncellemeleri bu dosyaya dokunmaz. `--keep "axis=value"` bir ekseni sabit tutar; konuyu koruyup sadece görünümü yeniden atmanı sağlar.
|
||||
|
||||
`moves.py`, varsayılandan kaçan her cevabın arkasındaki ana hamlenin kısa bir kaydını tutar, örneğin "neon tube wall, almost no type". Model yeni bir iş göstermeden önce bunu okur, böylece geçen sefer işe yarayan bir hamleyi sırf işe yaradı diye tekrar kullanmaz.
|
||||
|
||||
`rough.py` bir SVG alır, düz çizgilerini, şekillerini ve harflerini sarsar ve tekrarlanan işaretlerin eşit aralığını bozar; böylece kodla çizilen el yapımı görünüm plotter çıktısı gibi durmaz. Sadece baskı, boya, damga ve mürekkep gibi el yapımı yöntemler içindir; ekran, kamera ve render görünümleri kendi izlerini korur.
|
||||
|
||||
`check.py` bir SVG'yi tam boyda ve ikon boyunda çizer; kenardan taşan, bir şeklin altında kalan, kontrastı düşük ya da fazla küçük yazıları listeler. Boyut sınırı postere göredir; uygulama ekranı için `--min-text 0.6` kullan.
|
||||
|
||||
Görsel kurallar `visuals.md` içindedir. Model onu sadece görsel işte okur, bu yüzden bir isim ya da slogan bu kuralları yüklemez.
|
||||
|
||||
## Lisans
|
||||
|
||||
MIT
|
||||
|
||||
## Yıldız geçmişi
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
@@ -0,0 +1,68 @@
|
||||
<p align="center">
|
||||
<img src="../.claude-plugin/icon.png" width="140" height="140" alt="橙色钟形曲线,尾部远处有一个点">
|
||||
</p>
|
||||
|
||||
# antialgorithm
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/mankidev/antialgorithm/releases"><img src="https://img.shields.io/github/v/release/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="Latest release"></a>
|
||||
<a href="../LICENSE"><img src="https://img.shields.io/github/license/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="MIT license"></a>
|
||||
<a href="https://github.com/mankidev/antialgorithm/stargazers"><img src="https://img.shields.io/github/stars/mankidev/antialgorithm?color=F07A1E&labelColor=171717" alt="GitHub stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center"><sub><a href="../README.md">English</a> | <a href="README_TR.md">Türkçe</a> | 简体中文 | <a href="README_JA.md">日本語</a> | <a href="README_KO.md">한국어</a> | <a href="README_ES.md">Español</a> | <a href="README_PT.md">Português</a> | <a href="README_DE.md">Deutsch</a> | <a href="README_FR.md">Français</a> | <a href="README_RU.md">Русский</a></sub></p>
|
||||
|
||||

|
||||
|
||||
面向创意工作的智能体技能:名字、故事、游戏点子、海报、界面。它让模型先说出自己第一个、最平均的选择,再根据从项目里找到的理由离开这个选择。
|
||||
|
||||
两行海报来自同一个提示词:`Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` 上面一行是不加技能时一次跑出的六张,一张没删。下面一行是在技能还在编写时,从大约十二次运行里挑出来的。
|
||||
|
||||

|
||||
|
||||
## 安装
|
||||
|
||||
[skills](https://github.com/vercel-labs/skills) 命令行工具会把它放到你的智能体读取技能的位置,支持 Codex、Cursor、OpenCode、Claude Code 等:
|
||||
|
||||
```
|
||||
npx skills add mankidev/antialgorithm
|
||||
```
|
||||
|
||||
或者把它克隆到你的智能体的 skills 文件夹:
|
||||
|
||||
```
|
||||
git clone https://github.com/mankidev/antialgorithm <skills 文件夹>/antialgorithm
|
||||
```
|
||||
|
||||
在 Claude Code 中也可以作为插件安装(2.1.275 之前的版本请先运行 `/plugin marketplace add mankidev/antialgorithm`):
|
||||
|
||||
```
|
||||
/plugin install antialgorithm --marketplace mankidev/antialgorithm
|
||||
```
|
||||
|
||||
脚本需要 Python 3。`check.py` 还需要 numpy、Pillow 和 `rsvg-convert`(或 cairosvg 包)。
|
||||
|
||||
## 脚本
|
||||
|
||||
`seed.py` 在请求信息太少时掷出一个起点。视觉种子给出制作方法、配色、版式、字体、用于构思的一个动词和一个尺度、一个场景、一个地区,有一半的概率还会给出一个物件。文字种子给出一种口吻、一个切入角度和一种语域。点子种子给出一个动词、一个限制、一个尺度和一种压力。它取自系统随机源,所以两个人发送同一个提示词也会从不同的地方开始。它还会把每个种子保存到 `~/.local/state/antialgorithm/history.jsonl`(设置了 `$XDG_STATE_HOME` 时保存在其下),并跳过最近几次用过的值,所以你自己的种子不会在不同会话之间重复。插件更新不会动这个文件。`--keep "axis=value"` 可以固定某个轴,保留主题,只重新掷外观。
|
||||
|
||||
`moves.py` 为每个避开默认选择的回答记下它的主要手法,例如 "neon tube wall, almost no type"。模型在展示新作品前会先读它,这样就不会仅仅因为某个手法上次奏效就再用一次。
|
||||
|
||||
`rough.py` 读取一个 SVG,抖动其中的直线、形状和文字,并打乱重复标记的均匀间距,让用代码画出的手工感不再像绘图仪画的。它只用于印刷、绘画、印章、墨水这类手工方法;屏幕、相机和渲染风格保留它们自己的痕迹。
|
||||
|
||||
`check.py` 以原尺寸和图标尺寸渲染 SVG,列出超出边缘、被形状遮住、对比度太低或太小的文字。尺寸下限是按海报设定的;检查应用界面时请用 `--min-text 0.6`。
|
||||
|
||||
视觉规则在 `visuals.md` 里,模型只在做视觉工作时才读取,所以起名字或写标语时不会加载这些规则。
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT
|
||||
|
||||
## Star 历史
|
||||
|
||||
<a href="https://star-history.com/#mankidev/antialgorithm&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date&theme=dark">
|
||||
<img src="https://api.star-history.com/svg?repos=mankidev/antialgorithm&type=Date" alt="Star history chart for mankidev/antialgorithm">
|
||||
</picture>
|
||||
</a>
|
||||
+425
-89
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import copy
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
@@ -9,15 +10,23 @@ import sys
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
try:
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
except ImportError as missing:
|
||||
sys.exit(f"check.py needs the numpy and Pillow packages ({missing})")
|
||||
|
||||
SVG_NS = "http://www.w3.org/2000/svg"
|
||||
ET.register_namespace("", SVG_NS)
|
||||
ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
|
||||
XLINK_HREF = "{http://www.w3.org/1999/xlink}href"
|
||||
NUM = re.compile(r"[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?")
|
||||
SHAPES = {"rect", "circle", "ellipse", "line", "polyline", "polygon", "path", "image", "use"}
|
||||
HOLDERS = {"defs", "clipPath", "mask", "pattern", "filter", "marker", "symbol"}
|
||||
LENGTH = re.compile(r"\s*([-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?)\s*(px|pt|pc|in|cm|mm|q|em|ex)?\s*$", re.IGNORECASE)
|
||||
UNITS = {"px": 1, "pt": 4 / 3, "pc": 16, "in": 96, "cm": 96 / 2.54, "mm": 96 / 25.4, "q": 96 / 101.6, "em": 16, "ex": 8}
|
||||
ALIGN = {"Min": 0.0, "Mid": 0.5, "Max": 1.0}
|
||||
TRANSFORM = re.compile(r"(matrix|scale|rotate|skewX|skewY)\s*\(([^)]*)\)")
|
||||
|
||||
|
||||
def tag(el):
|
||||
@@ -39,12 +48,16 @@ def cairo_dir():
|
||||
os.path.join(apps, "GIMP 3", "bin"), os.path.join(pf, "GIMP 2", "bin"),
|
||||
os.path.join(apps, "GIMP 2", "bin"),
|
||||
]
|
||||
return next((d for d in dirs if d and os.path.isfile(os.path.join(d, "libcairo-2.dll"))), None)
|
||||
return next((d for d in dirs if d and os.path.isabs(d) and os.path.isfile(os.path.join(d, "libcairo-2.dll"))), None)
|
||||
|
||||
|
||||
def render(svg_path, png_path, width):
|
||||
if shutil.which("rsvg-convert"):
|
||||
subprocess.run(["rsvg-convert", "-w", str(width), svg_path, "-o", png_path], check=True, stderr=subprocess.DEVNULL)
|
||||
rsvg = shutil.which("rsvg-convert")
|
||||
if rsvg:
|
||||
done = subprocess.run([rsvg, "-w", str(width), svg_path, "-o", png_path], check=False, capture_output=True)
|
||||
if done.returncode:
|
||||
err = " ".join(done.stderr.decode("utf-8", "replace").split())
|
||||
sys.exit(f"rsvg-convert could not render the SVG: {err[:300] or 'exit code ' + str(done.returncode)}")
|
||||
return
|
||||
found = cairo_dir()
|
||||
if found:
|
||||
@@ -53,7 +66,189 @@ def render(svg_path, png_path, width):
|
||||
import cairosvg
|
||||
except (ImportError, OSError):
|
||||
sys.exit("needs rsvg-convert, or the cairosvg python package with a cairo library it can load")
|
||||
cairosvg.svg2png(url=svg_path, write_to=png_path, output_width=width)
|
||||
tree = read_svg(svg_path)
|
||||
for_cairo(tree.getroot())
|
||||
try:
|
||||
cairosvg.svg2png(bytestring=ET.tostring(tree.getroot()), url=svg_path, write_to=png_path, output_width=width)
|
||||
except (ValueError, TypeError, LookupError, ArithmeticError, SyntaxError, OSError, MemoryError) as e:
|
||||
sys.exit(f"cairosvg could not render the SVG: {' '.join(str(e).split())[:300] or type(e).__name__}")
|
||||
|
||||
|
||||
def style_value(el, prop):
|
||||
value = el.get(prop)
|
||||
for decl in el.get("style", "").split(";"):
|
||||
k, _, v = decl.partition(":")
|
||||
if k.strip() == prop:
|
||||
value = v.strip()
|
||||
return value
|
||||
|
||||
|
||||
def add_style(el, decl):
|
||||
st = el.get("style", "")
|
||||
el.set("style", (st + ";" if st else "") + decl)
|
||||
|
||||
|
||||
def stroke_first(order):
|
||||
words = [w for w in (order or "").split() if w in ("fill", "stroke", "markers")]
|
||||
words += [w for w in ("fill", "stroke", "markers") if w not in words]
|
||||
return words.index("stroke") < words.index("fill")
|
||||
|
||||
|
||||
def for_cairo(root):
|
||||
if style_value(root, "text-rendering") is None:
|
||||
root.set("text-rendering", "optimizeSpeed")
|
||||
parent = {c: p for p in root.iter() for c in p}
|
||||
for t in texts(root):
|
||||
el, order = t, None
|
||||
while el is not None and order is None:
|
||||
order = style_value(el, "paint-order")
|
||||
el = parent.get(el)
|
||||
if not stroke_first(order):
|
||||
continue
|
||||
under = copy.deepcopy(t)
|
||||
for e in under.iter():
|
||||
e.attrib.pop("id", None)
|
||||
add_style(e, "fill:none")
|
||||
for e in t.iter():
|
||||
add_style(e, "stroke:none")
|
||||
up = parent[t]
|
||||
up.insert(list(up).index(t), under)
|
||||
|
||||
|
||||
def scaled(value, size):
|
||||
m = LENGTH.match(value)
|
||||
if not m:
|
||||
return None
|
||||
n, unit = float(m.group(1)), (m.group(2) or "px").lower()
|
||||
return n * size if unit == "em" else n * size / 2 if unit == "ex" else n * UNITS[unit]
|
||||
|
||||
|
||||
def font_size(el, parent):
|
||||
chain = []
|
||||
while el is not None:
|
||||
chain.append(el)
|
||||
el = parent.get(el)
|
||||
size = 16.0
|
||||
for e in reversed(chain):
|
||||
v = (style_value(e, "font-size") or "").strip()
|
||||
if v.endswith("%") and NUM.fullmatch(v[:-1]):
|
||||
size *= float(v[:-1]) / 100
|
||||
elif v and scaled(v, size):
|
||||
size = scaled(v, size)
|
||||
return size
|
||||
|
||||
|
||||
def transform_matrix(value):
|
||||
m = np.eye(2)
|
||||
for name, args in TRANSFORM.findall(value or ""):
|
||||
v = [float(n) for n in NUM.findall(args)]
|
||||
if not v:
|
||||
continue
|
||||
a = math.radians(v[0])
|
||||
if name == "matrix" and len(v) == 6:
|
||||
t = [[v[0], v[2]], [v[1], v[3]]]
|
||||
elif name == "scale":
|
||||
t = [[v[0], 0], [0, v[1] if len(v) > 1 else v[0]]]
|
||||
elif name == "rotate":
|
||||
t = [[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]]
|
||||
elif name == "skewX":
|
||||
t = [[1, math.tan(a)], [0, 1]]
|
||||
elif name == "skewY":
|
||||
t = [[1, 0], [math.tan(a), 1]]
|
||||
else:
|
||||
continue
|
||||
m = m @ np.array(t)
|
||||
return m
|
||||
|
||||
|
||||
def ancestry(el, parent):
|
||||
chain = []
|
||||
while el is not None:
|
||||
chain.append(el)
|
||||
el = parent.get(el)
|
||||
return chain[::-1]
|
||||
|
||||
|
||||
def line_direction(text, parent, vertical):
|
||||
m = np.eye(2)
|
||||
for e in ancestry(text, parent):
|
||||
m = m @ transform_matrix(e.get("transform"))
|
||||
return m @ np.array([0.0, 1.0] if vertical else [1.0, 0.0])
|
||||
|
||||
|
||||
def opacity(text, parent):
|
||||
total, fill = 1.0, None
|
||||
for e in reversed(ancestry(text, parent)):
|
||||
for prop in ("opacity", "fill-opacity"):
|
||||
v = (style_value(e, prop) or "").strip()
|
||||
n = float(v[:-1]) / 100 if v.endswith("%") and NUM.fullmatch(v[:-1]) else float(v) if NUM.fullmatch(v) else None
|
||||
if n is None:
|
||||
continue
|
||||
if prop == "opacity":
|
||||
total *= min(max(n, 0.0), 1.0)
|
||||
elif fill is None:
|
||||
fill = min(max(n, 0.0), 1.0)
|
||||
return total * (1.0 if fill is None else fill)
|
||||
|
||||
|
||||
def vertical_text(text, parent):
|
||||
for e in reversed(ancestry(text, parent)):
|
||||
mode = style_value(e, "writing-mode")
|
||||
if mode:
|
||||
return mode.strip().startswith(("tb", "vertical"))
|
||||
return False
|
||||
|
||||
|
||||
def line_count(text, parent, axis):
|
||||
marks, pos = [], [0.0]
|
||||
|
||||
def walk(el):
|
||||
size = font_size(el, parent)
|
||||
at = [v for v in (scaled(t, size) for t in (el.get(axis) or "").replace(",", " ").split()) if v is not None]
|
||||
by = [v for v in (scaled(t, size) for t in (el.get("d" + axis) or "").replace(",", " ").split()) if v is not None]
|
||||
k = 0
|
||||
|
||||
def place(n):
|
||||
if n < len(at):
|
||||
pos[0] = at[n]
|
||||
if n < len(by):
|
||||
pos[0] += by[n]
|
||||
|
||||
def chars(s):
|
||||
nonlocal k
|
||||
for ch in re.sub(r"\s+", " ", s or ""):
|
||||
if k:
|
||||
place(k)
|
||||
k += 1
|
||||
if not ch.isspace():
|
||||
marks.append(pos[0])
|
||||
|
||||
place(0)
|
||||
chars(el.text)
|
||||
for c in el:
|
||||
walk(c)
|
||||
chars(c.tail)
|
||||
|
||||
walk(text)
|
||||
gap = 0.5 * font_size(text, parent)
|
||||
return 1 + int((np.diff(sorted(marks)) > gap).sum())
|
||||
|
||||
|
||||
def luminance(rgb):
|
||||
c = rgb / 255
|
||||
c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
|
||||
return c @ np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)
|
||||
|
||||
|
||||
def ratio(a, b):
|
||||
return (max(a, b) + 0.05) / (min(a, b) + 0.05)
|
||||
|
||||
|
||||
def text_contrast(img, mask, ring, cov):
|
||||
behind = img[ring].mean(axis=0)
|
||||
c = cov[mask][:, None]
|
||||
letters = ((img[mask] - (1 - c) * behind) / c).clip(0, 255)
|
||||
return ratio(luminance(letters).mean(), luminance(img[ring]).mean())
|
||||
|
||||
|
||||
def flat(png, bg):
|
||||
@@ -62,13 +257,50 @@ def flat(png, bg):
|
||||
return im[:, :, :3] * a + bg * (1 - a)
|
||||
|
||||
|
||||
def size_of(root):
|
||||
def length(value):
|
||||
m = LENGTH.match(value or "")
|
||||
if not m:
|
||||
return None
|
||||
n = float(m.group(1)) * UNITS[(m.group(2) or "px").lower()]
|
||||
return n if 0 < n < math.inf else None
|
||||
|
||||
|
||||
def view_box(root):
|
||||
vb = [float(n) for n in NUM.findall(root.get("viewBox", ""))]
|
||||
if len(vb) == 4:
|
||||
return vb
|
||||
w = float(NUM.search(root.get("width", "600")).group())
|
||||
h = float(NUM.search(root.get("height", "600")).group())
|
||||
return [0.0, 0.0, w, h]
|
||||
if len(vb) != 4:
|
||||
return None
|
||||
if not all(math.isfinite(v) for v in vb) or vb[2] <= 0 or vb[3] <= 0:
|
||||
sys.exit("the viewBox needs a width and height above zero")
|
||||
return vb
|
||||
|
||||
|
||||
def renders_as_is(root):
|
||||
wv, hv = root.get("width"), root.get("height")
|
||||
if length(wv) and length(hv):
|
||||
return True
|
||||
return view_box(root) is not None and all(v is None or v.strip().endswith("%") for v in (wv, hv))
|
||||
|
||||
|
||||
def canvas(root):
|
||||
vb = view_box(root)
|
||||
w, h = length(root.get("width")), length(root.get("height"))
|
||||
if vb is None:
|
||||
if w is None or h is None:
|
||||
sys.exit('the SVG has no viewBox and no width and height, so its canvas size is unknown; add viewBox="0 0 W H"')
|
||||
return w, h, [0.0, 0.0, w, h]
|
||||
if w is None and h is None:
|
||||
w, h = vb[2], vb[3]
|
||||
elif w is None:
|
||||
w = h * vb[2] / vb[3]
|
||||
elif h is None:
|
||||
h = w * vb[3] / vb[2]
|
||||
words = root.get("preserveAspectRatio", "").replace("defer", "").split()
|
||||
if words[:1] == ["none"]:
|
||||
return w, h, vb
|
||||
s = (max if "slice" in words[1:] else min)(w / vb[2], h / vb[3])
|
||||
m = re.fullmatch(r"x(Min|Mid|Max)Y(Min|Mid|Max)", words[0] if words else "")
|
||||
ax, ay = (ALIGN[m.group(1)], ALIGN[m.group(2)]) if m else (0.5, 0.5)
|
||||
return w, h, [vb[0] + (vb[2] - w / s) * ax, vb[1] + (vb[3] - h / s) * ay, w / s, h / s]
|
||||
|
||||
|
||||
def texts(root):
|
||||
@@ -98,21 +330,84 @@ def hide(el):
|
||||
el.set("style", (st + ";" if st else "") + "display:none")
|
||||
|
||||
|
||||
def drop(el, prop):
|
||||
el.attrib.pop(prop, None)
|
||||
st = el.get("style", "")
|
||||
if prop in st:
|
||||
el.set("style", re.sub(prop + r"\s*:[^;]*;?", "", st))
|
||||
|
||||
|
||||
def text_paths(root):
|
||||
refs = (el.get("href") or el.get(XLINK_HREF) or "" for el in root.iter() if tag(el) == "textPath")
|
||||
return {r[1:] for r in refs if r.startswith("#")}
|
||||
|
||||
|
||||
def strip(el, solo, keep=()):
|
||||
for c in el:
|
||||
if tag(c) in HOLDERS:
|
||||
continue
|
||||
if solo:
|
||||
if tag(c) in SHAPES and c.get("id") in keep:
|
||||
add_style(c, "opacity:0")
|
||||
elif tag(c) in SHAPES:
|
||||
hide(c)
|
||||
drop(c, "clip-path")
|
||||
drop(c, "filter")
|
||||
strip(c, solo, keep)
|
||||
|
||||
|
||||
def write(tree, path):
|
||||
tree.write(path, encoding="unicode")
|
||||
|
||||
|
||||
CJK = re.compile(r"[\u3040-\u30ff\u3400-\u9fff\uff00-\uffef]")
|
||||
KANA = re.compile(r"[\u3040-\u30ff\u31f0-\u31ff\uff65-\uff9f]")
|
||||
HANGUL = re.compile(r"[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af\uffa0-\uffdc]")
|
||||
HAN = re.compile(r"[\u3000-\u303f\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uff64]")
|
||||
CJK_FONT = {"Japanese": "Noto Sans CJK JP", "Korean": "Noto Sans CJK KR", "Chinese": "Noto Sans CJK SC"}
|
||||
|
||||
|
||||
def cjk_font_missing(root):
|
||||
"""True when the SVG has Japanese text but fontconfig lists no Japanese font."""
|
||||
if not any(CJK.search("".join(el.itertext())) for el in root.iter() if tag(el) == "text"):
|
||||
return False
|
||||
if not shutil.which("fc-list"):
|
||||
return False
|
||||
out = subprocess.run(["fc-list", ":lang=ja", "family"], capture_output=True, text=True).stdout
|
||||
return not out.strip()
|
||||
def cjk_fonts_missing(root):
|
||||
text = "".join("".join(el.itertext()) for el in root.iter() if tag(el) == "text")
|
||||
found = {name: rx.search(text) for name, rx in (("kana", KANA), ("hangul", HANGUL), ("han", HAN))}
|
||||
if not any(found.values()) or not shutil.which("fc-list"):
|
||||
return []
|
||||
lang = "Japanese" if found["kana"] else "Korean" if found["hangul"] else "Chinese"
|
||||
langs = {"kana": "Japanese", "hangul": "Korean", "han": lang}
|
||||
missing = []
|
||||
for kind, m in found.items():
|
||||
if not m or langs[kind] in missing:
|
||||
continue
|
||||
fonts = subprocess.run(["fc-list", f":charset={ord(m.group()):x}", "family"], check=False, capture_output=True, text=True).stdout
|
||||
if not fonts.strip():
|
||||
missing.append(langs[kind])
|
||||
return missing
|
||||
|
||||
|
||||
def bounded(kind, low, high):
|
||||
def parse(text):
|
||||
try:
|
||||
value = kind(text)
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(f"not a number: {text}") from None
|
||||
if not low <= value <= high:
|
||||
raise argparse.ArgumentTypeError(f"must be from {low:g} to {high:g}")
|
||||
return value
|
||||
|
||||
return parse
|
||||
|
||||
|
||||
def read_svg(path):
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
except OSError as e:
|
||||
sys.exit(f"cannot open {path}: {e.strerror}")
|
||||
if data[:2] == b"\x1f\x8b":
|
||||
sys.exit(f"{path} is gzip-compressed (svgz); unzip it to a plain .svg first")
|
||||
try:
|
||||
return ET.ElementTree(ET.fromstring(data))
|
||||
except ET.ParseError as e:
|
||||
sys.exit(f"{path} is not valid SVG XML: {e}")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -121,26 +416,50 @@ def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("svg")
|
||||
ap.add_argument("--out", default=None)
|
||||
ap.add_argument("--width", type=int, default=800)
|
||||
ap.add_argument("--small", type=int, default=64)
|
||||
ap.add_argument("--min-text", type=float, default=1.2, help="smallest text height as a percent of the image side; about 0.6 for interfaces")
|
||||
ap.add_argument("--width", type=bounded(int, 100, 4000), default=800)
|
||||
ap.add_argument("--small", type=bounded(int, 8, 1024), default=64)
|
||||
ap.add_argument("--min-text", type=bounded(float, 0, 100), default=1.2, help="smallest text height as a percent of the image side; about 0.6 for interfaces")
|
||||
args = ap.parse_args()
|
||||
tmp = tempfile.mkdtemp()
|
||||
try:
|
||||
check(args, tmp)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
def check(args, tmp):
|
||||
tree = read_svg(args.svg)
|
||||
root = tree.getroot()
|
||||
vw, vh, (x0, y0, w, h) = canvas(root)
|
||||
full_h = args.width * vh / vw
|
||||
sx, sy = args.width / w, full_h / h
|
||||
p = round(0.25 * max(args.width, full_h))
|
||||
if (args.width + 2 * p) * (full_h + 2 * p) > Image.MAX_IMAGE_PIXELS:
|
||||
sys.exit(f"the image is too tall to check at --width {args.width}; use a smaller --width")
|
||||
src = args.svg
|
||||
if not renders_as_is(root):
|
||||
root.set("width", str(vw))
|
||||
root.set("height", str(vh))
|
||||
src = os.path.join(tmp, "sized.svg")
|
||||
write(tree, src)
|
||||
|
||||
name = os.path.splitext(os.path.basename(args.svg))[0]
|
||||
out = args.out or os.path.join(tempfile.gettempdir(), "antialgorithm_check", name)
|
||||
os.makedirs(out, exist_ok=True)
|
||||
tree = ET.parse(args.svg)
|
||||
root = tree.getroot()
|
||||
x0, y0, w, h = size_of(root)
|
||||
scale = args.width / w
|
||||
pad = 0.25 * max(w, h)
|
||||
|
||||
if args.out:
|
||||
out = args.out
|
||||
os.makedirs(out, exist_ok=True)
|
||||
else:
|
||||
base = os.path.join(tempfile.gettempdir(), "antialgorithm_check")
|
||||
os.makedirs(base, exist_ok=True)
|
||||
out = tempfile.mkdtemp(prefix=name + "-", dir=base)
|
||||
full_png = os.path.join(out, "full.png")
|
||||
small_png = os.path.join(out, "small.png")
|
||||
render(args.svg, full_png, args.width)
|
||||
render(args.svg, small_png, args.small)
|
||||
render(src, full_png, args.width)
|
||||
render(src, small_png, args.small)
|
||||
full = flat(full_png, 255)
|
||||
clear = bool((np.asarray(Image.open(full_png).convert("RGBA"))[:, :, 3] < 250).any())
|
||||
rows, cols = full.shape[:2]
|
||||
if cols != args.width or abs(rows - full_h) > 1:
|
||||
sys.exit(f"the renderer drew {cols}x{rows} px, not {args.width}x{full_h:.0f}; check the width, height and viewBox of the svg element")
|
||||
clear = bool((np.asarray(Image.open(full_png).convert("RGBA"))[:int(full_h + 1e-6), :, 3] < 250).any())
|
||||
full_dark = flat(full_png, 0) if clear else None
|
||||
|
||||
parent = {c: p for p in root.iter() for c in p}
|
||||
@@ -155,66 +474,55 @@ def main():
|
||||
el = parent.get(el)
|
||||
return False
|
||||
|
||||
def ancestor_filtered(el):
|
||||
return filtered(parent.get(el))
|
||||
|
||||
own_filter = [has_filter(t) for t in texts(root)]
|
||||
text_filtered = [filtered(t) for t in texts(root)]
|
||||
plain = None
|
||||
if any(own_filter):
|
||||
if any(text_filtered):
|
||||
nf = copy.deepcopy(tree)
|
||||
for t in texts(nf.getroot()):
|
||||
t.attrib.pop("filter", None)
|
||||
st = t.get("style", "")
|
||||
if "filter" in st:
|
||||
t.set("style", re.sub(r"filter\s*:[^;]*;?", "", st))
|
||||
nf_svg = os.path.join(out, "_nofilter.svg")
|
||||
nf_png = os.path.join(out, "_nofilter.png")
|
||||
strip(nf.getroot(), False)
|
||||
nf_svg = os.path.join(tmp, "nofilter.svg")
|
||||
nf_png = os.path.join(tmp, "nofilter.png")
|
||||
write(nf, nf_svg)
|
||||
render(nf_svg, nf_png, args.width)
|
||||
plain = flat(nf_png, 255)
|
||||
os.remove(nf_svg)
|
||||
os.remove(nf_png)
|
||||
|
||||
problems = []
|
||||
if cjk_font_missing(root):
|
||||
problems.append("Japanese text found but no Japanese font is installed, so it may render as empty boxes (install Noto Sans CJK JP)")
|
||||
tmp = tempfile.mkdtemp()
|
||||
for lang in cjk_fonts_missing(root):
|
||||
problems.append(f"{lang} text found but no installed font has its characters, so it may render as empty boxes (install {CJK_FONT[lang]})")
|
||||
n = len(texts(root))
|
||||
paths = text_paths(root)
|
||||
on_path = [any(tag(e) == "textPath" for e in t.iter()) for t in texts(root)]
|
||||
unseen = []
|
||||
skipped = 0
|
||||
for i in range(n):
|
||||
solo = copy.deepcopy(tree)
|
||||
sroot = solo.getroot()
|
||||
def strip(el):
|
||||
for c in el:
|
||||
if tag(c) in HOLDERS:
|
||||
continue
|
||||
if tag(c) in SHAPES:
|
||||
hide(c)
|
||||
if "filter" in c.attrib:
|
||||
del c.attrib["filter"]
|
||||
st = c.get("style", "")
|
||||
if "filter" in st:
|
||||
c.set("style", re.sub(r"filter\s*:[^;]*;?", "", st))
|
||||
strip(c)
|
||||
|
||||
strip(sroot)
|
||||
strip(sroot, True, paths)
|
||||
for j, t in enumerate(texts(sroot)):
|
||||
if j != i:
|
||||
hide(t)
|
||||
sroot.set("viewBox", f"{x0 - pad} {y0 - pad} {w + 2 * pad} {h + 2 * pad}")
|
||||
sroot.set("width", str(w + 2 * pad))
|
||||
sroot.set("height", str(h + 2 * pad))
|
||||
sroot.set("viewBox", f"{x0 - p / sx} {y0 - p / sy} {(args.width + 2 * p) / sx} {(rows + 2 * p) / sy}")
|
||||
sroot.set("width", str(args.width + 2 * p))
|
||||
sroot.set("height", str(rows + 2 * p))
|
||||
sroot.set("preserveAspectRatio", "none")
|
||||
sp = os.path.join(tmp, f"s{i}.svg")
|
||||
write(solo, sp)
|
||||
pp = os.path.join(tmp, f"s{i}.png")
|
||||
render(sp, pp, int(round((w + 2 * pad) * scale)))
|
||||
render(sp, pp, args.width + 2 * p)
|
||||
a = np.asarray(Image.open(pp).convert("RGBA"))[:, :, 3]
|
||||
ys, xs = np.nonzero(a > 40)
|
||||
peak = int(a.max())
|
||||
name = label(texts(root)[i])
|
||||
if len(xs) == 0:
|
||||
if peak < 3 and on_path[i] and shutil.which("rsvg-convert"):
|
||||
unseen.append((name, "is on a textPath, which rsvg-convert does not draw, so it is missing from the renders and was not checked; check it by eye"))
|
||||
skipped += 1
|
||||
continue
|
||||
if peak < 3:
|
||||
problems.append(f"text '{name}': draws nothing")
|
||||
continue
|
||||
p = int(round(pad * scale))
|
||||
cw, ch = full.shape[1], full.shape[0]
|
||||
ys, xs = np.nonzero(a > 40 * peak / 255)
|
||||
t = texts(root)[i]
|
||||
vertical = vertical_text(t, parent)
|
||||
sideways = vertical and not shutil.which("rsvg-convert")
|
||||
cw, ch = cols, rows
|
||||
sides = []
|
||||
if xs.min() < p:
|
||||
sides.append("left")
|
||||
@@ -224,45 +532,70 @@ def main():
|
||||
sides.append("top")
|
||||
if ys.max() >= p + ch:
|
||||
sides.append("bottom")
|
||||
if sideways:
|
||||
sides = []
|
||||
if sides:
|
||||
problems.append(f"text '{name}': runs off the {'/'.join(sides)} edge")
|
||||
lines = max(1, len(texts(root)[i].findall(f"{{{SVG_NS}}}tspan")))
|
||||
share = (ys.max() - ys.min() + 1) / scale / lines / max(w, h)
|
||||
upright = vertical and not sideways
|
||||
d = np.array([sx, sy]) * line_direction(t, parent, upright)
|
||||
across = np.array([-d[1], d[0]]) / (np.hypot(*d) or 1)
|
||||
reach = xs * across[0] + ys * across[1]
|
||||
lines = line_count(t, parent, "x" if upright else "y")
|
||||
share = (reach.max() - reach.min() + 1) / lines / max(args.width, full_h)
|
||||
if share * 100 < args.min_text and not sides:
|
||||
problems.append(f"text '{name}': very small, about {share * 100:.1f}% of the image side (want {args.min_text:g}%+)")
|
||||
if sideways:
|
||||
unseen.append((name, "uses a vertical writing-mode, which cairosvg does not support, so the renders show it sideways; only its size was checked, check the rest by eye"))
|
||||
continue
|
||||
|
||||
rgba = np.asarray(Image.open(pp).convert("RGBA"), dtype=np.float32)
|
||||
inner = rgba[p:p + ch, p:p + cw]
|
||||
ih, iw = min(inner.shape[0], ch), min(inner.shape[1], cw)
|
||||
mask = np.zeros(full.shape[:2], bool)
|
||||
mask[:ih, :iw] = inner[:ih, :iw, 3] > 200
|
||||
mask[:ih, :iw] = inner[:ih, :iw, 3] > 200 * peak / 255
|
||||
if mask.sum() < 4:
|
||||
continue
|
||||
own = np.zeros_like(full)
|
||||
own[:ih, :iw] = inner[:ih, :iw, :3]
|
||||
base = plain if own_filter[i] and plain is not None else full
|
||||
cover = (np.abs(base - own).mean(axis=2)[mask] > 60).mean()
|
||||
base = plain if text_filtered[i] else full
|
||||
solid = mask.copy()
|
||||
if opacity(t, parent) < 0.98:
|
||||
behind = copy.deepcopy(nf if text_filtered[i] else tree)
|
||||
hide(texts(behind.getroot())[i])
|
||||
bp = os.path.join(tmp, f"b{i}.svg")
|
||||
write(behind, bp)
|
||||
render(bp, bp + ".png", args.width)
|
||||
alpha = np.zeros(full.shape[:2] + (1,), np.float32)
|
||||
alpha[:ih, :iw] = inner[:ih, :iw, 3:4] / 255
|
||||
own = own * alpha + flat(bp + ".png", 255) * (1 - alpha)
|
||||
else:
|
||||
solid[:ih, :iw] &= inner[:ih, :iw, 3] > 200
|
||||
cover = (np.abs(base - own).mean(axis=2)[solid] > 60).mean() if solid.sum() >= 4 else 0.0
|
||||
ring = np.zeros_like(mask)
|
||||
r = max(2, int(3 * scale))
|
||||
r = max(2, int(3 * sx))
|
||||
for dy in (-r, 0, r):
|
||||
for dx in (-r, 0, r):
|
||||
ring |= np.roll(np.roll(mask, dy, 0), dx, 1)
|
||||
ring[:ih, :iw] &= inner[:ih, :iw, 3] == 0
|
||||
ring &= ~mask
|
||||
lum = lambda c: c @ np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)
|
||||
contrast = 255
|
||||
contrast = math.inf
|
||||
if ring.any():
|
||||
contrast = max(abs(lum(img[mask]).mean() - lum(img[ring]).mean()) for img in (full, full_dark) if img is not None)
|
||||
if cover > 0.04 and not ancestor_filtered(texts(root)[i]):
|
||||
cov = np.zeros(full.shape[:2], np.float32)
|
||||
cov[:ih, :iw] = inner[:ih, :iw, 3] / peak
|
||||
contrast = max(text_contrast(img, mask, ring, cov) for img in (full, full_dark) if img is not None)
|
||||
need = 2 if share * 100 >= 2 * args.min_text else 3
|
||||
if cover > 0.04:
|
||||
problems.append(f"text '{name}': {cover * 100:.0f}% covered or changed by something drawn over it")
|
||||
elif contrast < 30:
|
||||
problems.append(f"text '{name}': low contrast with what is behind it ({contrast:.0f}, want 30+)")
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
elif contrast < need:
|
||||
problems.append(f"text '{name}': low contrast with what is behind it ({contrast:.1f}:1, want {need}:1 or more)")
|
||||
|
||||
print(f"render: {full_png}")
|
||||
print(f"small {args.small}px: {small_png}")
|
||||
print(f"texts checked: {n}")
|
||||
print(f"texts checked: {n - skipped}")
|
||||
if clear:
|
||||
print("background has see-through parts; contrast was measured on white and on black, the better one counts")
|
||||
for name, why in unseen:
|
||||
print(f"note: text '{name}' {why}")
|
||||
if problems:
|
||||
print("problems:")
|
||||
for pr in problems:
|
||||
@@ -272,4 +605,7 @@ def main():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
try:
|
||||
main()
|
||||
except RecursionError:
|
||||
sys.exit("the SVG nests its elements too deeply to check")
|
||||
+113
-19
@@ -1,44 +1,138 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
|
||||
STATE = os.environ.get("XDG_STATE_HOME") or os.path.join(os.path.expanduser("~"), ".local", "state")
|
||||
PATH = os.environ.get("ANTIALGORITHM_HISTORY") or os.path.join(STATE, "antialgorithm", "history.jsonl")
|
||||
|
||||
def state_dir():
|
||||
xdg = os.environ.get("XDG_STATE_HOME", "")
|
||||
if os.path.isabs(xdg):
|
||||
return xdg
|
||||
return os.path.join(os.path.expanduser("~"), ".local", "state")
|
||||
|
||||
|
||||
def history_path():
|
||||
custom = os.environ.get("ANTIALGORITHM_HISTORY")
|
||||
if not custom:
|
||||
return os.path.join(state_dir(), "antialgorithm", "history.jsonl")
|
||||
custom = os.path.abspath(os.path.expanduser(custom))
|
||||
if os.path.isdir(custom):
|
||||
return os.path.join(custom, "history.jsonl")
|
||||
return custom
|
||||
|
||||
|
||||
PATH = history_path()
|
||||
OLD_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "history.jsonl")
|
||||
LIMIT = 300
|
||||
LOCK_WAIT = 15
|
||||
LOCK_STALE = 10
|
||||
|
||||
|
||||
def acquire(lock):
|
||||
deadline = time.monotonic() + LOCK_WAIT
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
os.close(os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
|
||||
return
|
||||
except FileExistsError:
|
||||
pass
|
||||
except PermissionError:
|
||||
if os.name != "nt":
|
||||
raise
|
||||
try:
|
||||
if time.time() - os.path.getmtime(lock) > LOCK_STALE:
|
||||
os.remove(lock)
|
||||
continue
|
||||
except (FileNotFoundError, PermissionError):
|
||||
pass
|
||||
time.sleep(0.02)
|
||||
raise TimeoutError(f"could not create the lock file {lock} within {LOCK_WAIT} s")
|
||||
|
||||
|
||||
def release(lock):
|
||||
try:
|
||||
os.remove(lock)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def retry_denied(action):
|
||||
for attempt in range(50):
|
||||
try:
|
||||
return action()
|
||||
except PermissionError:
|
||||
if attempt == 49:
|
||||
raise
|
||||
time.sleep(0.02)
|
||||
|
||||
|
||||
def read_text():
|
||||
with open(PATH, "rb") as f:
|
||||
data = f.read()
|
||||
if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
|
||||
return data.decode("utf-16", errors="replace")
|
||||
return data.decode("utf-8-sig", errors="surrogateescape")
|
||||
|
||||
|
||||
def migrate():
|
||||
if not os.path.exists(PATH) and os.path.exists(OLD_PATH):
|
||||
os.makedirs(os.path.dirname(PATH), exist_ok=True)
|
||||
shutil.copyfile(OLD_PATH, PATH)
|
||||
|
||||
|
||||
def load(kind=None):
|
||||
migrate()
|
||||
if os.path.exists(PATH) or not os.path.exists(OLD_PATH):
|
||||
return
|
||||
os.makedirs(os.path.dirname(PATH), exist_ok=True)
|
||||
lock = PATH + ".lock"
|
||||
acquire(lock)
|
||||
try:
|
||||
with open(PATH, encoding="utf-8") as f:
|
||||
lines = f.read().splitlines()
|
||||
if not os.path.exists(PATH):
|
||||
shutil.copyfile(OLD_PATH, PATH)
|
||||
finally:
|
||||
release(lock)
|
||||
|
||||
|
||||
def read_lines():
|
||||
try:
|
||||
text = retry_denied(read_text)
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
return [line.rstrip("\r") for line in text.split("\n") if line.strip()]
|
||||
|
||||
|
||||
def read():
|
||||
out = []
|
||||
for line in lines:
|
||||
for line in read_lines():
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if kind is None or entry.get("type") == kind:
|
||||
if isinstance(entry, dict):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def load(kind=None):
|
||||
try:
|
||||
migrate()
|
||||
rows = read()
|
||||
except OSError as e:
|
||||
print(f"could not read the history: {e}", file=sys.stderr)
|
||||
return []
|
||||
return [row for row in rows if kind is None or row.get("type") == kind]
|
||||
|
||||
|
||||
def add(entry):
|
||||
entry = {"date": time.strftime("%Y-%m-%d"), **entry}
|
||||
rows = load()[-(LIMIT - 1):] + [entry]
|
||||
migrate()
|
||||
os.makedirs(os.path.dirname(PATH), exist_ok=True)
|
||||
tmp = PATH + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
for row in rows:
|
||||
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
||||
os.replace(tmp, PATH)
|
||||
lock = PATH + ".lock"
|
||||
acquire(lock)
|
||||
try:
|
||||
lines = read_lines()[-(LIMIT - 1):] + [json.dumps(entry, ensure_ascii=False)]
|
||||
tmp = f"{PATH}.{os.getpid()}.tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8", errors="surrogateescape") as f:
|
||||
f.writelines(line + "\n" for line in lines)
|
||||
retry_denied(lambda: os.replace(tmp, PATH))
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
finally:
|
||||
release(lock)
|
||||
+7
-2
@@ -13,14 +13,19 @@ def main():
|
||||
ap.add_argument("text", nargs="*")
|
||||
ap.add_argument("--last", type=int, default=12)
|
||||
args = ap.parse_args()
|
||||
if args.last < 1:
|
||||
ap.error("--last must be 1 or more")
|
||||
if args.action == "add":
|
||||
text = " ".join(args.text).strip()
|
||||
if not text:
|
||||
sys.exit("add needs the move, for example: moves.py add \"poster: x-ray method, deep blue ground\"")
|
||||
history.add({"type": "move", "move": text})
|
||||
try:
|
||||
history.add({"type": "move", "move": text})
|
||||
except OSError as e:
|
||||
sys.exit(f"could not save the move: {e}")
|
||||
print(f"saved: {text}")
|
||||
return
|
||||
rows = history.load("move")[-args.last:]
|
||||
rows = [r for r in history.load("move") if isinstance(r.get("move"), str)][-args.last:]
|
||||
if not rows:
|
||||
print("no moves saved yet")
|
||||
return
|
||||
|
||||
+606
-92
@@ -3,15 +3,44 @@ import argparse
|
||||
import math
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
SVG_NS = "http://www.w3.org/2000/svg"
|
||||
ET.register_namespace("", SVG_NS)
|
||||
ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
|
||||
|
||||
MAX_DEPTH = 500
|
||||
REF_DIAG = 720
|
||||
SHAPE_ATTRS = ("x", "y", "width", "height", "x1", "y1", "x2", "y2", "points", "cx", "cy", "r", "rx", "ry")
|
||||
SKIP = {"defs", "clipPath", "mask", "pattern", "filter", "marker", "symbol", "linearGradient", "radialGradient", "style", "title", "desc"}
|
||||
NUM = re.compile(r"[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?")
|
||||
TOK = re.compile(r"[MmLlHhVvCcSsQqTtAaZz]|[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?")
|
||||
LENGTH = re.compile(r"\s*([-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?)\s*([a-zA-Z%]*)\s*$")
|
||||
UNIT_PX = {"": 1.0, "px": 1.0, "pt": 4 / 3, "pc": 16.0, "mm": 96 / 25.4, "cm": 96 / 2.54, "in": 96.0, "q": 96 / 101.6}
|
||||
TRANSFORM = re.compile(r"(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)")
|
||||
FONT_KEYWORDS = {"xx-small": 9.0, "x-small": 10.0, "small": 13.0, "medium": 16.0, "large": 18.0, "x-large": 24.0, "xx-large": 32.0}
|
||||
SIMPLE = re.compile(r"(\*|[\w-]+)|#([\w-]+)|\.([\w-]+)|\[\s*([\w:-]+)\s*(?:([~|^$*]?=)\s*(\"[^\"]*\"|'[^']*'|[^\]\s]*)\s*)?\]|(:[\w-]+)")
|
||||
COMPOUND = re.compile(r"\s*([>+~])\s*|\s+|((?:[^\s>+~\[(]|\[[^\]]*\]|\([^)]*\))+)")
|
||||
CSS_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
|
||||
IMPORTANT = re.compile(r"!\s*important\s*$", re.IGNORECASE)
|
||||
INITIAL = {
|
||||
"opacity": "1", "display": "inline", "overflow": "visible", "clip-path": "none", "mask": "none", "filter": "none",
|
||||
"transform": "none", "stop-color": "black", "stop-opacity": "1", "flood-color": "black", "flood-opacity": "1",
|
||||
"lighting-color": "white", "mix-blend-mode": "normal", "isolation": "auto", "baseline-shift": "baseline",
|
||||
"alignment-baseline": "auto", "text-decoration": "none", "unicode-bidi": "normal",
|
||||
}
|
||||
PRESENTATION = {
|
||||
"alignment-baseline", "baseline-shift", "clip", "clip-path", "clip-rule", "color", "color-interpolation",
|
||||
"color-interpolation-filters", "color-rendering", "cursor", "direction", "display", "dominant-baseline", "fill",
|
||||
"fill-opacity", "fill-rule", "filter", "flood-color", "flood-opacity", "font-family", "font-size",
|
||||
"font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "image-rendering",
|
||||
"letter-spacing", "lighting-color", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "overflow",
|
||||
"paint-order", "pointer-events", "shape-rendering", "stop-color", "stop-opacity", "stroke", "stroke-dasharray",
|
||||
"stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width",
|
||||
"text-anchor", "text-decoration", "text-rendering", "unicode-bidi", "vector-effect", "visibility", "word-spacing",
|
||||
"writing-mode",
|
||||
}
|
||||
ARGS = {"m": 2, "l": 2, "h": 1, "v": 1, "c": 6, "s": 4, "q": 4, "t": 2, "a": 7, "z": 0}
|
||||
|
||||
|
||||
@@ -26,18 +55,69 @@ def fnum(v, default=0.0):
|
||||
return float(m.group()) if m else default
|
||||
|
||||
|
||||
def style_get(el, key):
|
||||
st = el.get("style", "")
|
||||
m = re.search(rf"(?:^|;)\s*{key}\s*:\s*([^;]+)", st)
|
||||
return m.group(1).strip() if m else el.get(key)
|
||||
def length(v, ref=0.0, font=16.0, default=0.0, rem=16.0):
|
||||
m = LENGTH.match(str(v)) if v is not None else None
|
||||
if not m:
|
||||
return default
|
||||
x, unit = float(m.group(1)), m.group(2).lower()
|
||||
if unit == "%":
|
||||
return x * ref / 100
|
||||
if unit == "rem":
|
||||
return x * rem
|
||||
if unit in ("em", "ex"):
|
||||
return x * font * (0.5 if unit == "ex" else 1)
|
||||
return x * UNIT_PX[unit] if unit in UNIT_PX else default
|
||||
|
||||
|
||||
def fmt(x):
|
||||
return f"{x:.2f}".rstrip("0").rstrip(".")
|
||||
def font_px(v, parent, rem=16.0):
|
||||
v = (v or "").strip().lower()
|
||||
if v in FONT_KEYWORDS:
|
||||
return FONT_KEYWORDS[v]
|
||||
if v in ("smaller", "larger"):
|
||||
return parent / 1.2 if v == "smaller" else parent * 1.2
|
||||
return length(v, parent, parent, parent, rem)
|
||||
|
||||
|
||||
def pt(p):
|
||||
return f"{fmt(p[0])},{fmt(p[1])}"
|
||||
def font_shorthand_size(v):
|
||||
for word in v.split():
|
||||
size = word.split("/")[0].lower()
|
||||
if size in FONT_KEYWORDS or size in ("smaller", "larger"):
|
||||
return size
|
||||
m = LENGTH.match(size)
|
||||
if m and m.group(2):
|
||||
return size
|
||||
return None
|
||||
|
||||
|
||||
def declarations(body):
|
||||
out = {}
|
||||
for part in body.split(";"):
|
||||
if ":" not in part:
|
||||
continue
|
||||
key, value = (s.strip() for s in part.split(":", 1))
|
||||
important = bool(IMPORTANT.search(value))
|
||||
key, value = key.lower(), IMPORTANT.sub("", value).strip()
|
||||
if key == "font":
|
||||
key, value = "font-size", font_shorthand_size(value)
|
||||
if not value:
|
||||
continue
|
||||
for name in ("marker-start", "marker-mid", "marker-end") if key == "marker" else (key,):
|
||||
if important or not out.get(name, ("", False))[1]:
|
||||
out[name] = (value, important)
|
||||
return out
|
||||
|
||||
|
||||
def finite(*xs):
|
||||
return all(math.isfinite(x) for x in xs)
|
||||
|
||||
|
||||
def add_style(el, decl):
|
||||
st = el.get("style", "").strip().rstrip(";")
|
||||
el.set("style", f"{st};{decl}" if st else decl)
|
||||
|
||||
|
||||
def fmt(x, places=2):
|
||||
return f"{x:.{places}f}".rstrip("0").rstrip(".") if places else f"{x:.0f}"
|
||||
|
||||
|
||||
def lerp(a, b, t):
|
||||
@@ -51,6 +131,63 @@ def split_cubic(p0, c1, c2, p1):
|
||||
return (p0, a, d, m), (m, e, c, p1)
|
||||
|
||||
|
||||
def arc_cubics(p0, rx, ry, rot, large, sweep, p1):
|
||||
straight = [(lerp(p0, p1, 1 / 3), lerp(p0, p1, 2 / 3), p1)]
|
||||
if p0 == p1:
|
||||
return []
|
||||
rx, ry = abs(rx), abs(ry)
|
||||
if not finite(*p0, *p1, rx, ry, rot) or rx == 0 or ry == 0:
|
||||
return straight
|
||||
cos, sin = math.cos(math.radians(rot)), math.sin(math.radians(rot))
|
||||
hx, hy = (p0[0] - p1[0]) / 2, (p0[1] - p1[1]) / 2
|
||||
x1, y1 = cos * hx + sin * hy, -sin * hx + cos * hy
|
||||
grow = (x1 / rx) * (x1 / rx) + (y1 / ry) * (y1 / ry)
|
||||
if grow > 1:
|
||||
rx, ry = rx * math.sqrt(grow), ry * math.sqrt(grow)
|
||||
ax, ay = rx * y1, ry * x1
|
||||
top = rx * ry * rx * ry - ax * ax - ay * ay
|
||||
bottom = ax * ax + ay * ay
|
||||
co = math.sqrt(max(0.0, top / bottom)) if bottom else 0.0
|
||||
co = -co if large == sweep else co
|
||||
ux, uy = co * rx * y1 / ry, -co * ry * x1 / rx
|
||||
cx = cos * ux - sin * uy + (p0[0] + p1[0]) / 2
|
||||
cy = sin * ux + cos * uy + (p0[1] + p1[1]) / 2
|
||||
t1 = math.atan2((y1 - uy) / ry, (x1 - ux) / rx)
|
||||
turn = math.atan2((-y1 - uy) / ry, (-x1 - ux) / rx) - t1
|
||||
if sweep and turn < 0:
|
||||
turn += math.tau
|
||||
elif not sweep and turn > 0:
|
||||
turn -= math.tau
|
||||
if not finite(cx, cy, turn):
|
||||
return straight
|
||||
n = max(1, math.ceil(abs(turn) / (math.pi / 2) - 1e-9))
|
||||
step = turn / n
|
||||
k = 4 / 3 * math.tan(step / 4)
|
||||
|
||||
def at(t):
|
||||
return (cx + rx * math.cos(t) * cos - ry * math.sin(t) * sin, cy + rx * math.cos(t) * sin + ry * math.sin(t) * cos)
|
||||
|
||||
def towards(t):
|
||||
return (-rx * math.sin(t) * cos - ry * math.cos(t) * sin, -rx * math.sin(t) * sin + ry * math.cos(t) * cos)
|
||||
|
||||
out = []
|
||||
for i in range(n):
|
||||
a, b = t1 + i * step, t1 + (i + 1) * step
|
||||
pa, pb, da, db = at(a), at(b), towards(a), towards(b)
|
||||
end = p1 if i == n - 1 else pb
|
||||
out.append(((pa[0] + k * da[0], pa[1] + k * da[1]), (pb[0] - k * db[0], pb[1] - k * db[1]), end))
|
||||
return out
|
||||
|
||||
|
||||
def flat(pts):
|
||||
far = max(pts, key=lambda p: math.hypot(p[0] - pts[0][0], p[1] - pts[0][1]))
|
||||
dx, dy = far[0] - pts[0][0], far[1] - pts[0][1]
|
||||
reach = math.hypot(dx, dy)
|
||||
if reach == 0:
|
||||
return True
|
||||
return all(abs((p[0] - pts[0][0]) * dy - (p[1] - pts[0][1]) * dx) / reach <= 1e-9 * reach for p in pts)
|
||||
|
||||
|
||||
def parse_path(d):
|
||||
toks = TOK.findall(d)
|
||||
segs = []
|
||||
@@ -125,47 +262,303 @@ def parse_path(d):
|
||||
new_q = q1
|
||||
else:
|
||||
p = (a[5] + ox, a[6] + oy)
|
||||
segs.append(("A", a[0], a[1], a[2], int(a[3]), int(a[4]), p))
|
||||
segs.extend(("C", c1, c2, end) for c1, c2, end in arc_cubics(cur, a[0], a[1], a[2], a[3] != 0, a[4] != 0, p))
|
||||
cur = p
|
||||
last_c, last_q = new_c, new_q
|
||||
return segs
|
||||
|
||||
|
||||
def transform_scale(spec):
|
||||
a, b, c, d = 1.0, 0.0, 0.0, 1.0
|
||||
for name, args in TRANSFORM.findall(spec or ""):
|
||||
v = [float(n) for n in NUM.findall(args)] or [0.0]
|
||||
if name == "matrix" and len(v) == 6:
|
||||
m = v[:4]
|
||||
elif name == "scale":
|
||||
m = (v[0], 0.0, 0.0, v[1] if len(v) > 1 else v[0])
|
||||
elif name == "rotate":
|
||||
r = math.radians(v[0])
|
||||
m = (math.cos(r), math.sin(r), -math.sin(r), math.cos(r))
|
||||
elif name in ("skewX", "skewY"):
|
||||
k = math.tan(math.radians(v[0]))
|
||||
m = (1.0, 0.0, k, 1.0) if name == "skewX" else (1.0, k, 0.0, 1.0)
|
||||
else:
|
||||
continue
|
||||
a, b, c, d = a * m[0] + c * m[1], b * m[0] + d * m[1], a * m[2] + c * m[3], b * m[2] + d * m[3]
|
||||
total, det = a * a + b * b + c * c + d * d, a * d - b * c
|
||||
if not finite(total, det) or det == 0:
|
||||
return 0.0
|
||||
return math.sqrt((total + math.sqrt(max(0.0, total * total - 4 * det * det))) / 2)
|
||||
|
||||
|
||||
def css_rules(css):
|
||||
css, depth, start, prelude, body = CSS_COMMENT.sub("", css), 0, 0, "", 0
|
||||
for i, ch in enumerate(css):
|
||||
if ch == ";" and depth == 0:
|
||||
start = i + 1
|
||||
elif ch == "{":
|
||||
if depth == 0:
|
||||
prelude, body = css[start:i], i + 1
|
||||
depth += 1
|
||||
elif ch == "}" and depth:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
if not prelude.strip().startswith("@") and "{" not in css[body:i]:
|
||||
yield prelude, css[body:i]
|
||||
start = i + 1
|
||||
|
||||
|
||||
def split_selectors(prelude):
|
||||
parts, cur, level = [], "", 0
|
||||
for ch in prelude:
|
||||
if ch == "," and level == 0:
|
||||
parts.append(cur)
|
||||
cur = ""
|
||||
continue
|
||||
level += (ch in "([") - (ch in ")]")
|
||||
cur += ch
|
||||
return parts + [cur]
|
||||
|
||||
|
||||
def parse_compound(text):
|
||||
found = list(SIMPLE.finditer(text))
|
||||
if sum(len(m.group(0)) for m in found) != len(text):
|
||||
return None
|
||||
comp = {"type": None, "ids": [], "classes": [], "attrs": [], "pseudos": []}
|
||||
for m in found:
|
||||
if m.group(1):
|
||||
comp["type"] = m.group(1)
|
||||
elif m.group(2):
|
||||
comp["ids"].append(m.group(2))
|
||||
elif m.group(3):
|
||||
comp["classes"].append(m.group(3))
|
||||
elif m.group(4):
|
||||
comp["attrs"].append((m.group(4), m.group(5), (m.group(6) or "").strip("\"'")))
|
||||
elif m.group(7) in (":root", ":first-child", ":last-child"):
|
||||
comp["pseudos"].append(m.group(7))
|
||||
else:
|
||||
return None
|
||||
return comp
|
||||
|
||||
|
||||
def parse_selector(sel):
|
||||
parts, comb = [], None
|
||||
for m in COMPOUND.finditer(sel.strip()):
|
||||
if m.group(2):
|
||||
comp = parse_compound(m.group(2))
|
||||
if comp is None:
|
||||
return None
|
||||
parts.append((comb, comp))
|
||||
comb = None
|
||||
elif parts:
|
||||
comb = m.group(1) or " "
|
||||
return parts or None
|
||||
|
||||
|
||||
def specificity(parts):
|
||||
comps = [c for _, c in parts]
|
||||
return (
|
||||
sum(len(c["ids"]) for c in comps),
|
||||
sum(len(c["classes"]) + len(c["attrs"]) + len(c["pseudos"]) for c in comps),
|
||||
sum(1 for c in comps if c["type"] not in (None, "*")),
|
||||
)
|
||||
|
||||
|
||||
def attr_matches(have, op, want):
|
||||
if have is None:
|
||||
return False
|
||||
if not op:
|
||||
return True
|
||||
if op == "=":
|
||||
return have == want
|
||||
if op == "~=":
|
||||
return want in have.split()
|
||||
if op == "|=":
|
||||
return have == want or have.startswith(want + "-")
|
||||
if op == "^=":
|
||||
return bool(want) and have.startswith(want)
|
||||
if op == "$=":
|
||||
return bool(want) and have.endswith(want)
|
||||
return bool(want) and want in have
|
||||
|
||||
|
||||
class Sheet:
|
||||
def __init__(self, root):
|
||||
self.root = root
|
||||
self.parent = {c: p for p in root.iter() for c in p}
|
||||
rules = []
|
||||
for e in root.iter():
|
||||
if tag(e) != "style" or not e.text:
|
||||
continue
|
||||
for prelude, body in css_rules(e.text):
|
||||
decls = declarations(body)
|
||||
for sel in split_selectors(prelude):
|
||||
parts = parse_selector(sel)
|
||||
if parts and decls:
|
||||
rules.append((specificity(parts), len(rules), parts, decls))
|
||||
rules.sort(key=lambda r: (r[0], r[1]), reverse=True)
|
||||
self.matched = {e: [r for r in rules if self.matches(r[2], len(r[2]) - 1, e)] for e in root.iter()}
|
||||
self.inline = {e: declarations(e.get("style", "")) for e in root.iter()}
|
||||
|
||||
def keep_values(self, root):
|
||||
after = Sheet(root)
|
||||
for el, then in self.matched.items():
|
||||
now = after.matched.get(el, [])
|
||||
changed = {r[1] for r in then} ^ {r[1] for r in now}
|
||||
if not changed:
|
||||
continue
|
||||
set_here = {p for p, v in declarations(el.get("style", "")).items() if self.inline[el].get(p) != v}
|
||||
for prop in sorted({p for r in then + now if r[1] in changed for p in r[3]} - set_here):
|
||||
want = self.cascade(el, prop, then)
|
||||
if want == after.cascade(el, prop, now):
|
||||
continue
|
||||
value = INITIAL.get(prop, "inherit") if want is None else want
|
||||
if prop in PRESENTATION and prop not in declarations(el.get("style", "")) and not any(prop in r[3] for r in now):
|
||||
el.set(prop, value)
|
||||
else:
|
||||
add_style(el, f"{prop}:{value}{' !important' if any(r[3].get(prop, ('', False))[1] for r in now) else ''}")
|
||||
|
||||
def cascade(self, el, prop, rules):
|
||||
own = declarations(el.get("style", ""))
|
||||
for important in (True, False):
|
||||
if prop in own and own[prop][1] == important:
|
||||
return own[prop][0]
|
||||
for rule in rules:
|
||||
if prop in rule[3] and rule[3][prop][1] == important:
|
||||
return rule[3][prop][0]
|
||||
return el.get(prop)
|
||||
|
||||
def get(self, el, prop):
|
||||
return self.cascade(el, prop, self.matched.get(el, []))
|
||||
|
||||
def inherited(self, el, prop):
|
||||
while el is not None:
|
||||
value = self.get(el, prop)
|
||||
if value is not None and value.strip() != "inherit":
|
||||
return value.strip()
|
||||
el = self.parent.get(el)
|
||||
return None
|
||||
|
||||
def has_marker(self, el, props=("marker-start", "marker-mid", "marker-end")):
|
||||
return any(self.inherited(el, p) not in (None, "none") for p in props)
|
||||
|
||||
def simple(self, comp, el):
|
||||
if comp["type"] not in (None, "*") and comp["type"] != tag(el):
|
||||
return False
|
||||
if any(el.get("id") != i for i in comp["ids"]):
|
||||
return False
|
||||
classes = el.get("class", "").split()
|
||||
if any(c not in classes for c in comp["classes"]):
|
||||
return False
|
||||
if not all(attr_matches(el.get(name), op, want) for name, op, want in comp["attrs"]):
|
||||
return False
|
||||
parent = self.parent.get(el)
|
||||
for p in comp["pseudos"]:
|
||||
if p == ":root" and el is not self.root:
|
||||
return False
|
||||
if p != ":root" and (parent is None or el is not parent[0 if p == ":first-child" else -1]):
|
||||
return False
|
||||
return True
|
||||
|
||||
def matches(self, parts, i, el):
|
||||
if not self.simple(parts[i][1], el):
|
||||
return False
|
||||
if i == 0:
|
||||
return True
|
||||
comb = parts[i][0]
|
||||
parent = self.parent.get(el)
|
||||
if comb in (">", " "):
|
||||
while parent is not None:
|
||||
if self.matches(parts, i - 1, parent):
|
||||
return True
|
||||
if comb == ">":
|
||||
return False
|
||||
parent = self.parent.get(parent)
|
||||
return False
|
||||
before = [] if parent is None else list(parent)[: list(parent).index(el)]
|
||||
if comb == "+":
|
||||
before = before[-1:]
|
||||
return any(self.matches(parts, i - 1, s) for s in before)
|
||||
|
||||
|
||||
def shape_animated(el):
|
||||
return any(tag(c) in ("animate", "set") and c.get("attributeName") in SHAPE_ATTRS for c in el)
|
||||
|
||||
|
||||
class Rougher:
|
||||
def __init__(self, amp, rng, root, box):
|
||||
self.amp = amp
|
||||
self.base_amp = amp
|
||||
self.base_diag = math.hypot(box[2], box[3])
|
||||
self.amount = amp * REF_DIAG / (1.4 * self.base_diag)
|
||||
self.scale = self.outer_scale = 1.0
|
||||
self.rng = rng
|
||||
self.root = root
|
||||
self.box = box
|
||||
self.free = True
|
||||
self.filter_id = None
|
||||
self.font = 16.0
|
||||
self.whole = False
|
||||
self.sheet = Sheet(root)
|
||||
self.rem = font_px(self.sheet.get(root, "font-size"), 16.0)
|
||||
self.filters = {}
|
||||
|
||||
def size(self, el, key, axis):
|
||||
_, _, w, h = self.box
|
||||
ref = (w, h, math.hypot(w, h) / math.sqrt(2))[axis]
|
||||
return length(el.get(key), ref, self.font, rem=self.rem)
|
||||
|
||||
@property
|
||||
def amp(self):
|
||||
return self.base_amp / self.scale
|
||||
|
||||
@property
|
||||
def diag(self):
|
||||
return self.base_diag / self.scale
|
||||
|
||||
def places(self, diag):
|
||||
return min(12, max(0, math.ceil(math.log10(REF_DIAG * 100 / diag))))
|
||||
|
||||
def num(self, x):
|
||||
return fmt(x, self.places(self.diag))
|
||||
|
||||
def pt(self, p):
|
||||
return f"{self.num(p[0])},{self.num(p[1])}"
|
||||
|
||||
def fits(self, *xs):
|
||||
limit = 1e6 * self.diag
|
||||
return all(math.isfinite(x) and abs(x) <= limit for x in xs)
|
||||
|
||||
def j(self, scale=1.0):
|
||||
return self.rng.gauss(0, self.amp * scale)
|
||||
|
||||
def edge(self):
|
||||
return math.hypot(self.box[2], self.box[3]) / REF_DIAG
|
||||
|
||||
def jx(self, x, scale):
|
||||
x0, _, w, _ = self.box
|
||||
d = self.j(scale)
|
||||
if self.free and x <= x0 + 1:
|
||||
return x - abs(d) - 1
|
||||
if self.free and x >= x0 + w - 1:
|
||||
return x + abs(d) + 1
|
||||
d, edge = self.j(scale), self.edge()
|
||||
if self.free and x <= x0 + edge:
|
||||
return x - abs(d) - edge
|
||||
if self.free and x >= x0 + w - edge:
|
||||
return x + abs(d) + edge
|
||||
return x + d
|
||||
|
||||
def jy(self, y, scale):
|
||||
_, y0, _, h = self.box
|
||||
d = self.j(scale)
|
||||
if self.free and y <= y0 + 1:
|
||||
return y - abs(d) - 1
|
||||
if self.free and y >= y0 + h - 1:
|
||||
return y + abs(d) + 1
|
||||
d, edge = self.j(scale), self.edge()
|
||||
if self.free and y <= y0 + edge:
|
||||
return y - abs(d) - edge
|
||||
if self.free and y >= y0 + h - edge:
|
||||
return y + abs(d) + edge
|
||||
return y + d
|
||||
|
||||
def jp(self, p, scale=0.6):
|
||||
return (self.jx(p[0], scale), self.jy(p[1], scale))
|
||||
|
||||
def steps(self, a, b):
|
||||
return max(1, int(math.hypot(b[0] - a[0], b[1] - a[1]) / (self.amp * 18 + 1e-6)))
|
||||
if self.whole:
|
||||
return 1
|
||||
shortest = max(self.amp * 18, self.diag / 160, 1e-9)
|
||||
return max(1, min(200, int(math.hypot(b[0] - a[0], b[1] - a[1]) / shortest)))
|
||||
|
||||
def wobble(self, pts, closed):
|
||||
out = []
|
||||
@@ -176,60 +569,90 @@ class Rougher:
|
||||
out.append(self.jp(lerp(a, b, k / n)))
|
||||
if not closed:
|
||||
out.append(self.jp(seq[-1]))
|
||||
d = "M" + " L".join(pt(p) for p in out)
|
||||
d = "M" + " L".join(self.pt(p) for p in out)
|
||||
return d + ("Z" if closed else "")
|
||||
|
||||
def to_path(self, el, d):
|
||||
keep = {k: v for k, v in el.attrib.items() if k not in {"x", "y", "width", "height", "x1", "y1", "x2", "y2", "points", "cx", "cy", "r", "rx", "ry"}}
|
||||
el.clear()
|
||||
if shape_animated(el):
|
||||
return
|
||||
if tag(el) in ("rect", "circle", "ellipse") and self.sheet.has_marker(el):
|
||||
add_style(el, "marker:none")
|
||||
for k in SHAPE_ATTRS:
|
||||
el.attrib.pop(k, None)
|
||||
el.tag = f"{{{SVG_NS}}}path"
|
||||
for k, v in keep.items():
|
||||
el.set(k, v)
|
||||
el.set("d", d)
|
||||
|
||||
def shift(self, el):
|
||||
dx, dy = self.j(0.8), self.j(0.8)
|
||||
amp = self.base_amp / self.outer_scale
|
||||
dx, dy = self.rng.gauss(0, amp * 0.8), self.rng.gauss(0, amp * 0.8)
|
||||
tr = el.get("transform", "")
|
||||
el.set("transform", f"translate({fmt(dx)},{fmt(dy)}) {tr}".strip())
|
||||
places = self.places(self.base_diag / self.outer_scale)
|
||||
el.set("transform", f"translate({fmt(dx, places)},{fmt(dy, places)}) {tr}".strip())
|
||||
|
||||
def line(self, el):
|
||||
p = [(fnum(el.get("x1")), fnum(el.get("y1"))), (fnum(el.get("x2")), fnum(el.get("y2")))]
|
||||
p = [(self.size(el, "x1", 0), self.size(el, "y1", 1)), (self.size(el, "x2", 0), self.size(el, "y2", 1))]
|
||||
if not self.fits(*p[0], *p[1]):
|
||||
return
|
||||
self.to_path(el, self.wobble(p, False))
|
||||
if tag(el) == "path":
|
||||
add_style(el, "fill:none")
|
||||
self.shift(el)
|
||||
|
||||
def rect(self, el):
|
||||
if fnum(el.get("rx")) or fnum(el.get("ry")):
|
||||
return
|
||||
x, y, w, h = (fnum(el.get(k)) for k in ("x", "y", "width", "height"))
|
||||
if w <= 0 or h <= 0 or str(el.get("width", "")).endswith("%"):
|
||||
x, y, w, h = (self.size(el, k, axis) for k, axis in (("x", 0), ("y", 1), ("width", 0), ("height", 1)))
|
||||
rx, ry = self.size(el, "rx", 0), self.size(el, "ry", 1)
|
||||
if not self.fits(x, y, w, h, rx, ry) or w <= 0 or h <= 0:
|
||||
return
|
||||
if w >= 0.9 * self.box[2] and h >= 0.9 * self.box[3]:
|
||||
return
|
||||
self.to_path(el, self.wobble([(x, y), (x + w, y), (x + w, y + h), (x, y + h)], True))
|
||||
auto_x, auto_y = (LENGTH.match(el.get(k) or "") is None for k in ("rx", "ry"))
|
||||
rx, ry = (ry if auto_x else rx), (rx if auto_y else ry)
|
||||
rx, ry = min(max(rx, 0.0), w / 2), min(max(ry, 0.0), h / 2)
|
||||
if rx == 0 or ry == 0:
|
||||
self.to_path(el, self.wobble([(x, y), (x + w, y), (x + w, y + h), (x, y + h)], True))
|
||||
return
|
||||
qx, qy = rx * 0.4477, ry * 0.4477
|
||||
r, b = x + w, y + h
|
||||
segs = [
|
||||
("M", (x + rx, y)), ("L", (r - rx, y)), ("C", (r - qx, y), (r, y + qy), (r, y + ry)),
|
||||
("L", (r, b - ry)), ("C", (r, b - qy), (r - qx, b), (r - rx, b)),
|
||||
("L", (x + rx, b)), ("C", (x + qx, b), (x, b - qy), (x, b - ry)),
|
||||
("L", (x, y + ry)), ("C", (x, y + qy), (x + qx, y), (x + rx, y)), ("Z",),
|
||||
]
|
||||
segs = [s for i, s in enumerate(segs) if s[0] != "L" or s[1] != segs[i - 1][-1]]
|
||||
self.to_path(el, self.rough_segments(segs))
|
||||
|
||||
def poly(self, el, closed):
|
||||
nums = [float(n) for n in NUM.findall(el.get("points", ""))]
|
||||
pts = list(zip(nums[0::2], nums[1::2]))
|
||||
if len(pts) >= 2:
|
||||
if len(pts) >= 2 and self.fits(*nums):
|
||||
if not closed:
|
||||
self.keep_unfilled(el, [pts])
|
||||
self.to_path(el, self.wobble(pts, closed))
|
||||
|
||||
def ellipse(self, el):
|
||||
cx, cy = fnum(el.get("cx")), fnum(el.get("cy"))
|
||||
cx, cy = self.size(el, "cx", 0), self.size(el, "cy", 1)
|
||||
if tag(el) == "circle":
|
||||
rx = ry = fnum(el.get("r"))
|
||||
rx = ry = self.size(el, "r", 2)
|
||||
else:
|
||||
rx, ry = fnum(el.get("rx")), fnum(el.get("ry"))
|
||||
if rx <= 0 or ry <= 0:
|
||||
rx, ry = self.size(el, "rx", 0), self.size(el, "ry", 1)
|
||||
if not self.fits(cx, cy, rx, ry) or rx <= 0 or ry <= 0:
|
||||
return
|
||||
n = max(12, int(2 * math.pi * max(rx, ry) / (self.amp * 10 + 1e-6)))
|
||||
n = min(n, 160)
|
||||
reach = max(rx, ry)
|
||||
n = max(8, min(24, int(math.tau * reach / max(self.amp * 25, self.diag / 60, 1e-9))))
|
||||
drift = self.rng.uniform(0, math.tau)
|
||||
pts = []
|
||||
for k in range(n):
|
||||
a = math.tau * k / n
|
||||
r = 1 + 0.5 * self.j(1 / max(rx, ry)) + 0.015 * math.sin(3 * a + drift)
|
||||
r = 1 + 0.5 * self.j(1 / reach) + 0.015 * self.amount * math.sin(3 * a + drift)
|
||||
pts.append((cx + rx * r * math.cos(a), cy + ry * r * math.sin(a)))
|
||||
d = "M" + " L".join(pt(p) for p in pts) + "Z"
|
||||
d = "M" + self.pt(pts[0])
|
||||
for i in range(n):
|
||||
before, a, b, after = pts[i - 1], pts[i], pts[(i + 1) % n], pts[(i + 2) % n]
|
||||
c1 = (a[0] + (b[0] - before[0]) / 6, a[1] + (b[1] - before[1]) / 6)
|
||||
c2 = (b[0] - (after[0] - a[0]) / 6, b[1] - (after[1] - a[1]) / 6)
|
||||
d += f" C{self.pt(c1)} {self.pt(c2)} {self.pt(b)}"
|
||||
d += "Z"
|
||||
small = max(rx, ry) < self.amp * 6
|
||||
self.to_path(el, d)
|
||||
if small:
|
||||
@@ -238,11 +661,11 @@ class Rougher:
|
||||
def straight(self, out, a, b):
|
||||
n = self.steps(a, b)
|
||||
for k in range(1, n):
|
||||
out.append("L" + pt(self.jp(lerp(a, b, k / n))))
|
||||
out.append("L" + self.pt(self.jp(lerp(a, b, k / n))))
|
||||
|
||||
def curve(self, out, seg, ja, jb, depth=0):
|
||||
p0, c1, c2, p1 = seg
|
||||
if depth < 3 and math.hypot(p1[0] - p0[0], p1[1] - p0[1]) > self.amp * 30:
|
||||
if depth < 3 and not self.whole and math.hypot(p1[0] - p0[0], p1[1] - p0[1]) > self.amp * 30:
|
||||
left, right = split_cubic(*seg)
|
||||
jm = self.jp(left[3])
|
||||
self.curve(out, left, ja, jm, depth + 1)
|
||||
@@ -252,12 +675,28 @@ class Rougher:
|
||||
db = (jb[0] - p1[0], jb[1] - p1[1])
|
||||
k1 = (c1[0] + da[0] + self.j(0.35), c1[1] + da[1] + self.j(0.35))
|
||||
k2 = (c2[0] + db[0] + self.j(0.35), c2[1] + db[1] + self.j(0.35))
|
||||
out.append(f"C{pt(k1)} {pt(k2)} {pt(jb)}")
|
||||
out.append(f"C{self.pt(k1)} {self.pt(k2)} {self.pt(jb)}")
|
||||
|
||||
def path(self, el):
|
||||
segs = parse_path(el.get("d", ""))
|
||||
if not segs or segs[0][0] != "M":
|
||||
return
|
||||
coords = [v for s in segs for p in s[1:] for v in p]
|
||||
if self.fits(*coords):
|
||||
if not any(seg[0] == "Z" for seg in segs):
|
||||
runs = [[]]
|
||||
for seg in segs:
|
||||
if seg[0] == "M" and runs[-1]:
|
||||
runs.append([])
|
||||
runs[-1].extend(seg[1:])
|
||||
self.keep_unfilled(el, runs)
|
||||
el.set("d", self.rough_segments(segs))
|
||||
|
||||
def keep_unfilled(self, el, runs):
|
||||
if self.sheet.inherited(el, "fill") is None and all(flat(run) for run in runs):
|
||||
el.set("fill", "none")
|
||||
|
||||
def rough_segments(self, segs):
|
||||
out = []
|
||||
cur = start = (0.0, 0.0)
|
||||
jcur = jstart = cur
|
||||
@@ -266,29 +705,25 @@ class Rougher:
|
||||
if kind == "M":
|
||||
cur = start = s[1]
|
||||
jcur = jstart = self.jp(cur)
|
||||
out.append("M" + pt(jcur))
|
||||
out.append("M" + self.pt(jcur))
|
||||
elif kind == "L":
|
||||
self.straight(out, cur, s[1])
|
||||
cur, jcur = s[1], self.jp(s[1])
|
||||
out.append("L" + pt(jcur))
|
||||
cur, jcur = s[1], jstart if s[1] == start else self.jp(s[1])
|
||||
out.append("L" + self.pt(jcur))
|
||||
elif kind == "C":
|
||||
jend = self.jp(s[3])
|
||||
jend = jstart if s[3] == start else self.jp(s[3])
|
||||
self.curve(out, (cur, s[1], s[2], s[3]), jcur, jend)
|
||||
cur, jcur = s[3], jend
|
||||
elif kind == "A":
|
||||
_, rx, ry, rot, large, sweep, p = s
|
||||
jcur = self.jp(p)
|
||||
out.append(f"A{fmt(rx)} {fmt(ry)} {fmt(rot)} {large} {sweep} {pt(jcur)}")
|
||||
cur = p
|
||||
else:
|
||||
self.straight(out, cur, start)
|
||||
out.append("Z")
|
||||
cur, jcur = start, jstart
|
||||
el.set("d", " ".join(out))
|
||||
return " ".join(out)
|
||||
|
||||
def ensure_filter(self):
|
||||
if self.filter_id:
|
||||
return self.filter_id
|
||||
freq, scale = fmt(0.9 * REF_DIAG / self.diag, 4), self.num(self.amp * 2.2)
|
||||
if (freq, scale) in self.filters:
|
||||
return self.filters[freq, scale]
|
||||
used = {e.get("id") for e in self.root.iter() if e.get("id")}
|
||||
fid, k = "rough-edge", 2
|
||||
while fid in used:
|
||||
@@ -298,52 +733,66 @@ class Rougher:
|
||||
defs = ET.Element(f"{{{SVG_NS}}}defs")
|
||||
self.root.insert(0, defs)
|
||||
f = ET.SubElement(defs, f"{{{SVG_NS}}}filter", {"id": fid, "x": "-5%", "y": "-5%", "width": "110%", "height": "110%"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feTurbulence", {"type": "fractalNoise", "baseFrequency": "0.9", "numOctaves": "2", "seed": str(self.rng.randint(1, 9999)), "result": "n"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feDisplacementMap", {"in": "SourceGraphic", "in2": "n", "scale": fmt(self.amp * 2.2), "xChannelSelector": "R", "yChannelSelector": "G"})
|
||||
self.filter_id = fid
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feTurbulence", {"type": "fractalNoise", "baseFrequency": freq, "numOctaves": "2", "seed": str(self.rng.randint(1, 9999)), "result": "n"})
|
||||
ET.SubElement(f, f"{{{SVG_NS}}}feDisplacementMap", {"in": "SourceGraphic", "in2": "n", "scale": scale, "xChannelSelector": "R", "yChannelSelector": "G"})
|
||||
self.filters[freq, scale] = fid
|
||||
return fid
|
||||
|
||||
def shake(self, el, chars, k):
|
||||
def shake(self, el, chars, k, size):
|
||||
n = len(chars)
|
||||
if not n:
|
||||
return
|
||||
if not el.get("rotate"):
|
||||
el.set("rotate", " ".join(fmt(self.rng.gauss(0, 2.2 * k)) for _ in range(n)))
|
||||
own = el.get("dy", "")
|
||||
if len(NUM.findall(own)) > 1:
|
||||
return
|
||||
given = [length(v, self.box[3], size, rem=self.rem) for v in re.split(r"[\s,]+", el.get("dy", "").strip()) if v]
|
||||
given += [0.0] * (n - len(given))
|
||||
offs = [self.rng.gauss(0, self.amp * 0.5 * k) for _ in range(n)]
|
||||
dys = [offs[0] + fnum(own)] + [offs[i] - offs[i - 1] for i in range(1, n)]
|
||||
el.set("dy", " ".join(fmt(d) for d in dys))
|
||||
moves = [offs[0]] + [offs[i] - offs[i - 1] for i in range(1, n)]
|
||||
el.set("dy", " ".join(self.num(d + m) for d, m in zip(given, moves + [0.0] * (len(given) - n))))
|
||||
|
||||
def on_canvas(self, size):
|
||||
return size * REF_DIAG / self.diag
|
||||
|
||||
def calm(self, size):
|
||||
size = self.on_canvas(size)
|
||||
return 0.25 if size < 16 else (0.6 if size < 32 else 1.0)
|
||||
|
||||
def font_of(self, el, parent):
|
||||
return font_px(self.sheet.get(el, "font-size"), parent, self.rem)
|
||||
|
||||
def text(self, el, size):
|
||||
k = 0.25 if size < 16 else (0.6 if size < 32 else 1.0)
|
||||
kids = list(el)
|
||||
if not kids:
|
||||
self.shake(el, el.text or "", k)
|
||||
if not list(el):
|
||||
self.shake(el, el.text or "", self.calm(size), size)
|
||||
else:
|
||||
for t in el.iter():
|
||||
if t is not el and tag(t) == "tspan" and not list(t):
|
||||
ts = style_get(t, "font-size")
|
||||
tsize = fnum(ts, size) if ts else size
|
||||
self.shake(t, t.text or "", 0.25 if tsize < 16 else (0.6 if tsize < 32 else 1.0))
|
||||
if size >= 28 and not el.get("filter") and "".join(el.itertext()).strip():
|
||||
stack = [(c, self.font_of(c, size)) for c in el]
|
||||
while stack:
|
||||
t, tsize = stack.pop()
|
||||
if tag(t) == "tspan" and not list(t):
|
||||
self.shake(t, t.text or "", self.calm(tsize), tsize)
|
||||
stack.extend((c, self.font_of(c, tsize)) for c in t)
|
||||
if self.on_canvas(size) >= 28 and not el.get("filter") and "".join(el.itertext()).strip():
|
||||
el.set("filter", f"url(#{self.ensure_filter()})")
|
||||
|
||||
def walk(self, el, size):
|
||||
fs = style_get(el, "font-size")
|
||||
if fs:
|
||||
size = fnum(fs, size)
|
||||
for child in list(el):
|
||||
t = tag(child)
|
||||
if t in SKIP or child.get("data-rough") == "off":
|
||||
continue
|
||||
was = self.free
|
||||
stretch = transform_scale(child.get("transform"))
|
||||
if not stretch:
|
||||
continue
|
||||
was = self.free, self.box, self.scale
|
||||
if child.get("transform"):
|
||||
self.free = False
|
||||
self.outer_scale = self.scale
|
||||
self.scale *= stretch
|
||||
self.font = font = self.font_of(child, size)
|
||||
self.whole = t in ("path", "line", "polyline", "polygon") and self.sheet.has_marker(child, ("marker-mid",))
|
||||
if t == "svg" and not self.enter_viewport(child):
|
||||
self.free, self.box, self.scale = was
|
||||
continue
|
||||
if t == "text":
|
||||
cs = style_get(child, "font-size")
|
||||
self.text(child, fnum(cs, size) if cs else size)
|
||||
self.text(child, font)
|
||||
else:
|
||||
if t == "line":
|
||||
self.line(child)
|
||||
@@ -357,27 +806,92 @@ class Rougher:
|
||||
self.ellipse(child)
|
||||
elif t == "path":
|
||||
self.path(child)
|
||||
self.walk(child, size)
|
||||
self.free = was
|
||||
elif t == "use":
|
||||
self.shift(child)
|
||||
self.walk(child, font)
|
||||
self.free, self.box, self.scale = was
|
||||
|
||||
def enter_viewport(self, el):
|
||||
w, h = (self.size(el, k, axis) if el.get(k) is not None else self.box[axis + 2] for k, axis in (("width", 0), ("height", 1)))
|
||||
vb = [float(n) for n in NUM.findall(el.get("viewBox", ""))]
|
||||
if len(vb) == 4 and vb[2] > 0 and vb[3] > 0:
|
||||
sx, sy = w / vb[2], h / vb[3]
|
||||
fit = el.get("preserveAspectRatio", "")
|
||||
stretch = max(sx, sy) if "slice" in fit or fit.strip() == "none" else min(sx, sy)
|
||||
self.box = vb
|
||||
else:
|
||||
stretch = 1.0
|
||||
self.box = [0.0, 0.0, w, h]
|
||||
if not finite(w, h, *self.box, stretch) or w <= 0 or h <= 0 or stretch <= 0:
|
||||
return False
|
||||
self.scale *= stretch
|
||||
self.free = True
|
||||
return True
|
||||
|
||||
|
||||
def depth(root):
|
||||
deepest = 0
|
||||
stack = [(root, 1)]
|
||||
while stack:
|
||||
el, d = stack.pop()
|
||||
deepest = max(deepest, d)
|
||||
stack.extend((c, d + 1) for c in el)
|
||||
return deepest
|
||||
|
||||
|
||||
def read_svg(path):
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
except OSError as e:
|
||||
raise SystemExit(f"rough.py: cannot open {path}: {e.strerror}")
|
||||
if data[:2] == b"\x1f\x8b":
|
||||
raise SystemExit(f"rough.py: {path} is gzip-compressed (svgz); unzip it to a plain .svg first")
|
||||
try:
|
||||
return ET.ElementTree(ET.fromstring(data))
|
||||
except ET.ParseError as e:
|
||||
raise SystemExit(f"rough.py: {path} is not valid SVG XML: {e}")
|
||||
|
||||
|
||||
def amount(v):
|
||||
try:
|
||||
x = float(v)
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(f"not a number: {v}")
|
||||
if not math.isfinite(x) or x < 0:
|
||||
raise argparse.ArgumentTypeError(f"must be a finite number of 0 or more: {v}")
|
||||
return x
|
||||
|
||||
|
||||
def main():
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("src")
|
||||
ap.add_argument("dst")
|
||||
ap.add_argument("--amount", type=float, default=1.0)
|
||||
ap.add_argument("--amount", type=amount, default=1.0)
|
||||
ap.add_argument("--seed", type=int)
|
||||
args = ap.parse_args()
|
||||
rng = random.Random(args.seed) if args.seed is not None else random.SystemRandom()
|
||||
tree = ET.parse(args.src)
|
||||
tree = read_svg(args.src)
|
||||
root = tree.getroot()
|
||||
if depth(root) > MAX_DEPTH:
|
||||
raise SystemExit(f"rough.py: {args.src} nests elements more than {MAX_DEPTH} levels deep; flatten the groups and run it again")
|
||||
vb = [float(n) for n in NUM.findall(root.get("viewBox", ""))]
|
||||
box = vb if len(vb) == 4 else [0.0, 0.0, fnum(root.get("width"), 600), fnum(root.get("height"), 600)]
|
||||
w, h = box[2], box[3]
|
||||
amp = args.amount * math.hypot(w, h) / 720 * 1.4
|
||||
Rougher(amp, rng, root, box).walk(root, 16.0)
|
||||
tree.write(args.dst, encoding="unicode", xml_declaration=False)
|
||||
print(f"wrote {args.dst} (amp {amp:.2f})")
|
||||
if not finite(*box) or w <= 0 or h <= 0:
|
||||
raise SystemExit(f"rough.py: the canvas size {fmt(w)} x {fmt(h)} from viewBox or width/height is not usable")
|
||||
amp = args.amount * math.hypot(w, h) / REF_DIAG * 1.4
|
||||
rougher = Rougher(amp, rng, root, box)
|
||||
rougher.walk(root, rougher.rem)
|
||||
rougher.sheet.keep_values(root)
|
||||
try:
|
||||
with open(args.dst, "w", encoding="utf-8", newline="\n") as out:
|
||||
tree.write(out, encoding="unicode", xml_declaration=False)
|
||||
except OSError as e:
|
||||
raise SystemExit(f"rough.py: cannot write {args.dst}: {e.strerror}")
|
||||
print(f"wrote {args.dst} (amp {amp:.3g})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+36
-6
@@ -11,8 +11,11 @@ RECENT = {}
|
||||
|
||||
def load_recent(seeds=12):
|
||||
RECENT.clear()
|
||||
for entry in reversed(history.load("seed")[-seeds:]):
|
||||
for axis, value in entry.get("seed", {}).items():
|
||||
valid = [e["seed"] for e in history.load("seed") if isinstance(e.get("seed"), dict)]
|
||||
for seed in reversed(valid[-seeds:]):
|
||||
for axis, value in seed.items():
|
||||
if not isinstance(value, str):
|
||||
continue
|
||||
RECENT.setdefault(axis, [])
|
||||
if value not in RECENT[axis]:
|
||||
RECENT[axis].append(value)
|
||||
@@ -208,6 +211,12 @@ def pools(kind):
|
||||
return dict(IDEA)
|
||||
|
||||
|
||||
def rolled_axes(only, keep):
|
||||
if only == "method" and "color" not in keep:
|
||||
return ["method", "color"]
|
||||
return [only]
|
||||
|
||||
|
||||
def roll_once(kind, keep, only=None):
|
||||
out = {}
|
||||
for name, items in pools(kind).items():
|
||||
@@ -223,12 +232,26 @@ def roll_once(kind, keep, only=None):
|
||||
out["anchor"] = pick("anchor", ANCHOR)
|
||||
out.update(keep)
|
||||
if only:
|
||||
out = {k: v for k, v in out.items() if k in keep or k == only}
|
||||
out = {k: v for k, v in out.items() if k in keep or k in rolled_axes(only, keep)}
|
||||
if out.get("method") in FIXED_COLOR and "color" in out and "color" not in keep:
|
||||
out["color"] = "the method's own colors"
|
||||
return out
|
||||
|
||||
|
||||
def known_values(axis):
|
||||
values = {**VISUAL, **TEXT, **IDEA, "setting": SETTING, "region": REGION, "anchor": ANCHOR + NO_ANCHOR}
|
||||
values["method"] = [m for items in METHOD_FAMILIES.values() for m in items]
|
||||
values["color"] = VISUAL["color"] + ["the method's own colors"]
|
||||
return values.get(axis, [])
|
||||
|
||||
|
||||
def canonical(axis, value):
|
||||
for known in known_values(axis):
|
||||
if known.casefold() == value.casefold():
|
||||
return known
|
||||
return value
|
||||
|
||||
|
||||
def axes_of(kind):
|
||||
return list(roll_once(kind, {}))
|
||||
|
||||
@@ -243,6 +266,8 @@ def roll(kind, keep=None, only=None):
|
||||
|
||||
|
||||
def main():
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("kind", nargs="?", default="visual", choices=["visual", "text", "idea"])
|
||||
ap.add_argument("--only", help="roll one axis again, for example --only method")
|
||||
@@ -255,7 +280,9 @@ def main():
|
||||
k, sep, v = item.partition("=")
|
||||
if not sep:
|
||||
sys.exit(f"--keep needs axis=value, got '{item}'")
|
||||
keep[k.strip()] = v.strip()
|
||||
if not v.strip():
|
||||
sys.exit(f"--keep needs a value after '=', got '{item}'")
|
||||
keep[k.strip()] = canonical(k.strip(), v.strip())
|
||||
axes = axes_of(args.kind)
|
||||
for name in [*keep, *([args.only] if args.only else [])]:
|
||||
if name not in axes:
|
||||
@@ -264,11 +291,14 @@ def main():
|
||||
keep.pop(args.only, None)
|
||||
seed = roll(args.kind, keep, args.only)
|
||||
if args.only:
|
||||
seed = {args.only: seed[args.only]}
|
||||
seed = {k: seed[k] for k in rolled_axes(args.only, keep)}
|
||||
for k, v in seed.items():
|
||||
print(f"{k}: {v}")
|
||||
if not args.no_log:
|
||||
history.add({"type": "seed", "kind": args.kind, "seed": seed})
|
||||
try:
|
||||
history.add({"type": "seed", "kind": args.kind, "seed": seed})
|
||||
except OSError as e:
|
||||
print(f"could not save the seed to the history: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ When the method is made by hand, code must carry the hand in the geometry, not o
|
||||
|
||||
Look at the result at full size. If a hand-made piece has lines that look plotted, curves that look computed or text that looks typed, it still reads as machine made, however much grain is on it.
|
||||
|
||||
Typing coordinates by hand gives clean marks. Generate the method's marks with a short script instead of writing them one by one. Stop at the number of marks the eye needs: a poster built from thousands of tiny pieces is slow to make and heavy to open, so keep an SVG under about 200 KB. For an SVG, `python3 scripts/rough.py in.svg out.svg [--amount 1.0]` breaks straight lines, rects, polygons, circles and paths, moves repeated marks off their even spacing, and shakes letters a little while keeping small text calm. Use it only for methods made by hand, such as print, paint, cut paper, stamps, chalk and ink. It is a start, not a style: the method and the design still have to carry the look.
|
||||
Typing coordinates by hand gives clean marks. Generate the method's marks with a short script instead of writing them one by one. Stop at the number of marks the eye needs: a poster built from thousands of tiny pieces is slow to make and heavy to open, so keep an SVG under about 200 KB. For an SVG, `python3 scripts/rough.py in.svg out.svg [--amount 1.0]` breaks straight lines, rects, polygons, circles and paths, moves repeated marks off their even spacing (but not the tiles of a `<pattern>`, which repeat exactly), and shakes letters a little while keeping small text calm. Use it only for methods made by hand, such as print, paint, cut paper, stamps, chalk and ink. It is a start, not a style: the method and the design still have to carry the look.
|
||||
|
||||
Before showing any SVG, run `python3 scripts/check.py file.svg`. It renders the image at full size and at icon size, and lists text that runs off an edge, is covered by a shape, has low contrast or is too small. Fix all of it, run it again, then open both renders and look at them yourself. It does not see letters drawn as paths or text that spills out of its own box, so check those by eye. For other formats, render the image and do the same checks by eye.
|
||||
|
||||
|
||||
Reference in new issue
Block a user