graph-graphics 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. graph_graphics-0.0.1.dist-info/METADATA +81 -0
  2. graph_graphics-0.0.1.dist-info/RECORD +49 -0
  3. graph_graphics-0.0.1.dist-info/WHEEL +5 -0
  4. graph_graphics-0.0.1.dist-info/entry_points.txt +2 -0
  5. graph_graphics-0.0.1.dist-info/licenses/LICENSE +131 -0
  6. graph_graphics-0.0.1.dist-info/licenses/LICENSE-ARTWORK +407 -0
  7. graph_graphics-0.0.1.dist-info/licenses/LICENSING.md +30 -0
  8. graph_graphics-0.0.1.dist-info/top_level.txt +1 -0
  9. graph_ics/__init__.py +46 -0
  10. graph_ics/__main__.py +4 -0
  11. graph_ics/animation.py +232 -0
  12. graph_ics/cli.py +121 -0
  13. graph_ics/colonies.py +145 -0
  14. graph_ics/color_fields.py +29 -0
  15. graph_ics/colors.py +17 -0
  16. graph_ics/contours.py +207 -0
  17. graph_ics/coverage.py +151 -0
  18. graph_ics/data/README.md +18 -0
  19. graph_ics/data/__init__.py +1 -0
  20. graph_ics/data/spain_population.json.gz +0 -0
  21. graph_ics/data/spain_population_sources.json +33 -0
  22. graph_ics/data/uk_population.json.gz +0 -0
  23. graph_ics/data/uk_population_sources.json +33 -0
  24. graph_ics/drawing.py +30 -0
  25. graph_ics/edge.py +72 -0
  26. graph_ics/fields.py +134 -0
  27. graph_ics/gallery.py +118 -0
  28. graph_ics/gallery_page.py +95 -0
  29. graph_ics/graph.py +548 -0
  30. graph_ics/growth.py +403 -0
  31. graph_ics/logo.py +144 -0
  32. graph_ics/node.py +92 -0
  33. graph_ics/obj.py +5 -0
  34. graph_ics/option_gallery.py +178 -0
  35. graph_ics/py.typed +0 -0
  36. graph_ics/quality.py +42 -0
  37. graph_ics/rendering.py +159 -0
  38. graph_ics/replay.py +314 -0
  39. graph_ics/samples.py +206 -0
  40. graph_ics/scene.py +103 -0
  41. graph_ics/scene_gallery.py +86 -0
  42. graph_ics/site_paths.py +33 -0
  43. graph_ics/site_structure.py +149 -0
  44. graph_ics/spatial.py +86 -0
  45. graph_ics/styles.py +98 -0
  46. graph_ics/text.py +114 -0
  47. graph_ics/uk.py +48 -0
  48. graph_ics/validation.py +45 -0
  49. graph_ics/vector.py +28 -0
graph_ics/fields.py ADDED
@@ -0,0 +1,134 @@
1
+ """World-coordinate scalar fields and bounded spatial style controls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from math import floor, isfinite, sqrt
8
+ from pathlib import Path
9
+ from typing import Literal, Protocol
10
+ import sys
11
+
12
+ from .spatial import Bounds, validate_bounds
13
+
14
+
15
+ class ScalarField(Protocol):
16
+ def sample(self, x: float, y: float) -> float: ...
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ConstantField:
21
+ value: float
22
+
23
+ def __post_init__(self) -> None:
24
+ if not isfinite(self.value): raise ValueError('Field value must be finite')
25
+
26
+ def sample(self, x: float, y: float) -> float:
27
+ return self.value
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class CallableField:
32
+ function: Callable[[float, float], float]
33
+
34
+ def sample(self, x: float, y: float) -> float:
35
+ value = self.function(x, y)
36
+ if not isfinite(value): raise ValueError('Field returned a nonfinite value')
37
+ return value
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class ImageField:
42
+ """Bilinear scalar raster; row zero maps to min_y (screen-down coordinates).
43
+
44
+ Pixel centers at the first/last row and column map to the world bounds.
45
+ Values may be any finite scalars. PNG loading maps a selected channel from
46
+ [0,1] to value_range; RGB is unpremultiplied, transparent RGB becomes zero.
47
+ """
48
+ pixels: tuple[tuple[float, ...], ...]
49
+ bounds: Bounds
50
+ outside: Literal['clamp', 'constant', 'error'] = 'clamp'
51
+ outside_value: float = 0.0
52
+
53
+ def __post_init__(self) -> None:
54
+ validate_bounds(self.bounds)
55
+ if self.bounds[0] == self.bounds[2] or self.bounds[1] == self.bounds[3]: raise ValueError('Image world bounds need positive area')
56
+ if not self.pixels or not self.pixels[0] or any(len(row) != len(self.pixels[0]) for row in self.pixels): raise ValueError('Raster must be rectangular and nonempty')
57
+ if not all(isfinite(v) for row in self.pixels for v in row) or not isfinite(self.outside_value): raise ValueError('Raster values must be finite')
58
+ if self.outside not in ('clamp', 'constant', 'error'): raise ValueError('Invalid out-of-range policy')
59
+
60
+ def sample(self, x: float, y: float) -> float:
61
+ if not isfinite(x) or not isfinite(y): raise ValueError('Sample coordinates must be finite')
62
+ x0, y0, x1, y1 = self.bounds
63
+ if not (x0 <= x <= x1 and y0 <= y <= y1):
64
+ if self.outside == 'error': raise ValueError('Sample lies outside image bounds')
65
+ if self.outside == 'constant': return self.outside_value
66
+ u = min(1, max(0, (x-x0)/(x1-x0)))*(len(self.pixels[0])-1)
67
+ v = min(1, max(0, (y-y0)/(y1-y0)))*(len(self.pixels)-1)
68
+ i, j = floor(u), floor(v)
69
+ k, next_row = min(i+1, len(self.pixels[0])-1), min(j+1, len(self.pixels)-1)
70
+ a = self.pixels[j][i]*(1-(u-i))+self.pixels[j][k]*(u-i)
71
+ b = self.pixels[next_row][i]*(1-(u-i))+self.pixels[next_row][k]*(u-i)
72
+ return a*(1-(v-j))+b*(v-j)
73
+
74
+ @classmethod
75
+ def from_png(cls, path: str | Path, bounds: Bounds, *, channel: Literal['red', 'green', 'blue', 'alpha', 'luminance'] = 'luminance',
76
+ value_range: tuple[float, float] = (0, 1), outside: Literal['clamp', 'constant', 'error'] = 'clamp', outside_value: float = 0) -> ImageField:
77
+ import cairo
78
+ if channel not in ('red', 'green', 'blue', 'alpha', 'luminance'): raise ValueError('Unknown image channel')
79
+ if not all(isfinite(v) for v in value_range): raise ValueError('Image range must be finite')
80
+ image = cairo.ImageSurface.create_from_png(str(path))
81
+ image.flush()
82
+ data, stride = image.get_data(), image.get_stride()
83
+ rows: list[tuple[float, ...]] = []
84
+ for y in range(image.get_height()):
85
+ row: list[float] = []
86
+ for x in range(image.get_width()):
87
+ offset = y*stride+x*4
88
+ pixel = int.from_bytes(data[offset:offset+4], sys.byteorder)
89
+ alpha = 255 if image.get_format() == cairo.FORMAT_RGB24 else (pixel >> 24) & 255
90
+ r, g, b = (((pixel >> shift) & 255)/alpha if alpha else 0.0 for shift in (16, 8, 0))
91
+ value = {'red': r, 'green': g, 'blue': b, 'alpha': alpha/255, 'luminance': 0.2126*r+0.7152*g+0.0722*b}[channel]
92
+ row.append(value_range[0]+value*(value_range[1]-value_range[0]))
93
+ rows.append(tuple(row))
94
+ return cls(tuple(rows), bounds, outside, outside_value)
95
+
96
+
97
+ def positive_sample(field: ScalarField | None, x: float, y: float, default: float = 1) -> float:
98
+ value = default if field is None else field.sample(x, y)
99
+ if not isfinite(value) or value <= 0: raise ValueError('Style and density fields must return positive finite values')
100
+ return value
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class SpatialFields:
105
+ """Scale multipliers are independent; density is nodes per square world unit.
106
+
107
+ coordinated_scale links radius, buffer, gap, length, and thickness. Density
108
+ derives preferred center spacing as 1/sqrt(density), not an exact count.
109
+ """
110
+ radius: ScalarField | None = None
111
+ length: ScalarField | None = None
112
+ thickness: ScalarField | None = None
113
+ density: ScalarField | None = None
114
+ coordinated_scale: ScalarField | None = None
115
+ scale_limits: tuple[float, float] = (0.1, 10)
116
+ spacing_limits: tuple[float, float] = (0.1, 10000)
117
+ ring_ratio: float | None = None
118
+ refinement_steps: int = 6
119
+
120
+ def __post_init__(self) -> None:
121
+ for low, high in (self.scale_limits, self.spacing_limits):
122
+ if not isfinite(low) or not isfinite(high) or not 0 < low <= high: raise ValueError('Require positive finite ordered limits')
123
+ if self.ring_ratio is not None and (not isfinite(self.ring_ratio) or not 0 <= self.ring_ratio < 1): raise ValueError('Ring ratio must be in [0,1)')
124
+ if type(self.refinement_steps) is not int or not 1 <= self.refinement_steps <= 32: raise ValueError('Refinement steps must be between 1 and 32')
125
+
126
+ def scale(self, field: ScalarField | None, x: float, y: float) -> float:
127
+ value = positive_sample(field, x, y)*positive_sample(self.coordinated_scale, x, y)
128
+ if not isfinite(value): raise ValueError('Combined scale overflowed')
129
+ return min(self.scale_limits[1], max(self.scale_limits[0], value))
130
+
131
+ def spacing(self, x: float, y: float) -> float:
132
+ if self.density is None: return 0
133
+ value = 1/sqrt(positive_sample(self.density, x, y))
134
+ return min(self.spacing_limits[1], max(self.spacing_limits[0], value))
graph_ics/gallery.py ADDED
@@ -0,0 +1,118 @@
1
+ """Reproducible visual catalogue with palette filters, explanations, and timings."""
2
+ from dataclasses import asdict
3
+ from html import escape
4
+ from pathlib import Path
5
+ from time import perf_counter
6
+ import json
7
+ import platform
8
+ import importlib.metadata
9
+ import networkx as nx
10
+ from .samples import EXAMPLES, build_example, explain_option, describe_example
11
+ from typing import Any
12
+ from collections.abc import Sequence, Mapping
13
+ from .gallery_page import gallery_page, page_content
14
+ from .styles import GraphStyle
15
+ from .rendering import export_graph
16
+ from .validation import validate_graph
17
+ from .option_gallery import generate_controls
18
+
19
+
20
+ def generate_gallery(output: str | Path = 'docs', *, quick: bool = False, all_palettes: bool = False) -> Path:
21
+ destination = Path(output)
22
+ from .site_paths import arrange_pages
23
+ arrange_pages(destination, flat=True)
24
+ figures = destination/'figures'
25
+ figures.mkdir(parents=True, exist_ok=True)
26
+ regular = [example for example in EXAMPLES if example.target_nodes < 1000]
27
+ palettes = GraphStyle.palette_names()
28
+ selected = ('arctic','arctic','linen','blueprint','aurora','porcelain','forest','arctic','orchid','ember','forest','blueprint','linen','porcelain','porcelain','porcelain','porcelain','porcelain','porcelain','blueprint')
29
+ cases = [(example, palette) for example in regular[:3] for palette in ('arctic','ember')] if quick else [(example, palette) for example in regular for palette in palettes] if all_palettes else list(zip(regular, selected))
30
+ if not quick:
31
+ cases.extend((example, palette) for example, palette in zip(EXAMPLES[-3:], ('arctic', 'aurora', 'blueprint')))
32
+ cases.extend((example, palette) for example in EXAMPLES if example.name in ('uk_population','uk_density_only','uk_colors','spain_population') for palette in ('porcelain','arctic'))
33
+ records: list[dict[str, object]] = []
34
+ for spec, palette in cases:
35
+ graph = build_example(spec.name, palette=palette, nodes=120 if quick else None)
36
+ initial = len(graph.nodes)
37
+ started = perf_counter()
38
+ graph.build()
39
+ generation_seconds = perf_counter()-started
40
+ started = perf_counter()
41
+ validation = validate_graph(graph)
42
+ validation_seconds = perf_counter()-started
43
+ style = GraphStyle.named(palette)
44
+ stem = f'{spec.name}-{palette}'
45
+ started = perf_counter()
46
+ dimensions = export_graph(graph, figures/f'{stem}.png', frame='region', margin=16, background=style.background)
47
+ export_graph(graph, figures/f'{stem}.svg', frame='region', margin=16, background=style.background)
48
+ render_seconds = perf_counter()-started
49
+ run = graph.growth()
50
+ accepted = len(graph.nodes)+run.removed_nodes-initial+run.loops_added+run.bridges_added
51
+ command = f'python -m graph_ics render --example {spec.name} --palette {palette} --seed 7'+(' --nodes 120' if quick else '')+f' --output examples/output/{stem}.png'
52
+ report: dict[str, object] = dict(example=spec.name, palette=palette, seed=7, fill_area=run.settings.fill_area, target_nodes=graph.target_nodes, nodes=len(graph.nodes), edges=len(graph.edges),
53
+ dimensions=dimensions, attempts=run.attempts, accepted_attempts=accepted, rejected_attempts=run.attempts-accepted, status=run.status.value,
54
+ generation_seconds=generation_seconds, validation_seconds=validation_seconds, render_seconds=render_seconds,
55
+ validation=asdict(validation), quality=asdict(run.quality_report()), components=nx.number_connected_components(graph.to_networkx()),
56
+ command=command, options=spec.options, explanation=spec.explanation, limitation=spec.limitation)
57
+ if run.coverage is not None: report['coverage'] = asdict(run.coverage_report())
58
+ if graph.contours is not None: report['contours'] = asdict(graph.contour_report())
59
+ records.append(report)
60
+ print(f'{stem}: {len(graph.nodes)} nodes, {generation_seconds:.2f}s growth, {validation_seconds:.2f}s validation', flush=True)
61
+ environment = dict(python=platform.python_version(), platform=platform.platform(), dependencies={name: importlib.metadata.version(name) for name in ('graph-ics', 'shapely', 'networkx', 'pycairo')})
62
+ (destination/'manifest.json').write_text(json.dumps(dict(environment=environment, quick=quick, all_palettes=all_palettes, cases=records), indent=2)+'\n', encoding='utf-8')
63
+ from .logo import generate_logos
64
+ generate_logos(destination/'logo')
65
+ generate_controls(destination)
66
+ write_gallery_index(destination, records, quick=quick)
67
+ from .site_structure import build_structure
68
+ build_structure(destination)
69
+ arrange_pages(destination)
70
+ return destination/'index.html'
71
+
72
+
73
+ def write_gallery_index(destination: Path, records: Sequence[Mapping[str, Any]], *, quick: bool = False) -> None:
74
+ """Present measured outputs without rerunning generation or changing their metadata."""
75
+ cards: list[str] = []
76
+ for record in records:
77
+ spec = describe_example(str(record['example']))
78
+ palette = str(record['palette'])
79
+ style = GraphStyle.named(palette)
80
+ stem = f'{spec.name}-{palette}'
81
+ dimensions = record['dimensions']
82
+ swatches = ''.join(f'<span title="{color}" style="background:{color}"></span>' for color in (style.node_color, style.edge_color, style.background or '#ffffff'))
83
+ notes = ''.join(f'<li><code>{escape(option)}</code>: {escape(explain_option(option))}</li>' for option in spec.options)
84
+ count = f"{record['nodes']:,} nodes"
85
+ if record.get('fill_area'): count += f" (cap {record['target_nodes']:,})"
86
+ elif record['nodes'] < record['target_nodes']: count += f" of {record['target_nodes']:,} requested"
87
+ title = spec.title.replace(' / large', '').replace(' experiment', ' (experimental)')
88
+ coverage = record.get('coverage', {})
89
+ coverage_note = f'<p class="hint">Coverage: {coverage.get("occupied_tiles",0)}/{coverage.get("usable_tiles",0)} tiles contain nodes. Tile occupancy is not exact area coverage.</p>' if coverage else ''
90
+ cards.append(f'<article data-palette="{palette}" data-example="{spec.name}" data-large="{str(spec.target_nodes >= 1000).lower()}">'
91
+ f'<a class="image-link" href="figures/{stem}.png" aria-label="Open {escape(title)} in {palette}"><img loading="lazy" src="figures/{stem}.png" alt="{escape(title)} in {palette}"></a>'
92
+ f'<div class="swatches" aria-label="Palette colours">{swatches}</div><h2>{escape(title)}</h2><p class="meta">{palette.title()} &middot; {count}<br>{dimensions[0]} &times; {dimensions[1]}</p>'
93
+ f'<p>{escape(spec.explanation)}</p><div class="downloads"><a href="figures/{stem}.png" download>Download PNG</a><a href="figures/{stem}.svg" download>Download SVG</a></div>'
94
+ f'<details><summary>Options, limits, and command</summary><ul>{notes}</ul><p class="notice">{escape(spec.limitation)}</p><pre class="command">{escape(str(record["command"]))}</pre>'
95
+ f'{coverage_note}<p class="hint">Seed {record["seed"]}. {record["attempts"]:,} placement attempts; {record["generation_seconds"]:.2f}s growth. Stop: {escape(str(record["status"]).replace("_", " "))}.</p></details></article>')
96
+ palettes = sorted({str(record['palette']) for record in records})
97
+ names = sorted({str(record['example']) for record in records})
98
+ palette_options = ''.join(f'<option value="{name}">{name.title()}</option>' for name in palettes)
99
+ example_options = ''.join(f'<option value="{name}">{escape(describe_example(name).title)}</option>' for name in names)
100
+ mode = 'Quick preview' if quick else 'Example library'
101
+ content = f'<header class="intro"><span class="eyebrow">{mode}</span><h1>Art grown from connections.</h1><p>graph_ics is a visual art project and Python library for growing sprawling networks. Shape them with text, boundaries and spatial maps, then export still images or animate their growth.</p><div class="paths"><a class="button" href="#examples">Explore the artwork</a><a class="button" href="#start">Make your first graph</a></div></header>'
102
+ hero = next((record for record in records if record['example'] == 'arctic_atlas'), records[0]) if records else None
103
+ if (destination/'logo/figures/landscape@2x.png').exists(): content = '<div class="hero">'+content+'<a href="logo/index.html"><img src="logo/figures/landscape@2x.png" alt="graph_ics wordmark in a continuing graph network"></a></div>'
104
+ elif hero is not None: content = '<div class="hero">'+content+f'<a href="figures/{hero["example"]}-{hero["palette"]}.png"><img src="figures/{hero["example"]}-{hero["palette"]}.png" alt="graph_ics network artwork"></a></div>'
105
+ content += '<section id="examples"><h2>Find your starting point</h2><p class="hint">New here? Start with Sprawling coverage or Text with breathing room. The visual guide compares shapes, connections and angles side by side. Click any image to inspect its full resolution.</p>'
106
+ if quick: content += '<p class="notice">This is the six-scene preview. Run <code>graph-ics gallery</code> without <code>--quick</code> for all recipes and large compositions. Add <code>--all-palettes</code> for every recipe-colour combination.</p>'
107
+ content += '<div class="filters" role="search" aria-label="Filter examples"><label>Search<input id="search" type="search" placeholder="Try angles, text, density..."></label><label>Palette<select id="palette"><option value="">All palettes</option>'+palette_options+'</select></label><label>Example<select id="example"><option value="">All examples</option>'+example_options+'</select></label><label class="check"><input id="large" type="checkbox"> Large compositions</label><button id="reset" type="button">Reset</button><span id="count" aria-live="polite"></span></div><noscript>All examples are shown below. Search, filters and command-copy buttons need JavaScript; images and downloads work without it.</noscript><div class="cards">'+''.join(cards)+'</div><p id="empty" hidden>No examples match. Try a different filter or reset the selection.</p><button id="more" type="button" hidden>Show more examples</button><details><summary>How these examples are generated</summary><p>Each image is built from a fixed recipe and seed, then checked for containment, collisions, angle limits and rival clearance. The displayed node count is the achieved result; dense or narrow regions can stop short of the requested target. Boundary following and terminal anchoring are experimental.</p><p><a href="manifest.json">Download generation measurements and environment details (JSON)</a>. PNG and SVG use the same geometry. Colour previews can differ slightly between screens and renderers.</p></details>'
108
+ content += '</section>'
109
+ content += '<section id="guide">'+page_content((destination/'controls.html').read_text(encoding='utf-8')).replace('<h1>','<h2>').replace('</h1>','</h2>')+'</section>'
110
+ content += '<section id="population-map">'+page_content((destination/'uk_population.html').read_text(encoding='utf-8')).replace('<h1>','<h2>').replace('</h1>','</h2>')+'</section>'
111
+ content += '<section id="start" class="start"><h2>Make it yours</h2><p>From the repository root, install the rendering dependencies in your Python environment and generate your first image.</p><pre class="command">python -m pip install -e ".[render]"\ngraph-ics render --example typography --palette arctic --output examples/output/arctic.png</pre><p>Use <code>graph-ics describe NAME</code> to inspect a recipe and <code>graph-ics render --help</code> for the full command reference. <code>graph-ics gallery --all-palettes</code> generates the complete colour matrix. PNGs, SVGs and replay frames are written locally.</p></section>'
112
+ content += '<section class="about"><h2>About the project</h2><p>graph_ics began in 2022, when I needed graphics for a presentation about money laundering and anti-money laundering and decided to build a generator to create them. It went through several iterations over the years before I finally had time to bring it together as a usable library and share the results.</p><p><a href="https://pippidis.no">Johannes Pippidis Lorentzen</a> &middot; <a href="manuals/index.html">Read the manuals</a></p></section>'
113
+ script = """
114
+ const cards=[...document.querySelectorAll('article[data-example]')];const search=document.getElementById('search'),palette=document.getElementById('palette'),example=document.getElementById('example'),large=document.getElementById('large'),more=document.getElementById('more');let limit=9;
115
+ function filter(){const query=search.value.trim().toLowerCase();const matches=cards.filter(card=>(!palette.value||card.dataset.palette===palette.value)&&(!example.value||card.dataset.example===example.value)&&(!large.checked||card.dataset.large==='true')&&(!query||card.textContent.toLowerCase().includes(query)));const shown=new Set(matches.slice(0,limit));for(const card of cards)card.hidden=!shown.has(card);document.getElementById('count').textContent=matches.length+' examples';document.getElementById('empty').hidden=matches.length!==0;more.hidden=matches.length<=limit;more.textContent='Show '+Math.min(24,Math.max(0,matches.length-limit))+' more examples';}
116
+ for(const control of [search,palette,example,large])control.addEventListener('input',()=>{limit=9;filter();});more.addEventListener('click',()=>{limit+=24;filter();});document.getElementById('reset').addEventListener('click',()=>{search.value=palette.value=example.value='';large.checked=false;limit=9;filter();});filter();
117
+ """
118
+ (destination/'index.html').write_text(gallery_page('Example library', content, script=script), encoding='utf-8')
@@ -0,0 +1,95 @@
1
+ """Shared, self-contained presentation for the offline example library."""
2
+ from html import escape
3
+ import re
4
+
5
+ CSS = """
6
+ :root{color-scheme:light;--ink:#284d68;--muted:#526872;--paper:#ffffff;--line:#d5dfe5;--accent:#a64152}
7
+ *{box-sizing:border-box}html{scroll-behavior:smooth;scroll-padding-top:90px}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.6 system-ui,-apple-system,sans-serif}a{color:var(--accent);text-underline-offset:3px}a:hover{color:#284d68}a:focus-visible,button:focus-visible,select:focus-visible,input:focus-visible,summary:focus-visible{outline:3px solid #a64152;outline-offset:4px}
8
+ .topbar{position:sticky;top:0;z-index:10;padding:18px max(24px,calc((100vw - 1440px)/2));background:#ffffffed;color:var(--ink);border-bottom:1px solid var(--line);backdrop-filter:blur(12px);display:flex;gap:28px;align-items:center;flex-wrap:wrap}.brand{font-weight:750;letter-spacing:.04em}.topbar a{color:inherit;text-decoration:none}.topbar a[aria-current]{border-bottom:2px solid var(--accent)}.topbar nav{min-width:0;display:flex;gap:24px;flex-wrap:wrap}.container{max-width:1488px;padding:36px 24px 64px;margin:auto}.intro{margin-bottom:32px}.eyebrow{text-transform:uppercase;letter-spacing:.15em;font-size:.75rem;font-weight:700;color:var(--accent)}h1{font-size:clamp(2.3rem,5vw,4rem);line-height:1.08;letter-spacing:-.04em;margin:14px 0 20px}h2{font-size:1.55rem;line-height:1.25}h3{font-size:1.1rem;line-height:1.35}.intro p{font-size:1.1rem;color:var(--muted)}.paths{display:flex;gap:14px;flex-wrap:wrap}.button,button{border:1px solid var(--line);background:white;color:var(--ink);padding:9px 14px;border-radius:6px;font:inherit;cursor:pointer;text-decoration:none}.button:hover,button:hover{background:#edf2f5}.filters{display:flex;gap:18px;flex-wrap:wrap;align-items:end;padding:20px;background:#f0f4f6;border:1px solid var(--line);border-radius:8px;margin:28px 0}.filters label{display:grid;gap:5px;font-size:.85rem;font-weight:650}.filters .check{display:flex;align-items:center;padding:10px 0}.filters input[type=search]{min-width:230px}.filters input,.filters select{font:inherit;padding:9px;border:1px solid #aabbb8;border-radius:4px;background:white;color:var(--ink)}.filters input[type=checkbox]{width:18px;height:18px}#count{margin-left:auto;font-size:.9rem;color:var(--muted)}
9
+ .grid,.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px}article{min-width:0;background:#fff;border:1px solid var(--line);border-radius:8px;overflow:hidden;padding:18px}article[hidden]{display:none}article h2,article h3{margin:10px 0}article p{font-size:.94rem}.image-link{display:block;margin:-18px -18px 18px;background:#f5f7f8}.image-link img{display:block;width:100%;height:260px;object-fit:contain}article img{width:100%;height:auto;display:block}article .meta{font-size:.82rem;color:var(--muted)}.swatches{display:flex;gap:4px}.swatches span{width:20px;height:9px;border:1px solid #0002;border-radius:2px}.downloads{display:flex;gap:16px;font-size:.9rem;font-weight:650;margin:15px 0}.downloads a{white-space:nowrap}details{border-top:1px solid var(--line);padding-top:12px;margin-top:16px}summary{cursor:pointer;font-weight:650}li{margin:8px 0}ul{padding-left:21px}code{font-size:.88em}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f0f4f6;padding:14px;border-radius:5px;font-size:.82rem;line-height:1.65}button.copy{font-size:.78rem;padding:5px 10px;margin-bottom:5px}.hint,.notice{color:var(--muted);font-size:.9rem}.notice{border-left:3px solid #7f9baa;padding:8px 16px;background:#f0f4f6}.section-nav{display:flex;gap:10px 22px;flex-wrap:wrap;margin:24px 0}.section-nav a{font-size:.9rem}section{margin:48px 0}img{max-width:100%;height:auto}.hero{display:grid;grid-template-columns:1fr 1.2fr;gap:36px;align-items:center;margin-bottom:40px}.hero .intro{margin:0}.hero img{border-radius:8px;width:100%}.start{background:#f0f4f6;padding:24px;border-radius:8px}table{border-collapse:collapse;width:100%;text-align:left;font-size:.9rem}th,td{padding:12px;border-bottom:1px solid var(--line);vertical-align:top}.table-scroll{overflow-x:auto}.comparison{display:grid;grid-template-columns:1fr 1fr;gap:24px}.comparison img{max-width:100%;max-height:1000px;width:auto;display:block;margin:auto}.comparison figure{margin:0;background:white;padding:20px;border:1px solid var(--line)}figcaption{margin-top:15px;font-size:.9rem;color:var(--muted)}footer{border-top:1px solid var(--line);margin-top:60px;padding-top:20px;font-size:.85rem;color:var(--muted)}#more{display:block;margin:30px auto}#empty{padding:40px;text-align:center}.alpha{background:repeating-conic-gradient(#ddd 0% 25%,#fff 0% 50%) 0/16px 16px}noscript{display:block;padding:12px}.style-key{max-width:760px;width:100%;height:auto}
10
+ @media(max-width:1050px){.grid,.cards{grid-template-columns:repeat(2,minmax(0,1fr))}.topbar{gap:16px}#count{margin-left:0}}@media(max-width:650px){.grid,.cards,.comparison,.hero{grid-template-columns:1fr}.container{padding:24px 16px}.topbar{position:sticky;top:0;z-index:10;padding:16px}.topbar nav{gap:14px}.filters{gap:12px}.filters label,.filters input[type=search]{width:100%;min-width:0}.image-link img{height:240px}h1{font-size:2.5rem}td{padding:8px}}
11
+ """
12
+ CSS += """
13
+ h1,h2{font-family:Georgia,'Times New Roman',serif;font-weight:400}h1{letter-spacing:-.035em}.brand{display:flex;align-items:center;gap:10px}.brand img{width:32px;height:32px}.hero{padding:28px 0 50px}.intro{max-width:none}.container{max-width:1320px}.skip-link{position:absolute;top:-100px;left:16px;z-index:20;background:white;padding:12px}.skip-link:focus{top:8px}.manual{max-width:none;margin:0}.manual h2{margin-top:48px}.manual pre{overflow:auto}.manual table{display:block;overflow:auto}.about{border-top:1px solid var(--line);padding-top:30px}.topbar nav{gap:18px;font-size:.9rem}dialog{border:1px solid var(--line);border-radius:8px;width:90vw;max-width:1400px;height:85vh;padding:16px}dialog::backdrop{background:#132b3ddd}.viewer-tools{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.viewer-canvas{overflow:auto;height:calc(100% - 65px);margin-top:16px}.viewer-canvas img{max-width:none;display:block}.animation-toggle{display:block;margin:12px 0}footer{display:flex;gap:20px;justify-content:space-between;flex-wrap:wrap}section{margin:64px 0}@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}}@media(max-width:650px){.hero{padding-top:0}.topbar{position:relative}.manual h1{font-size:2.1rem}html{scroll-padding-top:20px}}
14
+ """
15
+ MEDIA_SCRIPT = """
16
+ (()=>{
17
+ for(const image of document.querySelectorAll('img[data-animation]')){
18
+ const button=document.createElement('button');button.className='animation-toggle';button.textContent='Play animation';button.type='button';let playing=false;
19
+ button.onclick=()=>{playing=!playing;image.src=playing?image.dataset.animation:image.dataset.poster;button.textContent=playing?'Pause animation':'Play animation';button.setAttribute('aria-pressed',String(playing));};
20
+ button.setAttribute('aria-pressed','false');image.before(button);
21
+ }
22
+ const links=[...document.querySelectorAll('a.image-link')];if(!links.length)return;
23
+ const dialog=document.createElement('dialog');dialog.setAttribute('aria-label','Artwork viewer');
24
+ dialog.innerHTML='<div class="viewer-tools"><button type="button" data-close>Close</button><label>Zoom <input type="range" min="50" max="300" value="100" aria-label="Image zoom"></label><a download>Download original</a></div><div class="viewer-canvas"><img alt=""></div>';
25
+ document.body.append(dialog);const picture=dialog.querySelector('img'),slider=dialog.querySelector('input'),download=dialog.querySelector('a');let origin;
26
+ const zoom=()=>{picture.style.width=slider.value+'%';};slider.oninput=zoom;
27
+ dialog.querySelector('[data-close]').onclick=()=>dialog.close();dialog.addEventListener('close',()=>origin?.focus());
28
+ for(const link of links)link.addEventListener('click',event=>{if(event.ctrlKey||event.metaKey||event.shiftKey)return;event.preventDefault();origin=link;picture.src=link.href;picture.alt=link.querySelector('img')?.alt||'Graph artwork';download.href=link.href;slider.value='100';zoom();dialog.showModal();});
29
+ })();
30
+ """
31
+
32
+
33
+ CSS += """
34
+ .guide-layout{display:grid;grid-template-columns:235px minmax(0,1fr);gap:48px}.chapter-nav{position:sticky;top:100px;align-self:start;max-height:80vh;overflow:auto}.chapter-nav ol{padding-left:24px}.chapter-nav a{text-decoration:none;color:var(--ink)}.chapter-nav a[aria-current]{color:var(--accent);font-weight:700}.guide-body{min-width:0}.guide-body .grid{grid-template-columns:repeat(2,minmax(0,1fr))}.guide-body h2{margin-top:40px}.breadcrumbs{font-size:.85rem;margin-bottom:24px}.chapter-pager{display:flex;justify-content:space-between;gap:24px;border-top:1px solid var(--line);padding-top:24px;margin-top:48px}.on-this-page{border-left:2px solid var(--line);padding-left:20px}.mobile-chapters{display:none}.feature-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:32px}.feature-grid img{width:100%;height:230px;object-fit:contain}.guide-body pre{overflow-wrap:anywhere}.guide-body table{display:block;overflow:auto}.guide-body article{padding:16px}.guide-body>article{border:0;padding:0}.guide-body p{max-width:none}@media(max-width:850px){.guide-layout{display:block}.chapter-nav{display:none}.mobile-chapters{display:block;margin-bottom:28px}.feature-grid{grid-template-columns:1fr}}@media(max-width:550px){.guide-body .grid{grid-template-columns:1fr}}
35
+ """
36
+ CSS += """
37
+ .about-page{width:100%}.about-page .intro{max-width:none;margin-bottom:36px}.about-page .intro p,.about-page section p{font-size:1rem;line-height:1.75;color:var(--ink);max-width:none}.about-page section{margin:36px 0}.about-page section h2{margin-bottom:16px}.about-page h1{font-size:clamp(2.2rem,4vw,3.4rem)}.reference-nav{list-style:none;padding-left:14px;border-left:1px solid var(--line);margin:10px 0}.reference-nav li{font-size:.88rem}.breadcrumbs{display:flex;flex-wrap:wrap;gap:6px}
38
+ """
39
+ CSS += """
40
+ .repository-link{margin-left:auto;display:inline-flex;align-items:center;gap:8px;min-height:44px;white-space:nowrap;font-size:.9rem}.repository-link svg{width:22px;height:22px;fill:currentColor;flex-shrink:0}.repository-link:hover{color:var(--accent)}@media(max-width:1050px){.topbar .brand{order:0}.topbar .repository-link{order:1}.topbar nav{order:2;flex-basis:100%}}
41
+ """
42
+ REPOSITORY_LINK = '<a class="repository-link" href="https://github.com/pippidis/graph_ics" aria-label="graph_ics on GitHub"><svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82A7.65 7.65 0 0 1 8 3.86c.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"/></svg><span>GitHub</span></a>'
43
+
44
+ COPY_SCRIPT = """
45
+ for(const pre of document.querySelectorAll('pre.command')){const button=document.createElement('button');button.className='copy';button.type='button';button.textContent='Copy command';button.addEventListener('click',async()=>{try{await navigator.clipboard.writeText(pre.textContent);button.textContent='Copied';setTimeout(()=>button.textContent='Copy command',1800);}catch{const range=document.createRange();range.selectNodeContents(pre);const selection=window.getSelection();selection.removeAllRanges();selection.addRange(range);button.textContent='Selected - press Ctrl/Cmd+C';}});pre.before(button);}
46
+ """
47
+
48
+
49
+ NAVIGATION_SCRIPT = """
50
+ (()=>{
51
+ const links=Array.from(document.querySelectorAll('.topbar nav a'));
52
+ const sections=links.map(link=>({link,section:document.getElementById(new URL(link.href).hash.slice(1))})).filter(item=>item.section);
53
+ if(!sections.length)return;
54
+ const select=link=>{for(const item of links){if(item===link)item.setAttribute('aria-current','location');else item.removeAttribute('aria-current');}};
55
+ const fromHash=()=>{
56
+ const target=document.getElementById(decodeURIComponent(location.hash.slice(1)));
57
+ if(!target)return false;
58
+ const match=sections.find(item=>item.section===target||item.section.contains(target));
59
+ if(match){select(match.link);return true;}
60
+ return false;
61
+ };
62
+ const fromScroll=()=>{
63
+ const offset=document.querySelector('.topbar').getBoundingClientRect().bottom+30;
64
+ let current=sections[0];
65
+ for(const item of sections){if(item.section.getBoundingClientRect().top<=offset)current=item;}
66
+ if(window.innerHeight+window.scrollY>=document.documentElement.scrollHeight-2)current=sections[sections.length-1];
67
+ select(current.link);
68
+ };
69
+ let scrollingToHash=false,settle;
70
+ const navigate=()=>{scrollingToHash=fromHash();clearTimeout(settle);settle=setTimeout(()=>{scrollingToHash=false;},1200);};
71
+ for(const item of sections)item.link.addEventListener('click',()=>{select(item.link);scrollingToHash=true;clearTimeout(settle);settle=setTimeout(()=>{scrollingToHash=false;},1200);});
72
+ window.addEventListener('hashchange',navigate);
73
+ window.addEventListener('scroll',()=>{if(!scrollingToHash)fromScroll();},{passive:true});
74
+ window.addEventListener('scrollend',()=>{scrollingToHash=false;fromScroll();});
75
+ if(location.hash)navigate();else fromScroll();
76
+ })();
77
+ """
78
+
79
+
80
+ def gallery_page(title: str, content: str, *, active: str = 'gallery', script: str = '') -> str:
81
+ prefix = '../' if active in ('logo', 'manuals', 'guide') else ''
82
+ selected = 'guide' if active in ('manuals', 'guide', 'controls', 'uk') else 'about' if active == 'logo' else active
83
+ links = [(key, prefix+path, label) for key,path,label in [('home','index.html','Home'),('gallery','gallery/index.html','Gallery'),('guide','guide/index.html','Guide'),('about','about/index.html','About')]]
84
+ icon_base = prefix+'logo/figures/'
85
+ home = prefix+'index.html'
86
+ content = re.sub(r'<img(?![^>]*loading=)', '<img loading="lazy" decoding="async"', content)
87
+ icons = f'<link rel="icon" type="image/svg+xml" href="{icon_base}favicon.svg"><link rel="icon" href="{icon_base}favicon.ico" sizes="any"><link rel="apple-touch-icon" href="{icon_base}icon-180.png">'
88
+ metadata = '<meta property="og:site_name" content="graph_ics"><meta property="og:type" content="website"><meta property="og:title" content="'+escape(title)+' | graph_ics"><meta property="og:image" content="https://graph-ics.pippidis.no/logo/figures/banner@2x.png">'
89
+ navigation = ''.join(f'<a href="{path}"'+(' aria-current="page"' if key == selected else '')+f'>{label}</a>' for key,path,label in links)
90
+ return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>'+escape(title)+' | graph_ics</title>'+icons+metadata+'<meta name="description" content="graph_ics: generative artwork from sprawling networks. Explore examples, spatial maps, typography and the Python manual."><style>'+CSS+'</style></head><body><a class="skip-link" href="#main">Skip to content</a><header class="topbar"><a class="brand" href="'+home+'"><img src="'+icon_base+'icon-64.png" alt="" width="32" height="32">graph_ics</a><nav aria-label="Library">'+navigation+'</nav>'+REPOSITORY_LINK+'</header><main class="container" id="main"><!-- CONTENT START -->'+content+'<!-- CONTENT END --><footer><span>graph_ics &middot; Art grown from connections.</span><span>A project by <a href="https://pippidis.no">Johannes Pippidis Lorentzen</a></span></footer></main><script>'+COPY_SCRIPT+NAVIGATION_SCRIPT+MEDIA_SCRIPT+script+'</script></body></html>'
91
+
92
+
93
+ def page_content(path: str) -> str:
94
+ """Extract the generated content fragment for the single-page public gallery."""
95
+ return path.split('<!-- CONTENT START -->', 1)[1].split('<!-- CONTENT END -->', 1)[0]