portfetch 2.3.0__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.
portfetch/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """portfetch: your photo as an ASCII portrait in a neofetch-style profile card."""
2
+
3
+ __version__ = "2.3.0"
portfetch/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from portfetch.cli import main
2
+
3
+ main()
portfetch/art.py ADDED
@@ -0,0 +1,143 @@
1
+ """Turn a photo (or a text file) into ASCII art."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from PIL import Image, ImageEnhance, ImageOps
8
+
9
+ # Characters ordered from light to dense.
10
+ CHARSETS = {
11
+ "detailed": " .'`^\",:;Il!i><~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$",
12
+ "letters": " .,:;i1tfLCG08@",
13
+ "simple": " .:-=+*#%@",
14
+ "dots": " .:;+=xX$&",
15
+ "binary": " #",
16
+ }
17
+
18
+ # A monospace glyph is about 0.6 times as wide as the font size. With line
19
+ # height equal to font size, one row of text is 1 / 0.6 times taller than a
20
+ # column is wide, so rows are squashed by this factor to keep proportions.
21
+ CHAR_ASPECT = 0.6
22
+
23
+
24
+ class ArtError(ValueError):
25
+ pass
26
+
27
+
28
+ def load_art(cfg: dict | None, base: Path) -> list[str]:
29
+ """Return the art as equal-length lines, or [] when no art is configured."""
30
+ if not cfg:
31
+ return []
32
+ if cfg.get("text"):
33
+ raw = (base / cfg["text"]).read_text(encoding="utf-8").splitlines()
34
+ lines = trim_blank([line.rstrip() for line in raw])
35
+ width = max((len(line) for line in lines), default=0)
36
+ return [line.ljust(width) for line in lines]
37
+ if cfg.get("image"):
38
+ return image_to_ascii(base / cfg["image"], cfg)
39
+ return []
40
+
41
+
42
+ def image_to_ascii(path: Path, cfg: dict) -> list[str]:
43
+ cols = int(cfg.get("columns", 64))
44
+ charset = cfg.get("charset", "letters")
45
+ ramp = CHARSETS.get(charset, charset)
46
+ if len(ramp) < 2:
47
+ raise ArtError("ascii.charset needs at least two characters")
48
+
49
+ img = Image.open(path)
50
+ img = ImageOps.exif_transpose(img).convert("RGBA")
51
+ # Transparent areas (e.g. from a background remover) become white.
52
+ canvas = Image.new("RGBA", img.size, (255, 255, 255, 255))
53
+ canvas.alpha_composite(img)
54
+ img = canvas.convert("L")
55
+
56
+ crop = cfg.get("crop") # [left, top, right, bottom] as fractions 0..1
57
+ if crop:
58
+ w, h = img.size
59
+ left, top, right, bottom = crop
60
+ img = img.crop((int(left * w), int(top * h), int(right * w), int(bottom * h)))
61
+
62
+ if cfg.get("brightness", 1.0) != 1.0:
63
+ img = ImageEnhance.Brightness(img).enhance(float(cfg["brightness"]))
64
+ if cfg.get("contrast", 1.0) != 1.0:
65
+ img = ImageEnhance.Contrast(img).enhance(float(cfg["contrast"]))
66
+
67
+ w, h = img.size
68
+ rows = max(1, round(cols * (h / w) * CHAR_ASPECT))
69
+ img = img.resize((cols, rows), Image.LANCZOS)
70
+
71
+ background: set[tuple[int, int]] = set()
72
+ if cfg.get("remove_background"):
73
+ background = flood_background(img, int(cfg.get("background_tolerance", 18)))
74
+
75
+ if cfg.get("equalize"):
76
+ img = equalize(img, background)
77
+
78
+ invert = bool(cfg.get("invert", False))
79
+ cutoff = int(cfg.get("background_threshold", 245))
80
+ top_index = len(ramp) - 1
81
+ out = []
82
+ for y in range(rows):
83
+ line = []
84
+ for x in range(cols):
85
+ v = img.getpixel((x, y))
86
+ if (x, y) in background or (not invert and v >= cutoff):
87
+ line.append(" ")
88
+ continue
89
+ density = (v / 255) if invert else (1 - v / 255)
90
+ line.append(ramp[round(density * top_index)])
91
+ out.append("".join(line))
92
+ return trim_blank(out)
93
+
94
+
95
+ def flood_background(img: Image.Image, tolerance: int) -> set[tuple[int, int]]:
96
+ """Flood-fill from the image edges to find a plain, roughly uniform backdrop.
97
+
98
+ A cell joins the background when it is within `tolerance` of the neighbor
99
+ it was reached from, so gentle gradients (studio lighting) are followed
100
+ while the sharp edge of hair, skin or clothing stops the fill.
101
+ """
102
+ w, h = img.size
103
+ px = img.load()
104
+ edges = [(x, y) for x in range(w) for y in (0, h - 1)]
105
+ edges += [(x, y) for y in range(h) for x in (0, w - 1)]
106
+ values = sorted(px[p] for p in edges)
107
+ median = values[len(values) // 2]
108
+ stack = [p for p in edges if abs(px[p] - median) <= tolerance * 2]
109
+ seen = set(stack)
110
+ while stack:
111
+ x, y = stack.pop()
112
+ for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
113
+ if 0 <= nx < w and 0 <= ny < h and (nx, ny) not in seen:
114
+ v = px[nx, ny]
115
+ if abs(v - px[x, y]) <= tolerance and abs(v - median) <= tolerance * 3:
116
+ seen.add((nx, ny))
117
+ stack.append((nx, ny))
118
+ return seen
119
+
120
+
121
+ def equalize(img: Image.Image, background: set[tuple[int, int]]) -> Image.Image:
122
+ """Spread the subject's tones over 0..255, ignoring the backdrop."""
123
+ w, h = img.size
124
+ values = sorted(img.getpixel((x, y)) for y in range(h) for x in range(w)
125
+ if (x, y) not in background)
126
+ if not values:
127
+ return img
128
+ cdf: dict[int, float] = {}
129
+ for i, v in enumerate(values):
130
+ cdf[v] = (i + 1) / len(values)
131
+ lut, last = [], 0.0
132
+ for v in range(256):
133
+ last = cdf.get(v, last)
134
+ lut.append(round(last * 255))
135
+ return img.point(lut)
136
+
137
+
138
+ def trim_blank(lines: list[str]) -> list[str]:
139
+ while lines and not lines[0].strip():
140
+ lines.pop(0)
141
+ while lines and not lines[-1].strip():
142
+ lines.pop()
143
+ return lines
portfetch/cli.py ADDED
@@ -0,0 +1,262 @@
1
+ """Command line interface: `portfetch init | render | preview | print | themes | animations`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import html
7
+ import sys
8
+ import tempfile
9
+ import webbrowser
10
+ from pathlib import Path
11
+
12
+ from portfetch import __version__, core, panel, stats, svg, themes
13
+
14
+ WORKFLOW = """\
15
+ name: portfetch
16
+
17
+ on:
18
+ workflow_dispatch: # run by hand from the Actions tab
19
+ schedule:
20
+ - cron: "0 6 * * *" # daily, keeps GitHub numbers and uptime fresh
21
+ push:
22
+ branches: [main]
23
+ paths: ["{config}", "assets/**"]
24
+
25
+ permissions:
26
+ contents: write
27
+
28
+ jobs:
29
+ render:
30
+ runs-on: ubuntu-latest
31
+ steps:
32
+ - uses: actions/checkout@v4
33
+ - uses: ethanbrownecon/portfetch@v2.3.0
34
+ with:
35
+ config: {config}
36
+ """
37
+
38
+ SNIPPET = """\
39
+ <picture>
40
+ <source media="(prefers-color-scheme: dark)" srcset="assets/portfetch-dark.svg">
41
+ <img alt="{alt}" src="assets/portfetch-light.svg">
42
+ </picture>"""
43
+
44
+
45
+ def main(argv: list[str] | None = None) -> None:
46
+ parser = argparse.ArgumentParser(
47
+ prog="portfetch",
48
+ description="Your photo as an ASCII portrait in a neofetch-style profile card.",
49
+ )
50
+ parser.add_argument("--version", action="version", version=f"portfetch {__version__}")
51
+ sub = parser.add_subparsers(dest="command")
52
+
53
+ def with_config(p):
54
+ p.add_argument("-c", "--config", default="portfetch.yml", help="config file (default: portfetch.yml)")
55
+ p.add_argument("--offline", action="store_true", help="skip the GitHub API and use sample numbers")
56
+ return p
57
+
58
+ p = sub.add_parser("init", help="write a starter config, workflow and README snippet")
59
+ p.add_argument("-c", "--config", default="portfetch.yml")
60
+ p.add_argument("--github", metavar="USER", help="fill the config from this public GitHub profile")
61
+ p.add_argument("--photo", metavar="PATH", help="portrait to use for the ASCII art")
62
+ p.add_argument("--force", action="store_true", help="overwrite existing files")
63
+
64
+ with_config(sub.add_parser("render", help="write the SVG cards (the default command)"))
65
+ p = with_config(sub.add_parser("preview", help="open a local page with the cards in light and dark"))
66
+ p.add_argument("--all", action="store_true", help="also show every animation style side by side")
67
+ p.add_argument("--no-open", action="store_true", help="write the page without opening a browser")
68
+ p = with_config(sub.add_parser("showcase", help="write one SVG that cycles through several styles"))
69
+ p.add_argument("-o", "--output", help="file to write (default: showcase.output in the config)")
70
+ with_config(sub.add_parser("print", help="print the card in this terminal"))
71
+ sub.add_parser("themes", help="list color themes")
72
+ sub.add_parser("animations", help="list animation styles and window styles")
73
+
74
+ args = parser.parse_args(argv)
75
+ command = args.command or "render"
76
+ if command == "render" and not hasattr(args, "config"):
77
+ args = parser.parse_args(["render", *(argv or sys.argv[1:])])
78
+
79
+ try:
80
+ {
81
+ "init": cmd_init, "render": cmd_render, "showcase": cmd_showcase, "preview": cmd_preview, "print": cmd_print,
82
+ "themes": cmd_themes, "animations": cmd_animations,
83
+ }[command](args)
84
+ except (FileNotFoundError, panel.ConfigError, ValueError) as exc:
85
+ sys.exit(f"portfetch: {exc}")
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+
90
+ def cmd_render(args) -> None:
91
+ card = core.build(Path(args.config), offline=args.offline)
92
+ for path in core.write(card):
93
+ print(f"wrote {_rel(path)}")
94
+
95
+
96
+ def cmd_showcase(args) -> None:
97
+ card = core.build(Path(args.config), offline=args.offline)
98
+ target = args.output or (card.showcase or {}).get("output")
99
+ path = Path(args.output) if args.output else (card.base / target if target else Path("portfetch-showcase.svg"))
100
+ print(f"wrote {_rel(core.write_showcase(card, path))}")
101
+
102
+
103
+ def cmd_preview(args) -> None:
104
+ card = core.build(Path(args.config), offline=args.offline)
105
+ out = Path(tempfile.mkdtemp(prefix="portfetch-"))
106
+ sections = []
107
+
108
+ def add(title: str, anim: svg.Animation) -> None:
109
+ cells = []
110
+ for name, (_, palette) in card.outputs.items():
111
+ file = out / f"{anim.style}-{name}.svg"
112
+ file.write_text(svg.render(card.art, card.rows, palette, card.layout, anim, card.header), encoding="utf-8")
113
+ page_bg = "#0d1117" if name == "dark" else "#ffffff"
114
+ cells.append(f'<div class="cell" style="background:{page_bg}"><img src="{file.name}"></div>')
115
+ sections.append(f"<h2>{html.escape(title)}</h2>" + "".join(cells))
116
+
117
+ add(f"Your config: {card.animation.style}", card.animation)
118
+ if args.all:
119
+ for style, about in svg.ANIMATIONS.items():
120
+ if style != card.animation.style:
121
+ add(f"{style}: {about}", svg.Animation(style=style, duration=card.animation.duration,
122
+ cursor=card.animation.cursor or style != "none"))
123
+
124
+ page = out / "index.html"
125
+ page.write_text(
126
+ "<!doctype html><meta charset=utf-8><title>portfetch preview</title>"
127
+ "<style>body{font:15px system-ui;margin:24px;background:#f0f2f5}"
128
+ ".cell{padding:24px;border-radius:8px;margin:8px 0}img{max-width:100%}"
129
+ "button{position:fixed;top:16px;right:16px;font-size:15px;padding:8px 14px}</style>"
130
+ "<button onclick=\"document.querySelectorAll('img').forEach(i=>i.src=i.src.split('?')[0]+'?'+Date.now())\">"
131
+ "Replay</button>" + "".join(sections),
132
+ encoding="utf-8",
133
+ )
134
+ print(f"preview: {page}")
135
+ if not args.no_open:
136
+ webbrowser.open(page.as_uri())
137
+
138
+
139
+ def cmd_print(args) -> None:
140
+ card = core.build(Path(args.config), offline=args.offline)
141
+ palette = next(iter(card.outputs.values()))[1]
142
+ if "dark" in card.outputs:
143
+ palette = card.outputs["dark"][1]
144
+
145
+ def ansi(hex_color: str) -> str:
146
+ h = hex_color.lstrip("#")
147
+ return f"\033[38;2;{int(h[0:2], 16)};{int(h[2:4], 16)};{int(h[4:6], 16)}m"
148
+
149
+ reset = "\033[0m"
150
+ art_w = len(card.art[0]) if card.art else 0
151
+ height = max(len(card.art), len(card.rows))
152
+ art_off = (height - len(card.art)) // 2
153
+ row_off = (height - len(card.rows)) // 2
154
+ for i in range(height):
155
+ a = card.art[i - art_off] if 0 <= i - art_off < len(card.art) else " " * art_w
156
+ r = card.rows[i - row_off] if 0 <= i - row_off < len(card.rows) else []
157
+ info = "".join(ansi(palette[role]) + text for role, text in r)
158
+ print(f"{ansi(palette['art'])}{a}{reset} {info}{reset}")
159
+
160
+
161
+ def cmd_themes(_args) -> None:
162
+ for name, pal in themes.THEMES.items():
163
+ swatch = "".join(
164
+ f"\033[48;2;{int(pal[r][1:3], 16)};{int(pal[r][3:5], 16)};{int(pal[r][5:7], 16)}m \033[0m"
165
+ for r in ("background", "art", "key", "value", "section", "cursor")
166
+ )
167
+ print(f"{swatch} {name}")
168
+
169
+
170
+ def cmd_animations(_args) -> None:
171
+ print("Animations (animation: <style>):")
172
+ for name, about in svg.ANIMATIONS.items():
173
+ print(f" {name:<11} {about}")
174
+ print("\nWindows (window: <style>):")
175
+ for name, about in svg.WINDOWS.items():
176
+ print(f" {name:<11} {about}")
177
+
178
+
179
+ def cmd_init(args) -> None:
180
+ config = Path(args.config)
181
+ workflow = Path(".github/workflows/portfetch.yml")
182
+ for path in (config, workflow):
183
+ if path.exists() and not args.force:
184
+ sys.exit(f"portfetch: {path} already exists (use --force to overwrite)")
185
+
186
+ profile: dict = {}
187
+ if args.github:
188
+ try:
189
+ profile = stats.github_profile(args.github)
190
+ except Exception as exc: # network errors should not block a starter file
191
+ print(f"warning: couldn't read the GitHub profile ({exc})", file=sys.stderr)
192
+
193
+ user = args.github or "you"
194
+ name = profile.get("name") or user
195
+ photo = args.photo or "assets/photo.jpg"
196
+ lines = [f" - Name: {_yaml(name)}"]
197
+ if profile.get("bio"):
198
+ lines.append(f" - Bio: {_yaml(profile['bio'][:40])}")
199
+ lines.append(f" - Role: {_yaml(profile.get('company') or 'Your role')}")
200
+ lines.append(" - Uptime: \"{uptime}\"")
201
+ lines += [" -", " - Interests: Something you love", " - Interests: Another thing",
202
+ " -", " - Languages: Python, SQL", " - Tools: Git, LaTeX", " - section: Contact"]
203
+ if profile.get("blog"):
204
+ lines.append(f" - Website: {_yaml(profile['blog'])}")
205
+ lines.append(f" - GitHub: {user}")
206
+ if profile.get("location"):
207
+ lines.append(f" - Location: {_yaml(profile['location'])}")
208
+ lines += [" - section: GitHub Stats", ' - Repos: "{repos}"', ' - Stars: "{stars}"',
209
+ ' - Followers: "{followers}"', ' - Commits: "{commits}"']
210
+ since = (profile.get("created_at") or "2020-01-01")[:10]
211
+
212
+ config.write_text(f"""\
213
+ # portfetch config: https://github.com/ethanbrownecon/portfetch
214
+ # Render with `portfetch render`; preview with `portfetch preview --all`.
215
+
216
+ header: {user}@github
217
+ width: 58
218
+ github_user: {user}
219
+ uptime_since: {since} # date for {{uptime}}; your GitHub join date by default
220
+
221
+ ascii:
222
+ image: {photo}
223
+ columns: 64
224
+ charset: letters # detailed | letters | simple | dots | binary | your own string
225
+ contrast: 1.3
226
+ remove_background: true # drop a plain backdrop behind you
227
+
228
+ animation: boot # none | fade | boot | typewriter | scan | decode
229
+ window: card # card | macos | none
230
+
231
+ lines:
232
+ {chr(10).join(lines)}
233
+
234
+ output:
235
+ light: assets/portfetch-light.svg
236
+ dark: assets/portfetch-dark.svg
237
+
238
+ theme:
239
+ light: github-light # `portfetch themes` lists them all
240
+ dark: github-dark
241
+ """, encoding="utf-8")
242
+ workflow.parent.mkdir(parents=True, exist_ok=True)
243
+ workflow.write_text(WORKFLOW.format(config=config.as_posix()), encoding="utf-8")
244
+
245
+ print(f"wrote {config} and {workflow}")
246
+ if not Path(photo).exists():
247
+ print(f"next: add your portrait at {photo}")
248
+ print("then: portfetch preview --all")
249
+ print("\nAdd this to README.md:\n")
250
+ print(SNIPPET.format(alt=html.escape(f"{name}: profile card")))
251
+
252
+
253
+ def _yaml(text: str) -> str:
254
+ text = str(text).replace("\n", " ").strip()
255
+ return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
256
+
257
+
258
+ def _rel(path: Path) -> str:
259
+ try:
260
+ return str(path.relative_to(Path.cwd()))
261
+ except ValueError:
262
+ return str(path)
portfetch/core.py ADDED
@@ -0,0 +1,126 @@
1
+ """Load a config and produce cards."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ from dataclasses import dataclass, replace
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+
11
+ from portfetch import art as art_mod
12
+ from portfetch import panel, stats, svg, themes
13
+
14
+
15
+ @dataclass
16
+ class Card:
17
+ art: list[str]
18
+ rows: list[list[panel.Span]]
19
+ header: str
20
+ layout: svg.Layout
21
+ animation: svg.Animation
22
+ outputs: dict[str, tuple[Path, dict]] # name -> (path, palette)
23
+ showcase: dict | None = None
24
+ base: Path | None = None
25
+
26
+
27
+ def load_config(path: Path) -> dict:
28
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
29
+ if not isinstance(data, dict):
30
+ raise panel.ConfigError(f"{path} should be a YAML mapping")
31
+ return data
32
+
33
+
34
+ def build(config_path: Path, offline: bool = False) -> Card:
35
+ config_path = config_path.resolve()
36
+ cfg = load_config(config_path)
37
+ base = config_path.parent
38
+
39
+ values: dict[str, str] = {}
40
+ if cfg.get("github_user"):
41
+ values.update(stats.offline_stats() if offline else stats.github_stats(cfg["github_user"]))
42
+ if cfg.get("uptime_since"):
43
+ values["uptime"] = stats.uptime(cfg["uptime_since"])
44
+ today = dt.date.today()
45
+ values["updated"] = today.isoformat()
46
+ values["year"] = str(today.year)
47
+
48
+ ascii_cfg = cfg.get("ascii") or {}
49
+ art = art_mod.load_art(ascii_cfg, base)
50
+ rows = panel.build_rows(cfg, values)
51
+ header = stats.fill(str(cfg.get("header", "user@github")), values)
52
+
53
+ window = cfg.get("window", "card")
54
+ if window not in svg.WINDOWS:
55
+ raise panel.ConfigError(f"unknown window '{window}'. Choose from: {', '.join(svg.WINDOWS)}")
56
+ layout = svg.Layout(
57
+ width=int(cfg.get("width", 60)),
58
+ font_size=float(cfg.get("font_size", 14)),
59
+ line_height=float(cfg.get("line_height", 20)),
60
+ padding=float(cfg.get("padding", 28)),
61
+ gap=float(cfg.get("gap", 28)),
62
+ art_font_size=ascii_cfg.get("font_size"),
63
+ window=window,
64
+ title=stats.fill(str(cfg.get("title", "")), values),
65
+ )
66
+ animation = svg.Animation.from_config(cfg.get("animation"))
67
+
68
+ theme_cfg = cfg.get("theme") or {}
69
+ outputs_cfg = cfg.get("output") or {"light": "portfetch-light.svg", "dark": "portfetch-dark.svg"}
70
+ outputs = {
71
+ name: (base / rel, themes.resolve(theme_cfg.get(name), name))
72
+ for name, rel in outputs_cfg.items()
73
+ }
74
+ return Card(art, rows, header, layout, animation, outputs, cfg.get("showcase"), base)
75
+
76
+
77
+ def write(card: Card, animation: svg.Animation | None = None) -> list[Path]:
78
+ written = []
79
+ for path, palette in card.outputs.values():
80
+ path.parent.mkdir(parents=True, exist_ok=True)
81
+ path.write_text(
82
+ svg.render(card.art, card.rows, palette, card.layout, animation or card.animation, card.header),
83
+ encoding="utf-8",
84
+ )
85
+ written.append(path)
86
+ if card.showcase and card.showcase.get("output"):
87
+ written.append(write_showcase(card, card.base / card.showcase["output"]))
88
+ return written
89
+
90
+
91
+ DEFAULT_SCENES = [
92
+ {"animation": "boot", "theme": "github-dark", "window": "card"},
93
+ {"animation": "typewriter", "theme": "dracula", "window": "macos"},
94
+ {"animation": "decode", "theme": "tokyo-night", "window": "card"},
95
+ {"animation": "scan", "theme": "green-screen", "window": "macos"},
96
+ {"animation": "fade", "theme": "catppuccin-latte", "window": "card"},
97
+ {"animation": "boot", "theme": "gruvbox-dark", "window": "macos"},
98
+ ]
99
+
100
+
101
+ def showcase_scenes(card: Card, specs: list[dict] | None = None) -> list[svg.Scene]:
102
+ """One scene per spec: the same card with another animation, theme or window."""
103
+ scenes = []
104
+ for spec in specs or DEFAULT_SCENES:
105
+ anim_spec = spec.get("animation", card.animation.style)
106
+ anim = svg.Animation.from_config(anim_spec)
107
+ if not isinstance(anim_spec, dict) or "cursor" not in anim_spec:
108
+ anim.cursor = True
109
+ window = spec.get("window", card.layout.window)
110
+ if window not in svg.WINDOWS:
111
+ raise panel.ConfigError(f"unknown window '{window}' in showcase")
112
+ layout = replace(card.layout, window=window)
113
+ theme_spec = spec.get("theme", "github-dark")
114
+ palette = themes.resolve(theme_spec, "dark")
115
+ theme_name = theme_spec if isinstance(theme_spec, str) else theme_spec.get("preset", "custom")
116
+ caption = spec.get("caption", f"animation: {anim.style} · theme: {theme_name} · window: {window}")
117
+ scenes.append(svg.Scene(card.art, card.rows, palette, layout, anim, card.header, caption))
118
+ return scenes
119
+
120
+
121
+ def write_showcase(card: Card, path: Path, specs: list[dict] | None = None) -> Path:
122
+ opts = card.showcase or {}
123
+ scenes = showcase_scenes(card, specs or opts.get("scenes"))
124
+ path.parent.mkdir(parents=True, exist_ok=True)
125
+ path.write_text(svg.showcase(scenes, hold=float(opts.get("hold", 2.5)), fade=float(opts.get("fade", 0.9))), encoding="utf-8")
126
+ return path
portfetch/panel.py ADDED
@@ -0,0 +1,52 @@
1
+ """Build the info panel: rows of colored spans, each exactly `width` characters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from portfetch.stats import fill
8
+
9
+ RULE = "─" # box-drawing horizontal line; one cell wide in monospace fonts
10
+
11
+ Span = tuple[str, str] # (color role, text)
12
+
13
+
14
+ class ConfigError(ValueError):
15
+ pass
16
+
17
+
18
+ def build_rows(cfg: dict, values: dict[str, str]) -> list[list[Span]]:
19
+ width = int(cfg.get("width", 60))
20
+ rows: list[list[Span]] = []
21
+
22
+ header = fill(str(cfg.get("header", "user@github")), values)
23
+ rows.append([("header", header + " "), ("dots", RULE * max(3, width - len(header) - 1))])
24
+
25
+ for item in cfg.get("lines") or []:
26
+ if item is None or item == "":
27
+ rows.append([("dots", ".".ljust(width))])
28
+ elif isinstance(item, dict) and "section" in item:
29
+ title = fill(str(item["section"]), values)
30
+ rows.append([("dots", RULE + " "), ("section", title + " "),
31
+ ("dots", RULE * max(3, width - len(title) - 3))])
32
+ elif isinstance(item, dict) and len(item) == 1:
33
+ key, value = next(iter(item.items()))
34
+ key = fill(str(key), values)
35
+ value = fill("" if value is None else str(value), values)
36
+ gap = width - len(key) - len(value) - 5 # ". " + ":" + " " + dots + " "
37
+ if gap < 1:
38
+ print(f"warning: '{key}: {value}' is longer than width {width}", file=sys.stderr)
39
+ gap = 1
40
+ rows.append([("dots", ". "), ("key", key + ":"),
41
+ ("dots", " " + "." * gap + " "), ("value", value)])
42
+ elif isinstance(item, str):
43
+ rows.append([("value", (" " + fill(item, values)).ljust(width))])
44
+ else:
45
+ raise ConfigError(
46
+ f"can't read line {item!r}. Use 'Key: value', 'section: Title', plain text, or a bare '-'."
47
+ )
48
+ return rows
49
+
50
+
51
+ def row_text(row: list[Span]) -> str:
52
+ return "".join(text for _, text in row)