Compare commits

..
71 Commits
Author SHA1 Message Date
manki dd4c56ae82 Merge pull request #8 from vlasky/fix/rough-css
rough.py: keep and read `<style>` rules
2026-11-26 11:55:25 +03:00
manki cd0e9e4c56 Merge pull request #12 from vlasky/docs/windows-python
SKILL.md, CONTRIBUTING.md: say to use python or py on Windows when python3 is not found
2026-11-26 10:20:27 +03:00
Vlad Lasky e38bc879bc rough.py: keep the stylesheet values of shapes turned into paths
Retagging <line>, <rect>, <circle> and the other shapes as <path> broke
<style> rules that select by element name. In t2.svg, line.css{stroke:
#e33} and circle{fill:#3c6} stopped matching, so the red line vanished
and the green circle went black. Rules for path went the other way:
path{fill:none} began to empty every converted circle and rect.

Copying each rule to a selector that matches the converted path cannot
keep its specificity: :where() and :is() would, but librsvg 2.63 ignores
both. A copied rule path[data-rough-shape="circle"] (0,1,1) then beats a
class rule (0,1,0), so in

  <style>circle{fill:#c00} .blue{fill:#06c}</style>
  <circle cx="75" cy="75" r="50"/>
  <circle class="blue" cx="225" cy="75" r="50"/>

both circles came out red. Rewriting path to path:not([data-rough-shape])
raised path rules from (0,0,1) to (0,1,1) in the same way, so with
path{fill:#c00} .x{fill:#06c}, a real <path class="x"> turned red as soon
as the drawing also had a shape to convert.

The stylesheet is now left as it is. Each element's matching rules are
found once before any shape changes and once after, and where they
differ, the value the original cascade gave each property those rules
declare is written back onto the element: the first circle above gets
fill="#c00", the blue one is left alone. If a rule the matcher sees
still sets the property on the path, the value goes into the style
attribute instead, with !important when such a rule is !important, so
path{stroke-dasharray:4} does not reach converted shapes. A property the
original did not get at all is written as inherit, or as its initial
value (opacity:1) if it is not inherited; unset and initial are not
used, because librsvg 2.63 ignores both and cairosvg reads unset as
initial. Values rough.py sets itself, fill:none on lines and marker:none
on shapes, are kept.

Writing the value as a presentation attribute where possible keeps it
below any rule the matcher does not see. A rule with another
pseudo-class that still matches the path, such as .a:nth-child(3) or
.a:not(.b), still wins over it. A rule that names the old tag with such a
pseudo-class, circle:nth-child(2){fill:#0a0}, is still lost, as before.
Rules inside @media blocks are not matched, as in librsvg and cairosvg,
so a type rule in one, such as circle{fill:#fff} in
@media (prefers-color-scheme: dark), stops reaching converted shapes in
a browser.
2026-11-26 18:09:10 +11:00
Vlad Lasky a671ca5253 rough.py: read the text size from the font shorthand
A size given with the font shorthand, as in .head { font: bold 40px/1
serif } or style="font: italic 36px serif", was not read, so both
headlines were handled as 16px text: calm shaking and no edge filter.
Worse, style="font: 12px sans-serif" next to font-size="40" was treated
as 40-unit text, although the shorthand in the style attribute wins and
the text renders at 12.

The shorthand now counts as a font-size declaration, in the style
attribute and in stylesheet rules alike: the first word that is a size
keyword (large, smaller and so on) or a length with a unit, with any
/line-height after it dropped.
2026-11-26 18:02:06 +11:00
Vlad Lasky a94c5a539d rough.py: read font-size, markers, fill and rem from stylesheet rules
The text, marker, fill and rem fixes only saw the style attribute,
presentation attributes and inheritance, so values set by a <style>
rule were missed:

- poster.svg sets font-size: 72px on its title through the .title class,
  and the title was handled as 16px text: calm shaking and no edge
  filter.
- In r11.svg a polyline gets its markers from .m { marker: url(#dot) },
  and its 2 mid dots grew to 20 as the jitter cut its edges into
  pieces.
- In f1.svg the straight paths without a fill came out with black
  slivers along them, because any document with a stylesheet was left
  without fill="none", in case a rule filled an ancestor.
- With :root { font-size: 40px }, rem still counted as 16 px, so tspans
  with dy="1rem" stepped 16 units instead of 40 and overlapped.

Stylesheet rules are now matched against elements with a small engine
for type, class, id, attribute, :root, :first-child and :last-child with
any combinator. Each element is matched once, against the document as
it was read, so a shape that has already turned into a path does not
change what its siblings match. A property comes from the cascade:
!important in the style attribute, then !important rules by specificity
and order, then the style attribute, then the other rules, then the
presentation attribute, then the parent.

Not matched: rules with other pseudo-classes (:hover, :nth-child,
:not() and so on), and rules inside @media or any other at-rule block.
librsvg 2.63 and cairosvg both ignore @media blocks, even @media screen,
so leaving them out follows what they draw. With rules resolved, the
fill check sees a fill set by a stylesheet (f1.svg: the .blue class)
and leaves it, and only fills the matcher cannot see are left to the
renderer: a fill set only by a :hover rule, say, still overrides the
added attribute, as it should.
2026-11-26 18:01:53 +11:00
Vlad Lasky 5578f7202f SKILL.md, CONTRIBUTING.md: say to use python or py on Windows when python3 is not found
The python.org installer for Windows creates python.exe and the py launcher but no python3.exe, so python3 opens the Microsoft Store placeholder and exits with code 9009. Add the wording agreed in #11 next to the first script command in SKILL.md and above the test commands in CONTRIBUTING.md.
2026-11-26 17:54:12 +11:00
manki 86b68117a0 Merge pull request #7 from vlasky/fix/rough-core
rough.py: fix stacked text, black slivers, unit and scale errors, and crashes
2026-11-26 09:06:56 +03:00
manki ba63136110 Merge pull request #9 from vlasky/fix/check
check.py: fix false alarms that make the model change good work, and catch problems it missed
2026-11-26 09:06:53 +03:00
manki a538068ce6 Merge pull request #6 from vlasky/fix/history
seed.py, history.py, moves.py: keep seeds working when the history is broken, busy or on Windows
2026-11-26 09:06:49 +03:00
manki b7a2c7d224 Merge pull request #10 from vlasky/docs/readme-seeds
README: say that text and idea seeds also give a setting, region and object
2026-11-26 09:06:46 +03:00
mankidev 75de35ef5e Updated the Turkish README for text and idea seeds 2026-11-26 09:05:51 +03:00
Vlad Lasky 37ad27773e check.py: look for the cairo DLL only in absolute folders
With LOCALAPPDATA unset, os.path.join('', 'Programs') made the GIMP folders relative, so cairo_dir() searched 'Programs\GIMP 3\bin' under the current folder and put a libcairo-2.dll planted there on PATH. A relative entry in CAIROCFFI_DLL_DIRECTORIES did the same. Skip any folder that is not absolute.
2026-11-26 15:02:05 +11:00
Vlad Lasky 3541f7a280 check.py: say in one line when numpy or Pillow is missing
check.py needs numpy and Pillow, but a plain Python has neither (the usual case on Windows), and the import failed with a ModuleNotFoundError traceback. Stop with one line that names both packages instead, like the other setup errors.
2026-11-26 15:01:42 +11:00
Vlad Lasky e7d5d9721a check.py: run rsvg-convert from the path that which() found
shutil.which() finds rsvg-convert through PATHEXT, so on Windows it also finds an rsvg-convert.cmd or .bat wrapper. subprocess.run(['rsvg-convert', ...]) then looks only for an .exe and failed with FileNotFoundError [WinError 2], a long traceback, and never fell back to cairosvg. Pass the path which() returned, so the wrapper runs and its errors come back as the usual one-line message.
2026-11-26 15:01:34 +11:00
Vlad Lasky d7d615ad28 rough.py: write the output with LF line endings on every platform
ElementTree opens the output in text mode, so on Windows every newline in the SVG became CRLF and the same input and seed gave different bytes than on Linux (209 of 242 test files differed only in line endings). Open the file ourselves as UTF-8 with newline='\n' and hand it to ElementTree.
2026-11-26 15:00:41 +11:00
Vlad Lasky 71cf367192 rough.py: write stdout as UTF-8
On Windows, stdout through a pipe uses the ANSI code page. When the output path has a character outside it, such as 'Łódź.svg' under cp1252, the closing 'wrote ...' line raised UnicodeEncodeError and rough.py exited 1 after the file had already been written, so a caller trusting the exit code thought it failed. moves.py and check.py already write stdout as UTF-8; do the same here.
2026-11-26 15:00:02 +11:00
Vlad Lasky a6c67f8cb2 history.py: keep every line and byte of the file when adding a row
An earlier commit on this branch made a corrupt history readable by
decoding with errors="replace" and skipping lines that are not JSON
objects. But add() rewrote the file from the rows it had parsed, so the
next add destroyed whatever it could not read, where upstream crashed
and left the file alone:

- Windows PowerShell 5 writes UTF-16 LE by default (`$rows | Out-File`).
  The whole file failed to parse, `moves.py` said "no moves saved yet",
  and the next add left a file with only the new row, with no warning.
- A cp1252 file from `Set-Content` ("Łódź" saved as ANSI) was listed as
  "L�dz", and the next add wrote U+FFFD into the file for good.
- Any line that was not a JSON object was dropped at the next add.

Now:
- A file that starts with a UTF-16 BOM (FF FE or FE FF) is decoded as
  UTF-16, and the next add writes it back as UTF-8.
- Anything else is decoded as UTF-8 with errors="surrogateescape" and
  written back the same way, so bytes that are not UTF-8 survive byte
  for byte. The listing shows them as "?", since stdout already uses
  errors="replace".
- add() keeps the existing lines as text and appends the new row,
  instead of re-serialising parsed rows. Lines that are not JSON objects
  stay in the file. They count toward the 300-row cap and are trimmed
  oldest first like the rest. Blank lines are dropped, and a "\r" at the
  end of a line is removed, so a CRLF file comes back with one line
  ending per row.
- load() still returns only the lines that parse as JSON objects.

On Linux: the bytes of a cp1252 file were unchanged after an add, UTF-16
LE and BE files with CRLF kept all 3 rows and became UTF-8, junk lines
("not json at all", 5, null) were still there after an add, and a
300-line file with a junk first line dropped exactly that line when one
row was added.
2026-11-26 14:56:06 +11:00
Vlad Lasky 95ee5116fc history.py: retry a read that Windows refuses during a rename
Readers don't take the lock. On Windows, opening history.jsonl while a
writer's os.replace is swapping it in fails with PermissionError for a
moment. load() turned that into "could not read the history" and an
empty list, so `moves.py` printed "no moves saved yet" and seed.py
stopped avoiding recent values, even though nothing was wrong with the
file.

Opening and reading now go through the same short retry as the rename
in add(): PermissionError is retried every 20 ms, up to 50 times (about
1 s). On Linux and macOS a file that really can't be read now warns
after that second instead of at once.

On Windows (Python 3.14, NTFS), one process looping read() while 4
others did 40 adds each got PermissionError on 104, 90 and 78 of about
4400 to 5200 reads in three runs before, and on 0 of about 3500 to 4500
reads after.
2026-11-26 14:56:06 +11:00
Vlad Lasky 7623f75478 moves.py: require --last to be at least 1
The listing sliced rows[-args.last:], so `--last 0` became rows[-0:],
which is every move, and `--last -1` became rows[1:], every move but the
oldest. Neither is what the flag says. A count below 1 now stops with
"--last must be 1 or more" (argparse usage error, exit 2).
2026-11-26 14:56:06 +11:00
Vlad Lasky bb1105d630 seed.py: match kept values to the pools and reject empty ones
`--keep "method=X-ray image"` did not match "x-ray image" in the pool,
so it was taken as a new method and skipped the rule that a fixed-colour
method gets "the method's own colors": the seed came back with
"color: two colors that clash". `--keep "method="` was accepted and
printed "method: " with nothing after it.

A kept value that matches a pool value of that axis without regard to
case (casefold) is now replaced by the pool value, so every rule keyed
on it applies: X-ray image becomes x-ray image and gets its own colours,
Iceland, "A Plain List" and "The Method's Own Colors" match too. A value
that matches nothing is still kept as given, because --keep is how a
subject or a fact from the user's request is held fixed ("region=Łódź",
"anchor=a red tram", a method the pools don't list), and the skill wants
the start point to come from the request when it carries one. An empty
value, or one of spaces only, now stops with "--keep needs a value after
'='".
2026-11-26 14:56:06 +11:00
Vlad Lasky f47a4aa3e3 seed.py: roll the colour with the method when --only method leaves it free
`seed.py visual --only method` never returned any of the 12 methods that
bring their own colours (x-ray image, thermal camera image, LED dot
matrix and so on): 0 in 300 rolls. With --only, roll_once() dropped
every axis that was not kept or rolled, so colour was missing, and
clashes() counts a fixed-colour method without "the method's own colors"
as a clash and rolls again.

The reverse case was wrong too. After a seed such as "method: x-ray
image, color: the method's own colors", the model rolls the method again
and does not keep the colour, since that colour belongs to the old
method. It got back only "method: woodcut" and was left with "the
method's own colors" for a woodcut, which means nothing.

The colour depends on the method, so when --only method is used without
--keep color, the colour is rolled with it and printed:

- a fixed-colour method prints "color: the method's own colors";
- any other method prints a fresh colour from the pool, checked by
  clashes() like a full seed (so "the colors of a machine screen" comes
  only with a screen method).

With --keep color the output is the method alone, as before, and it
fits the kept colour: "the method's own colors" gives a fixed-colour
method, any other colour gives a method that does not fix its own, and a
machine-screen colour gives a screen method. Either way the model's
seed stays consistent if it replaces exactly the lines it is shown.
The logged row holds the same lines as the output.

After, in 300 rolls each: --only method gave 60 fixed-colour methods,
all with "color: the method's own colors", and no machine-screen colour
on a non-screen method; with --keep "color=the method's own colors"
all 300 were fixed-colour methods; with --keep color=fluorescent none
were. Every --only method output without a kept colour had two lines,
and every one with a kept colour had one.
2026-11-26 14:56:06 +11:00
Vlad Lasky 3801e69d03 history.py, seed.py, moves.py: warn instead of crashing when history fails
With an unwritable history location (ANTIALGORITHM_HISTORY under a
read-only folder), seed.py printed the seed and then exited 1 with a
PermissionError traceback, and `moves.py add` failed the same way. An
agent that sees a failed command may throw the seed away and pick a
start point from its own taste, which is what the skill forbids, so the
seed has to succeed whatever happens to the history.

Now:
- load() turns a read error (no permission, a folder in the way) into
  one line on stderr and an empty history, so seeds are still rolled,
  only without avoiding recent values.
- seed.py prints the seed, and if saving fails it prints one line on
  stderr and still exits 0.
- `moves.py add` prints "could not save the move: <reason>" and exits 1,
  since saving is its whole job, but without a traceback.

add() still reads the file itself and fails on a read error rather than
treating the history as empty, so a file it cannot read is never
overwritten with a single row. This is one finding across three files:
the history module decides what a failure is, and each script decides
what it means for its own exit status.
2026-11-26 14:56:06 +11:00
Vlad Lasky 67d79fd095 history.py: lock the history file while adding a row
Agents can run several sessions at once, and each one rolls seeds and
saves moves. add() read the whole file, appended a row and wrote it back
through a shared PATH + ".tmp", so parallel writers broke it two ways:

- 40 parallel `seed.py idea` runs gave a FileNotFoundError traceback
  when one writer renamed the shared tmp file away from under another,
  and only 38 of 40 rows were saved;
- even with distinct tmp names, two writers that read the same file each
  wrote back their own copy without the other's row: 20 parallel
  `moves.py add` runs left 18 rows.

add() now holds a lock file (history.jsonl.lock) across its read and
write. The lock is taken with os.open(O_CREAT | O_EXCL), which is atomic
on Linux, macOS and Windows and needs only the standard library; fcntl
is Unix-only and msvcrt is Windows-only. A writer that finds the lock
retries every 20 ms for up to 15 s. A lock older than 10 s is taken to be
left by a crashed writer and removed, since a real holder keeps it for
milliseconds; so a leftover lock costs one wait at most, never a
permanently broken history. The tmp file name includes the pid, so a
writer that breaks a stale lock still can't clobber another's tmp file.

On Windows, os.open on a lock file that another process is deleting
fails with PermissionError (ERROR_ACCESS_DENIED), not FileExistsError,
so on Windows PermissionError is retried the same way. A first version
that did not saved 196 and 193 of 200 rows in two runs of 20 processes
x 10 adds on Windows (Python 3.14, NTFS), with every failure at
os.open; with the retry 7 runs saved 1400 of 1400. The cost is that on
Windows a lock that can never be created (a read-only folder) fails
after the 15 s wait, with "could not create the lock file <path>",
instead of at once. On Linux and macOS PermissionError there always
means the folder is not writable, so it still fails at once.

On Windows, os.replace fails with PermissionError while another process
has the target open, which a reader (seed.py, moves.py) may have for a
moment, so the rename is retried for up to 1 s. migrate() takes the same
lock and re-checks before copying, so two first runs can't both copy the
old repo-root file over a row that one of them has just added. The
300-row cap is unchanged.

After: 40 parallel seeds saved 40 rows and 20 parallel adds saved 20
distinct moves, with empty stderr, in each of 4 runs; 320 more seeds
from 8 parallel loops left exactly 300 rows.
2026-11-26 14:56:06 +11:00
Vlad Lasky 8275ce3ac4 rough.py: resolve rem against the root element's font-size
rem lengths were always 16 px. With style="font-size: 40px" on the root
<svg>, a circle with r="1.5rem" should have radius 60 and tspans with
dy="1rem" should step 40 units; rough.py drew radius 24 and stepped 16,
and the two lines of text overlapped.

The root <svg>'s font-size is now read once, from its style attribute or
its font-size attribute, and every rem in coordinates, dy and font sizes
is resolved against it. Without one it stays 16 px. Checked: a
font-size="20" attribute gives 20, style="font-size:2rem" gives 32,
none gives 16.

librsvg 2.63 does not draw rem in geometry attributes at all (the
original renders without its circle and rect), so the converted output,
which has plain numbers, now shows them at the size a browser would.
2026-11-26 14:55:38 +11:00
Vlad Lasky 033f404957 rough.py: shake text that already lists per-letter dy values
shake() returned early when dy held more than one value, a check from
upstream 7f92b83, so text whose author had placed letters one by one
(dy.svg: dy="0 -10 -10 20 20 -20" on WAVE ON, dy="0,0.25em,..." on
STEPS AND) got no baseline jitter at all.

Each listed value is now resolved as a length (em against the element's
font-size, % against the canvas height) and the small offsets are added
on top of it. When the list is shorter than the text the missing entries
count as 0, as SVG says for dx/dy (the last value does not repeat);
values beyond the last character are kept as they are, since SVG ignores
them. x, y, dx and rotate lists are not changed; rotate is still only
added when the author has none.

Rendered with cairosvg, because librsvg ignores per-letter dy lists: the
author's wave and steps are unchanged and the letters get the same small
shake as single-valued text.
2026-11-26 14:55:38 +11:00
Vlad Lasky 09d1de592d rough.py: report unreadable, malformed or unwritable files in one line
Bad input ended in a traceback: an empty file (empty.svg), an undefined
entity such as &nbsp; (nbsp.svg) or an external one (ext.svg), a
billion-laughs file (laughs.svg) and a gzip-compressed .svgz all died
with xml.etree.ElementTree.ParseError, and a missing input or an output
in a missing folder with FileNotFoundError.

The input is now read as bytes and parsed in read_svg(), which uses the
same wording check.py uses on branch fix/check: "cannot open <file>:
<reason>", "<file> is gzip-compressed (svgz); unzip it to a plain .svg
first" and "<file> is not valid SVG XML: <parser message>". Writing
the output reports "cannot write <file>: <reason>". Each message starts
with rough.py: like the script's other errors, and the exit code is 1.
Checked on Python 3.9 and 3.15 with the files above, a directory given
as input or output, a file without read permission and a read-only
output folder.
2026-11-26 14:55:38 +11:00
Vlad Lasky f1955174a3 rough.py: keep straight open paths and polylines unfilled after jitter
An open <path> or <polyline> with no fill set anywhere is filled black by
default, but draws nothing while its points lie on one line, because the
fill encloses no area. Once jitter moves the points off that line the
fill appears: M40 580 L360 580 in scaled.svg came out as a hairline with
black slivers along it.

Such an element now gets fill="none" before it is roughened, but only
when every subpath is open (no Z) and all its points, control points
included, lie on one straight line, and no fill comes from an attribute,
the style attribute or an ancestor.

Left alone on purpose: any fill that is set (a fill="#c33" attribute,
fill inherited from a group), because the author asked for it even if it
was invisible; open curves and bent polylines, which do enclose area and
already render filled; and closed subpaths. A document with a non-empty
<style> element is left alone entirely, f1.svg among them: a rule there
may fill an ancestor, and without reading the rules the added attribute
could override the fill the element inherits from it.
2026-11-26 14:55:38 +11:00
Vlad Lasky 59fc116bc7 visuals.md: say that rough.py leaves <pattern> tiles alone
visuals.md said rough.py moves repeated marks off their even spacing.
That is now true for separate shapes and for <use> copies, but a
<pattern> is one tile that the renderer repeats, and rough.py skips
pattern contents, so a hatch or dot pattern still repeats exactly. The
sentence now says so, so the model draws marks it wants uneven as
separate shapes or <use> copies instead of a pattern.
2026-11-26 14:46:57 +11:00
Vlad Lasky f9d1f05a68 rough.py: give each <use> copy its own small offset
<use> elements were walked past without change, so marks repeated with
<use>, the usual way to stamp the same tick, dot or tile many times,
stayed on their exact even spacing (r13d.svg: twelve ticks every 20
units), although visuals.md says rough.py moves repeated marks off it.

Each <use> now gets the same small whole-shape offset that small circles
and lines get: a translate in its parent's coordinates, sized by the
parent's scale, put in front of any transform it already has. The
referenced content itself is shared by all copies, so the copies move
but do not change shape.
2026-11-26 14:46:57 +11:00
Vlad Lasky 9f624addd0 rough.py: draw circles and ellipses as smooth wobbly curves
Circles and ellipses became closed polygons of 12 to 160 straight
segments. At full size the facets show (r13c.svg: the r=150 circle's
outline is a ring of visible corners and kinks), which reads as a
plotted polygon rather than a hand-drawn curve.

They are now 8 to 24 jittered points joined by a closed Catmull-Rom
spline written as cubic Beziers, so the outline stays round between the
points. The radial noise is the same as before; the three-lobe
distortion of 1.5% now grows with --amount, so --amount 0 leaves the
shape round (renders within 0.02% of the pixels of the original circle)
instead of keeping the lobes. The files stay about the same size.
2026-11-26 14:46:57 +11:00
Vlad Lasky d3bd799ba0 rough.py: roughen rounded rects instead of skipping them
rect() returned early whenever rx or ry was set, so every rounded rect,
a common shape in posters and cards, stayed perfectly clean (r13b.svg:
five rounded rects, none touched).

A rounded rect is now built as four straight sides and four quarter-
ellipse cubics, with rx and ry resolved as lengths, a missing or auto
radius taken from the other one, and both clamped to half the width and
height as SVG does. The outline then goes through the same jitter as a
path. At --amount 0 it renders the same as the original rect.

Two details found on the way: a side of zero length (a pill whose
straight part vanishes) is dropped, since jittering the same point twice
drew a spike; and in any path, a segment that ends exactly at the start
of its subpath now reuses the jittered start point, which removes the
small kink where a closed outline met itself.
2026-11-26 14:46:57 +11:00
Vlad Lasky 57a14deca3 rough.py: wobble path arcs by turning them into cubic curves
Arc commands were copied through with only their end point moved, so
every A in a path stayed a perfect circular or elliptical arc, while
visuals.md says rough.py breaks curves. In r13a.svg the half circle, the
rotated ellipse and the chain of arcs came out machine smooth.

parse_path() now converts each arc to cubic Beziers of at most a quarter
turn, using the centre parameterisation from the SVG implementation
notes (radii scaled up when too small, zero radii drawn as a straight
segment). The cubics then go through the same jitter as other curves.
At --amount 0 the converted arcs render the same as the originals. An arc
with non-finite or absurd radii falls under the existing size check and
leaves the path unchanged.
2026-11-26 14:46:57 +11:00
Vlad Lasky f5768b44b4 rough.py: keep the vertex count of shapes that draw mid markers
Every point the jitter inserts is a vertex, and marker-mid draws a marker
at every vertex. In marker.svg the polyline with marker-mid="url(#dot)"
went from 2 mid dots to about 20, and in r11.svg the same happened to a
path whose marker-mid was inherited from its group. Circles and rects
inside that group, which never draw markers, sprouted a dot at every
point once they became paths.

A path, line, polyline or polygon whose marker-mid is set, directly, in
its style attribute (also through the marker shorthand) or inherited, now
keeps its own vertices: they are still jittered, but edges are not cut
into pieces and curves are not split. Rects, circles and ellipses that
inherit any marker get marker:none in their style when they become
paths, as they never showed markers before. Markers set by <style> rules
are not seen yet.
2026-11-26 14:46:51 +11:00
Vlad Lasky c4ce2ef9d5 rough.py: judge text size against the canvas
Text was sorted into calm, medium and strong shaking by fixed sizes (16
and 32 user units) and got the rough-edge filter from 28 units, with
baseFrequency fixed at 0.9 per user unit. So the same design drawn at
0.25x, 1x and 10x coordinates (sc025.svg, sc1.svg, sc10.svg) was treated
three ways: at 0.25x the 44-unit title shrank to 11 units, was kept calm
and got no edge filter.

Sizes are now measured against a 720-unit canvas diagonal in the text's
local units, so the thresholds keep their meaning on a 400x600 poster and
scale with everything else. The filter's baseFrequency and displacement
follow the same scale, with one filter per distinct scale. Font sizes
come from the style attribute, then the font-size attribute, then the
parent, through nested tspans as well; keywords such as large and smaller
count. After the change the three sc files get identical rotations and
the same filter relative to their size.
2026-11-26 14:46:20 +11:00
Vlad Lasky 947071bf39 rough.py: size the edge snap and the number rounding to the canvas
Points within 1 user unit of the canvas edge were pushed out by their
jitter plus 1 unit, and every coordinate was rounded to 2 decimals. Both
are absolute. In unit.svg (viewBox 0 0 1 1) the whole canvas counts as
the edge: the white line and the green square were pushed off the
canvas, and 0.01 rounding put visible steps in the circle. In icon24.svg
(viewBox 0 0 24 24) a 1-unit push is 4% of the icon.

The edge band is now 1/720 of the current viewport's diagonal (1 unit on
a 400x600 canvas, as before), and numbers keep enough decimals for
1/72000 of the canvas diagonal in the local units: 2 on 400x600, 5 on a
1x1 viewBox, 1 on a 10x canvas. The amp in the closing message is shown
to 3 significant digits instead of 2 decimals, so it no longer reads
0.00 on small canvases.
2026-11-26 14:45:14 +11:00
Vlad Lasky 947892e0b7 rough.py: scale the jitter by the transforms and nested viewports above a shape
The amplitude came from the root viewBox only, in root user units, and
was applied unchanged in every local coordinate system. In scaled.svg a
24-unit icon drawn inside scale(6), and the same icon in a nested
<svg viewBox="0 0 24 24"> 240 wide, got 6 and 10 times the intended
shake: the square turned into a skewed quad and the circle into a blob.
The nested <svg> also kept the outer canvas for its edge rule and for
resolving %.

The walk now tracks how large one local unit is in root units. Each
transform list is multiplied out and its largest singular value taken,
so a non-uniform scale never shakes harder than intended in any
direction; a nested <svg> adds its viewBox scale (meet, slice or none),
becomes the box for % lengths and edge snapping, and counts as a free
canvas edge again since it clips. Jitter, the step floor and the size
limit are divided by that scale. The small whole-shape offset is a
translate in the parent's system, so it uses the parent's scale.
Groups with a singular transform such as scale(0) draw nothing and are
skipped.
2026-11-26 14:45:14 +11:00
Vlad Lasky 5923835bd2 rough.py: resolve units in shape coordinates
line x1..y2, rect x/y/width/height and circle or ellipse cx/cy/r/rx/ry
were read with fnum(), which drops the unit. In r4.svg a line from 5% to
95% across a 400-wide canvas became a line from 5 to 95, and a circle
with r=10% shrank to radius 10. t2.svg had the same with x2="100%".
Rects with a % width were skipped outright.

These attributes now go through the same length resolver as dy: % against
the canvas width or height, or for r against the diagonal divided by
sqrt 2 as SVG defines it, em and ex against the element's font-size, and
the absolute units converted to user units. Full-canvas rects given as
100% are still recognised as the background and left alone.
2026-11-26 14:44:44 +11:00
Vlad Lasky 83f0f5a2bd rough.py: keep em-based tspan spacing so lines don't stack
shake() read a tspan's own dy with fnum(), which keeps only the number,
so dy="1.2em" in t1.svg (font-size 40) became 1.2 user units instead of
48. The three lines FIRST, SECOND and THIRD were drawn on top of each
other.

dy is now resolved as a length: em and ex against the element's own
font-size, % against the canvas height, and px, pt, pc, mm, cm, in, Q
and rem converted to user units. An unknown unit counts as 0, as SVG
does for an invalid length. Font sizes given in em or % are resolved
against the inherited size the same way, instead of being read as bare
numbers.
2026-11-26 14:44:32 +11:00
Vlad Lasky cd66a0eb10 rough.py: keep a line unfilled after it becomes a path
A <line> is never filled, but the <path> it was turned into is. With the
default black fill, or a fill inherited from a group or set in its own
style, the jittered line drew a filled sliver between its points (r2.svg
at --amount 2: black, red and blue wedges along three hairlines).

The converted line now gets fill:none in its style attribute. It goes in
the style attribute rather than a fill attribute, so that a stylesheet
rule such as path{fill:red} cannot fill it again.

The finding also named <polyline>, but a polyline is filled in SVG just
like the open path it becomes (the black wedge under the polyline in
r2.svg renders the same before and after), so it is left as it is.
2026-11-26 14:44:14 +11:00
Vlad Lasky df86cfc615 rough.py: keep a shape's children when it is turned into a path
to_path() called el.clear(), which also drops child elements, text and
tail. In t2.svg the <title>tooltip</title> inside a circle was lost, and
so were <desc>, <animate> and <set> children; the cleared tail also
pulled every following element onto one line.

Only the geometry attributes are now removed before the tag changes, so
children and whitespace stay. A shape whose geometry is animated (an
<animate> or <set> child whose attributeName is r, x1, width, points
and so on) is left as it is, because the animation would target an
attribute the path no longer has.
2026-11-26 14:44:14 +11:00
Vlad Lasky 81bdcca43c rough.py: stop with a clear message on very deep nesting
deep.svg, 3000 nested <g>, ended in a RecursionError traceback. Both
walk() and ElementTree's own writer recurse once per level, so anything
past about 1000 levels fails, and the writer cannot be made iterative
without replacing it.

The depth is now measured with a loop before any work, and a file nested
more than 500 levels deep stops with a message that says so. 500 leaves
room under Python's default limit of 1000 for both recursions on every
supported version; real drawings nest a few tens of levels at most.
Checked: 498 groups (500 levels with the root and the line) still runs on
Python 3.9 and 3.15, 499 and 3000 get the message.
2026-11-26 14:44:14 +11:00
Vlad Lasky f157372f2f rough.py: leave shapes with huge or infinite coordinates unchanged
A path with L1e300 1e300 (hugepath.svg) hung, a line to x2=1e9
(huge.svg) died with MemoryError and a rect with width=1e999 (inf.svg)
with OverflowError: the number of points per edge grew with the length,
and int() of an infinite count failed.

Shapes whose numbers are not finite or lie more than a million canvas
diagonals from the origin are now left as they are, since jitter means
nothing at that size and the output would be hundreds of KB of digits.
Each edge is also cut into at most 200 pieces, so a long line that does
fit (x2=1e7) stays small. A viewBox or width/height that is infinite or
not positive now stops the run with a message naming the size instead of
writing inf and nan coordinates.
2026-11-26 14:44:14 +11:00
Vlad Lasky 73db93c590 rough.py: bound the number of points a straight edge is broken into
steps() divided each edge length by amp*18 + 1e-6. With --amount 0 the
divisor was 1e-6, so a 400-unit line asked for 400 million points and
the run never finished (poster400.svg timed out after 10 s), and
--amount 0.001 turned a 1.3 KB poster into a 1.6 MB file.

The shortest piece an edge is cut into is now also at least 1/160 of the
canvas diagonal. At the default amount this floor is lower than amp*18,
so --amount 1 output is byte-identical to before; at 0 or tiny amounts
the poster now comes out at about 15 KB.
2026-11-26 14:44:14 +11:00
Vlad Lasky c65de3d658 rough.py: reject an --amount that is not a finite number of 0 or more
--amount was a plain float, so "--amount nan" crashed with "ValueError:
cannot convert float NaN to integer", "--amount inf" wrote paths such as
d="Minf,nan Linf,inf ..." that no renderer can draw, and "--amount -1"
was accepted with a negative amplitude. The value now goes through an
argparse type that stops with a usage error for anything that is not a
finite number of 0 or more.
2026-11-26 14:44:14 +11:00
Vlad Lasky 6953bcdf91 check.py: render the backdrop only for text with opacity, not for thin text
The see-through text check rendered the design once more without the
text whenever the text never reached alpha 250. Thin opaque text
also stays below 250, so every 12-14 px label of a 1440x900 interface
at the default 800 px width got an extra render: 82 renders instead
of 42 for many40.svg, and the run took twice as long (3.7 s to 7.3 s),
in a check that visuals.md already says can take minutes.

Decide from the opacity and fill-opacity set on the text and its
ancestors (attribute or inline style) instead. For other text the
cover check compares only the pixels the text covers almost fully
(alpha above 200), as before the see-through change; comparing the
partly covered pixels of thin text without the backdrop called every
label of the 1440x900 test interface 53-100% covered. Contrast still
uses the letter mask scaled by the strongest alpha.

Text at opacity 0.6 (bad_covered_faint: 95% covered) and 0.1
(bad_faint: low contrast) is still checked against the blend, the
regression set gives the same output as before this commit, and
many40.svg is back to 42 renders. Opacity set from a <style> sheet is
not seen; such text is cover-checked as opaque, as it was upstream.
2026-11-26 14:40:39 +11:00
Vlad Lasky 8822002a42 check.py: under cairosvg, check only the size of vertical text and say why
cairosvg ignores writing-mode and draws vertical text as one
horizontal line. A 30 px writing-mode="tb" word placed near the right
edge (TALL in good_rotated, VERTICALSMALLTEXT in feat.svg) was then
reported as running off the right edge, which it does not do in a
browser or in rsvg-convert. cairosvg is the usual renderer on Windows.

Under cairosvg, skip the edge, cover and contrast checks for text in a
vertical writing mode and print a note that the renders show it
sideways. Its letters keep their size when drawn sideways, so the size
check still runs on them (TINYVERTICALTEXTHERE at font-size 4 is still
reported).

The note for text on a textPath under rsvg-convert now uses the same
"note:" line.
2026-11-26 14:32:40 +11:00
Vlad Lasky 9e5d619a01 check.py: measure text size across the line, so rotated and vertical text is checked
The size check took the height of the text's bounding box. For text
turned by a transform the box height is the length of the line, so
5 px fine print rotated by -90 or -30 degrees (horiz.svg,
bad_small_rotated) passed while the same text set straight was
reported. Text with writing-mode="tb" (feat.svg, bad_small_vertical)
passed for the same reason. The visual seed axis "type set
vertically" makes both common.

Work out the direction of the line from the transforms of the text
and its ancestors (matrix, scale, rotate, skewX, skewY; translate does
not turn it) and the viewport scale, and measure the ink across that
direction. For vertical writing modes (tb, tb-rl, vertical-rl,
vertical-lr) the line runs down the page and the lines are counted by
x and dx. Horizontal, rotated (-90), diagonal (45) and nested-group
rotated 6 px text now all measure 1.0% of the side with rsvg-convert;
before, only the horizontal one was reported.

cairosvg ignores writing-mode and draws such text sideways, so under
cairosvg it is measured as the horizontal text it renders.
2026-11-26 14:31:17 +11:00
Vlad Lasky 38623fcb29 check.py: count the lines of a text by where they start, not by its tspans
The size check divided the text height by the number of direct
<tspan> children. A single line split into styled tspans, such as
<tspan font-weight="bold">LIVE</tspan> <tspan>MUSIC</tspan>
<tspan>FRIDAY</tspan> at font-size 20 or 24 (c1.svg, good_tspans),
was taken as three lines and called "very small, about 0.9% of the
image side" though it is a normal 2.6% line.

Follow the baseline through the text instead: each character takes
its position from the y and dy lists of its element (with em and ex
resolved against the font size, which is read from the element and
its ancestors), the baseline carries on after a tspan as in SVG, and
lines are the groups of characters whose baselines are more than half
the font size apart. Styled runs, superscripts and the per-letter dy
jitter that rough.py adds stay one line; dy="1.2em" lines, absolute y
lines and a y list that stacks one letter per row count each line.

Not followed: positions set from a <style> sheet, font sizes in CSS
classes (16 px is assumed), and a parent's y or dy list continuing
past a child tspan.
2026-11-26 14:30:17 +11:00
Vlad Lasky 669a37fae7 check.py: measure contrast as a luminance ratio
Contrast was the difference of the mean gamma-encoded luma of the
letters and of the ring around them, on a 0-255 scale, with 30 as the
limit. That number depends on where on the grey scale the pair sits,
and it passed pairs that are close to invisible: #ddd on white (WCAG
ratio 1.36), #fff on #fc0 (1.51), #0a0 on #f00 (1.29) and #555 on
#333 (1.69) all measured 31-35 and passed (contrast.svg,
bad_lowcontrast*.svg).

Use the WCAG relative luminance (linear sRGB) and the ratio
(L1 + 0.05) / (L2 + 0.05). Limits: 2:1 for large text and 3:1 for
small text, where large means a line at least twice --min-text tall
(2.4% of the image side by default, 1.2% with --min-text 0.6, which
is about 17 px on a 1440 px screen, close to the WCAG large-text
size). These are below the WCAG AA values (3:1 and 4.5:1) on purpose:
posters use quiet, low-contrast type on purpose (white on orange
#f60 is 2.94:1, red on blue 2.07:1), and every report makes the model
change the design. 2:1 still catches every near-invisible pair above,
and 3:1 is the WCAG floor for anything that must be read.

Two measuring fixes make the ratio usable on small text. The ring
around the letters no longer includes the antialiased edge pixels of
the text itself, which pulled the background towards the text colour.
The letter colour is un-mixed from the background using the per-pixel
coverage of the text render, so a pixel 85% covered by white counts
as white. Thin text in a scaled-down render still reads a little low:
white 14 px labels on #2a5 (3.0:1) in a 1440x900 interface measure
2.7:1 at the default 800 px width and 3.0:1 at --width 1440.
2026-11-26 14:22:05 +11:00
Vlad Lasky f77fb75e85 check.py: check see-through text instead of skipping it
The per-text render found the letters by alpha > 200, and its pixels
with alpha > 40. Text with opacity or fill-opacity below about 0.78
never reaches alpha 200, so the mask was empty and the cover and
contrast checks were silently skipped: in c2.svg, #eee text at
opacity 0.7 on white passed while the same colour at full opacity was
reported, and a red bar over text at opacity 0.6 (bad_covered_faint)
passed. Below opacity 0.16 the text was called "draws nothing" (FAINT
at 0.1 in bad_faint, FAINT GHOST TEXT at 0.06 in c1.svg), which sends
the model looking for a bug instead of a contrast problem.

Scale both thresholds by the strongest alpha the text reaches, and
keep "draws nothing" for text with no alpha at all (peak below 3 of
255). For see-through text, the full render shows the text blended
with what is behind it, so compare it with that blend: render the
design once more without this text (only for text whose peak alpha is
below 250) and mix it with the text by the text's alpha. Now c2.svg
reports both pale texts, bad_covered_faint is 95% covered, and the
faint texts report low contrast. Half-transparent white text over a
gradient, in a filtered group, with its own filter and on a
transparent ground all still pass, with rsvg-convert and cairosvg.
2026-11-26 14:12:03 +11:00
Vlad Lasky a1d6c54adc check.py: keep the path under text on a textPath, and say when rsvg-convert cannot draw it
Text on a <textPath> was always reported as "draws nothing". The
per-text renders hide every shape, including the <path> the textPath
follows, so the text had no path to sit on (c1.svg, ALONG THE CURVE).

Make the referenced paths transparent instead of hiding them, so the
text keeps its geometry. With cairosvg the text is now checked like
any other.

rsvg-convert (2.63) does not draw textPath at all, not even in the
full render. There the old "draws nothing" sent the model to fix text
that browsers show fine. Under rsvg-convert, text on a textPath that
draws nothing is now listed as not checked, with a note that it is
also missing from the renders and has to be checked by eye. It is no
longer counted as a problem or in "texts checked".
2026-11-26 14:10:59 +11:00
Vlad Lasky 4d6f034429 check.py: report text cut by a clip-path
The per-text renders kept clip-paths. Text inside a canvas-sized clip
(a common frame that keeps roughened shapes inside the image) was
clipped there too, so it never reached the margin and "runs off the
edge" was not reported: CUTOFF at x=250, font-size 60 in c1.svg and
bad_offedge_clip.svg passed, although half the word is cut away.

Drop clip-path (attribute and style) from every element in the
per-text renders, as filters already are. Text cut at the canvas edge
is now reported as running off; text cut by a smaller clip inside the
canvas is now reported by the cover check (WINDOWED clipped to a
150x80 window: 51% covered). Text inside a clip it fits in, and the
canvas-sized frame with text inside it, still pass.

Clip-paths set from a <style> sheet are not seen, as with filters.
2026-11-26 14:09:41 +11:00
Vlad Lasky f3d1b67b33 check.py: check text inside a filtered group for cover against an unfiltered render
Text whose parent group has a filter skipped the cover check. In
grpfilter2.svg a green bar drawn over PARTLY HID inside a grain-filtered
group went unreported (the same text outside the group: 67% covered),
and in grpfilter.svg a red box over COVERED came out as "low contrast
(0)" instead of covered.

The exclusion came in with 7f92b83, together with the no-filter render
for text that has its own filter. The per-text renders drop every
filter, so a displacement filter on a group moves the group's text in
the full render but not in the per-text render, and the edges no
longer match: removing the exclusion alone makes ROUGH in a
displacement-filtered group "6% covered".

Keep that purpose but restore the check: the no-filter render now
drops filters from every element, the same way the per-text renders
do, and any text with a filter on itself or an ancestor is compared
against it. Contrast is still measured on the real, filtered render.
2026-11-26 14:09:04 +11:00
Vlad Lasky 88ef36ff41 check.py: render with grey text antialiasing and paint-order under cairosvg
Through cairosvg nearly every text was reported covered. cairo draws
text with subpixel (colour) antialiasing on this system. On the
transparent per-text render the edge pixels then carry per-channel
coverage, which becomes colours such as (243, 255, 5) after
un-premultiplying, while the full render shows the same pixels as near
white. vbonly.svg (white HELLO on #123) was 11% covered, and a
1440x900 interface had its title 38% covered.

cairosvg picks subpixel only for the default text-rendering; any
explicit value gives grey antialiasing. Set text-rendering to
optimizeSpeed on the svg element (unless it sets its own), which
changes only the antialiasing mode, for every cairosvg render, so the
full render and the per-text renders agree. full.png changes the same
way.

cairosvg also ignores paint-order, so text with paint-order="stroke"
had its outline drawn over the fill. A white OUTLINE with a 4 px black
stroke on a dark ground read as black on dark: "low contrast (7)".
Under cairosvg, draw such text as a stroke-only copy under a
fill-only original, which is what paint-order="stroke" means.
rsvg-convert supports both and is unchanged.

Regression set under cairosvg: 15 false "covered" reports and one
false "low contrast" gone; no report that was correct went away.
Not tested with cairo on Windows, where the default font antialiasing
comes from the Windows font backend.
2026-11-26 14:08:02 +11:00
Vlad Lasky 4bce7f46ac check.py: warn about missing Korean and Chinese fonts too, and name the right language
The font check looked only for a Japanese font (fc-list :lang=ja) and
called any CJK text Japanese. With only Latin fonts installed, Korean
text (밤의 음악) passed without a warning although it renders as empty
boxes, and Chinese text (夜晚音乐) was reported as "Japanese text".

Find kana, hangul and Han characters separately and ask fontconfig
whether any installed font has one of them (fc-list :charset=<code>),
which is the question that decides whether boxes appear. Han
characters with kana are Japanese, with hangul Korean, otherwise
Chinese. Suggest the matching Noto Sans CJK font.

Checked with FONTCONFIG_FILE pointing at three font sets: Latin only
(Japanese, Korean and Chinese each reported, mixed text gives two
lines), Latin plus a Japanese font (only Korean reported) and Latin
plus a Korean font that also has kana and Han (nothing reported).

Also drop the docstring, which CONTRIBUTING.md does not allow.
2026-11-26 14:06:49 +11:00
Vlad Lasky a157c67258 check.py: give each run its own output folder and always remove scratch files
Renders went to <tempdir>/antialgorithm_check/<file name>, so two
files called final.svg in different folders, or two runs at once (the
skill suggests running long checks in the background), wrote over each
other's full.png and small.png. Two final.svg files checked in
parallel both reported .../antialgorithm_check/final/full.png.

The per-text renders went to a mkdtemp folder that was removed only at
the very end, so any failure on the way left it behind (shown with an
rsvg-convert that fails on the second text: the tmpXXXX folder
stayed). The _nofilter render was written into the output folder.

Without --out, make a fresh <file name>-XXXXXXXX folder under
antialgorithm_check for each run; the script prints its paths, so
nothing else needs to know the name. Put all scratch files in one temp
folder that main() removes in a finally block. --out works as before.

Runs no longer overwrite earlier renders, so old folders stay in the
temp directory until the system clears it.
2026-11-26 14:05:43 +11:00
Vlad Lasky 885f857cf7 check.py: stop with a one-line message on bad input instead of a traceback
These inputs ended in a Python traceback, which tells the model nothing
it can act on:

- an empty file, malformed XML or a gzip-compressed .svgz (ParseError),
  and a missing file (FileNotFoundError);
- --width 0, --width -5 or --small 0 (bare CalledProcessError, with
  the rsvg-convert stderr thrown away);
- --width 20000 (Pillow DecompressionBombError) and a 100x3000 design
  at --width 4000 (rsvg-convert refused the size);
- about 3000 nested <g> elements (RecursionError under cairosvg).

--min-text nan or -1 was accepted and turned the size check off.

Validate the options in argparse (--width 100 to 4000, --small 8 to
1024, --min-text 0 to 100; nan fails the range test), read the file
with a short message for each failure, name svgz files, keep the
stderr of rsvg-convert and the message of cairosvg when they fail,
refuse renders larger than the Pillow limit before making them, and
turn a RecursionError into a message. Each case now prints one line
and exits non-zero.

The cairosvg exceptions are listed by type rather than caught with a
bare Exception, so a programming error still shows its traceback.
2026-11-26 14:03:43 +11:00
Vlad Lasky a8dfa6bf76 check.py: ignore the part-covered last row when looking for see-through parts
When the render height is not a whole number of pixels, for example a
600x500 design at 800 px wide (666.67 px) or 1080x1920 (1422.2 px), the
last row of the full render is only partly covered and its alpha is
below 250. The "background has see-through parts" note was then
printed for fully opaque designs, and contrast was also measured on
black for no reason.

Look for see-through pixels only in the rows that lie wholly inside
the canvas. Verified on o600x500.svg and a 1080x1920 poster (note
gone, with rsvg and cairosvg) and on a design with no background and
the mismatch.svg letterbox (note still printed).
2026-11-26 14:01:43 +11:00
Vlad Lasky af1fd3d16f check.py: map the canvas the way the renderer does
The canvas was taken from the viewBox alone, or from width and height
when there was no viewBox. Three things went wrong:

- When width/height and the viewBox have different shapes, the
  renderer fits the viewBox into the viewport (preserveAspectRatio,
  meet by default), but the per-text renders used the viewBox shape.
  mismatch.svg (viewBox 400x600, width 400, height 400) and a
  400x600 poster shown in a 600x600 viewport had every text called
  "covered" or "runs off the bottom edge".
- width="100%" (or "auto", or missing) with no viewBox was read as
  100x100 (nowh.svg), and width="auto" with no viewBox crashed with
  AttributeError.
- A viewBox with only one of width/height renders as 800x600 under
  cairosvg instead of 800x1200, so the renders did not line up.

Work out the viewport size in px (width/height with their units, or
from the viewBox aspect when one is missing or a percentage), then the
part of the user space it shows, following preserveAspectRatio
(xMin/Mid/Max, meet, slice, none). The per-text renders map that
region to the same pixels with preserveAspectRatio="none", so the
scale may differ per axis. When the renderers would disagree on the
size, render a copy with explicit width and height. After the full
render, stop with a one-line message if its size is not the expected
one (for example CSS width on the svg element). An SVG with no viewBox
and no fixed width and height has no defined canvas, so ask for a
viewBox instead of guessing. A viewBox with zero or negative size
draws nothing; say so instead of dividing by zero.

Text size is now measured against the rendered image side, which is
the same number as before for files whose shapes agree.
2026-11-26 14:01:18 +11:00
Vlad Lasky 199bceb6b6 check.py: line up the padded render so portrait text isn't called covered
Each text is rendered on its own with a margin of a quarter of the
image side, then compared pixel by pixel with the full render. The
margin was pad * scale pixels, a fraction, but the comparison cut the
render at round(pad * scale). On portrait canvases such as 1080x1920,
360x640, 390x844, 333x517 and 357x499 at the default 800 px width the
two images were half a pixel apart, and every text on a plain white
ground was reported 14-17% covered.

Choose the margin as a whole number of pixels first and derive the
user-unit margin from it, so the solo render sits exactly p pixels
in from the full render.
2026-11-26 13:57:46 +11:00
Vlad Lasky 9411daa610 history.py, seed.py, moves.py: skip malformed history rows
One bad row in history.jsonl broke both scripts until the file was
deleted by hand:

- a byte that is not UTF-8 (`{"type":"move","move":"x \xff"}`) raised
  UnicodeDecodeError in load();
- a line that is valid JSON but not an object (`5`, `null`) raised
  AttributeError on entry.get();
- `"seed": null` or `"seed": ["a"]` raised AttributeError in
  load_recent(), and `"seed": {"color": ["a"]}` raised an unhashable
  TypeError in pick();
- a move row without "move" raised KeyError in the listing.

load() now decodes with errors="replace", so a stray byte costs one
character instead of the whole file, and returns only JSON objects.
load_recent() skips seeds that are not objects and values that are not
strings, and moves.py lists only rows whose move is a string. Bad shapes
are filtered out before the recent-seed and --last slices, so they don't
take a slot from a good row.

This is one finding across three files: the reader and both consumers
each crashed on a different shape of the same corrupt file. Rows that
are JSON objects are written back unchanged by the next add, so no good
row is lost; only lines that are not JSON objects drop out.
2026-11-26 13:57:42 +11:00
Vlad Lasky 3caf74aa65 history.py: split history on newlines only and skip a BOM
load() used str.splitlines(), which also splits on U+2028, U+2029,
U+0085, form feed and the other Unicode line breaks. json.dumps with
ensure_ascii=False writes those raw, so `moves.py add "a<U+2028>b"`
printed "saved:" but the row came back as two broken halves: the next
listing said "no moves saved yet", and the next add rewrote the file
without it.

A UTF-8 BOM, as left by Notepad, made the first line fail to parse, so
that row was dropped silently and erased at the next write.

Rows are written one per "\n", so split on "\n" alone, and read with
utf-8-sig so a leading BOM is skipped. newline="" keeps a "\r" from a
CRLF edit at the end of its line, where json.loads ignores it.
2026-11-26 13:57:42 +11:00
Vlad Lasky a2519e6216 history.py: resolve the history path before using it
ANTIALGORITHM_HISTORY=rel.jsonl made every write fail, because
os.makedirs(os.path.dirname("rel.jsonl")) is os.makedirs("") and raises
FileNotFoundError. A directory in ANTIALGORITHM_HISTORY raised
IsADirectoryError, "~/x.jsonl" created a folder literally named "~" in
the current directory, and a relative XDG_STATE_HOME was used as given,
although the XDG Base Directory spec says relative paths are invalid and
must be ignored.

Now ANTIALGORITHM_HISTORY is tilde-expanded and made absolute, a
directory there means history.jsonl inside it, and XDG_STATE_HOME is used
only when it is absolute, falling back to ~/.local/state.
2026-11-26 13:57:42 +11:00
Vlad Lasky 11edce7cef seed.py: write stdout as UTF-8
When stdout is a pipe on Windows, Python writes with the ANSI code page.
`seed.py visual --keep "region=Łódź"` under PYTHONIOENCODING=cp1252
raised UnicodeEncodeError while printing the region, so the seed was cut
off and no history row was saved. moves.py and check.py already write
UTF-8 for the same reason (ae1458e); do the same here.
2026-11-26 13:55:49 +11:00
Vlad Lasky 150b06f22a README: say that text and idea seeds also give a setting, region and object
seed.py adds setting, region and anchor to every seed kind (roll_once), but the README listed them only for visual seeds. A text seed, for example, prints voice, entry, register, setting, region and anchor.
2026-11-26 13:47:38 +11:00
mankidev a6392c0d35 Added README translations, star chart and contributing guide 2026-11-20 20:08:32 +03:00
mankidev 5ca280b4b7 Added the icon to the README 2026-11-20 19:52:24 +03:00
mankidev aef169a928 Added badges to the README 2026-11-20 19:49:33 +03:00
mankidev 1f4ae9080b Added plugin icon 2026-11-20 19:48:01 +03:00
mankidev aa279bbb3d Made the skill text agent neutral 2026-11-20 19:40:58 +03:00
mankidev 21e2dca3ec Made the README agent neutral 2026-11-20 19:39:52 +03:00
19 changed files with 1888 additions and 234 deletions

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+49
View File
@@ -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.
+36 -22
View File
@@ -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>
![Six posters without the skill on top, six with it below](images/showcase.png)
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>
+3 -3
View File
@@ -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.
+68
View File
@@ -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>
![Oben sechs Plakate ohne den Skill, unten sechs mit ihm](../images/showcase.png)
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.
![Diagramm, wie oft eine Wahl getroffen wird: ein hoher Gipfel um den Durchschnitt, als sichere Zone markiert, auf beiden Seiten flach](../images/graph.png)
## 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>
+68
View File
@@ -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>
![Arriba, seis carteles sin la skill; abajo, seis con ella](../images/showcase.png)
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.
![Gráfica de cuántas veces se elige una opción: un pico alto alrededor de la media marcado como zona segura, plano a ambos lados](../images/graph.png)
## 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>
+68
View File
@@ -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>
![En haut, six affiches sans le skill ; en bas, six avec](../images/showcase.png)
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.
![Graphique de la fréquence à laquelle un choix est fait : un pic haut autour de la moyenne, marqué zone sûre, plat des deux côtés](../images/graph.png)
## 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>
+68
View File
@@ -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>
![上はスキルなしのポスター6枚、下はスキルありの6枚](../images/showcase.png)
クリエイティブな作業のためのエージェントスキルです。対象は名前、ストーリー、ゲームのアイデア、ポスター、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枚も外していません。下の段は、スキルを書いている途中に実行した十数回の中から選んだものです。
![ある選択が選ばれる頻度のグラフ:平均のまわりに安全地帯と書かれた高い山があり、両側は平ら](../images/graph.png)
## インストール
[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>
+68
View File
@@ -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>
![위는 스킬 없이 만든 포스터 여섯 장, 아래는 스킬을 쓴 여섯 장](../images/showcase.png)
창작 작업을 위한 에이전트 스킬: 이름, 이야기, 게임 아이디어, 포스터, UI. 모델이 처음 떠올린 가장 평균적인 선택을 먼저 말하게 하고, 프로젝트에서 가져온 이유를 들어 그 선택에서 벗어나게 합니다.
두 줄 모두 같은 프롬프트에서 나왔습니다: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` 윗줄은 스킬 없이 한 번에 돌린 여섯 개로, 하나도 빼지 않았습니다. 아랫줄은 스킬을 아직 쓰는 중에 돌린 열두 번 정도의 결과에서 골랐습니다.
![어떤 선택이 얼마나 자주 선택되는지 보여 주는 그래프: 평균 근처에 안전 지대라고 표시된 높은 봉우리가 있고 양옆은 평평함](../images/graph.png)
## 설치
[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>
+68
View File
@@ -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>
![Em cima, seis pôsteres sem a skill; embaixo, seis com ela](../images/showcase.png)
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.
![Gráfico de quantas vezes uma escolha é feita: um pico alto em torno da média marcado como zona segura, plano dos dois lados](../images/graph.png)
## 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>
+68
View File
@@ -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>
![Сверху шесть постеров без скилла, снизу шесть со скиллом](../images/showcase.png)
Скилл для агентов для творческой работы: названия, истории, идеи для игр, постеры, интерфейсы. Он заставляет модель сначала назвать свой первый, самый усреднённый вариант, а потом уйти от него по причине, взятой из проекта.
Оба ряда получены из одного и того же промпта: `Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` Верхний ряд: шесть запусков без скилла подряд, ни один не выброшен. Нижний ряд отобран примерно из дюжины запусков, сделанных, пока скилл ещё писался.
![График того, как часто выбирают вариант: высокий пик вокруг среднего, отмеченный как безопасная зона, по бокам ровно](../images/graph.png)
## Установка
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>
+68
View File
@@ -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>
![Üstte skill olmadan altı poster, altta skill ile altı poster](../images/showcase.png)
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.
![Bir seçimin ne sıklıkla yapıldığını gösteren grafik: ortalamanın çevresinde güvenli bölge diye işaretlenmiş yüksek bir tepe, iki yanı düz](../images/graph.png)
## 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>
+68
View File
@@ -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>
![上面是不用技能的六张海报,下面是用了技能的六张](../images/showcase.png)
面向创意工作的智能体技能:名字、故事、游戏点子、海报、界面。它让模型先说出自己第一个、最平均的选择,再根据从项目里找到的理由离开这个选择。
两行海报来自同一个提示词:`Design a poster for a music festival as a 400x600 SVG. Save the final SVG as final.svg in the current folder.` 上面一行是不加技能时一次跑出的六张,一张没删。下面一行是在技能还在编写时,从大约十二次运行里挑出来的。
![一个选择被选中频率的图表:平均值附近有一个高峰,标为安全区,两侧平坦](../images/graph.png)
## 安装
[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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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.