design_engine.py 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816
  1. #!/usr/bin/env python3
  2. """
  3. design_engine.py — Aesthetic computation engine for art-direction-first PDF production.
  4. Philosophy: The LLM handles narrative and composition; this script handles the math
  5. that models get wrong — precise color harmony, algorithmic SVG, and spatial tension.
  6. Three core functions:
  7. 1. generate_color_palette(intent) — HSL-locked low-saturation palettes
  8. 2. generate_generative_svg(svg_type) — Algorithmic art backgrounds
  9. 3. calculate_layout(elements) — Deliberate offset/overlap coordinates
  10. Usage:
  11. "$(command -v zcode-python || command -v python3)" design_engine.py palette --intent calm --mode dark
  12. "$(command -v zcode-python || command -v python3)" design_engine.py palette --intent tension --mode light
  13. "$(command -v zcode-python || command -v python3)" design_engine.py svg --intent flow --dimensions 720x960
  14. "$(command -v zcode-python || command -v python3)" design_engine.py svg --intent grid --dimensions 720x960
  15. "$(command -v zcode-python || command -v python3)" design_engine.py layout --elements hero,body,meta --dimensions 720x960 --style offset
  16. "$(command -v zcode-python || command -v python3)" design_engine.py full --intent energy --mode dark --dimensions 720x960 --output-dir ./assets/
  17. """
  18. import argparse
  19. import colorsys
  20. import json
  21. import math
  22. import os
  23. import random
  24. import sys
  25. # ═══════════════════════════════════════════════════════════════════════
  26. # 1. COLOR PALETTE — HSL with Saturation Clamped to [0.05, 0.25]
  27. # ═══════════════════════════════════════════════════════════════════════
  28. #
  29. # Core constraint: Saturation MUST be between 0.05 and 0.25.
  30. # This eliminates candy-colored, web-app-looking outputs and locks
  31. # everything into the "high-end grey" (高级灰) tonal range.
  32. #
  33. # Two modes:
  34. # - Dark: background L < 0.10, text L > 0.85
  35. # - Light: background L > 0.95, text L < 0.15
  36. # The "muddy middle" (L between 0.30 and 0.70) is forbidden for backgrounds.
  37. # Intent → base hue mapping (degrees on the HSL wheel)
  38. # 5 intents: Calm, Tension, Energy, Authority, Warmth
  39. # Plus utility intents (nature, cold, neutral) for keyword auto-derive
  40. INTENT_HUES = {
  41. "calm": 210, # Steel blue-grey, low saturation (merges old serenity+minimalism)
  42. "tension": 0, # Warm near-black vs cold
  43. "energy": 30, # Amber undertone
  44. "authority": 280, # Muted violet, formal/premium (replaces old elegance)
  45. "warmth": 20, # Terracotta undertone
  46. # Utility intents (for keyword auto-derive, not exposed in UI)
  47. "nature": 150, # Desaturated sage
  48. "cold": 200, # Slate blue
  49. "neutral": 45, # Warm grey
  50. # Legacy aliases (backward compatibility)
  51. "serenity": 210, # → calm
  52. "elegance": 280, # → authority
  53. "minimalism": 0, # → calm (achromatic variant)
  54. }
  55. # Theme keywords → intent mapping (for auto-derive from document description)
  56. # When the user doesn't specify an intent, scan the document title/description
  57. # for these keywords and map to the closest intent.
  58. THEME_KEYWORDS = {
  59. # Technology / Data / Analytics
  60. "tech": "cold", "数据": "cold", "data": "cold", "AI": "cold",
  61. "科技": "cold", "digital": "cold", "analytics": "cold", "分析": "cold",
  62. # Nature / Environment / Sustainability
  63. "green": "nature", "绿色": "nature", "环保": "nature", "eco": "nature",
  64. "sustainability": "nature", "生态": "nature", "forest": "nature",
  65. # Business / Finance / Corporate
  66. "report": "neutral", "报告": "neutral", "finance": "neutral", "财务": "neutral",
  67. "annual": "neutral", "年度": "neutral", "corporate": "neutral",
  68. # Creative / Marketing / Social
  69. "marketing": "energy", "运营": "energy", "social": "energy", "品牌": "energy",
  70. "campaign": "energy", "活动": "energy", "launch": "energy",
  71. # Authority / Formal / Premium / Luxury
  72. "luxury": "authority", "奢华": "authority", "fashion": "authority", "时尚": "authority",
  73. "premium": "authority", "高端": "authority", "gala": "authority",
  74. "formal": "authority", "正式": "authority", "professional": "authority", "专业": "authority",
  75. "government": "authority", "政府": "authority", "bidding": "authority", "投标": "authority",
  76. "政府报告": "authority", "政府文书": "authority", "公文": "authority",
  77. "thesis": "authority", "毕业论文": "authority", "dissertation": "authority",
  78. "开题": "authority", "开题报告": "authority", "proposal": "authority", "学位": "authority",
  79. # Calm / Meditation / Healthcare / Minimalist
  80. "health": "calm", "健康": "calm", "meditation": "calm",
  81. "wellness": "calm", "calm": "calm", "医疗": "calm",
  82. "minimalist": "calm", "极简": "calm", "simple": "calm", "简约": "calm",
  83. # Urgent / Warning / Emergency
  84. "urgent": "tension", "warning": "tension", "紧急": "tension",
  85. "alert": "tension", "crisis": "tension",
  86. # Warm / Food / Lifestyle
  87. "food": "warmth", "美食": "warmth", "lifestyle": "warmth",
  88. "生活": "warmth", "home": "warmth", "家居": "warmth",
  89. }
  90. def derive_intent(text):
  91. """
  92. Auto-derive design intent from document title/description.
  93. Scans for theme keywords and returns the best-matching intent.
  94. Falls back to 'neutral' if no keywords match.
  95. Usage:
  96. "$(command -v zcode-python || command -v python3)" design_engine.py derive "Social Media Operations Monthly Report" → energy
  97. "$(command -v zcode-python || command -v python3)" design_engine.py derive "2025 Annual Sustainability Report" → nature
  98. """
  99. text_lower = text.lower()
  100. scores = {}
  101. for keyword, intent in THEME_KEYWORDS.items():
  102. if keyword.lower() in text_lower:
  103. scores[intent] = scores.get(intent, 0) + 1
  104. if not scores:
  105. return "neutral"
  106. # When tied, prefer specific intents over 'neutral' (which is a generic fallback)
  107. max_score = max(scores.values())
  108. top_intents = [k for k, v in scores.items() if v == max_score]
  109. if len(top_intents) > 1 and "neutral" in top_intents:
  110. top_intents.remove("neutral")
  111. return top_intents[0]
  112. # Intent → recommended harmony mapping (reduces LLM decision burden)
  113. # Used as fallback when LLM doesn't specify color_harmony
  114. INTENT_HARMONY_MAP = {
  115. "calm": "analogous", # peaceful, flowing transition (merges serenity+minimalism)
  116. "tension": "complementary", # maximum visual conflict
  117. "energy": "triadic", # vibrant, multi-directional
  118. "authority": "split_complementary", # sophisticated, formal (replaces elegance)
  119. "warmth": "analogous", # natural, earthy cohesion
  120. # Utility intents
  121. "nature": "analogous", # organic harmony
  122. "cold": "split_complementary", # icy precision with subtle warmth
  123. "neutral": "split_complementary", # safe default, still interesting
  124. # Legacy aliases
  125. "serenity": "analogous",
  126. "elegance": "split_complementary",
  127. "minimalism": "monochrome",
  128. }
  129. def _hsl_to_hex(h, s, l):
  130. """Convert HSL (h: 0-360, s: 0-1, l: 0-1) to hex string."""
  131. r, g, b = colorsys.hls_to_rgb(h / 360.0, l, s)
  132. return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
  133. # Muddy / ugly hue zones that produce unattractive accent colors at medium saturation.
  134. # These hue ranges tend to look "dirty" or "sickly" — yellow-green, brown-orange, etc.
  135. # When an accent lands here, we nudge it to the nearest attractive neighbor.
  136. _UGLY_HUE_ZONES = [
  137. # (start, end, nudge_low, nudge_high) — hues that look muddy
  138. # at S 0.4-0.7, L 0.35-0.55. When accent lands here, redirect.
  139. (28, 105, 15, 120), # Dirty yellow/brown/olive/yellow-green zone
  140. # nudge_low=15 (warm red-orange), nudge_high=120 (true green)
  141. ]
  142. def _sanitize_accent_hue(hue):
  143. """Nudge accent hue away from muddy/ugly zones toward attractive neighbors."""
  144. hue = hue % 360
  145. for start, end, nudge_low, nudge_high in _UGLY_HUE_ZONES:
  146. if start <= hue <= end:
  147. mid = (start + end) / 2
  148. return nudge_low if hue < mid else nudge_high
  149. return hue
  150. def _hex_to_rgb(hex_str):
  151. """Convert hex to 'r,g,b' string for rgba() usage."""
  152. hex_str = hex_str.lstrip('#')
  153. return f"{int(hex_str[0:2], 16)},{int(hex_str[2:4], 16)},{int(hex_str[4:6], 16)}"
  154. def _relative_luminance(hex_str):
  155. """WCAG 2.1 relative luminance from hex color."""
  156. hex_str = hex_str.lstrip('#')
  157. channels = []
  158. for i in (0, 2, 4):
  159. c = int(hex_str[i:i+2], 16) / 255.0
  160. channels.append(c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4)
  161. return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
  162. def _contrast_ratio(hex1, hex2):
  163. """WCAG contrast ratio between two hex colors."""
  164. l1, l2 = _relative_luminance(hex1), _relative_luminance(hex2)
  165. lighter, darker = max(l1, l2), min(l1, l2)
  166. return (lighter + 0.05) / (darker + 0.05)
  167. def generate_color_palette(intent="neutral", mode="minimal", harmony=None, seed=None):
  168. """
  169. Generative Color Harmony Engine — geometric accent computation + 5 aesthetic modes.
  170. LLM is FORBIDDEN from specifying HEX/RGB. It only selects:
  171. - intent → base hue (from INTENT_HUES)
  172. - mode → S/L physical boundaries (minimal/dark/pastel/jewel/light)
  173. - harmony → accent hue geometry (auto-recommended from intent if omitted)
  174. Returns dict with:
  175. - bg: 60% — dominant ground
  176. - mid: 30% — structural shade
  177. - accent: 10% — geometric harmony emphasis
  178. - text: primary text color
  179. - muted: secondary/caption text
  180. - surface: card/container background (translucent)
  181. """
  182. if seed is not None:
  183. random.seed(seed)
  184. # Auto-recommend harmony from intent if not specified
  185. if harmony is None or harmony == "auto":
  186. harmony = INTENT_HARMONY_MAP.get(intent, "split_complementary")
  187. base_hue = INTENT_HUES.get(intent, random.randint(0, 359))
  188. # 1. Geometric Accent Hue Derivation
  189. if harmony == "complementary":
  190. accent_hue = (base_hue + 180) % 360
  191. elif harmony == "split_complementary":
  192. accent_hue = (base_hue + random.choice([150, 210])) % 360
  193. elif harmony == "triadic":
  194. accent_hue = (base_hue + random.choice([120, 240])) % 360
  195. elif harmony == "analogous":
  196. accent_hue = (base_hue + random.choice([30, -30, 45, -45])) % 360
  197. else: # monochrome
  198. accent_hue = base_hue
  199. # Sanitize accent hue — avoid muddy yellow-green and brown-orange zones
  200. accent_hue = _sanitize_accent_hue(accent_hue)
  201. # 2. Five Aesthetic Modes — hard-lock S and L boundaries
  202. if mode == "minimal":
  203. # DEFAULT for 50%+ of documents. Editorial paper tone + high-purity accent.
  204. # bg has visible tint (S 0.08-0.15, L 0.92-0.96) — not dead white.
  205. is_warm = random.choice([True, False])
  206. paper_hue = random.randint(35, 45) if is_warm else random.randint(200, 215)
  207. bg = _hsl_to_hex(paper_hue, random.uniform(0.08, 0.15), random.uniform(0.92, 0.96))
  208. mid = _hsl_to_hex(paper_hue, random.uniform(0.10, 0.18), random.uniform(0.85, 0.90))
  209. accent = _hsl_to_hex(accent_hue, random.uniform(0.55, 0.72), random.uniform(0.42, 0.52))
  210. text = _hsl_to_hex(paper_hue, 0.05, random.uniform(0.10, 0.15))
  211. muted = _hsl_to_hex(paper_hue, 0.05, random.uniform(0.45, 0.55))
  212. surface = f"rgba(0,0,0,{random.uniform(0.01, 0.03):.2f})"
  213. elif mode == "dark":
  214. # Cyber/tech: ultra-low saturation, ultra-low lightness
  215. bg = _hsl_to_hex(base_hue, random.uniform(0.04, 0.10), random.uniform(0.04, 0.08))
  216. mid = _hsl_to_hex(base_hue, random.uniform(0.08, 0.15), random.uniform(0.12, 0.20))
  217. accent = _hsl_to_hex(accent_hue, random.uniform(0.45, 0.60), random.uniform(0.52, 0.62))
  218. text = _hsl_to_hex(base_hue, 0.05, random.uniform(0.88, 0.95))
  219. muted = _hsl_to_hex(base_hue, 0.05, random.uniform(0.45, 0.55))
  220. surface = f"rgba(255,255,255,{random.uniform(0.03, 0.06):.2f})"
  221. elif mode == "pastel":
  222. # Morandi/macaron: medium-low saturation, high lightness
  223. # Accent tightened: S capped at 0.50 to avoid clashing with tinted bg
  224. bg = _hsl_to_hex(base_hue, random.uniform(0.15, 0.35), random.uniform(0.85, 0.92))
  225. mid = _hsl_to_hex(base_hue, random.uniform(0.20, 0.40), random.uniform(0.75, 0.82))
  226. accent = _hsl_to_hex(accent_hue, random.uniform(0.38, 0.50), random.uniform(0.38, 0.48))
  227. text = _hsl_to_hex(base_hue, 0.15, random.uniform(0.15, 0.25))
  228. muted = _hsl_to_hex(base_hue, 0.20, random.uniform(0.45, 0.55))
  229. surface = f"rgba(255,255,255,{random.uniform(0.30, 0.50):.2f})"
  230. elif mode == "jewel":
  231. # Gem/luxury: medium-high saturation bg, accent must NOT compete — lower S, higher L
  232. bg = _hsl_to_hex(base_hue, random.uniform(0.40, 0.60), random.uniform(0.15, 0.25))
  233. mid = _hsl_to_hex(base_hue, random.uniform(0.40, 0.60), random.uniform(0.25, 0.35))
  234. accent = _hsl_to_hex(accent_hue, random.uniform(0.30, 0.50), random.uniform(0.65, 0.80))
  235. text = _hsl_to_hex(base_hue, 0.10, random.uniform(0.90, 0.96))
  236. muted = _hsl_to_hex(base_hue, 0.20, random.uniform(0.60, 0.70))
  237. surface = f"rgba(0,0,0,{random.uniform(0.20, 0.40):.2f})"
  238. else:
  239. # light — noticeably tinted, not dead white (S 0.10-0.20, L 0.91-0.95)
  240. bg = _hsl_to_hex(base_hue, random.uniform(0.10, 0.20), random.uniform(0.91, 0.95))
  241. mid = _hsl_to_hex(base_hue, random.uniform(0.15, 0.25), random.uniform(0.84, 0.90))
  242. accent = _hsl_to_hex(accent_hue, random.uniform(0.35, 0.45), random.uniform(0.35, 0.45))
  243. text = _hsl_to_hex(base_hue, 0.08, random.uniform(0.08, 0.15))
  244. muted = _hsl_to_hex(base_hue, 0.05, random.uniform(0.45, 0.55))
  245. surface = f"rgba(0,0,0,{random.uniform(0.02, 0.05):.2f})"
  246. # 3. WCAG Contrast Safety Net — ensure text:bg ratio ≥ 4.5:1
  247. text_cr = _contrast_ratio(text, bg)
  248. if text_cr < 4.5:
  249. # Push text darker (light modes) or lighter (dark modes)
  250. r, g, b = (int(bg.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
  251. _, bg_l, _ = colorsys.rgb_to_hls(r, g, b)
  252. if bg_l > 0.5:
  253. text = _hsl_to_hex(base_hue, 0.08, 0.08) # force near-black
  254. else:
  255. text = _hsl_to_hex(base_hue, 0.05, 0.95) # force near-white
  256. # 4. Accent-on-bg visibility check — ensure accent stands out (ratio ≥ 3:1)
  257. accent_cr = _contrast_ratio(accent, bg)
  258. if accent_cr < 3.0:
  259. # Nudge accent lightness away from bg
  260. r, g, b = (int(bg.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
  261. _, bg_l, _ = colorsys.rgb_to_hls(r, g, b)
  262. target_l = 0.35 if bg_l > 0.5 else 0.70
  263. r2, g2, b2 = (int(accent.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
  264. _, _, accent_s = colorsys.rgb_to_hls(r2, g2, b2)
  265. accent = _hsl_to_hex(accent_hue, accent_s, target_l)
  266. return {
  267. "bg": bg, "bg_rgb": _hex_to_rgb(bg),
  268. "mid": mid, "mid_rgb": _hex_to_rgb(mid),
  269. "accent": accent, "accent_rgb": _hex_to_rgb(accent),
  270. "text": text, "muted": muted,
  271. "surface": surface,
  272. "meta": {
  273. "intent": intent, "mode": mode, "harmony": harmony,
  274. "base_hue": base_hue, "accent_hue": accent_hue,
  275. "contrast": {
  276. "text_on_bg": round(_contrast_ratio(text, bg), 2),
  277. "accent_on_bg": round(_contrast_ratio(accent, bg), 2),
  278. }
  279. }
  280. }
  281. def palette_to_css(palette):
  282. """Convert palette dict to CSS custom properties."""
  283. return f""":root {{
  284. /* 60% ground */
  285. --c-bg: {palette['bg']};
  286. --c-bg-rgb: {palette['bg_rgb']};
  287. /* 30% structure */
  288. --c-mid: {palette['mid']};
  289. --c-mid-rgb: {palette['mid_rgb']};
  290. /* 10% emphasis */
  291. --c-accent: {palette['accent']};
  292. --c-accent-rgb: {palette['accent_rgb']};
  293. /* Typography */
  294. --c-text: {palette['text']};
  295. --c-muted: {palette['muted']};
  296. /* Surfaces */
  297. --c-surface: {palette['surface']};
  298. }}"""
  299. # ═══════════════════════════════════════════════════════════════════════
  300. # 1b. CASCADE PALETTE — Role-Based Unified Color System
  301. # ═══════════════════════════════════════════════════════════════════════
  302. #
  303. # Iron Law: Area ∝ 1/Saturation.
  304. # The larger the colored area, the LOWER its saturation must be.
  305. #
  306. # Role tiers by area usage:
  307. # XL (>50% of page): page_bg, section_bg → S ≤ 0.08, near-white/near-black
  308. # L (20-50%): card_bg, table_stripe → S ≤ 0.15
  309. # M (5-20%): header_fill, sidebar → S ≤ 0.30
  310. # S (1-5%): border, divider, icon → S ≤ 0.50
  311. # XS (<1%): accent_dot, badge, tag → S up to 0.75 (the only place high-sat lives)
  312. #
  313. # Every color is derived from one base hue. No orphan colors.
  314. # Tier saturation caps — enforced at generation AND audit time
  315. CASCADE_TIER_CAPS = {
  316. "xl": 0.08, # Page background, section background
  317. "l": 0.15, # Card background, table stripe
  318. "m": 0.30, # Header fill, sidebar, cover decorative blocks
  319. "s": 0.50, # Borders, dividers, icons, chart grid lines
  320. "xs": 0.75, # Accent dot, badge, tag, data point highlight
  321. }
  322. def generate_cascade_palette(intent="neutral", mode="minimal", harmony=None, seed=None):
  323. """
  324. Generate a role-based palette cascade where every color is derived from one
  325. base hue and saturation is inversely proportional to usage area.
  326. Returns a dict with:
  327. roles: Complete role table (12 roles, each with hex, hsl, tier, usage_hint)
  328. cover: Subset of roles for cover page rendering
  329. body: Subset of roles for body content
  330. charts: Subset of roles for data visualization
  331. semantic: Low-saturation semantic colors (success, warning, error, info)
  332. meta: Generation metadata (intent, mode, harmony, base_hue, audit)
  333. css: Ready-to-use CSS custom properties
  334. reportlab: Ready-to-paste ReportLab Python code
  335. """
  336. if seed is not None:
  337. random.seed(seed)
  338. if harmony is None or harmony == "auto":
  339. harmony = INTENT_HARMONY_MAP.get(intent, "split_complementary")
  340. base_hue = INTENT_HUES.get(intent, random.randint(0, 359))
  341. # Geometric accent hue derivation (same logic as original)
  342. if harmony == "complementary":
  343. accent_hue = (base_hue + 180) % 360
  344. elif harmony == "split_complementary":
  345. accent_hue = (base_hue + random.choice([150, 210])) % 360
  346. elif harmony == "triadic":
  347. accent_hue = (base_hue + random.choice([120, 240])) % 360
  348. elif harmony == "analogous":
  349. accent_hue = (base_hue + random.choice([30, -30, 45, -45])) % 360
  350. else: # monochrome
  351. accent_hue = base_hue
  352. # Sanitize accent hue — avoid muddy zones
  353. accent_hue = _sanitize_accent_hue(accent_hue)
  354. # Secondary hue — between base and accent, for chart variety
  355. secondary_hue = _sanitize_accent_hue(
  356. (base_hue + accent_hue) / 2 if accent_hue != base_hue else (base_hue + 30) % 360
  357. )
  358. # Mode-dependent lightness anchors
  359. is_dark = mode == "dark"
  360. if is_dark:
  361. bg_l_range = (0.04, 0.08)
  362. text_l = random.uniform(0.88, 0.95)
  363. muted_l = random.uniform(0.50, 0.60)
  364. elif mode == "jewel":
  365. bg_l_range = (0.15, 0.25)
  366. text_l = random.uniform(0.90, 0.96)
  367. muted_l = random.uniform(0.60, 0.70)
  368. else: # minimal, pastel, light
  369. bg_l_range = (0.94, 0.97)
  370. text_l = random.uniform(0.08, 0.15)
  371. muted_l = random.uniform(0.45, 0.55)
  372. # ── Generate all 12 roles ──
  373. roles = {}
  374. # XL tier: page bg, section bg
  375. roles["page_bg"] = _make_role(
  376. base_hue, random.uniform(0.03, 0.08), random.uniform(*bg_l_range),
  377. "xl", "Page background, full-bleed areas")
  378. roles["section_bg"] = _make_role(
  379. base_hue, random.uniform(0.04, 0.08),
  380. random.uniform(bg_l_range[0] - 0.03, bg_l_range[1] - 0.02) if not is_dark
  381. else random.uniform(0.08, 0.14),
  382. "xl", "Section background, alternating bands")
  383. # L tier: card bg, table stripe
  384. roles["card_bg"] = _make_role(
  385. base_hue, random.uniform(0.06, 0.14),
  386. random.uniform(0.90, 0.94) if not is_dark else random.uniform(0.10, 0.16),
  387. "l", "Card/container background, table even rows")
  388. roles["table_stripe"] = _make_role(
  389. base_hue, random.uniform(0.05, 0.12),
  390. random.uniform(0.92, 0.96) if not is_dark else random.uniform(0.08, 0.12),
  391. "l", "Table alternating row fill")
  392. # M tier: header fill, sidebar, cover decorative block
  393. roles["header_fill"] = _make_role(
  394. base_hue, random.uniform(0.15, 0.28),
  395. random.uniform(0.25, 0.40) if not is_dark else random.uniform(0.20, 0.30),
  396. "m", "Table header, sidebar background, cover top bar")
  397. roles["cover_block"] = _make_role(
  398. base_hue, random.uniform(0.12, 0.25),
  399. random.uniform(0.30, 0.45) if not is_dark else random.uniform(0.15, 0.25),
  400. "m", "Cover decorative block, sidebar pillar")
  401. # S tier: border, divider, icon fill
  402. roles["border"] = _make_role(
  403. base_hue, random.uniform(0.10, 0.25),
  404. random.uniform(0.70, 0.82) if not is_dark else random.uniform(0.25, 0.35),
  405. "s", "Borders, divider lines, chart grid")
  406. roles["icon"] = _make_role(
  407. base_hue, random.uniform(0.25, 0.45),
  408. random.uniform(0.35, 0.50) if not is_dark else random.uniform(0.55, 0.70),
  409. "s", "Icons, bullet points, small UI elements")
  410. # XS tier: accent, badge, data highlight
  411. roles["accent"] = _make_role(
  412. accent_hue, random.uniform(0.50, 0.70),
  413. random.uniform(0.40, 0.55) if not is_dark else random.uniform(0.55, 0.70),
  414. "xs", "Primary accent: badges, tags, data point highlights, CTA")
  415. roles["accent_secondary"] = _make_role(
  416. secondary_hue, random.uniform(0.40, 0.60),
  417. random.uniform(0.45, 0.58) if not is_dark else random.uniform(0.50, 0.65),
  418. "xs", "Secondary accent: chart series 2, secondary badge")
  419. # Typography (no tier — text is special)
  420. roles["text_primary"] = _make_role(
  421. base_hue, 0.05, text_l,
  422. "text", "Primary body text")
  423. roles["text_muted"] = _make_role(
  424. base_hue, 0.04, muted_l,
  425. "text", "Captions, footnotes, secondary text")
  426. # ── Semantic colors (derived from base hue, low-sat) ──
  427. semantic = {
  428. "success": _make_role(140, random.uniform(0.25, 0.40),
  429. random.uniform(0.35, 0.45) if not is_dark else random.uniform(0.55, 0.65),
  430. "xs", "Positive: growth, pass, complete"),
  431. "warning": _make_role(40, random.uniform(0.30, 0.45),
  432. random.uniform(0.40, 0.50) if not is_dark else random.uniform(0.55, 0.65),
  433. "xs", "Caution: pending, alert"),
  434. "error": _make_role(5, random.uniform(0.30, 0.45),
  435. random.uniform(0.40, 0.50) if not is_dark else random.uniform(0.55, 0.65),
  436. "xs", "Negative: decline, fail, error"),
  437. "info": _make_role(210, random.uniform(0.25, 0.40),
  438. random.uniform(0.40, 0.50) if not is_dark else random.uniform(0.55, 0.65),
  439. "xs", "Informational: neutral status"),
  440. }
  441. # ── WCAG contrast enforcement ──
  442. page_bg_hex = roles["page_bg"]["hex"]
  443. text_hex = roles["text_primary"]["hex"]
  444. if _contrast_ratio(text_hex, page_bg_hex) < 4.5:
  445. if not is_dark:
  446. roles["text_primary"] = _make_role(base_hue, 0.08, 0.08, "text", "Primary body text")
  447. else:
  448. roles["text_primary"] = _make_role(base_hue, 0.05, 0.95, "text", "Primary body text")
  449. accent_hex = roles["accent"]["hex"]
  450. if _contrast_ratio(accent_hex, page_bg_hex) < 3.0:
  451. # Push accent lightness further from bg
  452. r, g, b = (int(page_bg_hex.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
  453. _, bg_l, _ = colorsys.rgb_to_hls(r, g, b)
  454. target_l = 0.35 if bg_l > 0.5 else 0.75
  455. roles["accent"] = _make_role(accent_hue, random.uniform(0.50, 0.70), target_l,
  456. "xs", "Primary accent: badges, tags, data point highlights, CTA")
  457. # ── Tier saturation audit (clamp any violations) ──
  458. for name, role in {**roles, **semantic}.items():
  459. tier = role["tier"]
  460. if tier in CASCADE_TIER_CAPS:
  461. cap = CASCADE_TIER_CAPS[tier]
  462. if role["hsl"][1] > cap:
  463. # Re-generate with capped saturation
  464. capped_s = cap * random.uniform(0.85, 1.0)
  465. fixed = _make_role(role["hsl"][0], capped_s, role["hsl"][2],
  466. tier, role["usage_hint"])
  467. if name in roles:
  468. roles[name] = fixed
  469. elif name in semantic:
  470. semantic[name] = fixed
  471. # ── Build convenience subsets ──
  472. cover_subset = {
  473. "background": roles["page_bg"]["hex"],
  474. "top_bar": roles["header_fill"]["hex"],
  475. "sidebar": roles["cover_block"]["hex"],
  476. "accent_line": roles["accent"]["hex"],
  477. "title": roles["text_primary"]["hex"],
  478. "subtitle": roles["text_muted"]["hex"],
  479. "watermark": roles["border"]["hex"], # low-opacity usage
  480. }
  481. body_subset = {
  482. "page_bg": roles["page_bg"]["hex"],
  483. "section_bg": roles["section_bg"]["hex"],
  484. "card_bg": roles["card_bg"]["hex"],
  485. "table_header": roles["header_fill"]["hex"],
  486. "table_stripe": roles["table_stripe"]["hex"],
  487. "border": roles["border"]["hex"],
  488. "heading": roles["text_primary"]["hex"],
  489. "body_text": roles["text_primary"]["hex"],
  490. "caption": roles["text_muted"]["hex"],
  491. "highlight": roles["accent"]["hex"],
  492. }
  493. chart_subset = {
  494. "series_1": roles["accent"]["hex"],
  495. "series_2": roles["accent_secondary"]["hex"],
  496. "series_3": roles["header_fill"]["hex"],
  497. "series_4": roles["icon"]["hex"],
  498. "series_5": roles["cover_block"]["hex"],
  499. "grid": roles["border"]["hex"],
  500. "axis_text": roles["text_muted"]["hex"],
  501. "label": roles["text_primary"]["hex"],
  502. "up": semantic["success"]["hex"],
  503. "down": semantic["error"]["hex"],
  504. }
  505. # ── Generate outputs ──
  506. css = _cascade_to_css(roles, semantic)
  507. reportlab_code = _cascade_to_reportlab(roles, semantic)
  508. audit_results = audit_cascade_palette(roles, semantic)
  509. return {
  510. "roles": {k: {"hex": v["hex"], "hsl": v["hsl"], "tier": v["tier"], "usage": v["usage_hint"]} for k, v in roles.items()},
  511. "cover": cover_subset,
  512. "body": body_subset,
  513. "charts": chart_subset,
  514. "semantic": {k: {"hex": v["hex"], "hsl": v["hsl"]} for k, v in semantic.items()},
  515. "meta": {
  516. "intent": intent, "mode": mode, "harmony": harmony,
  517. "base_hue": base_hue, "accent_hue": accent_hue, "secondary_hue": secondary_hue,
  518. "contrast": {
  519. "text_on_bg": round(_contrast_ratio(roles["text_primary"]["hex"], roles["page_bg"]["hex"]), 2),
  520. "accent_on_bg": round(_contrast_ratio(roles["accent"]["hex"], roles["page_bg"]["hex"]), 2),
  521. },
  522. "audit": audit_results,
  523. },
  524. "css": css,
  525. "reportlab": reportlab_code,
  526. }
  527. def _make_role(h, s, l, tier, usage_hint):
  528. """Create a role entry with hex, HSL tuple, tier, and usage hint."""
  529. hex_val = _hsl_to_hex(h, s, l)
  530. return {
  531. "hex": hex_val,
  532. "hsl": (round(h, 1), round(s, 3), round(l, 3)),
  533. "tier": tier,
  534. "usage_hint": usage_hint,
  535. }
  536. def _cascade_to_css(roles, semantic):
  537. """Convert cascade palette to CSS custom properties."""
  538. lines = [":root {"]
  539. lines.append(" /* ── XL tier: backgrounds (S ≤ 0.08) ── */")
  540. lines.append(f" --page-bg: {roles['page_bg']['hex']};")
  541. lines.append(f" --section-bg: {roles['section_bg']['hex']};")
  542. lines.append(" /* ── L tier: surfaces (S ≤ 0.15) ── */")
  543. lines.append(f" --card-bg: {roles['card_bg']['hex']};")
  544. lines.append(f" --table-stripe: {roles['table_stripe']['hex']};")
  545. lines.append(" /* ── M tier: structural fills (S ≤ 0.30) ── */")
  546. lines.append(f" --header-fill: {roles['header_fill']['hex']};")
  547. lines.append(f" --cover-block: {roles['cover_block']['hex']};")
  548. lines.append(" /* ── S tier: edges & icons (S ≤ 0.50) ── */")
  549. lines.append(f" --border: {roles['border']['hex']};")
  550. lines.append(f" --icon: {roles['icon']['hex']};")
  551. lines.append(" /* ── XS tier: emphasis (S ≤ 0.75) ── */")
  552. lines.append(f" --accent: {roles['accent']['hex']};")
  553. lines.append(f" --accent-secondary: {roles['accent_secondary']['hex']};")
  554. lines.append(" /* ── Typography ── */")
  555. lines.append(f" --text-primary: {roles['text_primary']['hex']};")
  556. lines.append(f" --text-muted: {roles['text_muted']['hex']};")
  557. lines.append(" /* ── Semantic (low-sat) ── */")
  558. for k, v in semantic.items():
  559. lines.append(f" --semantic-{k}: {v['hex']};")
  560. lines.append("}")
  561. return "\n".join(lines)
  562. def _cascade_to_reportlab(roles, semantic):
  563. """Convert cascade palette to ReportLab Python code."""
  564. lines = [
  565. "# ━━ Cascade Palette (auto-generated by design_engine.py palette-cascade) ━━",
  566. "from reportlab.lib import colors",
  567. "",
  568. "# XL tier: backgrounds (area > 50%, S ≤ 0.08)",
  569. f"PAGE_BG = colors.HexColor('{roles['page_bg']['hex']}')",
  570. f"SECTION_BG = colors.HexColor('{roles['section_bg']['hex']}')",
  571. "",
  572. "# L tier: surfaces (area 20-50%, S ≤ 0.15)",
  573. f"CARD_BG = colors.HexColor('{roles['card_bg']['hex']}')",
  574. f"TABLE_STRIPE = colors.HexColor('{roles['table_stripe']['hex']}')",
  575. "",
  576. "# M tier: structural fills (area 5-20%, S ≤ 0.30)",
  577. f"HEADER_FILL = colors.HexColor('{roles['header_fill']['hex']}')",
  578. f"COVER_BLOCK = colors.HexColor('{roles['cover_block']['hex']}')",
  579. "",
  580. "# S tier: edges & icons (area 1-5%, S ≤ 0.50)",
  581. f"BORDER = colors.HexColor('{roles['border']['hex']}')",
  582. f"ICON = colors.HexColor('{roles['icon']['hex']}')",
  583. "",
  584. "# XS tier: emphasis (area < 1%, S ≤ 0.75)",
  585. f"ACCENT = colors.HexColor('{roles['accent']['hex']}')",
  586. f"ACCENT_2 = colors.HexColor('{roles['accent_secondary']['hex']}')",
  587. "",
  588. "# Typography",
  589. f"TEXT_PRIMARY = colors.HexColor('{roles['text_primary']['hex']}')",
  590. f"TEXT_MUTED = colors.HexColor('{roles['text_muted']['hex']}')",
  591. "",
  592. "# Semantic (low-saturation, area-appropriate)",
  593. f"SEM_SUCCESS = colors.HexColor('{semantic['success']['hex']}')",
  594. f"SEM_WARNING = colors.HexColor('{semantic['warning']['hex']}')",
  595. f"SEM_ERROR = colors.HexColor('{semantic['error']['hex']}')",
  596. f"SEM_INFO = colors.HexColor('{semantic['info']['hex']}')",
  597. ]
  598. return "\n".join(lines)
  599. def audit_cascade_palette(roles, semantic):
  600. """Audit cascade palette for tier saturation violations and WCAG contrast."""
  601. violations = []
  602. for name, role in {**roles, **semantic}.items():
  603. tier = role["tier"]
  604. if tier in CASCADE_TIER_CAPS:
  605. cap = CASCADE_TIER_CAPS[tier]
  606. s = role["hsl"][1]
  607. if s > cap:
  608. violations.append(f"{name}: S={s:.3f} exceeds tier '{tier}' cap {cap}")
  609. # WCAG checks
  610. bg_hex = roles["page_bg"]["hex"]
  611. text_hex = roles["text_primary"]["hex"]
  612. cr = _contrast_ratio(text_hex, bg_hex)
  613. if cr < 4.5:
  614. violations.append(f"text_primary:page_bg contrast {cr:.2f} < 4.5:1 (WCAG AA)")
  615. accent_hex = roles["accent"]["hex"]
  616. cr_a = _contrast_ratio(accent_hex, bg_hex)
  617. if cr_a < 3.0:
  618. violations.append(f"accent:page_bg contrast {cr_a:.2f} < 3.0:1 (accent invisible)")
  619. # Header fill should be readable with white text on it
  620. hf_hex = roles["header_fill"]["hex"]
  621. cr_hf = _contrast_ratio("#ffffff", hf_hex)
  622. if cr_hf < 3.0:
  623. violations.append(f"white on header_fill contrast {cr_hf:.2f} < 3.0:1 (header text unreadable)")
  624. return violations
  625. # ═══════════════════════════════════════════════════════════════════════
  626. # 2. GENERATIVE SVG — Algorithmic Art Backgrounds
  627. # ═══════════════════════════════════════════════════════════════════════
  628. #
  629. # Two primary modes:
  630. # - "flow": 3-5 large-radius bézier curves at ultra-low opacity (0.05)
  631. # Creates organic, breathing atmospheric depth
  632. # - "grid": 1px reference grid or noise texture
  633. # Creates structured, architectural underlying rhythm
  634. #
  635. # All SVG is inline-ready (no external files needed).
  636. def _svg_open(w, h):
  637. return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}">'
  638. def _random_bezier_path(w, h):
  639. """Generate a single flowing bézier curve across the canvas."""
  640. # Start from a random edge point
  641. x0 = random.uniform(-w * 0.2, w * 0.3)
  642. y0 = random.uniform(0, h)
  643. # End at the opposite side
  644. x3 = random.uniform(w * 0.7, w * 1.2)
  645. y3 = random.uniform(0, h)
  646. # Control points — large sweeps for organic feel
  647. cx1 = random.uniform(w * 0.1, w * 0.5)
  648. cy1 = random.uniform(-h * 0.3, h * 1.3)
  649. cx2 = random.uniform(w * 0.5, w * 0.9)
  650. cy2 = random.uniform(-h * 0.3, h * 1.3)
  651. return f"M{x0:.0f},{y0:.0f} C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {x3:.0f},{y3:.0f}"
  652. def generate_flow_svg(w, h, color="#8a8a8a", curves=4, stroke_width=80, opacity=0.05):
  653. """
  654. Flow mode: ultra-wide, ultra-faint bézier curves.
  655. Creates atmospheric depth without competing with content.
  656. """
  657. random.seed(42)
  658. svg = _svg_open(w, h)
  659. svg += '\n <defs>'
  660. svg += '\n <linearGradient id="fg" x1="0" y1="0" x2="1" y2="1">'
  661. svg += f'\n <stop offset="0%" stop-color="{color}" stop-opacity="{opacity}"/>'
  662. svg += f'\n <stop offset="50%" stop-color="{color}" stop-opacity="{opacity * 1.5:.3f}"/>'
  663. svg += f'\n <stop offset="100%" stop-color="{color}" stop-opacity="{opacity * 0.5:.3f}"/>'
  664. svg += '\n </linearGradient>'
  665. svg += '\n </defs>'
  666. for i in range(curves):
  667. path = _random_bezier_path(w, h)
  668. sw = stroke_width + random.uniform(-20, 30)
  669. svg += f'\n <path d="{path}" fill="none" stroke="url(#fg)" '
  670. svg += f'stroke-width="{sw:.0f}" stroke-linecap="round" opacity="{opacity + i * 0.01:.3f}"/>'
  671. svg += '\n</svg>'
  672. return svg
  673. def generate_grid_svg(w, h, color="#888888", spacing=60, line_width=0.5, opacity=0.04):
  674. """
  675. Grid mode: architectural reference grid.
  676. Ultra-faint 1px lines creating underlying structure.
  677. """
  678. svg = _svg_open(w, h)
  679. svg += f'\n <g opacity="{opacity}">'
  680. # Vertical lines
  681. for x in range(0, int(w) + 1, spacing):
  682. svg += f'\n <line x1="{x}" y1="0" x2="{x}" y2="{h}" stroke="{color}" stroke-width="{line_width}"/>'
  683. # Horizontal lines
  684. for y in range(0, int(h) + 1, spacing):
  685. svg += f'\n <line x1="0" y1="{y}" x2="{w}" y2="{y}" stroke="{color}" stroke-width="{line_width}"/>'
  686. svg += '\n </g>'
  687. svg += '\n</svg>'
  688. return svg
  689. def generate_noise_svg(w, h, frequency=0.8, octaves=4, opacity=0.035):
  690. """
  691. Noise mode: feTurbulence grain texture.
  692. Adds tactile paper-like quality.
  693. """
  694. svg = _svg_open(w, h)
  695. svg += f"""
  696. <defs>
  697. <filter id="grain" x="0" y="0" width="100%" height="100%">
  698. <feTurbulence type="fractalNoise" baseFrequency="{frequency}"
  699. numOctaves="{octaves}" stitchTiles="stitch" result="noise"/>
  700. <feColorMatrix type="saturate" values="0" in="noise" result="grey"/>
  701. </filter>
  702. </defs>
  703. <rect width="{w}" height="{h}" filter="url(#grain)" opacity="{opacity}"/>"""
  704. svg += '\n</svg>'
  705. return svg
  706. def _generate_data_driven_svg(data_points, w=720, h=960, color="#8a8a8a"):
  707. """
  708. Content-Aware SVG: Transform business data arrays into Bézier background curves.
  709. The background subtly echoes the data's shape — a cross-modal design metaphor.
  710. """
  711. if not data_points or len(data_points) < 2:
  712. return generate_flow_svg(w, h, color)
  713. n = len(data_points)
  714. min_v = min(data_points)
  715. max_v = max(data_points)
  716. rng = max_v - min_v if max_v != min_v else 1.0
  717. # Normalize data to canvas coordinates
  718. # X: evenly spaced across width; Y: mapped to 20%-80% of height (inverted for SVG)
  719. points = []
  720. for i, v in enumerate(data_points):
  721. x = (i / (n - 1)) * w
  722. y_norm = (v - min_v) / rng # 0..1
  723. y = h * 0.8 - y_norm * (h * 0.6) # Map to 20%-80% height band
  724. points.append((x, y))
  725. # Build smooth Bézier path through all points (Catmull-Rom → cubic Bézier)
  726. def catmull_to_bezier(p0, p1, p2, p3, tension=0.5):
  727. """Convert 4 Catmull-Rom points to cubic Bézier control points for segment p1→p2."""
  728. cp1x = p1[0] + (p2[0] - p0[0]) / (6 * tension)
  729. cp1y = p1[1] + (p2[1] - p0[1]) / (6 * tension)
  730. cp2x = p2[0] - (p3[0] - p1[0]) / (6 * tension)
  731. cp2y = p2[1] - (p3[1] - p1[1]) / (6 * tension)
  732. return (cp1x, cp1y), (cp2x, cp2y)
  733. svg_paths = ""
  734. # Generate 3 layers at different offsets for depth
  735. for layer_idx, (opacity, y_offset, thickness) in enumerate([
  736. (0.08, 0, 3), (0.05, 60, 2), (0.03, -40, 1.5)
  737. ]):
  738. pts = [(px, py + y_offset) for px, py in points]
  739. # Pad start/end for Catmull-Rom
  740. padded = [pts[0]] + pts + [pts[-1]]
  741. d = f"M {padded[1][0]:.1f},{padded[1][1]:.1f} "
  742. for i in range(1, len(padded) - 2):
  743. cp1, cp2 = catmull_to_bezier(padded[i-1], padded[i], padded[i+1], padded[i+2])
  744. d += f"C {cp1[0]:.1f},{cp1[1]:.1f} {cp2[0]:.1f},{cp2[1]:.1f} {padded[i+1][0]:.1f},{padded[i+1][1]:.1f} "
  745. # Main stroke
  746. svg_paths += f'<path d="{d}" fill="none" stroke="{color}" stroke-width="{thickness}" opacity="{opacity}" />\n'
  747. # Filled area below the curve
  748. fill_d = d + f"L {w},{h} L 0,{h} Z"
  749. svg_paths += f'<path d="{fill_d}" fill="{color}" opacity="{opacity * 0.4}" />\n'
  750. return f'<svg viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg" style="width:100%;height:100%">{svg_paths}</svg>'
  751. def generate_supergraphic_svg(w, h, color="#8a8a8a", seed=42):
  752. """
  753. Supergraphic mode: oversized geometric shapes (circles, rectangles, polygons)
  754. cropped by the canvas edge, rendered at 3-5% opacity.
  755. Creates "blueprint of a larger world" feeling — McKinsey / Pentagram style.
  756. Shapes deliberately overflow the viewport so only partial arcs/edges are visible.
  757. """
  758. random.seed(seed)
  759. svg = _svg_open(w, h)
  760. # Layer 1: Giant concentric circles, center placed off-canvas
  761. cx = random.uniform(w * 0.6, w * 1.3) # right-biased, partially off-canvas
  762. cy = random.uniform(-h * 0.2, h * 0.4) # top-biased
  763. for i in range(4):
  764. r = w * (0.6 + i * 0.35) # radii from 60% to 165% of width — always overflowing
  765. opacity = 0.04 - i * 0.008 # outer rings fainter
  766. svg += f'\n <circle cx="{cx:.0f}" cy="{cy:.0f}" r="{r:.0f}" '
  767. svg += f'fill="none" stroke="{color}" stroke-width="1.5" opacity="{max(opacity, 0.015):.3f}"/>'
  768. # Layer 2: Oversized rotated rectangles, clipped by viewport
  769. for _ in range(2):
  770. rx = random.uniform(-w * 0.3, w * 0.5)
  771. ry = random.uniform(h * 0.3, h * 1.2)
  772. rw = random.uniform(w * 0.8, w * 1.6)
  773. rh = random.uniform(h * 0.5, h * 1.2)
  774. angle = random.uniform(-15, 25)
  775. svg += f'\n <rect x="{rx:.0f}" y="{ry:.0f}" width="{rw:.0f}" height="{rh:.0f}" '
  776. svg += f'fill="none" stroke="{color}" stroke-width="1" opacity="0.025" '
  777. svg += f'transform="rotate({angle:.1f} {rx + rw/2:.0f} {ry + rh/2:.0f})"/>'
  778. # Layer 3: A single massive polygon (pentagon/hexagon) barely visible
  779. sides = random.choice([5, 6, 8])
  780. pcx = random.uniform(-w * 0.1, w * 0.4)
  781. pcy = random.uniform(h * 0.5, h * 1.1)
  782. pr = w * random.uniform(0.9, 1.4)
  783. angle_offset = random.uniform(0, 360 / sides)
  784. points = []
  785. for i in range(sides):
  786. a = math.radians(angle_offset + i * 360 / sides)
  787. px = pcx + pr * math.cos(a)
  788. py = pcy + pr * math.sin(a)
  789. points.append(f"{px:.0f},{py:.0f}")
  790. svg += f'\n <polygon points="{" ".join(points)}" '
  791. svg += f'fill="none" stroke="{color}" stroke-width="1" opacity="0.02"/>'
  792. svg += '\n</svg>'
  793. return svg
  794. def generate_ordered_texture_svg(w, h, color="#8a8a8a", seed=42):
  795. """
  796. Ordered Texture mode: precision dot-matrix, coordinate grids, and contour lines
  797. placed in specific corners/edges of the canvas (not full coverage).
  798. Creates "engineered precision" feeling — ideal for tech, finance, data reports.
  799. """
  800. random.seed(seed)
  801. svg = _svg_open(w, h)
  802. # Region 1: Dot matrix in top-right corner (10x10 grid of small circles)
  803. dot_cols, dot_rows = 12, 10
  804. dot_spacing = 18
  805. dot_r = 2
  806. dot_origin_x = w - dot_cols * dot_spacing - 40 # right-aligned with margin
  807. dot_origin_y = 30 # top margin
  808. svg += '\n <g opacity="0.08">'
  809. for row in range(dot_rows):
  810. for col in range(dot_cols):
  811. dx = dot_origin_x + col * dot_spacing
  812. dy = dot_origin_y + row * dot_spacing
  813. svg += f'\n <circle cx="{dx}" cy="{dy}" r="{dot_r}" fill="{color}"/>'
  814. svg += '\n </g>'
  815. # Region 2: Coordinate grid lines in bottom-left quadrant (blueprint style)
  816. grid_x0, grid_y0 = 20, h * 0.7
  817. grid_x1, grid_y1 = w * 0.45, h - 20
  818. grid_spacing = 30
  819. svg += f'\n <g opacity="0.05" stroke="{color}" stroke-width="0.5" stroke-dasharray="4,6">'
  820. # Vertical lines
  821. x = grid_x0
  822. while x <= grid_x1:
  823. svg += f'\n <line x1="{x:.0f}" y1="{grid_y0:.0f}" x2="{x:.0f}" y2="{grid_y1:.0f}"/>'
  824. x += grid_spacing
  825. # Horizontal lines
  826. y = grid_y0
  827. while y <= grid_y1:
  828. svg += f'\n <line x1="{grid_x0:.0f}" y1="{y:.0f}" x2="{grid_x1:.0f}" y2="{y:.0f}"/>'
  829. y += grid_spacing
  830. svg += '\n </g>'
  831. # Region 3: Tick marks along the grid (ruler effect)
  832. svg += f'\n <g opacity="0.06" stroke="{color}" stroke-width="0.8">'
  833. x = grid_x0
  834. while x <= grid_x1:
  835. svg += f'\n <line x1="{x:.0f}" y1="{grid_y1:.0f}" x2="{x:.0f}" y2="{grid_y1 + 5:.0f}"/>'
  836. x += grid_spacing
  837. svg += '\n </g>'
  838. # Region 4: Flowing contour lines (Bézier) across mid-right area
  839. svg += f'\n <g opacity="0.04" fill="none" stroke="{color}" stroke-width="1">'
  840. for i in range(5):
  841. y_base = h * 0.35 + i * 35
  842. x_start = w * 0.55
  843. x_end = w + 20 # overflow right edge
  844. cx1 = x_start + (x_end - x_start) * 0.3 + random.uniform(-30, 30)
  845. cy1 = y_base + random.uniform(-40, 40)
  846. cx2 = x_start + (x_end - x_start) * 0.7 + random.uniform(-30, 30)
  847. cy2 = y_base + random.uniform(-40, 40)
  848. svg += f'\n <path d="M{x_start:.0f},{y_base:.0f} C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {x_end:.0f},{y_base + random.uniform(-20, 20):.0f}"/>'
  849. svg += '\n </g>'
  850. # Region 5: Cross-hair markers at 2-3 strategic points
  851. for _ in range(3):
  852. mx = random.uniform(w * 0.15, w * 0.85)
  853. my = random.uniform(h * 0.15, h * 0.85)
  854. size = 8
  855. svg += f'\n <g opacity="0.06" stroke="{color}" stroke-width="0.8">'
  856. svg += f'\n <line x1="{mx - size}" y1="{my}" x2="{mx + size}" y2="{my}"/>'
  857. svg += f'\n <line x1="{mx}" y1="{my - size}" x2="{mx}" y2="{my + size}"/>'
  858. svg += f'\n <circle cx="{mx}" cy="{my}" r="{size * 0.6:.0f}" fill="none"/>'
  859. svg += '\n </g>'
  860. svg += '\n</svg>'
  861. return svg
  862. def generate_generative_svg(svg_type="flow", w=720, h=960, color="#8a8a8a"):
  863. """Route to the appropriate SVG generator."""
  864. if svg_type == "flow":
  865. return generate_flow_svg(w, h, color)
  866. elif svg_type == "grid":
  867. return generate_grid_svg(w, h, color)
  868. elif svg_type == "noise":
  869. return generate_noise_svg(w, h)
  870. elif svg_type == "supergraphic":
  871. return generate_supergraphic_svg(w, h, color)
  872. elif svg_type == "ordered_texture":
  873. return generate_ordered_texture_svg(w, h, color)
  874. else:
  875. # Default: flow + noise layered
  876. flow = generate_flow_svg(w, h, color)
  877. return flow
  878. def generate_continuous_flow_svg(w, h, total_pages, color="#8a8a8a", curves=4, stroke_width=80, opacity=0.05):
  879. """
  880. Continuous Flow mode: generates ONE large SVG spanning all pages.
  881. Returns a list of per-page SVG strings, each using viewBox to slice the master.
  882. The bezier curves are constrained to have anchor points every ~480px vertically,
  883. ensuring visible content on every page.
  884. """
  885. total_h = h * total_pages
  886. random.seed(42)
  887. # Build the master path data
  888. paths_data = []
  889. for _ in range(curves):
  890. # Generate anchor points — one every 480px ensures ~2 per page
  891. num_anchors = max(3, int(total_h / 480))
  892. anchors = []
  893. for i in range(num_anchors):
  894. ax = random.uniform(w * 0.1, w * 0.9)
  895. ay = (total_h / (num_anchors - 1)) * i
  896. anchors.append((ax, ay))
  897. # Build cubic bezier path through anchors
  898. path = f"M{anchors[0][0]:.0f},{anchors[0][1]:.0f}"
  899. for i in range(1, len(anchors)):
  900. prev = anchors[i - 1]
  901. curr = anchors[i]
  902. # Control points: spread horizontally for organic feel
  903. cx1 = random.uniform(w * 0.0, w * 1.0)
  904. cy1 = prev[1] + (curr[1] - prev[1]) * 0.33 + random.uniform(-100, 100)
  905. cx2 = random.uniform(w * 0.0, w * 1.0)
  906. cy2 = prev[1] + (curr[1] - prev[1]) * 0.66 + random.uniform(-100, 100)
  907. path += f" C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {curr[0]:.0f},{curr[1]:.0f}"
  908. sw = stroke_width + random.uniform(-20, 30)
  909. paths_data.append((path, sw))
  910. # Generate per-page SVG slices
  911. page_svgs = []
  912. gradient_def = f'''<defs>
  913. <linearGradient id="fg" x1="0" y1="0" x2="1" y2="1">
  914. <stop offset="0%" stop-color="{color}" stop-opacity="{opacity}"/>
  915. <stop offset="50%" stop-color="{color}" stop-opacity="{opacity * 1.5:.3f}"/>
  916. <stop offset="100%" stop-color="{color}" stop-opacity="{opacity * 0.5:.3f}"/>
  917. </linearGradient>
  918. </defs>'''
  919. for page_idx in range(total_pages):
  920. vy = page_idx * h
  921. svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 {vy} {w} {h}" width="{w}" height="{h}">'
  922. svg += f'\n {gradient_def}'
  923. for i, (path, sw) in enumerate(paths_data):
  924. svg += f'\n <path d="{path}" fill="none" stroke="url(#fg)" '
  925. svg += f'stroke-width="{sw:.0f}" stroke-linecap="round" opacity="{opacity + i * 0.01:.3f}"/>'
  926. svg += '\n</svg>'
  927. page_svgs.append(svg)
  928. return page_svgs
  929. def generate_unified_svg(w, h, total_pages, svg_type, color="#8a8a8a", curves=4, stroke_width=80, opacity=0.05):
  930. """
  931. Generate a single SVG that spans the full continuous canvas (w x h*total_pages).
  932. Unlike generate_continuous_flow_svg which returns per-page slices,
  933. this returns ONE svg string for the entire document.
  934. Used by the continuous-canvas rendering mode.
  935. """
  936. total_h = h * total_pages
  937. random.seed(42)
  938. if svg_type in ("continuous_flow", "flow"):
  939. # Bezier curves spanning entire height
  940. paths_data = []
  941. for _ in range(curves):
  942. num_anchors = max(3, int(total_h / 480))
  943. anchors = []
  944. for i in range(num_anchors):
  945. ax = random.uniform(w * 0.1, w * 0.9)
  946. ay = (total_h / (num_anchors - 1)) * i
  947. anchors.append((ax, ay))
  948. path = f"M{anchors[0][0]:.0f},{anchors[0][1]:.0f}"
  949. for i in range(1, len(anchors)):
  950. prev = anchors[i - 1]
  951. curr = anchors[i]
  952. cx1 = random.uniform(w * 0.0, w * 1.0)
  953. cy1 = prev[1] + (curr[1] - prev[1]) * 0.33 + random.uniform(-100, 100)
  954. cx2 = random.uniform(w * 0.0, w * 1.0)
  955. cy2 = prev[1] + (curr[1] - prev[1]) * 0.66 + random.uniform(-100, 100)
  956. path += f" C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {curr[0]:.0f},{curr[1]:.0f}"
  957. sw = stroke_width + random.uniform(-20, 30)
  958. paths_data.append((path, sw))
  959. gradient_def = f'''<defs>
  960. <linearGradient id="fg" x1="0" y1="0" x2="1" y2="1">
  961. <stop offset="0%" stop-color="{color}" stop-opacity="{opacity}"/>
  962. <stop offset="50%" stop-color="{color}" stop-opacity="{opacity * 1.5:.3f}"/>
  963. <stop offset="100%" stop-color="{color}" stop-opacity="{opacity * 0.5:.3f}"/>
  964. </linearGradient>
  965. </defs>'''
  966. svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {total_h}" width="{w}" height="{total_h}">'
  967. svg += f'\n {gradient_def}'
  968. for i, (path, sw) in enumerate(paths_data):
  969. svg += f'\n <path d="{path}" fill="none" stroke="url(#fg)" '
  970. svg += f'stroke-width="{sw:.0f}" stroke-linecap="round" opacity="{opacity + i * 0.01:.3f}"/>'
  971. svg += '\n</svg>'
  972. return svg
  973. elif svg_type == "grid":
  974. # Grid pattern spanning full height
  975. svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {total_h}" width="{w}" height="{total_h}">'
  976. spacing = 60
  977. for x in range(0, w + 1, spacing):
  978. svg += f'\n <line x1="{x}" y1="0" x2="{x}" y2="{total_h}" stroke="{color}" stroke-width="0.5" opacity="{opacity}"/>'
  979. for y in range(0, int(total_h) + 1, spacing):
  980. svg += f'\n <line x1="0" y1="{y}" x2="{w}" y2="{y}" stroke="{color}" stroke-width="0.5" opacity="{opacity}"/>'
  981. svg += '\n</svg>'
  982. return svg
  983. elif svg_type == "noise":
  984. # Noise dots spanning full height
  985. svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {total_h}" width="{w}" height="{total_h}">'
  986. num_dots = int(200 * total_pages)
  987. for _ in range(num_dots):
  988. cx = random.uniform(0, w)
  989. cy = random.uniform(0, total_h)
  990. r = random.uniform(0.5, 2.5)
  991. svg += f'\n <circle cx="{cx:.0f}" cy="{cy:.0f}" r="{r:.1f}" fill="{color}" opacity="{random.uniform(opacity * 0.3, opacity * 1.5):.3f}"/>'
  992. svg += '\n</svg>'
  993. return svg
  994. return ""
  995. # ═══════════════════════════════════════════════════════════════════════
  996. # 3. LAYOUT CALCULATOR — Deliberate Spatial Tension
  997. # ═══════════════════════════════════════════════════════════════════════
  998. #
  999. # Returns absolute coordinates for elements with intentional:
  1000. # - Offset: elements not perfectly centered (art tension)
  1001. # - Overlap: controlled z-index collisions
  1002. # - Breathing margin: 15% minimum on all edges
  1003. BREATHING_MARGIN = 0.12 # 12% of canvas on each edge (was 15%, too tight for content-dense pages)
  1004. def calculate_layout(elements, w=720, h=960, style="offset"):
  1005. """
  1006. Calculate positioned layout for named elements.
  1007. Args:
  1008. elements: list of element names (e.g. ["hero", "body", "meta", "footer"])
  1009. style: "offset" (deliberate asymmetry), "centered" (formal), "stacked" (vertical flow)
  1010. Returns:
  1011. dict mapping element names to {x, y, w, h, rotation} in pixels
  1012. """
  1013. # Safe area (15% breathing margin on all sides)
  1014. safe_x = w * BREATHING_MARGIN
  1015. safe_y = h * BREATHING_MARGIN
  1016. safe_w = w * (1 - 2 * BREATHING_MARGIN)
  1017. safe_h = h * (1 - 2 * BREATHING_MARGIN)
  1018. layout = {}
  1019. if style == "offset":
  1020. # Asymmetric placement — elements shift left/right of center
  1021. regions = _divide_vertical(safe_x, safe_y, safe_w, safe_h, len(elements))
  1022. for i, name in enumerate(elements):
  1023. rx, ry, rw, rh = regions[i]
  1024. # Apply deliberate offset: odd elements shift left, even shift right
  1025. offset_x = rw * 0.08 * (-1 if i % 2 == 0 else 1)
  1026. layout[name] = {
  1027. "x": round(rx + offset_x, 1),
  1028. "y": round(ry, 1),
  1029. "w": round(rw * 0.85, 1), # Don't fill the full width
  1030. "h": round(rh * 0.85, 1),
  1031. "rotation": round(random.uniform(-1.5, 1.5), 2) if name != "body" else 0,
  1032. }
  1033. elif style == "centered":
  1034. # Formal centered — golden ratio vertical split
  1035. regions = _divide_vertical(safe_x, safe_y, safe_w, safe_h, len(elements))
  1036. for i, name in enumerate(elements):
  1037. rx, ry, rw, rh = regions[i]
  1038. layout[name] = {
  1039. "x": round(rx + (rw * 0.075), 1), # Slight horizontal centering margin
  1040. "y": round(ry, 1),
  1041. "w": round(rw * 0.85, 1),
  1042. "h": round(rh * 0.9, 1),
  1043. "rotation": 0,
  1044. }
  1045. elif style == "overlap":
  1046. # Controlled overlaps — elements bleed into each other's space
  1047. regions = _divide_vertical(safe_x, safe_y, safe_w, safe_h, len(elements))
  1048. for i, name in enumerate(elements):
  1049. rx, ry, rw, rh = regions[i]
  1050. overlap_y = rh * 0.15 if i > 0 else 0 # Pull up into previous region
  1051. layout[name] = {
  1052. "x": round(rx, 1),
  1053. "y": round(ry - overlap_y, 1),
  1054. "w": round(rw, 1),
  1055. "h": round(rh + overlap_y * 0.5, 1),
  1056. "rotation": 0,
  1057. "z_index": len(elements) - i, # Later elements on top
  1058. }
  1059. return layout
  1060. def _divide_vertical(x, y, w, h, n):
  1061. """Divide a rectangle into n vertical bands with golden-ratio-inspired proportions."""
  1062. if n <= 0:
  1063. return []
  1064. if n == 1:
  1065. return [(x, y, w, h)]
  1066. # Weighted distribution: first element (hero) gets more space
  1067. weights = [1.618 if i == 0 else 1.0 for i in range(n)]
  1068. total = sum(weights)
  1069. regions = []
  1070. current_y = y
  1071. for i in range(n):
  1072. region_h = h * weights[i] / total
  1073. regions.append((x, current_y, w, region_h))
  1074. current_y += region_h
  1075. return regions
  1076. # ═══════════════════════════════════════════════════════════════════════
  1077. # VALIDATION — Post-generation color audit
  1078. # ═══════════════════════════════════════════════════════════════════════
  1079. def audit_palette(palette):
  1080. """
  1081. Strict audit: mode-specific S/L bounds + WCAG contrast checks.
  1082. Returns list of violations (empty = clean).
  1083. """
  1084. violations = []
  1085. mode = palette.get("meta", {}).get("mode", "minimal")
  1086. for key in ["bg", "mid", "accent", "text"]:
  1087. hex_val = palette.get(key, "")
  1088. if not hex_val.startswith("#"):
  1089. continue
  1090. r, g, b = (int(hex_val[i:i+2], 16) / 255.0 for i in (1, 3, 5))
  1091. h, l, s = colorsys.rgb_to_hls(r, g, b)
  1092. # Tight bg/mid saturation limits per mode
  1093. if key in ("bg", "mid"):
  1094. limits = {"minimal": 0.20, "dark": 0.16, "pastel": 0.42, "jewel": 0.62, "light": 0.28}
  1095. cap = limits.get(mode, 0.15)
  1096. if s > cap:
  1097. violations.append(f"{key}: S={s:.3f} > {cap} in {mode} mode")
  1098. # Tight accent saturation — pastel/jewel reined in
  1099. if key == "accent":
  1100. accent_caps = {"minimal": 0.78, "dark": 0.62, "pastel": 0.52, "jewel": 0.52, "light": 0.48}
  1101. cap = accent_caps.get(mode, 0.60)
  1102. if s > cap:
  1103. violations.append(f"accent: S={s:.3f} > {cap} in {mode} mode")
  1104. # Lightness guardrails
  1105. if key == "bg":
  1106. if mode == "dark" and l > 0.10:
  1107. violations.append(f"bg L={l:.3f} > 0.10 in dark (muddy middle)")
  1108. elif mode == "minimal" and l < 0.90:
  1109. violations.append(f"bg L={l:.3f} < 0.90 in minimal (too dark for paper)")
  1110. elif mode == "light" and l < 0.88:
  1111. violations.append(f"bg L={l:.3f} < 0.88 in light (too dark)")
  1112. elif mode == "jewel" and l > 0.28:
  1113. violations.append(f"bg L={l:.3f} > 0.28 in jewel (not deep enough)")
  1114. elif mode == "pastel" and l < 0.83:
  1115. violations.append(f"bg L={l:.3f} < 0.83 in pastel (too dark for Morandi)")
  1116. # WCAG contrast checks
  1117. bg_hex = palette.get("bg", "")
  1118. text_hex = palette.get("text", "")
  1119. accent_hex = palette.get("accent", "")
  1120. if bg_hex.startswith("#") and text_hex.startswith("#"):
  1121. cr = _contrast_ratio(text_hex, bg_hex)
  1122. if cr < 4.5:
  1123. violations.append(f"text:bg contrast {cr:.2f} < 4.5:1 (WCAG AA fail)")
  1124. if bg_hex.startswith("#") and accent_hex.startswith("#"):
  1125. cr = _contrast_ratio(accent_hex, bg_hex)
  1126. if cr < 2.5:
  1127. violations.append(f"accent:bg contrast {cr:.2f} < 2.5:1 (accent invisible)")
  1128. return violations
  1129. # ═══════════════════════════════════════════════════════════════════════
  1130. # CLI
  1131. # ═══════════════════════════════════════════════════════════════════════
  1132. def main():
  1133. parser = argparse.ArgumentParser(
  1134. description="Design Engine — aesthetic computation for art-direction-first PDF",
  1135. formatter_class=argparse.RawDescriptionHelpFormatter,
  1136. epilog="""
  1137. Examples:
  1138. %(prog)s palette --intent serenity --mode dark
  1139. %(prog)s palette --intent tension --mode light --seed 42
  1140. %(prog)s palette-cascade --intent cold --mode minimal
  1141. %(prog)s palette-cascade --intent neutral --format reportlab
  1142. %(prog)s svg --intent flow --dimensions 720x960
  1143. %(prog)s svg --intent grid --dimensions 720x960
  1144. %(prog)s layout --elements hero,body,meta --dimensions 720x960 --style offset
  1145. %(prog)s full --intent serenity --mode dark --dimensions 720x960 --output-dir ./assets/
  1146. %(prog)s audit --css-file assets/palette.css
  1147. """
  1148. )
  1149. sub = parser.add_subparsers(dest="command")
  1150. # palette
  1151. p_pal = sub.add_parser("palette", help="Generate HSL-locked color palette")
  1152. p_pal.add_argument("--intent", default="neutral", choices=list(INTENT_HUES.keys()))
  1153. p_pal.add_argument("--mode", default="minimal", choices=["minimal", "dark", "pastel", "jewel", "light"])
  1154. p_pal.add_argument("--harmony", default="auto", choices=["auto", "complementary", "split_complementary", "triadic", "analogous", "monochrome"])
  1155. p_pal.add_argument("--seed", type=int, default=None)
  1156. p_pal.add_argument("--format", default="css", choices=["css", "json"])
  1157. # svg
  1158. p_svg = sub.add_parser("svg", help="Generate algorithmic SVG background")
  1159. p_svg.add_argument("--svg-type", default="flow", choices=["flow", "grid", "noise", "supergraphic", "ordered_texture"])
  1160. p_svg.add_argument("--dimensions", default="720x960")
  1161. p_svg.add_argument("--color", default="#8a8a8a")
  1162. # layout
  1163. p_lay = sub.add_parser("layout", help="Calculate element positions")
  1164. p_lay.add_argument("--elements", default="hero,body,meta")
  1165. p_lay.add_argument("--dimensions", default="720x960")
  1166. p_lay.add_argument("--style", default="offset", choices=["offset", "centered", "overlap"])
  1167. # full
  1168. p_full = sub.add_parser("full", help="Generate all assets at once")
  1169. p_full.add_argument("--intent", default="neutral")
  1170. p_full.add_argument("--mode", default="minimal", choices=["minimal", "dark", "pastel", "jewel", "light"])
  1171. p_full.add_argument("--harmony", default="auto", choices=["auto", "complementary", "split_complementary", "triadic", "analogous", "monochrome"])
  1172. p_full.add_argument("--svg-intent", default="flow", choices=["flow", "grid", "noise"])
  1173. p_full.add_argument("--dimensions", default="720x960")
  1174. p_full.add_argument("--elements", default="hero,body,meta")
  1175. p_full.add_argument("--style", default="offset")
  1176. p_full.add_argument("--seed", type=int, default=None)
  1177. p_full.add_argument("--output-dir", default="./assets/")
  1178. # audit
  1179. p_audit = sub.add_parser("audit", help="Audit a palette for constraint violations")
  1180. p_audit.add_argument("--palette-json", required=True)
  1181. # palette-cascade
  1182. p_pcas = sub.add_parser("palette-cascade", help="Generate role-based cascade palette (area ∝ 1/saturation)")
  1183. p_pcas.add_argument("--intent", default="neutral", choices=list(INTENT_HUES.keys()))
  1184. p_pcas.add_argument("--mode", default="minimal", choices=["minimal", "dark", "pastel", "jewel", "light"])
  1185. p_pcas.add_argument("--harmony", default="auto", choices=["auto", "complementary", "split_complementary", "triadic", "analogous", "monochrome"])
  1186. p_pcas.add_argument("--seed", type=int, default=None)
  1187. p_pcas.add_argument("--format", default="summary", choices=["summary", "json", "css", "reportlab"])
  1188. # compile
  1189. p_compile = sub.add_parser("compile", help="Compile a JSON Blueprint into a final HTML document")
  1190. p_compile.add_argument("--blueprint", required=True, help="Path to the JSON blueprint generated by LLM")
  1191. p_compile.add_argument("--output", default="poster.html", help="Path to save the output HTML")
  1192. # derive
  1193. p_derive = sub.add_parser("derive", help="Auto-derive design intent from document description")
  1194. p_derive.add_argument("text", help="Document title or description")
  1195. # Backward compat: positional command
  1196. parser.add_argument("legacy_command", nargs="?")
  1197. parser.add_argument("legacy_args", nargs="*")
  1198. args = parser.parse_args()
  1199. if args.command == "palette":
  1200. pal = generate_color_palette(args.intent, args.mode, harmony=args.harmony, seed=args.seed)
  1201. if args.format == "json":
  1202. print(json.dumps(pal, indent=2))
  1203. else:
  1204. print(palette_to_css(pal))
  1205. elif args.command == "svg":
  1206. w, h = map(int, args.dimensions.split("x"))
  1207. print(generate_generative_svg(args.svg_type, w, h, args.color))
  1208. elif args.command == "layout":
  1209. w, h = map(int, args.dimensions.split("x"))
  1210. elements = [e.strip() for e in args.elements.split(",")]
  1211. result = calculate_layout(elements, w, h, args.style)
  1212. print(json.dumps(result, indent=2))
  1213. elif args.command == "full":
  1214. w, h = map(int, args.dimensions.split("x"))
  1215. os.makedirs(args.output_dir, exist_ok=True)
  1216. # 1. Palette
  1217. pal = generate_color_palette(args.intent, args.mode, harmony=getattr(args, 'harmony', 'split_complementary'), seed=args.seed)
  1218. css = palette_to_css(pal)
  1219. css_path = os.path.join(args.output_dir, "palette.css")
  1220. with open(css_path, "w") as f:
  1221. f.write(css)
  1222. json_path = os.path.join(args.output_dir, "palette.json")
  1223. with open(json_path, "w") as f:
  1224. json.dump(pal, f, indent=2)
  1225. print(f"✅ {css_path}")
  1226. # 2. SVG
  1227. svg_color = pal["accent"] # Use accent for SVG strokes
  1228. svg = generate_generative_svg(args.svg_intent, w, h, svg_color)
  1229. svg_path = os.path.join(args.output_dir, "background.svg")
  1230. with open(svg_path, "w") as f:
  1231. f.write(svg)
  1232. print(f"✅ {svg_path}")
  1233. # 3. Layout
  1234. elements = [e.strip() for e in args.elements.split(",")]
  1235. lay = calculate_layout(elements, w, h, args.style)
  1236. lay_path = os.path.join(args.output_dir, "layout.json")
  1237. with open(lay_path, "w") as f:
  1238. json.dump(lay, f, indent=2)
  1239. print(f"✅ {lay_path}")
  1240. # 4. Audit
  1241. violations = audit_palette(pal)
  1242. if violations:
  1243. print("\n⚠️ Palette violations:")
  1244. for v in violations:
  1245. print(f" - {v}")
  1246. else:
  1247. print("\n✅ Palette passes all constraints")
  1248. print(f"\n🎨 {args.intent}/{args.mode} | {w}×{h} | {len(elements)} elements")
  1249. elif args.command == "audit":
  1250. with open(args.palette_json) as f:
  1251. pal = json.load(f)
  1252. violations = audit_palette(pal)
  1253. if violations:
  1254. print("⚠️ Violations found:")
  1255. for v in violations:
  1256. print(f" - {v}")
  1257. sys.exit(1)
  1258. else:
  1259. print("✅ Palette passes all constraints")
  1260. elif args.command == "derive":
  1261. intent = derive_intent(args.text)
  1262. print(f"Intent: {intent}")
  1263. print(f"Hue: {INTENT_HUES.get(intent, 45)}°")
  1264. # Also generate a quick palette preview
  1265. pal = generate_color_palette(intent, "dark")
  1266. print(f"Preview (dark): bg={pal['bg']} accent={pal['accent']}")
  1267. pal_light = generate_color_palette(intent, "light")
  1268. print(f"Preview (light): bg={pal_light['bg']} accent={pal_light['accent']}")
  1269. elif args.command == "palette-cascade":
  1270. cascade = generate_cascade_palette(args.intent, args.mode, harmony=args.harmony, seed=args.seed)
  1271. if args.format == "json":
  1272. print(json.dumps(cascade, indent=2, ensure_ascii=False, default=str))
  1273. elif args.format == "css":
  1274. print(cascade["css"])
  1275. elif args.format == "reportlab":
  1276. print(cascade["reportlab"])
  1277. else: # summary
  1278. meta = cascade["meta"]
  1279. print(f"🎨 Cascade Palette | Intent: {meta['intent']} | Mode: {meta['mode']} | Harmony: {meta['harmony']}")
  1280. print(f" Base hue: {meta['base_hue']}° | Accent hue: {meta['accent_hue']}° | Secondary hue: {meta['secondary_hue']}°")
  1281. print(f" Contrast: text:bg={meta['contrast']['text_on_bg']} | accent:bg={meta['contrast']['accent_on_bg']}")
  1282. print()
  1283. print(" TIER | ROLE | HEX | S | USAGE")
  1284. print(" ────── | ────────────────── | ─────── | ────── | ────────────")
  1285. for name, info in cascade["roles"].items():
  1286. tier = info['tier'].upper().ljust(6)
  1287. nm = name.ljust(18)
  1288. hx = info['hex'].ljust(7)
  1289. s_val = f"{info['hsl'][1]:.3f}".ljust(6)
  1290. print(f" {tier} | {nm} | {hx} | {s_val} | {info['usage']}")
  1291. print()
  1292. print(" Semantic:")
  1293. for name, info in cascade["semantic"].items():
  1294. print(f" {name}: {info['hex']} (S={info['hsl'][1]:.3f})")
  1295. if meta["audit"]:
  1296. print("\n ⚠️ Violations:")
  1297. for v in meta["audit"]:
  1298. print(f" - {v}")
  1299. else:
  1300. print("\n ✅ All tier constraints pass")
  1301. elif args.command == "compile":
  1302. try:
  1303. out_path, pal = compile_blueprint(args.blueprint, args.output)
  1304. print(f"✅ Blueprint compiled successfully to: {out_path}")
  1305. violations = audit_palette(pal)
  1306. if violations:
  1307. print("⚠️ Warning: Generated palette had minor violations (auto-corrected by engine):")
  1308. for v in violations: print(f" - {v}")
  1309. except Exception as e:
  1310. print(f"❌ Failed to compile blueprint: {str(e)}")
  1311. sys.exit(1)
  1312. else:
  1313. parser.print_help()
  1314. # ═══════════════════════════════════════════════════════════════════════
  1315. # 4. BLUEPRINT COMPILER — Converting JSON Intent to HTML Canvas
  1316. # ═══════════════════════════════════════════════════════════════════════
  1317. import re
  1318. # Base CSS that enforces the "Axioms" from visual_framework.md
  1319. BASE_CSS = """
  1320. @page {
  1321. size: var(--canvas-w, 720px) var(--canvas-h, 960px);
  1322. margin: 0;
  1323. }
  1324. :root {
  1325. --font-sans: 'Inter', 'Noto Sans SC', 'Helvetica Neue', 'Apple Color Emoji', 'Segoe UI Emoji', sans-serif;
  1326. --font-serif: 'Playfair Display', 'Noto Serif SC', 'Cormorant Garamond', 'Apple Color Emoji', serif;
  1327. --font-mono: 'SF Mono', 'Consolas', 'Apple Color Emoji', monospace;
  1328. /* Typographic Scale — 6-level fluid type system (Modular Scale) */
  1329. --text-scale-6: clamp(64px, 12vw, 150px); /* Hero / Display — oversized, single word or short phrase */
  1330. --text-scale-5: clamp(48px, 8vw, 96px); /* Primary Title — poster headline */
  1331. --text-scale-4: clamp(32px, 5vw, 56px); /* Subheadline — chapter opener or key quote */
  1332. --text-scale-3: clamp(20px, 3vw, 32px); /* Lead Paragraph — slightly larger than body */
  1333. --text-scale-2: 16px; /* Body — standard body text */
  1334. --text-scale-1: 12px; /* Meta / Caption — minimum readable size */
  1335. }
  1336. html, body {
  1337. margin: 0; padding: 0;
  1338. background: var(--c-bg);
  1339. color: var(--c-text);
  1340. font-family: var(--font-sans);
  1341. -webkit-font-smoothing: antialiased;
  1342. }
  1343. /* Browser preview: scale poster to fit viewport & center on matching background */
  1344. @media screen {
  1345. html {
  1346. height: auto;
  1347. display: flex;
  1348. justify-content: center;
  1349. align-items: flex-start;
  1350. min-height: 100vh;
  1351. background: var(--c-bg);
  1352. }
  1353. body {
  1354. transform-origin: top center;
  1355. margin: 0 auto;
  1356. box-shadow: 0 0 60px rgba(0,0,0,0.3);
  1357. /* scale injected by override_css with concrete canvas dimensions */
  1358. }
  1359. }
  1360. .canvas {
  1361. width: var(--canvas-w, 720px);
  1362. min-height: var(--canvas-h, 960px);
  1363. position: relative;
  1364. overflow: hidden;
  1365. box-sizing: border-box;
  1366. page-break-after: always;
  1367. }
  1368. /* ═══ Continuous Canvas Mode (multi-page as one seamless surface) ═══ */
  1369. .continuous-canvas {
  1370. width: var(--canvas-w, 720px);
  1371. position: relative;
  1372. overflow: hidden;
  1373. box-sizing: border-box;
  1374. /* height is set inline: canvas_h * total_pages */
  1375. }
  1376. .continuous-canvas .bg-layer-full {
  1377. position: absolute;
  1378. inset: 0;
  1379. z-index: 1;
  1380. pointer-events: none;
  1381. }
  1382. .continuous-canvas .bg-layer-full svg {
  1383. width: 100%;
  1384. height: 100%;
  1385. }
  1386. .continuous-canvas .page-section {
  1387. position: absolute;
  1388. left: 0;
  1389. width: 100%;
  1390. box-sizing: border-box;
  1391. overflow: visible;
  1392. /* top and height set inline per page */
  1393. }
  1394. .continuous-canvas .page-section .safe-zone {
  1395. position: absolute;
  1396. inset: 10% 12%;
  1397. display: grid;
  1398. grid-template-columns: repeat(12, 1fr);
  1399. grid-template-rows: repeat(12, minmax(0, auto));
  1400. align-content: start;
  1401. }
  1402. .continuous-canvas .page-section .page-ghost {
  1403. position: absolute;
  1404. bottom: -5%;
  1405. right: 5%;
  1406. font-size: 240px;
  1407. font-weight: 900;
  1408. color: var(--c-mid);
  1409. opacity: 0.05;
  1410. pointer-events: none;
  1411. z-index: 0;
  1412. }
  1413. /* 12% Breathing Margin Enforcer (balanced: enough air without wasting space) */
  1414. .safe-zone {
  1415. position: absolute;
  1416. inset: 10% 12%;
  1417. display: grid;
  1418. grid-template-columns: repeat(12, 1fr);
  1419. grid-template-rows: repeat(12, minmax(0, auto));
  1420. align-content: start;
  1421. /* gap is injected dynamically by compile_blueprint via inline style */
  1422. }
  1423. /* Grid-item wrapper — every component gets one */
  1424. .grid-item {
  1425. display: flex;
  1426. min-width: 0;
  1427. min-height: 0;
  1428. overflow: visible;
  1429. }
  1430. /* Global content-overflow protection — prevents ANY text/block from breaking out of its container */
  1431. .grid-item * {
  1432. max-width: 100%;
  1433. box-sizing: border-box;
  1434. }
  1435. .grid-item p, .grid-item li, .grid-item span, .grid-item h1, .grid-item h2, .grid-item h3, .grid-item h4, .grid-item td, .grid-item th, .grid-item div {
  1436. overflow-wrap: break-word;
  1437. word-break: break-word;
  1438. }
  1439. /* CJK-safe text wrapping: prefer keeping CJK word groups intact, but allow break when necessary */
  1440. .hero-type, .hero-sub, .glass-canvas, .shaped-content, .stat-label, .delta-metric, .delta-label {
  1441. text-wrap: balance;
  1442. overflow-wrap: break-word;
  1443. word-break: normal;
  1444. line-break: strict;
  1445. }
  1446. /* ═══ Micro-Typography: Computational Typesetting ═══ */
  1447. p, .glass-canvas, .shaped-content, li {
  1448. /* Algorithmic justification — eliminates white rivers between words */
  1449. text-align: justify;
  1450. hyphens: auto;
  1451. word-spacing: -0.05em;
  1452. /* Hanging punctuation — visually aligned optical edges */
  1453. hanging-punctuation: first last;
  1454. /* Kill orphans & widows — force min 3 lines carried across page breaks */
  1455. orphans: 3;
  1456. widows: 3;
  1457. }
  1458. .grid-item table {
  1459. width: 100%;
  1460. table-layout: fixed;
  1461. overflow: hidden;
  1462. }
  1463. .grid-item img {
  1464. max-width: 100%;
  1465. height: auto;
  1466. }
  1467. /* --- Archetype Layouts --- */
  1468. /* All archetypes share the 12×12 grid via .safe-zone.
  1469. Archetype classes may override alignment defaults on the canvas level. */
  1470. .archetype-cover_hero .safe-zone {
  1471. align-content: start;
  1472. inset: 12% 14%;
  1473. }
  1474. /* Cover hero typography scale: larger text for covers */
  1475. .archetype-cover_hero .hero-type {
  1476. font-size: clamp(42px, 8vw, 72px);
  1477. line-height: 1.15;
  1478. }
  1479. .archetype-cover_hero .hero-sub {
  1480. font-size: clamp(22px, 4vw, 32px);
  1481. line-height: 1.3;
  1482. opacity: 0.85;
  1483. }
  1484. .archetype-cover_hero .floating-meta {
  1485. font-size: clamp(16px, 2.5vw, 22px);
  1486. }
  1487. .archetype-split_vertical { display: grid; grid-template-columns: 1fr 1fr; min-height: 960px; }
  1488. .archetype-split_vertical .safe-zone { position: relative; inset: auto; padding: 10%; display: grid; grid-template-columns: repeat(12, 1fr); grid-template-rows: repeat(12, 1fr); align-content: center; }
  1489. .archetype-split_vertical.single-column { grid-template-columns: 1fr; }
  1490. .archetype-editorial_flow .safe-zone { align-content: center; }
  1491. .archetype-scattered_canvas .safe-zone { /* same 12×12 grid — scattered effect via grid_area placement */ }
  1492. .archetype-data_dashboard .safe-zone { /* same 12×12 grid — dashboard tiles via grid_area placement */ }
  1493. .archetype-shaped_editorial .safe-zone { align-content: center; }
  1494. /* Continuous canvas archetype overrides (page-section inherits archetype class) */
  1495. .continuous-canvas .page-section.archetype-cover_hero .safe-zone { align-content: start; inset: 12% 14%; }
  1496. .continuous-canvas .page-section.archetype-cover_hero .hero-type { font-size: clamp(42px, 8vw, 72px); line-height: 1.15; }
  1497. .continuous-canvas .page-section.archetype-cover_hero .hero-sub { font-size: clamp(22px, 4vw, 32px); line-height: 1.3; opacity: 0.85; }
  1498. .continuous-canvas .page-section.archetype-cover_hero .floating-meta { font-size: clamp(16px, 2.5vw, 22px); }
  1499. .continuous-canvas .page-section.archetype-editorial_flow .safe-zone { align-content: center; }
  1500. .continuous-canvas .page-section.archetype-shaped_editorial .safe-zone { align-content: center; inset: 5% 6%; }
  1501. /* --- Components --- */
  1502. .hero-type {
  1503. font-size: clamp(48px, 10vw, 110px);
  1504. line-height: 0.88;
  1505. letter-spacing: -0.03em;
  1506. margin: 0;
  1507. overflow-wrap: break-word;
  1508. word-break: break-word;
  1509. position: relative;
  1510. z-index: 10;
  1511. }
  1512. .hero-type.weight-black { font-weight: 900; }
  1513. .hero-type.weight-thin { font-weight: 100; letter-spacing: 0.05em; font-family: var(--font-serif); }
  1514. .hero-sub {
  1515. margin: 8px 0 0 0;
  1516. font-size: var(--text-scale-2);
  1517. line-height: 1.3;
  1518. opacity: 0.8;
  1519. }
  1520. /* Hero container needs vertical stacking */
  1521. .grid-item:has(.hero-type) {
  1522. flex-direction: column;
  1523. justify-content: center;
  1524. }
  1525. .hero-type, .hero-sub {
  1526. width: 100%;
  1527. }
  1528. .hero-type {
  1529. color: var(--c-text);
  1530. }
  1531. .glass-canvas {
  1532. background: var(--c-surface);
  1533. border: 1px solid rgba(128, 128, 128, 0.08);
  1534. border-radius: 2px;
  1535. padding: 36px;
  1536. font-size: 16px;
  1537. line-height: 1.6;
  1538. z-index: 5;
  1539. position: relative;
  1540. overflow-wrap: break-word;
  1541. word-break: break-word;
  1542. }
  1543. .floating-meta {
  1544. display: flex;
  1545. flex-direction: column;
  1546. font-size: 12px;
  1547. font-family: var(--font-mono);
  1548. letter-spacing: 0.1em;
  1549. color: var(--c-muted);
  1550. opacity: 0.6;
  1551. z-index: 20;
  1552. overflow: hidden;
  1553. text-overflow: ellipsis;
  1554. /* Positioned via grid_area in .grid-item wrapper — no absolute needed */
  1555. }
  1556. /* Legacy position helpers (kept for backwards compat with old blueprints) */
  1557. .pos-top-left { align-self: start; justify-self: start; }
  1558. .pos-top-right { align-self: start; justify-self: end; text-align: right; }
  1559. .pos-bottom-left { align-self: end; justify-self: start; }
  1560. .pos-bottom-right { align-self: end; justify-self: end; text-align: right; }
  1561. .stat-block { display: flex; flex-direction: column; margin-bottom: 24px; }
  1562. .stat-num { font-size: clamp(32px, 5vw, 56px); font-weight: 900; line-height: 0.9; color: var(--c-text); }
  1563. .stat-unit { font-size: clamp(14px, 2vw, 20px); font-weight: 300; color: var(--c-muted); margin-left: 4px; display: inline;}
  1564. .stat-label { font-size: 12px; letter-spacing: 0.15em; color: var(--c-accent); margin-top: 8px; text-transform: uppercase; }
  1565. .hairline { border: none; border-top: 0.5px solid var(--c-muted); opacity: 0.3; margin: 8px 0; width: 100%; }
  1566. .hairline.style-accent { border-top-color: var(--c-accent); width: 30%; margin-left: 0; opacity: 0.8;}
  1567. .page-ghost {
  1568. position: absolute; bottom: -5%; right: 5%;
  1569. font-size: 240px; font-weight: 900; color: var(--c-mid);
  1570. opacity: 0.05; pointer-events: none; z-index: 0;
  1571. }
  1572. .bg-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; }
  1573. .bg-layer svg { width: 100%; height: 100%; }
  1574. /* --- Shaped_Canvas (Semantic Shape-Wrapping) --- */
  1575. .shaped-canvas {
  1576. position: relative;
  1577. padding: 24px;
  1578. font-size: 16px;
  1579. line-height: 1.7;
  1580. z-index: 5;
  1581. overflow-wrap: break-word;
  1582. word-break: break-word;
  1583. }
  1584. .shape-float {
  1585. float: left;
  1586. margin: 0;
  1587. padding: 0;
  1588. }
  1589. .shape-circle { shape-outside: circle(45% at 50% 50%); width: 40%; height: 90%; }
  1590. .shape-wave { shape-outside: polygon(0 0, 80% 0, 60% 25%, 80% 50%, 60% 75%, 80% 100%, 0 100%); width: 45%; height: 100%; }
  1591. .shape-diagonal_slash { shape-outside: polygon(0 0, 100% 0, 0 100%); width: 50%; height: 100%; }
  1592. .shape-diamond { shape-outside: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); width: 45%; height: 90%; }
  1593. .shape-wedge_right { shape-outside: polygon(0 0, 60% 0, 100% 50%, 60% 100%, 0 100%); width: 50%; height: 100%; }
  1594. /* --- Archetype: shaped_editorial --- */
  1595. .archetype-shaped_editorial .safe-zone {
  1596. inset: 5% 6%;
  1597. /* Inherits 12×12 grid from .safe-zone */
  1598. align-content: center;
  1599. }
  1600. /* ═══ Tufte Marginalia System ═══ */
  1601. /* 30% sidenote rail for report/long-form archetypes */
  1602. .archetype-tufte_report .safe-zone {
  1603. display: grid;
  1604. grid-template-columns: 1fr 280px;
  1605. gap: 40px;
  1606. align-content: start;
  1607. }
  1608. .archetype-tufte_report .main-column {
  1609. display: grid;
  1610. grid-template-columns: repeat(12, 1fr);
  1611. grid-template-rows: repeat(12, 1fr);
  1612. gap: inherit;
  1613. }
  1614. .archetype-tufte_report .side-rail {
  1615. display: flex;
  1616. flex-direction: column;
  1617. gap: 24px;
  1618. padding-top: 8px;
  1619. }
  1620. .sidenote {
  1621. font-size: 13px;
  1622. line-height: 1.5;
  1623. color: var(--c-muted);
  1624. border-left: 2px solid var(--c-accent);
  1625. padding-left: 12px;
  1626. opacity: 0.85;
  1627. }
  1628. .sidenote .sidenote-label {
  1629. font-weight: 700;
  1630. font-size: 12px;
  1631. text-transform: uppercase;
  1632. letter-spacing: 0.08em;
  1633. color: var(--c-accent);
  1634. display: block;
  1635. margin-bottom: 4px;
  1636. }
  1637. /* ═══ Delta Widget — Data-to-Ink Ratio Component ═══ */
  1638. .delta-widget {
  1639. text-align: center;
  1640. padding: 16px 12px;
  1641. }
  1642. .delta-widget .delta-metric {
  1643. font-size: 12px;
  1644. font-weight: 600;
  1645. text-transform: uppercase;
  1646. letter-spacing: 0.1em;
  1647. color: var(--c-muted);
  1648. margin-bottom: 4px;
  1649. }
  1650. .delta-widget .delta-value {
  1651. font-size: 36px;
  1652. font-weight: 900;
  1653. color: var(--c-text);
  1654. line-height: 1.1;
  1655. }
  1656. .delta-widget .delta-change {
  1657. font-size: 14px;
  1658. font-weight: 700;
  1659. margin-top: 4px;
  1660. }
  1661. .delta-widget .delta-label {
  1662. font-size: 12px;
  1663. color: var(--c-muted);
  1664. margin-top: 8px;
  1665. }
  1666. /* ═══ Polymorphic Process_List — Container Query Adaptive ═══ */
  1667. .process-list-container {
  1668. container-type: inline-size;
  1669. width: 100%;
  1670. min-height: 100%;
  1671. }
  1672. /* Wide: horizontal timeline */
  1673. .process-list {
  1674. display: flex;
  1675. flex-direction: row;
  1676. align-items: flex-start;
  1677. gap: 8px;
  1678. list-style: none;
  1679. padding: 0;
  1680. margin: 0;
  1681. min-height: 100%;
  1682. }
  1683. .process-list .process-step {
  1684. flex: 1;
  1685. display: flex;
  1686. flex-direction: column;
  1687. align-items: center;
  1688. text-align: center;
  1689. position: relative;
  1690. padding: 12px 4px;
  1691. }
  1692. .process-step .step-num {
  1693. width: 32px; height: 32px; border-radius: 50%;
  1694. background: var(--c-accent); color: #fff;
  1695. display: flex; align-items: center; justify-content: center;
  1696. font-weight: 800; font-size: 14px; margin-bottom: 8px;
  1697. flex-shrink: 0;
  1698. }
  1699. .process-step .step-title { font-weight: 700; font-size: 13px; color: var(--c-text); }
  1700. .process-step .step-desc { font-size: 12px; color: var(--c-muted); margin-top: 4px; line-height: 1.4; }
  1701. /* Connector line between horizontal steps */
  1702. .process-step:not(:last-child)::after {
  1703. content: ''; position: absolute; top: 28px; right: -6px;
  1704. width: 12px; height: 2px; background: var(--c-accent); opacity: 0.5;
  1705. }
  1706. /* Narrow: vertical numbered list */
  1707. @container (max-width: 360px) {
  1708. .process-list {
  1709. flex-direction: column;
  1710. gap: 12px;
  1711. }
  1712. .process-list .process-step {
  1713. flex-direction: row;
  1714. text-align: left;
  1715. align-items: flex-start;
  1716. gap: 12px;
  1717. padding: 4px 0;
  1718. }
  1719. .process-step .step-num { margin-bottom: 0; }
  1720. .process-step:not(:last-child)::after { display: none; }
  1721. }
  1722. """
  1723. def _prevent_orphan_chars(text):
  1724. """
  1725. Prevent orphan characters at end of paragraphs.
  1726. Replace the last space/breakable point between the final two CJK chars
  1727. (or words) with &nbsp; so the browser never wraps a single trailing char
  1728. onto its own line.
  1729. """
  1730. # CJK orphan: bind last two CJK characters with a zero-width no-break joiner
  1731. # Match: (CJK char)(optional space)(CJK char) at end of string (before tags)
  1732. text = re.sub(r'([\u4e00-\u9fff\u3400-\u4dbf])[\s]+([\u4e00-\u9fff\u3400-\u4dbf])(?=\s*(?:<[^>]*>)*\s*$)', '\\g<1>\u2060\\g<2>', text)
  1733. # Latin orphan: bind last two words
  1734. text = re.sub(r'(\S+)\s+(\S+)\s*$', r'\1&nbsp;\2', text)
  1735. return text
  1736. def simple_markdown_to_html(md_text):
  1737. """Lightweight markdown → HTML for Glass Canvas. Handles paragraphs, headers, bold, italic, lists, and inline code."""
  1738. if not md_text:
  1739. return ""
  1740. lines = md_text.split('\n')
  1741. html_parts = []
  1742. in_list = False
  1743. paragraph_buffer = []
  1744. def flush_paragraph():
  1745. nonlocal paragraph_buffer
  1746. if paragraph_buffer:
  1747. text = ' '.join(paragraph_buffer)
  1748. # Apply inline formatting
  1749. text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
  1750. text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
  1751. text = re.sub(r'`(.*?)`', r'<code style="background:var(--c-surface);padding:2px 6px;border-radius:3px;font-size:max(12px, 0.9em)">\1</code>', text)
  1752. # Anti-orphan: prevent single trailing character on last line
  1753. text = _prevent_orphan_chars(text)
  1754. html_parts.append(f'<p style="margin:0 0 12px 0;line-height:1.7">{text}</p>')
  1755. paragraph_buffer = []
  1756. def apply_inline(text):
  1757. """Apply bold, italic, inline code."""
  1758. text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
  1759. text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
  1760. text = re.sub(r'`(.*?)`', r'<code style="background:var(--c-surface);padding:2px 6px;border-radius:3px;font-size:max(12px, 0.9em)">\1</code>', text)
  1761. return text
  1762. for line in lines:
  1763. stripped = line.strip()
  1764. # Empty line — flush paragraph
  1765. if not stripped:
  1766. flush_paragraph()
  1767. if in_list:
  1768. html_parts.append('</ul>')
  1769. in_list = False
  1770. continue
  1771. # Headers
  1772. if stripped.startswith('### '):
  1773. flush_paragraph()
  1774. if in_list:
  1775. html_parts.append('</ul>')
  1776. in_list = False
  1777. html_parts.append(f'<h3 style="font-size:16px;font-weight:700;margin:20px 0 8px 0;color:var(--c-accent);text-transform:uppercase;letter-spacing:0.05em;">{apply_inline(stripped[4:])}</h3>')
  1778. continue
  1779. if stripped.startswith('## '):
  1780. flush_paragraph()
  1781. if in_list:
  1782. html_parts.append('</ul>')
  1783. in_list = False
  1784. html_parts.append(f'<h2 style="font-size:20px;font-weight:700;margin:24px 0 12px 0;color:var(--c-text)">{apply_inline(stripped[3:])}</h2>')
  1785. continue
  1786. if stripped.startswith('# '):
  1787. flush_paragraph()
  1788. if in_list:
  1789. html_parts.append('</ul>')
  1790. in_list = False
  1791. html_parts.append(f'<h1 style="font-size:24px;font-weight:800;margin:28px 0 14px 0;color:var(--c-text)">{apply_inline(stripped[2:])}</h1>')
  1792. continue
  1793. # List items (- or *)
  1794. list_match = re.match(r'^[-*]\s+(.*)', stripped)
  1795. if list_match:
  1796. flush_paragraph()
  1797. if not in_list:
  1798. html_parts.append('<ul style="margin:8px 0;padding-left:20px;list-style-type:disc">')
  1799. in_list = True
  1800. html_parts.append(f'<li style="margin:4px 0;line-height:1.6">{apply_inline(list_match.group(1))}</li>')
  1801. continue
  1802. # Numbered list items
  1803. num_match = re.match(r'^(\d+)[.)]\s+(.*)', stripped)
  1804. if num_match:
  1805. flush_paragraph()
  1806. if in_list:
  1807. html_parts.append('</ul>')
  1808. in_list = False
  1809. html_parts.append(f'<p style="margin:4px 0 4px 20px;line-height:1.6"><strong>{num_match.group(1)}.</strong> {apply_inline(num_match.group(2))}</p>')
  1810. continue
  1811. # Normal text — accumulate into paragraph
  1812. paragraph_buffer.append(stripped)
  1813. # Flush remaining
  1814. flush_paragraph()
  1815. if in_list:
  1816. html_parts.append('</ul>')
  1817. return '\n'.join(html_parts)
  1818. def _parse_grid_area(comp):
  1819. """
  1820. Parse grid_area from component JSON.
  1821. Accepts two formats:
  1822. - Array: [row_start, col_start, row_end, col_end] — 1-based, max 13.
  1823. - String: "row_start / col_start / row_end / col_end" — 1-based, max 13.
  1824. Returns CSS grid-area string or None.
  1825. """
  1826. ga = comp.get("grid_area", None)
  1827. if ga is None:
  1828. return None
  1829. # Array format: [1, 1, 3, 5]
  1830. if isinstance(ga, list) and len(ga) == 4:
  1831. rs, cs, re, ce = [max(1, min(13, int(v))) for v in ga]
  1832. # Fix zero-height/zero-width grid areas (row_end must be > row_start)
  1833. if re <= rs:
  1834. re = min(13, rs + 1)
  1835. if ce <= cs:
  1836. ce = min(13, cs + 1)
  1837. return f"{rs} / {cs} / {re} / {ce}"
  1838. # String format: "1 / 1 / 3 / 5"
  1839. if isinstance(ga, str) and "/" in ga:
  1840. parts = [p.strip() for p in ga.split("/")]
  1841. if len(parts) == 4:
  1842. try:
  1843. rs, cs, re, ce = [max(1, min(13, int(p))) for p in parts]
  1844. # Fix zero-height/zero-width grid areas
  1845. if re <= rs:
  1846. re = min(13, rs + 1)
  1847. if ce <= cs:
  1848. ce = min(13, cs + 1)
  1849. return f"{rs} / {cs} / {re} / {ce}"
  1850. except ValueError:
  1851. pass
  1852. return None
  1853. def _parse_align(comp):
  1854. """
  1855. Parse align from component JSON.
  1856. Format: "vertical / horizontal" where each is start|center|end.
  1857. Returns (align-items, justify-content) tuple.
  1858. """
  1859. align = comp.get("align", "start / start")
  1860. if "/" in str(align):
  1861. parts = [p.strip() for p in str(align).split("/")]
  1862. v = parts[0] if parts[0] in ("start", "center", "end") else "start"
  1863. h = parts[1] if len(parts) > 1 and parts[1] in ("start", "center", "end") else "start"
  1864. else:
  1865. v, h = "start", "start"
  1866. return v, h
  1867. def _estimate_content_weight(comp):
  1868. """
  1869. Estimate the visual weight (space needed) of a component based on its content.
  1870. Returns a numeric weight proportional to how many grid rows it should occupy.
  1871. Text-heavy components (Glass_Canvas, Shaped_Canvas) get weight proportional to
  1872. character count. Fixed-height components (Stat_Block, Hero_Typography, etc.) get
  1873. a small fixed weight since they don't grow with content.
  1874. """
  1875. ctype = comp.get("type", "")
  1876. # Fixed-height components: their visual size is independent of text length
  1877. FIXED_WEIGHTS = {
  1878. "Hero_Typography": 2.5,
  1879. "Stat_Block": 2.0,
  1880. "Delta_Widget": 2.0,
  1881. "Hairline_Divider": 1.0,
  1882. "Floating_Meta": 1.0, # usually positioned in corners, but fallback
  1883. "Image_Asset": 3.0,
  1884. }
  1885. if ctype in FIXED_WEIGHTS:
  1886. return FIXED_WEIGHTS[ctype]
  1887. # Text-heavy components: weight scales with content length
  1888. text = comp.get("markdown_content", "") or comp.get("body", "") or ""
  1889. # Also count sub-items (Process_List steps)
  1890. for step in comp.get("steps", []):
  1891. text += step.get("title", "") + step.get("description", "")
  1892. char_count = len(text)
  1893. if ctype in ("Glass_Canvas", "Shaped_Canvas", "Process_List"):
  1894. # Rough estimate: ~40 CJK chars per line at 16px in a ~500px wide container,
  1895. # ~1.6 line-height, so each 40 chars ≈ 1 visual line ≈ ~25px.
  1896. # Grid row on a 960px canvas ≈ 80px each (960/12).
  1897. # So 40 chars ≈ 0.3 grid rows. But Glass_Canvas has padding (~72px total),
  1898. # headings, list spacing, etc. Add base weight for the container itself.
  1899. base = 2.0 # minimum for padding + heading
  1900. text_rows = char_count / 120.0 # ~120 chars per grid-row worth of space
  1901. return base + text_rows
  1902. # Unknown component type: estimate from text length with a reasonable default
  1903. if char_count > 0:
  1904. return 2.0 + char_count / 120.0
  1905. return 2.0
  1906. def _assign_floating_meta(comp):
  1907. """Assign grid_area to a Floating_Meta component based on its position."""
  1908. pos = comp.get("position", "top-right")
  1909. if "top" in pos and "left" in pos:
  1910. comp["grid_area"] = "1 / 1 / 2 / 7"
  1911. elif "top" in pos:
  1912. comp["grid_area"] = "1 / 7 / 2 / 13"
  1913. elif "bottom" in pos and "left" in pos:
  1914. comp["grid_area"] = "12 / 1 / 13 / 7"
  1915. else:
  1916. comp["grid_area"] = "12 / 7 / 13 / 13"
  1917. def _distribute_rows_by_weight(content_comps, start_row=1, end_row=13, full_width=True):
  1918. """
  1919. Distribute grid rows among content components proportionally to their content weight.
  1920. Each component gets at least 2 rows. Components fill start_row to end_row seamlessly.
  1921. """
  1922. nn = len(content_comps)
  1923. if nn == 0:
  1924. return
  1925. total_rows = end_row - start_row # available rows
  1926. # Calculate weights
  1927. weights = [_estimate_content_weight(c) for c in content_comps]
  1928. total_weight = sum(weights)
  1929. if total_weight == 0:
  1930. total_weight = nn # fallback: equal distribution
  1931. weights = [1.0] * nn
  1932. # Allocate rows proportionally, with minimum 2 per component
  1933. MIN_ROWS = 2
  1934. raw_rows = [(w / total_weight) * total_rows for w in weights]
  1935. # Ensure minimum, then redistribute excess
  1936. allocated = []
  1937. for r in raw_rows:
  1938. allocated.append(max(MIN_ROWS, round(r)))
  1939. # Adjust total to exactly fill the available rows
  1940. # First pass: if total exceeds available, shrink the largest allocations
  1941. while sum(allocated) > total_rows and any(a > MIN_ROWS for a in allocated):
  1942. max_idx = max(range(nn), key=lambda i: allocated[i])
  1943. allocated[max_idx] -= 1
  1944. # Second pass: if total is less than available, grow the heaviest components
  1945. while sum(allocated) < total_rows:
  1946. max_weight_idx = max(range(nn), key=lambda i: weights[i])
  1947. allocated[max_weight_idx] += 1
  1948. # Assign grid_area
  1949. col_start = 1
  1950. col_end = 13 if full_width else 7 # can be overridden by caller
  1951. current_row = start_row
  1952. for j, comp in enumerate(content_comps):
  1953. rs = current_row
  1954. re = min(end_row, current_row + allocated[j])
  1955. comp["grid_area"] = f"{rs} / {col_start} / {re} / {col_end}"
  1956. current_row = re
  1957. def _auto_assign_grid_areas(archetype, components):
  1958. """
  1959. Auto-assign grid_area to components that don't have one,
  1960. based on the archetype and number of components.
  1961. Mutates components in-place.
  1962. Skips Page_Ghost_Number (uses absolute positioning, not grid).
  1963. Uses content-aware row distribution: text-heavy components (Glass_Canvas)
  1964. get more rows than fixed-height components (Stat_Block, Hero_Typography).
  1965. """
  1966. # Filter out ghost numbers — they use absolute positioning, not grid
  1967. gridded = [c for c in components if c.get("type") != "Page_Ghost_Number"]
  1968. # Only process components without grid_area
  1969. needs_area = [c for c in gridded if not c.get("grid_area")]
  1970. if not needs_area:
  1971. return # All components already have grid_area
  1972. n = len(gridded)
  1973. if archetype == "cover_hero":
  1974. # Cover: stack vertically, full width, spread across page
  1975. # Typical: 2-4 components (Hero + Floating_Meta + optional divider/ghost)
  1976. if n <= 2:
  1977. slots = ["1 / 1 / 7 / 13", "9 / 1 / 13 / 13"]
  1978. elif n == 3:
  1979. slots = ["1 / 1 / 5 / 13", "5 / 1 / 9 / 13", "10 / 1 / 13 / 13"]
  1980. else:
  1981. slots = ["1 / 1 / 4 / 13", "4 / 1 / 7 / 13", "8 / 1 / 10 / 13", "10 / 1 / 13 / 13"]
  1982. for i, comp in enumerate(gridded):
  1983. if not comp.get("grid_area") and i < len(slots):
  1984. comp["grid_area"] = slots[i]
  1985. elif archetype == "data_dashboard":
  1986. # Dashboard: tile components in a 2-column or 3-column grid
  1987. has_area = [c for c in gridded if c.get("grid_area")]
  1988. no_area = [c for c in gridded if not c.get("grid_area")]
  1989. nn = len(no_area)
  1990. if nn <= 2:
  1991. slots = ["1 / 1 / 7 / 7", "1 / 7 / 7 / 13"]
  1992. elif nn <= 4:
  1993. slots = ["1 / 1 / 7 / 7", "1 / 7 / 7 / 13",
  1994. "7 / 1 / 13 / 7", "7 / 7 / 13 / 13"]
  1995. elif nn <= 6:
  1996. slots = ["1 / 1 / 5 / 7", "1 / 7 / 5 / 13",
  1997. "5 / 1 / 9 / 7", "5 / 7 / 9 / 13",
  1998. "9 / 1 / 13 / 7", "9 / 7 / 13 / 13"]
  1999. elif nn <= 9:
  2000. slots = ["1 / 1 / 5 / 5", "1 / 5 / 5 / 9", "1 / 9 / 5 / 13",
  2001. "5 / 1 / 9 / 5", "5 / 5 / 9 / 9", "5 / 9 / 9 / 13",
  2002. "9 / 1 / 13 / 5", "9 / 5 / 13 / 9", "9 / 9 / 13 / 13"]
  2003. else:
  2004. # Too many: 3-col grid, auto-expand rows
  2005. slots = []
  2006. cols = 3
  2007. row_h = max(2, 12 // ((nn + cols - 1) // cols))
  2008. for idx in range(nn):
  2009. r = idx // cols
  2010. c = idx % cols
  2011. rs = 1 + r * row_h
  2012. re = min(13, rs + row_h)
  2013. cs = 1 + c * 4
  2014. ce = min(13, cs + 4)
  2015. slots.append(f"{rs} / {cs} / {re} / {ce}")
  2016. j = 0
  2017. for comp in no_area:
  2018. if j < len(slots):
  2019. comp["grid_area"] = slots[j]
  2020. j += 1
  2021. elif archetype == "editorial_flow":
  2022. # Editorial: stack vertically, full width
  2023. # Handle Floating_Meta separately — assign to corners based on position
  2024. # Content components get rows proportional to their content weight
  2025. no_area = [c for c in gridded if not c.get("grid_area")]
  2026. content_comps = []
  2027. for comp in no_area:
  2028. if comp.get("type") == "Floating_Meta":
  2029. _assign_floating_meta(comp)
  2030. else:
  2031. content_comps.append(comp)
  2032. if content_comps:
  2033. _distribute_rows_by_weight(content_comps, start_row=1, end_row=13, full_width=True)
  2034. elif archetype == "split_vertical":
  2035. # Split: first half on left, second half on right
  2036. # Each side gets content-proportional row distribution
  2037. no_area = [c for c in gridded if not c.get("grid_area")]
  2038. nn = len(no_area)
  2039. mid = (nn + 1) // 2
  2040. left = no_area[:mid]
  2041. right = no_area[mid:]
  2042. # Left column: cols 1-7
  2043. if left:
  2044. weights_l = [_estimate_content_weight(c) for c in left]
  2045. total_w = sum(weights_l) or 1
  2046. current = 1
  2047. for j, comp in enumerate(left):
  2048. rows = max(2, round((weights_l[j] / total_w) * 12))
  2049. rs = current
  2050. re = min(13, current + rows)
  2051. comp["grid_area"] = f"{rs} / 1 / {re} / 7"
  2052. current = re
  2053. # Right column: cols 7-13
  2054. if right:
  2055. weights_r = [_estimate_content_weight(c) for c in right]
  2056. total_w = sum(weights_r) or 1
  2057. current = 1
  2058. for j, comp in enumerate(right):
  2059. rows = max(2, round((weights_r[j] / total_w) * 12))
  2060. rs = current
  2061. re = min(13, current + rows)
  2062. comp["grid_area"] = f"{rs} / 7 / {re} / 13"
  2063. current = re
  2064. elif archetype == "scattered_canvas":
  2065. # Scatter: distribute pseudo-randomly across the grid
  2066. no_area = [c for c in gridded if not c.get("grid_area")]
  2067. scatter_slots = [
  2068. "1 / 1 / 5 / 6", "1 / 7 / 4 / 13", "5 / 3 / 9 / 10",
  2069. "6 / 1 / 10 / 5", "7 / 8 / 11 / 13", "10 / 2 / 13 / 8",
  2070. "10 / 8 / 13 / 13", "3 / 1 / 6 / 5", "1 / 4 / 4 / 10",
  2071. ]
  2072. for j, comp in enumerate(no_area):
  2073. if j < len(scatter_slots):
  2074. comp["grid_area"] = scatter_slots[j]
  2075. elif archetype == "shaped_editorial":
  2076. # Shaped: main shaped canvas gets most of the page
  2077. no_area = [c for c in gridded if not c.get("grid_area")]
  2078. for j, comp in enumerate(no_area):
  2079. if comp.get("type") == "Shaped_Canvas":
  2080. comp["grid_area"] = "2 / 2 / 12 / 12"
  2081. elif comp.get("type") == "Floating_Meta":
  2082. _assign_floating_meta(comp)
  2083. else:
  2084. comp["grid_area"] = f"{1 + j * 3} / 1 / {min(13, 4 + j * 3)} / 13"
  2085. # Fallback: if still no grid_area, make full-width stacked rows
  2086. # Uses content-aware distribution instead of equal division
  2087. remaining = [c for c in gridded if not c.get("grid_area")]
  2088. if remaining:
  2089. # First, handle Floating_Meta components by position
  2090. non_meta = []
  2091. for comp in remaining:
  2092. if comp.get("type") == "Floating_Meta":
  2093. _assign_floating_meta(comp)
  2094. else:
  2095. non_meta.append(comp)
  2096. # Then distribute rows proportionally to content weight
  2097. if non_meta:
  2098. _distribute_rows_by_weight(non_meta, start_row=1, end_row=13, full_width=True)
  2099. def _wrap_grid_item(comp, inner_html):
  2100. """Wrap a rendered component in a .grid-item div with grid positioning."""
  2101. grid_area_css = _parse_grid_area(comp)
  2102. v_align, h_align = _parse_align(comp)
  2103. # Glass_Canvas and Process_List should stretch to fill their grid area
  2104. ctype = comp.get("type", "")
  2105. if ctype in ("Glass_Canvas", "Process_List"):
  2106. v_align = "stretch"
  2107. style_parts = []
  2108. if grid_area_css:
  2109. style_parts.append(f"grid-area: {grid_area_css}")
  2110. style_parts.append(f"align-items: {v_align}")
  2111. style_parts.append(f"justify-content: {h_align}")
  2112. style = "; ".join(style_parts) + ";"
  2113. return f'<div class="grid-item" style="{style}">\n{inner_html}</div>\n'
  2114. def render_component(comp):
  2115. """Convert a JSON component object into HTML string, wrapped in grid-item."""
  2116. # Flatten nested "content" and "style" dicts into top-level for compat
  2117. # e.g. {"content": {"heading": "Hi"}} → {"heading": "Hi"}
  2118. _content = comp.get("content", None)
  2119. if isinstance(_content, dict):
  2120. for k, v in _content.items():
  2121. if k not in comp:
  2122. comp[k] = v
  2123. _style = comp.get("style", None)
  2124. if isinstance(_style, dict):
  2125. for k, v in _style.items():
  2126. if k not in comp:
  2127. comp[k] = v
  2128. ctype = comp.get("type", "")
  2129. inner = ""
  2130. if ctype == "Hero_Typography":
  2131. weight = comp.get("weight", "black")
  2132. heading = comp.get("heading", "")
  2133. subheading = comp.get("subheading", "")
  2134. # Fallback: if "content" is a plain string, use it as heading
  2135. raw_content = comp.get("content", "")
  2136. if not heading and isinstance(raw_content, str) and raw_content:
  2137. heading = raw_content
  2138. # Sanitize consecutive <br> — collapse 3+ into max 2
  2139. heading = re.sub(r'(<br\s*/?>){3,}', '<br><br>', heading)
  2140. if subheading:
  2141. subheading = re.sub(r'(<br\s*/?>){3,}', '<br><br>', subheading)
  2142. scale = comp.get("scale", None)
  2143. # Build inline style from both scale and custom style props
  2144. style_parts = []
  2145. if scale is not None and 1 <= int(scale) <= 6:
  2146. style_parts.append(f"font-size: var(--text-scale-{int(scale)})")
  2147. heading_font_size = comp.get("heading_font_size", "")
  2148. heading_color = comp.get("heading_color", "")
  2149. heading_ls = comp.get("heading_letter_spacing", "")
  2150. text_align = comp.get("text_align", "")
  2151. if heading_font_size:
  2152. style_parts.append(f"font-size: {heading_font_size}")
  2153. if heading_color:
  2154. style_parts.append(f"color: {heading_color}")
  2155. if heading_ls:
  2156. style_parts.append(f"letter-spacing: {heading_ls}")
  2157. if text_align:
  2158. style_parts.append(f"text-align: {text_align}")
  2159. h_style = f' style="{"; ".join(style_parts)}"' if style_parts else ""
  2160. inner = f'<h1 class="hero-type weight-{weight}"{h_style}>{heading}</h1>\n'
  2161. if subheading:
  2162. sub_style_parts = []
  2163. sub_fs = comp.get("subheading_font_size", "")
  2164. sub_color = comp.get("subheading_color", "")
  2165. sub_ls = comp.get("subheading_letter_spacing", "")
  2166. if sub_fs:
  2167. sub_style_parts.append(f"font-size: {sub_fs}")
  2168. if sub_color:
  2169. sub_style_parts.append(f"color: {sub_color}")
  2170. if sub_ls:
  2171. sub_style_parts.append(f"letter-spacing: {sub_ls}")
  2172. if text_align:
  2173. sub_style_parts.append(f"text-align: {text_align}")
  2174. s_style = f' style="{"; ".join(sub_style_parts)}"' if sub_style_parts else ""
  2175. inner += f'<p class="hero-sub"{s_style}>{subheading}</p>\n'
  2176. elif ctype == "Glass_Canvas":
  2177. md = comp.get("markdown_content", "") or comp.get("body", "")
  2178. html_content = simple_markdown_to_html(md)
  2179. # Build inline style from custom style props
  2180. gs_parts = ["width:100%", "min-height:100%", "box-sizing:border-box"]
  2181. # --- Auto font-size scaling for Glass_Canvas ---
  2182. # When content is too long for the allocated grid rows, shrink font-size
  2183. # to avoid overflow into adjacent components.
  2184. # Estimation: ~80 chars per row at 16px base font-size (with padding).
  2185. user_font_size = comp.get("font_size", "")
  2186. if not user_font_size: # Only auto-scale when user hasn't set a custom size
  2187. grid_area_str = comp.get("grid_area", "")
  2188. if grid_area_str:
  2189. try:
  2190. ga_parts = [int(x.strip()) for x in grid_area_str.split("/")]
  2191. allocated_rows = ga_parts[2] - ga_parts[0] # row_end - row_start
  2192. content_len = len(md)
  2193. chars_per_row = 80 # approximate chars that fit in one grid row at 16px
  2194. needed_rows = max(1, content_len / chars_per_row)
  2195. if needed_rows > allocated_rows:
  2196. # Scale down proportionally, but never below 12px
  2197. scale = allocated_rows / needed_rows
  2198. new_size = max(12, int(16 * scale))
  2199. if new_size < 16:
  2200. gs_parts.append(f"font-size: {new_size}px")
  2201. except (ValueError, IndexError):
  2202. pass
  2203. for prop in ["background", "border", "border_radius", "padding", "font_size", "color", "line_height", "text_align"]:
  2204. val = comp.get(prop, "")
  2205. if val:
  2206. css_prop = prop.replace("_", "-")
  2207. gs_parts.append(f"{css_prop}: {val}")
  2208. grid_style = "; ".join(gs_parts) + ";"
  2209. tension = comp.get("tension_score", None)
  2210. if tension is not None:
  2211. weight = int(300 + (float(tension) * 600))
  2212. inner = f'<div class="glass-canvas" style="{grid_style}font-variation-settings: \'wght\' {weight};">{html_content}</div>\n'
  2213. else:
  2214. inner = f'<div class="glass-canvas" style="{grid_style}">{html_content}</div>\n'
  2215. elif ctype == "Floating_Meta":
  2216. pos = comp.get("position", "top-left")
  2217. items_html = "".join([f"<span>{item}</span>" for item in comp.get("items", [])])
  2218. fm_style_parts = []
  2219. for prop in ["font_size", "color", "letter_spacing", "text_align"]:
  2220. val = comp.get(prop, "")
  2221. if val:
  2222. fm_style_parts.append(f"{prop.replace('_', '-')}: {val}")
  2223. fm_style = f' style="{"; ".join(fm_style_parts)}"' if fm_style_parts else ""
  2224. inner = f'<div class="floating-meta pos-{pos}"{fm_style}>{items_html}</div>\n'
  2225. elif ctype == "Stat_Block":
  2226. inner = f'''<div class="stat-block">
  2227. <div><span class="stat-num">{comp.get("number", "")}</span><span class="stat-unit">{comp.get("unit", "")}</span></div>
  2228. <span class="stat-label">{comp.get("label", "")}</span>
  2229. </div>\n'''
  2230. elif ctype == "Hairline_Divider":
  2231. style = comp.get("style", "bleed")
  2232. inner = f'<hr class="hairline style-{style}">\n'
  2233. elif ctype == "Page_Ghost_Number":
  2234. # Ghost numbers are decorative overlays — still use absolute positioning
  2235. return f'<div class="page-ghost">{comp.get("number", "")}</div>\n'
  2236. elif ctype == "Shaped_Canvas":
  2237. shape = comp.get("shape_keyword", "circle")
  2238. md = comp.get("markdown_content", "") or comp.get("body", "")
  2239. html_content = simple_markdown_to_html(md)
  2240. sc_style_parts = []
  2241. for prop in ["background", "border", "border_radius", "padding"]:
  2242. val = comp.get(prop, "")
  2243. if val:
  2244. sc_style_parts.append(f"{prop.replace('_', '-')}: {val}")
  2245. sc_style = f' style="{"; ".join(sc_style_parts)}"' if sc_style_parts else ""
  2246. inner = f'''<div class="shaped-canvas"{sc_style}>
  2247. <div class="shape-float shape-{shape}" aria-hidden="true"></div>
  2248. <div class="shaped-content">{html_content}</div>
  2249. </div>\n'''
  2250. elif ctype == "Image_Asset":
  2251. src = comp.get("src", "")
  2252. alt = comp.get("alt", "")
  2253. fit = comp.get("object_fit", "cover")
  2254. inner = f'<img src="{src}" alt="{alt}" style="width:100%;height:100%;object-fit:{fit};border-radius:2px;" />\n'
  2255. elif ctype == "Sidenote_Block":
  2256. label = comp.get("label", "")
  2257. body = comp.get("body", "") or comp.get("markdown_content", "")
  2258. html_body = simple_markdown_to_html(body)
  2259. label_html = f'<span class="sidenote-label">{label}</span>' if label else ""
  2260. inner = f'<div class="sidenote">{label_html}{html_body}</div>\n'
  2261. # Sidenotes bypass grid-item wrapping for Tufte layout — returned raw
  2262. return inner
  2263. elif ctype == "Delta_Widget":
  2264. metric = comp.get("metric", "")
  2265. value = comp.get("value", "")
  2266. delta = comp.get("delta", "")
  2267. trend = comp.get("trend", "up") # up / down / flat
  2268. label = comp.get("label", "")
  2269. trend_symbol = {"up": "▲", "down": "▼", "flat": "─"}.get(trend, "")
  2270. trend_color = {"up": "#22c55e", "down": "#ef4444", "flat": "var(--c-muted)"}.get(trend, "var(--c-muted)")
  2271. inner = f'''<div class="delta-widget">
  2272. <div class="delta-metric">{metric}</div>
  2273. <div class="delta-value">{value}</div>
  2274. <div class="delta-change" style="color:{trend_color}"><span>{trend_symbol}</span> {delta}</div>
  2275. <div class="delta-label">{label}</div>
  2276. </div>\n'''
  2277. elif ctype == "Process_List":
  2278. steps = comp.get("steps", [])
  2279. steps_html = ""
  2280. for i, step in enumerate(steps):
  2281. title = step.get("title", "")
  2282. desc = step.get("description", "")
  2283. steps_html += f'<li class="process-step"><span class="step-num">{i+1}</span><div><div class="step-title">{title}</div><div class="step-desc">{desc}</div></div></li>\n'
  2284. inner = f'<div class="process-list-container"><ul class="process-list">{steps_html}</ul></div>\n'
  2285. else:
  2286. return f"<!-- Unknown component: {ctype} -->\n"
  2287. return _wrap_grid_item(comp, inner)
  2288. def compile_blueprint(json_path, output_html_path):
  2289. """Reads the LLM JSON blueprint and generates the final poster.html"""
  2290. with open(json_path, encoding='utf-8') as f:
  2291. blueprint = json.load(f)
  2292. art = blueprint.get("art_direction", {})
  2293. # Intent: auto-derive from document title if not explicitly provided
  2294. doc_title = blueprint.get("document_meta", {}).get("title", "")
  2295. intent = art.get("intent", None)
  2296. if not intent:
  2297. intent = derive_intent(doc_title) if doc_title else "neutral"
  2298. intent = intent.lower()
  2299. mode = art.get("palette_mode", "minimal").lower()
  2300. harmony = art.get("color_harmony", "auto").lower() # "auto" → intent-based recommendation
  2301. svg_type = art.get("background_svg", "flow")
  2302. pages = blueprint.get("pages", [])
  2303. total_pages = len(pages)
  2304. # 1. Compute Aesthetics — three pillars: intent + mode + harmony
  2305. palette = generate_color_palette(intent, mode, harmony=harmony)
  2306. css_vars = palette_to_css(palette)
  2307. # Detect if any component uses tension_score → switch to Variable Font URL
  2308. has_tension = False
  2309. for page in pages:
  2310. for comp in page.get("components", []):
  2311. if comp.get("tension_score") is not None:
  2312. has_tension = True
  2313. break
  2314. if has_tension:
  2315. break
  2316. # Generate SVG backgrounds
  2317. canvas_w = art.get("canvas_width", 720)
  2318. canvas_h = art.get("canvas_height", 960)
  2319. use_continuous = total_pages > 1 # Multi-page → continuous canvas mode
  2320. continuous_svgs = None
  2321. unified_svg = ""
  2322. bg_svg = ""
  2323. if use_continuous and svg_type != "none":
  2324. # Generate one unified SVG spanning the entire document
  2325. unified_svg = generate_unified_svg(canvas_w, canvas_h, total_pages, svg_type, palette['accent'])
  2326. elif not use_continuous:
  2327. if svg_type == "continuous_flow" and total_pages > 1:
  2328. continuous_svgs = generate_continuous_flow_svg(canvas_w, canvas_h, total_pages, palette['accent'])
  2329. elif svg_type != "none":
  2330. bg_svg = generate_generative_svg(svg_type, canvas_w, canvas_h, palette['accent'])
  2331. # Font URL: use variable axis range if tension is active
  2332. if has_tension:
  2333. font_url = "https://fonts.googleapis.com/css2?family=Inter:wght@100..900&family=Noto+Sans+SC:wght@300;400;500;700;900&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400&display=swap"
  2334. else:
  2335. font_url = "https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&family=Noto+Sans+SC:wght@300;400;500;700;900&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400&display=swap"
  2336. # 1b. Dynamic Gap — intent-driven grid density
  2337. # If the LLM explicitly sets grid_gap in art_direction, use that (override).
  2338. # Otherwise, derive from intent.
  2339. explicit_gap = art.get("grid_gap", None)
  2340. if explicit_gap is not None:
  2341. dynamic_gap = str(explicit_gap) if "px" in str(explicit_gap) else f"{explicit_gap}px"
  2342. else:
  2343. gap_mapping = {
  2344. "serenity": "48px",
  2345. "elegance": "32px",
  2346. "minimalism": "40px",
  2347. "warmth": "24px",
  2348. "neutral": "16px",
  2349. "tension": "8px",
  2350. "energy": "4px",
  2351. }
  2352. dynamic_gap = gap_mapping.get(intent, "16px")
  2353. # 2. Build override CSS for custom canvas size, background, bleed
  2354. override_css = ""
  2355. override_css += f":root {{ --canvas-w: {canvas_w}px; --canvas-h: {canvas_h}px; }}\n"
  2356. # @page size MUST use concrete values (CSS variables are NOT resolved in @page rules)
  2357. override_css += f"@page {{ size: {canvas_w}px {canvas_h}px; margin: 0; }}\n"
  2358. # html/body must match canvas size for full-bleed PDF output
  2359. # Use min-height (not height) so content taller than canvas_h expands naturally
  2360. override_css += f"html, body {{ width: {canvas_w}px; min-height: {canvas_h}px; }}\n"
  2361. bg_color = art.get("background_color", "")
  2362. if bg_color:
  2363. override_css += f".canvas {{ background: {bg_color}; }}\n"
  2364. override_css += f".continuous-canvas {{ background: {bg_color}; }}\n"
  2365. if art.get("bleed", False):
  2366. override_css += ".safe-zone { inset: 0 !important; padding: 0 !important; }\n"
  2367. # Screen preview: inject concrete scale value (CSS calc with var may not work in scale)
  2368. override_css += f"@media screen {{ body {{ scale: min(1, calc(100vw / {canvas_w}), calc(100vh / {canvas_h})); }} }}\n"
  2369. # 3. Build HTML Document
  2370. html = f"""<!DOCTYPE html>
  2371. <html lang="en">
  2372. <head>
  2373. <meta charset="UTF-8">
  2374. <link href="{font_url}" rel="stylesheet">
  2375. <title>{blueprint.get("document_meta", {}).get("title", "Document")}</title>
  2376. <style>
  2377. {css_vars}
  2378. {BASE_CSS}
  2379. {override_css}
  2380. </style>
  2381. </head>
  2382. <body>
  2383. """
  2384. # 3. Render Pages
  2385. if use_continuous:
  2386. # ═══ CONTINUOUS CANVAS MODE ═══
  2387. # Render all pages as one seamless surface, then let Playwright's page.pdf() slice it.
  2388. total_height = canvas_h * total_pages
  2389. html += f'\n<div class="continuous-canvas" style="height: {total_height}px; background: var(--c-bg);">\n'
  2390. # Unified background SVG spanning the entire document
  2391. if unified_svg:
  2392. html += f' <div class="bg-layer-full">{unified_svg}</div>\n'
  2393. # Render each page as an absolutely-positioned section within the continuous canvas
  2394. for page_idx, page in enumerate(pages):
  2395. archetype = page.get("archetype", "cover_hero")
  2396. page_top = page_idx * canvas_h
  2397. # Auto-assign grid areas
  2398. _auto_assign_grid_areas(archetype, page.get("components", []))
  2399. # Cognitive Load Margins
  2400. total_chars = 0
  2401. sidenotes = []
  2402. main_components = []
  2403. for comp in page.get("components", []):
  2404. text_content = comp.get("markdown_content", "") or comp.get("body", "") or ""
  2405. total_chars += len(text_content)
  2406. if comp.get("type") == "Sidenote_Block":
  2407. sidenotes.append(comp)
  2408. else:
  2409. main_components.append(comp)
  2410. for step in comp.get("steps", []):
  2411. total_chars += len(step.get("title", "")) + len(step.get("description", ""))
  2412. if total_chars > 500:
  2413. safe_inset = "8% 10%"
  2414. elif total_chars > 200:
  2415. safe_inset = "10% 12%"
  2416. else:
  2417. safe_inset = ""
  2418. safe_inset_style = f" inset: {safe_inset};" if safe_inset else ""
  2419. # Page section: positioned absolutely within continuous canvas
  2420. html += f'\n <div class="page-section archetype-{archetype}" style="top: {page_top}px; height: {canvas_h}px;">\n'
  2421. # Per-page data-driven SVG background (overlays on top of unified bg)
  2422. if svg_type != "none":
  2423. data_points = None
  2424. for comp in page.get("components", []):
  2425. dp = comp.get("data_points")
  2426. if dp and isinstance(dp, list) and all(isinstance(x, (int, float)) for x in dp):
  2427. data_points = dp
  2428. break
  2429. if data_points and len(data_points) >= 2:
  2430. page_svg = _generate_data_driven_svg(data_points, canvas_w, canvas_h, palette['accent'])
  2431. html += f' <div class="bg-layer" style="position:absolute;inset:0;z-index:2;pointer-events:none;">{page_svg}</div>\n'
  2432. # Tufte layout
  2433. if archetype == "tufte_report" and sidenotes:
  2434. html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
  2435. html += f' <div class="main-column" style="gap: {dynamic_gap};">\n'
  2436. for comp in main_components:
  2437. html += " " + render_component(comp)
  2438. html += ' </div>\n'
  2439. html += ' <div class="side-rail">\n'
  2440. for comp in sidenotes:
  2441. html += " " + render_component(comp)
  2442. html += ' </div>\n'
  2443. html += ' </div>\n'
  2444. else:
  2445. html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
  2446. for comp in page.get("components", []):
  2447. html += " " + render_component(comp)
  2448. html += ' </div>\n'
  2449. html += ' </div>\n'
  2450. html += '</div>\n'
  2451. else:
  2452. # ═══ LEGACY PER-PAGE MODE (single-page documents) ═══
  2453. for page_idx, page in enumerate(pages):
  2454. archetype = page.get("archetype", "cover_hero")
  2455. _auto_assign_grid_areas(archetype, page.get("components", []))
  2456. total_chars = 0
  2457. sidenotes = []
  2458. main_components = []
  2459. for comp in page.get("components", []):
  2460. text_content = comp.get("markdown_content", "") or comp.get("body", "") or ""
  2461. total_chars += len(text_content)
  2462. if comp.get("type") == "Sidenote_Block":
  2463. sidenotes.append(comp)
  2464. else:
  2465. main_components.append(comp)
  2466. for step in comp.get("steps", []):
  2467. total_chars += len(step.get("title", "")) + len(step.get("description", ""))
  2468. if total_chars > 500:
  2469. safe_inset = "8% 10%"
  2470. elif total_chars > 200:
  2471. safe_inset = "10% 12%"
  2472. else:
  2473. safe_inset = ""
  2474. safe_inset_style = f" inset: {safe_inset};" if safe_inset else ""
  2475. page_svg = ""
  2476. if svg_type != "none":
  2477. data_points = None
  2478. for comp in page.get("components", []):
  2479. dp = comp.get("data_points")
  2480. if dp and isinstance(dp, list) and all(isinstance(x, (int, float)) for x in dp):
  2481. data_points = dp
  2482. break
  2483. if data_points and len(data_points) >= 2:
  2484. page_svg = _generate_data_driven_svg(data_points, canvas_w, canvas_h, palette['accent'])
  2485. elif continuous_svgs and page_idx < len(continuous_svgs):
  2486. page_svg = continuous_svgs[page_idx]
  2487. elif bg_svg:
  2488. page_svg = bg_svg
  2489. html += f'\n<div class="canvas archetype-{archetype}">\n'
  2490. if page_svg:
  2491. html += f' <div class="bg-layer">{page_svg}</div>\n'
  2492. if archetype == "tufte_report" and sidenotes:
  2493. html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
  2494. html += f' <div class="main-column" style="gap: {dynamic_gap};">\n'
  2495. for comp in main_components:
  2496. html += " " + render_component(comp)
  2497. html += ' </div>\n'
  2498. html += ' <div class="side-rail">\n'
  2499. for comp in sidenotes:
  2500. html += " " + render_component(comp)
  2501. html += ' </div>\n'
  2502. html += ' </div>\n</div>\n'
  2503. else:
  2504. html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
  2505. for comp in page.get("components", []):
  2506. html += " " + render_component(comp)
  2507. html += ' </div>\n</div>\n'
  2508. html += "</body>\n</html>"
  2509. # 4. Save
  2510. with open(output_html_path, 'w', encoding='utf-8') as f:
  2511. f.write(html)
  2512. return output_html_path, palette
  2513. if __name__ == "__main__":
  2514. main()