okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
7.3 KiB199 linesraw
1#!/usr/bin/env python3
2"""Prepare local web assets from the supplied Strata logo masters.
3
4Requires fontTools only while preparing the outlined wordmark. The checked-in
5exports have no font or Python dependency at app runtime. Source files stay
6untouched; public/brand/source-manifest.json records every derivation.
7"""
8
9from __future__ import annotations
10
11import hashlib
12import json
13from pathlib import Path
14import shutil
15import xml.etree.ElementTree as ET
16
17from fontTools.pens.svgPathPen import SVGPathPen
18from fontTools.ttLib import TTFont
19
20
21APP = Path(__file__).resolve().parent.parent
22MASTERS = APP.parent / "Strata-Logo-DesignFiles"
23PUBLIC = APP / "public"
24BRAND = PUBLIC / "brand"
25FONT = PUBLIC / "fonts" / "GTWalsheimPro-Bold.woff2"
26SVG_NS = "http://www.w3.org/2000/svg"
27INK = {"light": "#221e1f", "dark": "#eef1f3"}
28GREEN = {"light": "#10b981", "dark": "#34d399"}
29
30
31def digest(path: Path) -> str:
32    return hashlib.sha256(path.read_bytes()).hexdigest()
33
34
35def source(relative: str) -> Path:
36    path = MASTERS / relative
37    if not path.is_file():
38        raise FileNotFoundError(path)
39    return path
40
41
42def record(entries: list[dict[str, str]], master: str, output: Path, method: str) -> None:
43    entries.append({
44        "source": master,
45        "source_sha256": digest(source(master)),
46        "output": output.relative_to(PUBLIC).as_posix(),
47        "output_sha256": digest(output),
48        "method": method,
49    })
50
51
52def copy(entries: list[dict[str, str]], master: str, output: Path) -> None:
53    output.parent.mkdir(parents=True, exist_ok=True)
54    shutil.copyfile(source(master), output)
55    record(entries, master, output, "unchanged copy")
56
57
58def art_rectangles(master: str) -> str:
59    root = ET.parse(source(master)).getroot()
60    rects = root.findall(f"{{{SVG_NS}}}rect")
61    if len(rects) != 3:
62        raise ValueError(f"Expected the three approved bars in {master}")
63    return "\n".join(
64        f'<rect x="{r.attrib["x"]}" y="{r.attrib["y"]}" '
65        f'width="{r.attrib["width"]}" height="{r.attrib["height"]}" '
66        f'rx="{r.attrib["rx"]}" fill="{r.attrib["fill"]}" />'
67        for r in rects
68    )
69
70
71def outlined_wordmark(font: TTFont) -> str:
72    cmap = font.getBestCmap()
73    glyphs = font.getGlyphSet()
74    scale = 44 / font["head"].unitsPerEm
75    tracking_units = 1.54 / scale
76    cursor = 0.0
77    paths = []
78    letters = "strata"
79    names = [cmap[ord(letter)] for letter in letters]
80    for index, name in enumerate(names):
81        pen = SVGPathPen(glyphs)
82        glyphs[name].draw(pen)
83        paths.append(f'<path transform="translate({cursor:.4f} 0)" d="{pen.getCommands()}" />')
84        cursor += font["hmtx"][name][0] - tracking_units
85        if index + 1 < len(names):
86            cursor += pair_kerning(font, name, names[index + 1])
87    return (f'<g transform="translate(60 37.75) scale({scale:.6f} -{scale:.6f})">'
88            + "".join(paths) + "</g>")
89
90
91def pair_kerning(font: TTFont, left: str, right: str) -> int:
92    """Apply the font's OpenType kern feature for this fixed six-letter word."""
93    gpos = font["GPOS"].table
94    kern_lookups = {
95        index
96        for feature in gpos.FeatureList.FeatureRecord
97        if feature.FeatureTag == "kern"
98        for index in feature.Feature.LookupListIndex
99    }
100    adjustment = 0
101    for index in sorted(kern_lookups):
102        lookup = gpos.LookupList.Lookup[index]
103        if lookup.LookupType != 2:
104            continue
105        for subtable in lookup.SubTable:
106            if left not in subtable.Coverage.glyphs:
107                continue
108            value = None
109            if subtable.Format == 1:
110                row = subtable.PairSet[subtable.Coverage.glyphs.index(left)]
111                value = next((pair.Value1 for pair in row.PairValueRecord
112                              if pair.SecondGlyph == right), None)
113                if value is None:
114                    continue
115            elif subtable.Format == 2:
116                first = subtable.ClassDef1.classDefs.get(left, 0)
117                second = subtable.ClassDef2.classDefs.get(right, 0)
118                value = subtable.Class1Record[first].Class2Record[second].Value1
119            adjustment += (value.XAdvance or 0) if value else 0
120            break
121    return adjustment
122
123
124def prepare_lockup(entries: list[dict[str, str]], theme: str, font: TTFont) -> None:
125    master = f"logo/strata-lockup-{theme}.svg"
126    output = BRAND / f"strata-lockup-{theme}.svg"
127    output.write_text(
128        '<svg xmlns="http://www.w3.org/2000/svg" width="182" height="48" '
129        'viewBox="0 0 182 48" role="img">\n'
130        f"{art_rectangles(master)}\n"
131        f'<g fill="{INK[theme]}">{outlined_wordmark(font)}</g>\n'
132        "</svg>\n"
133    )
134    record(entries, master, output, f"outlined GT Walsheim Pro Bold from {FONT.relative_to(APP)}")
135
136
137def prepare_favicon(entries: list[dict[str, str]]) -> None:
138    master = "web/favicon.svg"
139    root = ET.parse(source(master)).getroot()
140    rects = root.findall(f"{{{SVG_NS}}}rect")
141    if len(rects) != 3:
142        raise ValueError("Expected the supplied three-bar favicon")
143    output = PUBLIC / "favicon.svg"
144    bars = "\n".join(
145        f'<rect class="{r.attrib["class"]}" x="{r.attrib["x"]}" '
146        f'y="{r.attrib["y"]}" width="{r.attrib["width"]}" '
147        f'height="{r.attrib["height"]}" rx="{r.attrib["rx"]}" '
148        f'fill="{INK["light"] if r.attrib["class"] == "i" else GREEN["light"]}" />'
149        for r in rects
150    )
151    output.write_text(
152        '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" '
153        'viewBox="3 3 42 42">\n'
154        '<style>@media (prefers-color-scheme: dark) {'
155        f'.i {{ fill: {INK["dark"]}; }} .a {{ fill: {GREEN["dark"]}; }}'
156        '}</style>\n'
157        f'{bars}\n</svg>\n'
158    )
159    record(entries, master, output, "explicit light fills and self-contained dark media style")
160
161
162def prepare_manifest(entries: list[dict[str, str]]) -> None:
163    master = "web/site.webmanifest"
164    manifest = json.loads(source(master).read_text())
165    manifest.update({"id": "/", "start_url": "/#/chat", "scope": "/"})
166    output = PUBLIC / "site.webmanifest"
167    output.write_text(json.dumps(manifest, indent=2) + "\n")
168    record(entries, master, output, "root-local app identity and hash-route launch")
169
170
171def main() -> None:
172    BRAND.mkdir(parents=True, exist_ok=True)
173    entries: list[dict[str, str]] = []
174    for theme in ("light", "dark"):
175        copy(entries, f"logo/strata-mark-{theme}.svg", BRAND / f"strata-mark-{theme}.svg")
176    font = TTFont(FONT)
177    for theme in ("light", "dark"):
178        prepare_lockup(entries, theme, font)
179    prepare_favicon(entries)
180    for name in (
181        "favicon-16.png", "favicon-32.png", "favicon-48.png",
182        "favicon-dark-16.png", "favicon-dark-32.png", "favicon-dark-48.png",
183        "apple-touch-icon.png", "icon-192.png", "icon-512.png",
184    ):
185        copy(entries, f"web/{name}", PUBLIC / name)
186    prepare_manifest(entries)
187    (BRAND / "source-manifest.json").write_text(json.dumps({
188        "source_root": str(MASTERS),
189        "preparation": "scripts/prepare-brand-assets.py",
190        "font": str(FONT.relative_to(APP)),
191        "font_sha256": digest(FONT),
192        "note": "Derived SVGs omit source C2PA metadata; original masters remain untouched and each source hash is recorded here.",
193        "files": entries,
194    }, indent=2) + "\n")
195    print(f"Prepared {len(entries)} web assets in {PUBLIC}")
196
197
198if __name__ == "__main__":
199    main()