-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpokeproxy.py
More file actions
1444 lines (1260 loc) · 60.9 KB
/
Copy pathpokeproxy.py
File metadata and controls
1444 lines (1260 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""PokeProxy - Generate readable Pokemon TCG proxy cards with large text."""
import base64
import io
import json
import os
import re
import sys
import urllib.request
from pathlib import Path
import freetype
from set_codes import SET_MAP
CACHE_DIR = Path(__file__).parent / "cache"
OUTPUT_DIR = Path(__file__).parent / "output"
CLEAN_DIR = Path(__file__).parent.parent / "pokecleaner" / "output"
# Framehouse / PokeCleaner integration
FRAMEHOUSE_URL = "http://localhost:3000"
FLUX_W, FLUX_H = 736, 1024
DEFAULT_MASK_TOP = 0.20
DEFAULT_CLEAN_PROMPT = (
"continue the artwork illustration, extend the scene naturally, "
"no text, no writing, no letters, no numbers, no symbols, "
"clean artwork only, high quality illustration"
)
# Pokemon card dimensions: 2.5" x 3.5" at 300dpi = 750x1050
# We'll use a standard card ratio for SVG
CARD_W = 750
CARD_H = 1050 # 2.5" x 3.5" at 300dpi, ratio 5:7
# Artwork crop region on the 600x825 source image (approximate)
# The art sits roughly in the center, below the name bar, above the attacks
ART_TOP = 110
ART_BOTTOM = 430
ART_LEFT = 45
ART_RIGHT = 555
# Type colors — deeper/saturated to match real TCG cards
TYPE_COLORS = {
"Grass": "#3B9B2F",
"Fire": "#D4301A",
"Water": "#2980C0",
"Lightning": "#E8A800",
"Psychic": "#A8318C",
"Fighting": "#A0522D",
"Darkness": "#3E2D68",
"Metal": "#8A8A9A",
"Fairy": "#D44D8A",
"Dragon": "#5B2DA0",
"Colorless": "#8A8A70",
}
# SV-era type matchups: (weakness_type, weakness_value, resistance_type, resistance_value)
# None means no weakness/resistance for that slot
TYPE_MATCHUPS = {
"Fire": ("Water", "×2", None, None),
"Water": ("Lightning","×2", None, None),
"Grass": ("Fire", "×2", None, None),
"Lightning": ("Fighting", "×2", None, None),
"Psychic": ("Darkness", "×2", "Fighting", "-30"),
"Fighting": ("Psychic", "×2", None, None),
"Darkness": ("Grass", "×2", None, None),
"Metal": ("Fire", "×2", "Grass", "-30"),
"Dragon": (None, None, None, None),
"Colorless": ("Fighting", "×2", None, None),
"Fairy": ("Metal", "×2", "Darkness", "-30"),
}
# Energy symbols (single-letter abbreviations)
ENERGY_ABBREV = {
"Grass": "G",
"Fire": "R",
"Water": "W",
"Lightning": "L",
"Psychic": "P",
"Fighting": "F",
"Darkness": "D",
"Metal": "M",
"Fairy": "Y",
"Dragon": "N",
"Colorless": "C",
}
# Font stacks used across all card renderers
FONT_TITLE = "'Arial Black', 'Helvetica Neue', Impact, Arial, sans-serif"
FONT_BODY = "'Helvetica Neue', 'Arial Black', Arial, Helvetica, sans-serif"
MARGIN = 30
# --- FreeType font measurement ---
# Load the actual fonts used in SVG rendering for accurate text measurement
_TITLE_FACE = freetype.Face('/System/Library/Fonts/Supplemental/Arial Black.ttf')
_BODY_FACE = freetype.Face('/System/Library/Fonts/HelveticaNeue.ttc', 1) # Bold
def _measure_width(face, text, size_px):
"""Measure text width in pixels using FreeType glyph advances."""
face.set_pixel_sizes(0, size_px)
width = 0
for ch in text:
face.load_char(ch, freetype.FT_LOAD_DEFAULT)
width += face.glyph.advance.x >> 6
return width
def ft_wrap(face, text, size_px, max_width):
"""Word-wrap text using actual glyph measurements. Returns list of lines."""
if not text:
return []
# Strip energy symbols {X} for measurement (they render as single glyphs)
import re
clean = re.sub(r'\{[A-Z]\}', '\u2B24', text)
words = clean.split()
lines = []
current = []
for word in words:
test_line = ' '.join(current + [word])
if _measure_width(face, test_line, size_px) > max_width and current:
lines.append(' '.join(current))
current = [word]
else:
current.append(word)
if current:
lines.append(' '.join(current))
return lines
def ft_content_height(body_size, head_size, max_width, category,
trainer_effect, abilities, attacks):
"""Measure total content height using FreeType. Mirrors the render layout."""
line_h = int(body_size * 1.25) # LINE_H = BASE_LINE_H * scale = 30/24 * body
h = 0
if category == "Trainer" and trainer_effect:
h += len(ft_wrap(_BODY_FACE, trainer_effect, body_size, max_width)) * line_h
h += int(body_size * 0.83) # 20/24 * body_size
for ab in abilities:
h += int(head_size * 0.5) # gap after header text
effect = ab.get("effect", "")
h += len(ft_wrap(_BODY_FACE, effect, body_size, max_width)) * line_h
h += int(body_size * 1.46)
for atk in attacks:
h += int(head_size * 0.64) # gap after attack header
effect = atk.get("effect", "")
if effect:
h += len(ft_wrap(_BODY_FACE, effect, body_size, max_width)) * line_h
h += int(body_size * 1.25)
return h
def fetch_card(set_code: str, number: str) -> dict:
"""Fetch card data from TCGdex API."""
tcgdex_id = SET_MAP.get(set_code.upper())
if not tcgdex_id:
raise ValueError(f"Unknown set code: {set_code}. Known: {', '.join(SET_MAP.keys())}")
padded = number.zfill(3)
url = f"https://api.tcgdex.net/v2/en/cards/{tcgdex_id}-{padded}"
cache_file = CACHE_DIR / f"{tcgdex_id}-{padded}.json"
if cache_file.exists():
return json.loads(cache_file.read_text())
print(f" Fetching card data: {url}")
req = urllib.request.Request(url, headers={"User-Agent": "PokeProxy/1.0"})
with urllib.request.urlopen(req) as resp:
data = json.loads(resp.read())
CACHE_DIR.mkdir(parents=True, exist_ok=True)
cache_file.write_text(json.dumps(data, indent=2))
return data
def fetch_image(image_url: str, card_id: str) -> bytes:
"""Fetch and cache card image."""
cache_file = CACHE_DIR / f"{card_id}.png"
if cache_file.exists():
return cache_file.read_bytes()
full_url = image_url + "/high.png"
print(f" Fetching image: {full_url}")
req = urllib.request.Request(full_url, headers={"User-Agent": "PokeProxy/1.0"})
with urllib.request.urlopen(req) as resp:
data = resp.read()
CACHE_DIR.mkdir(parents=True, exist_ok=True)
cache_file.write_bytes(data)
return data
def check_framehouse(server_url: str = FRAMEHOUSE_URL) -> bool:
"""Ping framehouse server. Returns True if reachable."""
try:
req = urllib.request.Request(f"{server_url}/api/adapters")
urllib.request.urlopen(req, timeout=5)
return True
except Exception:
return False
def submit_compose(image_b64: str, prompt: str, seed: int = 42,
server_url: str = FRAMEHOUSE_URL) -> str | None:
"""Submit a Klein compose job to framehouse. Returns base64 result or None."""
job_spec = {
"intent": "compose",
"prompt": prompt,
"seed": seed,
"size": {"width": FLUX_W, "height": FLUX_H},
"inputs": {
"img1": {
"type": "image",
"base64": image_b64,
}
},
"timeoutMs": 180000,
}
url = f"{server_url}/api/generate/adaptive"
data = json.dumps(job_spec).encode()
req = urllib.request.Request(
url, data=data, headers={"Content-Type": "application/json"},
)
print(f" Submitting to framehouse ({server_url})...")
try:
resp = urllib.request.urlopen(req, timeout=300)
except Exception as e:
print(f" Framehouse request failed: {e}")
return None
result = json.loads(resp.read())
if result.get("status") == "failed":
print(f" Framehouse FAILED: {result.get('error', 'unknown')}")
return None
for artifact in result.get("artifacts", []):
if artifact.get("type") == "image" and artifact.get("data"):
return artifact["data"]
print(" Framehouse FAILED: No image in response")
return None
def clean_card_image(card_id: str, mode: str = "composite",
mask_top: float = DEFAULT_MASK_TOP, seed: int = 42,
server_url: str = FRAMEHOUSE_URL) -> Path | None:
"""Get a cleaned card image, generating via framehouse if needed.
mode: "composite" (original top + generated bottom) or "clean" (fully generated)
Returns path to the image file, or None on failure.
"""
from PIL import Image
suffix = f"_{mode}" # _composite or _clean
# Check local cache first
cached = CACHE_DIR / f"{card_id}{suffix}.png"
if cached.exists():
return cached
# Check legacy pokecleaner output
legacy = CLEAN_DIR / f"{card_id}{suffix}.png"
if legacy.exists():
return legacy
# Need to generate — load source image from cache
src = CACHE_DIR / f"{card_id}.png"
if not src.exists():
print(f" No source image for {card_id}")
return None
img = Image.open(src).convert("RGB")
img_resized = img.resize((FLUX_W, FLUX_H), Image.LANCZOS)
# Convert to base64 and submit
buf = io.BytesIO()
img_resized.save(buf, format="PNG")
img_b64 = base64.b64encode(buf.getvalue()).decode()
result_b64 = submit_compose(img_b64, DEFAULT_CLEAN_PROMPT, seed=seed,
server_url=server_url)
if not result_b64:
return None
result_img = Image.open(io.BytesIO(base64.b64decode(result_b64))).convert("RGB")
if result_img.size != (FLUX_W, FLUX_H):
result_img = result_img.resize((FLUX_W, FLUX_H), Image.LANCZOS)
# Save clean (fully generated)
CACHE_DIR.mkdir(parents=True, exist_ok=True)
clean_path = CACHE_DIR / f"{card_id}_clean.png"
result_img.save(clean_path)
print(f" Saved: {clean_path.name}")
# Save composite (original top + generated bottom)
top_px = int(FLUX_H * mask_top)
composite = img_resized.copy()
composite.paste(result_img.crop((0, top_px, FLUX_W, FLUX_H)), (0, top_px))
composite_path = CACHE_DIR / f"{card_id}_composite.png"
composite.save(composite_path)
print(f" Saved: {composite_path.name}")
return CACHE_DIR / f"{card_id}{suffix}.png"
def crop_artwork(image_data: bytes) -> str:
"""Crop the artwork portion from the card image, return as base64 PNG.
Uses PIL if available, otherwise embeds the full image.
"""
try:
from PIL import Image
img = Image.open(io.BytesIO(image_data))
# Scale crop coords to actual image size
scale_x = img.width / 600
scale_y = img.height / 825
box = (
int(ART_LEFT * scale_x),
int(ART_TOP * scale_y),
int(ART_RIGHT * scale_x),
int(ART_BOTTOM * scale_y),
)
cropped = img.crop(box)
buf = io.BytesIO()
cropped.save(buf, format="PNG")
return base64.b64encode(buf.getvalue()).decode()
except ImportError:
print(" Warning: Pillow not installed, using full card image. Install with: pip install Pillow")
return base64.b64encode(image_data).decode()
ENERGY_COLORS = {
"Grass": "#3B9B2F", "G": "#3B9B2F",
"Fire": "#D4301A", "R": "#D4301A",
"Water": "#2980C0", "W": "#2980C0",
"Lightning": "#E8A800", "L": "#E8A800",
"Psychic": "#A8318C", "P": "#A8318C",
"Fighting": "#A0522D", "F": "#A0522D",
"Darkness": "#3E2D68", "D": "#3E2D68",
"Metal": "#8A8A9A", "M": "#8A8A9A",
"Fairy": "#D44D8A", "Y": "#D44D8A",
"Dragon": "#5B2DA0", "N": "#5B2DA0",
"Colorless": "#8A8A70", "C": "#8A8A70",
}
# Text compression: shorten verbose Pokemon TCG phrasing
COMPRESS_RULES = [
# === Long phrases first (before sub-phrases get replaced) ===
# Evolution trigger
("When you play this Pokémon from your hand to evolve 1 of your Pokémon during your turn, you may",
"On evolve:"),
("When you play this Pokémon from your hand to evolve 1 of your Pokémon during your turn,",
"On evolve,"),
# Knock out — long forms first
("is Knocked Out by damage from an attack from your opponent's Pokémon", "is KO'd by opponent"),
("were Knocked Out during your opponent's last turn", "were KO'd last turn"),
("would be Knocked Out", "would be KO'd"),
("is Knocked Out", "is KO'd"),
("Knocked Out", "KO'd"),
# Next turn restrictions
("During your next turn, this Pokémon can't attack", "Can't attack next turn"),
("During your next turn, this Pokémon can't use", "Can't use next turn:"),
# Cure
("This Pokémon recovers from all Special Conditions", "Cure all conditions"),
# Switch
("Switch your Active Pokémon with 1 of your Benched Pokémon", "Switch Active with Bench"),
("1 of your opponent's Benched Pokémon to the Active Spot", "1 of opponent's Bench to Active"),
# === Pokemon references ===
("your opponent's Active Pokémon", "the Defending Pokémon"),
("your opponent's Benched Pokémon", "opponent's Bench"),
("your Active Pokémon", "your Active"),
("your Benched Pokémon", "your Bench"),
("to your Pokémon in any way you like", "to your Pokémon however you like"),
("this Pokémon", "it"),
("This Pokémon", "It"),
# === Turn / timing ===
("Once during your first turn, you may", "First turn, you may"),
("Once during your turn", "Once a turn"),
("Once during each player's turn, that player may", "Once a turn, each player may"),
("As often as you like during your turn, you may", "Any number of times,"),
("As often as you like on your turn, you may", "Any number of times,"),
("during your turn", "on your turn"),
# === Search / deck ===
("Search your deck for", "Search deck for"),
("search your deck for", "search deck for"),
("Then, shuffle your deck.", "Shuffle deck."),
("then, shuffle your deck.", "shuffle deck."),
("Shuffle the other cards back into your deck", "Shuffle the rest back"),
("shuffle your deck", "shuffle deck"),
("reveal them, and put them into your hand", "and take them"),
("reveal it, and put it into your hand", "and take it"),
("and put it into your hand", "and take it"),
("and put them into your hand", "and take them"),
("from your discard pile into your hand", "from discard to hand"),
("from your discard pile into your deck", "from discard to deck"),
("from your discard pile", "from discard"),
("into your hand", "to hand"),
# === Boilerplate clauses ===
("If you attached Energy to a Pokémon in this way, ", "If so, "),
("If you attached Energy to your Active in this way, ", "If so, "),
("Energy card", "Energy"),
# === Energy ===
("Basic Energy cards", "Basic Energy"),
("Basic Energy card", "Basic Energy"),
("Energy cards", "Energy"),
("Energys", "Energy"),
# === Prize ===
("your opponent takes 1 fewer Prize card", "opponent takes 1 fewer Prize"),
("Prize card your opponent has taken", "Prize taken"),
("Prize cards", "Prizes"),
("Prize card", "Prize"),
# === Play conditions ===
("You can use this card only if you discard", "Discard"),
("other cards from your hand", "other cards to play"),
("another card from your hand", "1 card to play"),
# === Damage / effects ===
("(Don't apply Weakness and Resistance for Benched Pokémon.)", "(Bench damage)"),
("(before applying Weakness and Resistance)", ""),
("This attack does", "Does"),
("this attack does", "does"),
("more damage for each", "+damage per"),
("more damage", "extra"),
("has any damage counters on it", "has damage"),
("has no damage counters on it", "has no damage"),
("damage counters", "damage"),
("damage on it", "damage"),
("damage to itself", "self-damage"),
# === Status / conditions ===
("is now Poisoned", "becomes Poisoned"),
("is now Confused", "becomes Confused"),
("is now Asleep", "becomes Asleep"),
("is now Burned", "becomes Burned"),
("is now Paralyzed", "becomes Paralyzed"),
# === Misc ===
("Flip a coin. If heads, ", "Flip: heads, "),
("Look at the top", "Check top"),
("in order to use this Ability", "to use this"),
("You can't use more than 1", "Max 1"),
("Ability each turn", "per turn"),
("Ability during your turn", "per turn"),
("Ability on your turn", "per turn"),
("you may draw cards until you have", "draw up to"),
("cards in your hand", "cards"),
]
def compress_text(text: str) -> str:
"""Apply shorthand compression rules to card effect text."""
for pattern, replacement in COMPRESS_RULES:
text = text.replace(pattern, replacement)
# Clean up double spaces
while " " in text:
text = text.replace(" ", " ")
return text.strip()
def fit_attack_header(name, damage, cost_count, head_size, card_w, margin):
"""Shrink attack name + damage font sizes until they fit without overlap.
Returns (name_size, dmg_size).
"""
dot_r = max(8, int(head_size * 0.5))
cost_w = (dot_r * 2 + 4) * cost_count + 6 if cost_count else 0
name_x = margin + cost_w + 6
available = card_w - 2 * margin - cost_w - 12 # space for name + gap + damage
name_size = head_size
dmg_size = int(head_size * 1.21)
dmg_str = str(damage) if damage else ""
for _ in range(6): # up to 6 shrink steps
name_w = _measure_width(_TITLE_FACE, name, name_size)
dmg_w = _measure_width(_TITLE_FACE, dmg_str, dmg_size) if dmg_str else 0
gap = 20
if name_w + gap + dmg_w <= available:
break
# Shrink both proportionally
name_size = int(name_size * 0.88)
dmg_size = int(dmg_size * 0.88)
return name_size, dmg_size
def escape_xml(text: str) -> str:
"""Escape text for XML/SVG."""
return text.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
def wrap_text(text: str, max_chars: int) -> list[str]:
"""Word-wrap text to fit within max_chars per line."""
words = text.split()
lines = []
current = ""
for word in words:
if current and len(current) + 1 + len(word) > max_chars:
lines.append(current)
current = word
else:
current = f"{current} {word}" if current else word
if current:
lines.append(current)
return lines
def render_energy_dots(x: int, y: int, cost: list[str], radius: int) -> tuple[list[str], int]:
"""Render energy cost as colored circles. Returns (svg_elements, new_x)."""
elems = []
cx = x + radius
cy = y - radius + 2 # vertically center with text baseline
for energy in cost:
c = ENERGY_COLORS.get(energy, "#888")
elems.append(f' <circle cx="{cx}" cy="{cy}" r="{radius}" fill="{c}" stroke="#333" stroke-width="1.5"/>')
# White letter inside the dot
letter = ENERGY_ABBREV.get(energy, "?")
elems.append(f' <text x="{cx}" y="{cy + 1}" font-family="Helvetica, Arial, sans-serif" font-size="{int(radius * 1.3)}" font-weight="bold" fill="white" text-anchor="middle" dominant-baseline="central">{letter}</text>')
cx += radius * 2 + 4
return elems, cx - x + 6 # total width consumed
def energy_inline_svg(text: str, font_size: int) -> str:
"""Convert {D}, {W} etc. in text to colored circle Unicode + tspan markup.
Returns SVG tspan markup that can be placed inside a <text> element."""
import re
def replace_energy(m):
letter = m.group(1)
color = ENERGY_COLORS.get(letter, "#888")
# Use a filled circle Unicode char, colored, with the letter after it
return f'<tspan fill="{color}" font-size="{int(font_size * 1.1)}">⬤</tspan>'
escaped = escape_xml(text)
# Now replace the escaped {X} patterns — escape_xml won't touch {X}
return re.sub(r'\{([A-Z])\}', replace_energy, escaped)
def render_footer_svg(lines, card, category, card_type, retreat, body_size,
set_name, local_id, *, footer_y, sep_offset, sep_color,
fill, retreat_dot_fill, info_y, info_fill):
"""Render card footer: weakness/resistance icons, retreat dots, and set info."""
if category == "Trainer":
weakness = None
resistance = None
retreat = 0
else:
weakness = card.get("weaknesses")
resistance = card.get("resistances")
if not weakness and not resistance and card_type in TYPE_MATCHUPS:
wt, wv, rt, rv = TYPE_MATCHUPS[card_type]
if wt:
weakness = [{"type": wt, "value": wv}]
if rt:
resistance = [{"type": rt, "value": rv}]
has_footer = weakness or resistance or retreat
if has_footer:
lines.append(f' <line x1="20" y1="{footer_y - sep_offset}" x2="{CARD_W - 20}" y2="{footer_y - sep_offset}" stroke="{sep_color}" stroke-width="1"/>')
footer_x = MARGIN
dot_r = int(body_size * 0.45)
mid_y = footer_y - body_size * 0.35
tri_s = int(body_size * 0.55)
if weakness:
for w in weakness:
wtype = w.get("type", "")
wval = w.get("value", "")
tx = int(footer_x) + tri_s
lines.append(f' <polygon points="{tx - tri_s},{int(mid_y - tri_s)} {tx + tri_s},{int(mid_y - tri_s)} {tx},{int(mid_y + tri_s)}" fill="{fill}" filter="url(#shadow)"/>')
footer_x += tri_s * 2 + 6
wcolor = ENERGY_COLORS.get(wtype, "#888")
lines.append(f' <circle cx="{int(footer_x + dot_r)}" cy="{int(mid_y)}" r="{dot_r}" fill="{wcolor}" stroke="#333" stroke-width="1.5"/>')
footer_x += dot_r * 2 + 4
lines.append(f' <text x="{int(footer_x)}" y="{footer_y}" font-family="{FONT_BODY}" font-size="{body_size}" font-weight="700" fill="{fill}" filter="url(#shadow)">{escape_xml(wval)}</text>')
footer_x += body_size * 2.5
if resistance:
for r in resistance:
rtype = r.get("type", "")
rval = r.get("value", "")
tx = int(footer_x) + tri_s
lines.append(f' <polygon points="{tx},{int(mid_y - tri_s)} {tx + tri_s},{int(mid_y + tri_s)} {tx - tri_s},{int(mid_y + tri_s)}" fill="{fill}" filter="url(#shadow)"/>')
footer_x += tri_s * 2 + 6
rcolor = ENERGY_COLORS.get(rtype, "#888")
lines.append(f' <circle cx="{int(footer_x + dot_r)}" cy="{int(mid_y)}" r="{dot_r}" fill="{rcolor}" stroke="#333" stroke-width="1.5"/>')
footer_x += dot_r * 2 + 4
lines.append(f' <text x="{int(footer_x)}" y="{footer_y}" font-family="{FONT_BODY}" font-size="{body_size}" font-weight="700" fill="{fill}" filter="url(#shadow)">{escape_xml(rval)}</text>')
footer_x += body_size * 2.5
if retreat:
if weakness or resistance:
footer_x += body_size * 0.5
lines.append(f' <line x1="{int(footer_x)}" y1="{int(mid_y - tri_s)}" x2="{int(footer_x)}" y2="{int(mid_y + tri_s)}" stroke="{fill}" stroke-width="1" opacity="0.4"/>')
footer_x += body_size * 0.5
ax = int(footer_x)
amy = int(mid_y)
as_ = tri_s
lines.append(f' <polygon points="{ax},{amy} {ax + as_},{amy - as_} {ax + as_},{amy + as_}" fill="{fill}" filter="url(#shadow)"/>')
lines.append(f' <line x1="{ax + as_}" y1="{amy}" x2="{ax + as_ * 2}" y2="{amy}" stroke="{fill}" stroke-width="3" filter="url(#shadow)"/>')
footer_x += as_ * 2 + 8
for _ in range(retreat):
lines.append(f' <circle cx="{int(footer_x + dot_r)}" cy="{int(mid_y)}" r="{dot_r}" fill="{retreat_dot_fill}" stroke="#333" stroke-width="2"/>')
footer_x += dot_r * 2 + 4
lines.append(f' <text x="{CARD_W // 2}" y="{info_y}" font-family="{FONT_BODY}" font-size="18" font-weight="600" fill="{info_fill}" text-anchor="middle">{escape_xml(set_name)} {escape_xml(local_id)}</text>')
def is_fullart(card: dict) -> bool:
"""Detect if a card is a full-art variant (artwork spans the entire card)."""
rarity = (card.get("rarity") or "").lower()
fullart_rarities = [
"illustration rare",
"special illustration rare",
"special art rare",
"hyper rare",
"art rare",
]
if any(r in rarity for r in fullart_rarities):
return True
# Card number above official set count is usually a secret/full-art
card_count = card.get("set", {}).get("cardCount", {})
official = card_count.get("official", 999)
local_id = card.get("localId", "0")
try:
if int(local_id) > official:
return True
except ValueError:
pass
return False
def generate_fullart_svg(card: dict, image_b64: str, overlay_opacity: float = 0.7,
font_size: int = None, max_cover: float = 0.55,
render_header: bool = False) -> str:
"""Generate an SVG proxy for a full-art card.
Uses the full card image as background with a gradient overlay
on the lower portion, then renders large readable text on top.
overlay_opacity: max darkness of the text background (0.0–1.0).
font_size: force body font size in px (None = auto-select 36 or 30).
max_cover: max fraction of card the overlay can cover (0.0–1.0).
"""
name = escape_xml(card.get("name", "Unknown"))
hp = card.get("hp", "")
types = card.get("types", [])
stage = card.get("stage", "")
card_type = types[0] if types else "Colorless"
color = TYPE_COLORS.get(card_type, "#888888")
retreat = card.get("retreat", 0)
abilities = card.get("abilities", [])
attacks = card.get("attacks", [])
set_name = card.get("set", {}).get("name", "")
local_id = card.get("localId", "")
category = card.get("category", "Pokemon")
trainer_type = card.get("trainerType", "")
trainer_effect = compress_text(card.get("effect", ""))
abilities = [
{**ab, "effect": compress_text(ab.get("effect", ""))}
for ab in abilities
]
attacks = [
{**atk, "effect": compress_text(atk.get("effect", ""))}
for atk in attacks
]
if category == "Trainer":
if trainer_type == "Supporter":
color = "#C04010"
elif trainer_type == "Stadium":
color = "#1A7A3A"
else:
color = "#1860A0"
text_max_w = CARD_W - 2 * MARGIN
# Measure text to determine how much overlay we need
has_text = bool(
(category == "Trainer" and trainer_effect)
or abilities or attacks
)
HEAD_RATIO = 28 / 24
text_pad = 50
footer_h = 80
half_card = int(CARD_H * 0.50)
# Try large (36) first, drop to medium (30) if overlay would cover >50% of card
BODY_LARGE, BODY_MEDIUM = 36, 30
if font_size is not None:
# Forced font size — skip auto-selection
BODY_SIZE = font_size
if has_text:
head_candidate = int(BODY_SIZE * HEAD_RATIO)
text_h = ft_content_height(
BODY_SIZE, head_candidate, text_max_w,
category, trainer_effect, abilities, attacks)
text_block_h = text_h + text_pad + footer_h
overlay_top = CARD_H - text_block_h - 40
else:
text_h = 0
overlay_top = CARD_H - footer_h - 40
elif has_text:
for body_candidate in [BODY_LARGE, BODY_MEDIUM]:
head_candidate = int(body_candidate * HEAD_RATIO)
text_h = ft_content_height(
body_candidate, head_candidate, text_max_w,
category, trainer_effect, abilities, attacks)
text_block_h = text_h + text_pad + footer_h
overlay_top = CARD_H - text_block_h - 40
if overlay_top >= half_card:
break # fits in bottom half
BODY_SIZE = body_candidate
else:
text_h = 0
BODY_SIZE = BODY_LARGE
overlay_top = CARD_H - footer_h - 40
HEAD_SIZE = int(BODY_SIZE * HEAD_RATIO)
LINE_H = int(BODY_SIZE * 1.25)
# Compute final overlay position
if has_text:
text_block_h = text_h + text_pad + footer_h
overlay_top = CARD_H - text_block_h - 40
overlay_top = max(overlay_top, int(CARD_H * (1.0 - max_cover)))
lines = []
lines.append(f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 {CARD_W} {CARD_H}" width="{CARD_W}" height="{CARD_H}">')
lines.append(" <defs>")
# Gradient overlay: transparent at top, quickly ramps to near-opaque
lines.append(' <linearGradient id="overlay-grad" x1="0" y1="0" x2="0" y2="1">')
lines.append(f' <stop offset="0%" stop-color="#000" stop-opacity="0"/>')
lines.append(f' <stop offset="15%" stop-color="#000" stop-opacity="{overlay_opacity * 0.6:.2f}"/>')
lines.append(f' <stop offset="40%" stop-color="#000" stop-opacity="{overlay_opacity * 0.85:.2f}"/>')
lines.append(f' <stop offset="100%" stop-color="#000" stop-opacity="{overlay_opacity:.2f}"/>')
lines.append(' </linearGradient>')
# Header gradient: dark at top, transparent at bottom
lines.append(' <linearGradient id="header-grad" x1="0" y1="0" x2="0" y2="1">')
lines.append(f' <stop offset="0%" stop-color="#000" stop-opacity="0.7"/>')
lines.append(f' <stop offset="100%" stop-color="#000" stop-opacity="0"/>')
lines.append(' </linearGradient>')
# Text shadow filter
lines.append(' <filter id="shadow" x="-2%" y="-2%" width="104%" height="104%">')
lines.append(' <feDropShadow dx="1" dy="1" stdDeviation="1.5" flood-color="#000" flood-opacity="0.7"/>')
lines.append(" </filter>")
lines.append(' <filter id="shadow-title" x="-2%" y="-5%" width="104%" height="110%">')
lines.append(' <feDropShadow dx="2" dy="2" stdDeviation="2" flood-color="#000" flood-opacity="0.8"/>')
lines.append(" </filter>")
# Clip path for rounded corners
lines.append(f' <clipPath id="card-clip"><rect width="{CARD_W}" height="{CARD_H}" rx="25" ry="25"/></clipPath>')
lines.append(" </defs>")
# Full card image as background
lines.append(f' <g clip-path="url(#card-clip)">')
lines.append(f' <image x="0" y="0" width="{CARD_W}" height="{CARD_H}" preserveAspectRatio="xMidYMid slice"')
lines.append(f' href="data:image/png;base64,{image_b64}"/>')
# Header overlay for clean images (AI-generated, no card text)
if render_header:
lines.append(f' <rect x="0" y="0" width="{CARD_W}" height="120" fill="url(#header-grad)"/>')
# Bottom gradient overlay for text
overlay_h = CARD_H - overlay_top
lines.append(f' <rect x="0" y="{overlay_top}" width="{CARD_W}" height="{overlay_h}" fill="url(#overlay-grad)"/>')
lines.append(f' </g>')
# Solid black footer strip — fully opaque, covers the card's own copyright/illustrator text
footer_strip_h = 50
lines.append(f' <rect x="0" y="{CARD_H - footer_strip_h}" width="{CARD_W}" height="{footer_strip_h}" rx="0" fill="#000" clip-path="url(#card-clip)"/>')
# Card border
lines.append(f' <rect width="{CARD_W}" height="{CARD_H}" rx="25" ry="25" fill="none" stroke="{color}" stroke-width="4"/>')
# Header text for clean images
if render_header:
lines.append(f' <text x="30" y="57" font-family="{FONT_TITLE}" font-size="42" font-weight="900" fill="white" filter="url(#shadow-title)">{name}</text>')
if category == "Trainer":
icon_size = 40
icon_x = CARD_W - 30 - icon_size
icon_y = 20
icon_colors = {"Supporter": "#FFD040", "Stadium": "#50E878", "Item": "#60C8FF", "Tool": "#60C8FF"}
icon_fill = icon_colors.get(trainer_type, "#FFD040")
if trainer_type == "Supporter":
lines.append(f' <g transform="translate({icon_x},{icon_y})">')
lines.append(f' <circle cx="{icon_size//2}" cy="{int(icon_size*0.28)}" r="{int(icon_size*0.22)}" fill="{icon_fill}"/>')
lines.append(f' <path d="M{int(icon_size*0.15)},{icon_size} Q{int(icon_size*0.15)},{int(icon_size*0.45)} {icon_size//2},{int(icon_size*0.42)} Q{int(icon_size*0.85)},{int(icon_size*0.45)} {int(icon_size*0.85)},{icon_size} Z" fill="{icon_fill}"/>')
lines.append(f' </g>')
elif trainer_type in ("Item", "Tool"):
r = icon_size // 2
cx = icon_x + r
cy = icon_y + r
lines.append(f' <circle cx="{cx}" cy="{cy}" r="{r}" fill="{icon_fill}" stroke="white" stroke-width="2"/>')
lines.append(f' <rect x="{cx - r}" y="{cy - 2}" width="{icon_size}" height="4" fill="white"/>')
lines.append(f' <circle cx="{cx}" cy="{cy}" r="{int(r*0.3)}" fill="white" stroke="{icon_fill}" stroke-width="2"/>')
elif trainer_type == "Stadium":
sx, sy, s = icon_x, icon_y, icon_size
lines.append(f' <polygon points="{sx},{sy + int(s*0.4)} {sx + s//2},{sy + int(s*0.08)} {sx + s},{sy + int(s*0.4)}" fill="{icon_fill}"/>')
lines.append(f' <rect x="{sx + int(s*0.05)}" y="{sy + int(s*0.82)}" width="{int(s*0.9)}" height="{int(s*0.12)}" rx="2" fill="{icon_fill}"/>')
cw, ch, ctop = int(s * 0.12), int(s * 0.44), sy + int(s * 0.38)
for col_x in [sx + int(s*0.15), sx + s//2 - cw//2, sx + int(s*0.85) - cw]:
lines.append(f' <rect x="{col_x}" y="{ctop}" width="{cw}" height="{ch}" rx="1" fill="{icon_fill}"/>')
elif hp:
# Pokemon: HP + type energy dot
hp_text = f'{hp} HP'
lines.append(f' <text x="{CARD_W - 30}" y="57" font-family="{FONT_TITLE}" font-size="38" font-weight="900" fill="white" text-anchor="end" filter="url(#shadow-title)">{hp_text}</text>')
# Text content starts below the overlay top + padding
y = overlay_top + text_pad + int(BODY_SIZE * 0.5)
# Trainer effect text
if category == "Trainer" and trainer_effect:
wrapped = ft_wrap(_BODY_FACE, trainer_effect, BODY_SIZE, text_max_w)
for wline in wrapped:
y += LINE_H
markup = energy_inline_svg(wline, BODY_SIZE)
lines.append(f' <text x="{MARGIN}" y="{y}" font-family="{FONT_BODY}" font-size="{BODY_SIZE}" font-weight="700" fill="white" filter="url(#shadow)">{markup}</text>')
y += int(BODY_SIZE * 0.83)
# Abilities
for ab in abilities:
ab_type = ab.get("type", "Ability")
ab_name = escape_xml(ab.get("name", ""))
ab_effect = ab.get("effect", "")
# Colored bar behind ability name — opaque enough to read on any artwork
bar_h = int(HEAD_SIZE * 1.5)
lines.append(f' <rect x="20" y="{y - int(HEAD_SIZE * 1.07)}" width="{CARD_W - 40}" height="{bar_h}" rx="5" fill="{color}" opacity="0.7"/>')
lines.append(f' <text x="{MARGIN}" y="{y}" font-family="{FONT_TITLE}" font-size="{HEAD_SIZE}" font-weight="900" fill="white" filter="url(#shadow)">{escape_xml(ab_type)}: {ab_name}</text>')
y += int(HEAD_SIZE * 0.5)
wrapped = ft_wrap(_BODY_FACE, ab_effect, BODY_SIZE, text_max_w)
for wline in wrapped:
y += LINE_H
markup = energy_inline_svg(wline, BODY_SIZE)
lines.append(f' <text x="{MARGIN}" y="{y}" font-family="{FONT_BODY}" font-size="{BODY_SIZE}" font-weight="700" fill="white" filter="url(#shadow)">{markup}</text>')
y += int(BODY_SIZE * 1.46)
# Attacks
for atk in attacks:
atk_cost = atk.get("cost", [])
atk_name = escape_xml(atk.get("name", ""))
damage = atk.get("damage", "")
effect = atk.get("effect", "")
bar_h = int(HEAD_SIZE * 1.57)
lines.append(f' <rect x="20" y="{y - int(HEAD_SIZE * 1.0)}" width="{CARD_W - 40}" height="{bar_h}" rx="5" fill="white" opacity="0.1"/>')
dot_r = max(8, int(HEAD_SIZE * 0.5))
dot_x = MARGIN
if atk_cost:
dot_elems, dot_w = render_energy_dots(MARGIN, y + 2, atk_cost, dot_r)
lines.extend(dot_elems)
dot_x = MARGIN + dot_w + 6
atk_name_size, atk_dmg_size = fit_attack_header(atk_name, damage, len(atk_cost), HEAD_SIZE, CARD_W, MARGIN)
lines.append(f' <text x="{dot_x}" y="{y + 2}" font-family="{FONT_TITLE}" font-size="{atk_name_size}" font-weight="900" fill="white" filter="url(#shadow)">{atk_name}</text>')
if damage:
lines.append(f' <text x="{CARD_W - MARGIN}" y="{y + 2}" font-family="{FONT_TITLE}" font-size="{atk_dmg_size}" font-weight="900" fill="#FF6644" text-anchor="end" filter="url(#shadow)">{escape_xml(str(damage))}</text>')
y += int(HEAD_SIZE * 0.64)
if effect:
wrapped = ft_wrap(_BODY_FACE, effect, BODY_SIZE, text_max_w)
for wline in wrapped:
y += LINE_H
markup = energy_inline_svg(wline, BODY_SIZE)
lines.append(f' <text x="{MARGIN}" y="{y}" font-family="{FONT_BODY}" font-size="{BODY_SIZE}" font-weight="700" fill="white" filter="url(#shadow)">{markup}</text>')
y += int(BODY_SIZE * 1.25)
render_footer_svg(lines, card, category, card_type, retreat, BODY_SIZE,
set_name, local_id, footer_y=CARD_H - 55, sep_offset=18,
sep_color="rgba(255,255,255,0.3)", fill="rgba(255,255,255,0.9)",
retreat_dot_fill="white", info_y=CARD_H - 18,
info_fill="rgba(255,255,255,0.5)")
lines.append("</svg>")
return "\n".join(lines)
def generate_svg(card: dict, artwork_b64: str) -> str:
"""Generate an SVG proxy card with large readable text."""
name = escape_xml(card.get("name", "Unknown"))
hp = card.get("hp", "")
types = card.get("types", [])
stage = card.get("stage", "")
card_type = types[0] if types else "Colorless"
color = TYPE_COLORS.get(card_type, "#888888")
retreat = card.get("retreat", 0)
abilities = card.get("abilities", [])
attacks = card.get("attacks", [])
set_name = card.get("set", {}).get("name", "")
local_id = card.get("localId", "")
category = card.get("category", "Pokemon")
trainer_type = card.get("trainerType", "")
trainer_effect = compress_text(card.get("effect", ""))
abilities = [
{**ab, "effect": compress_text(ab.get("effect", ""))}
for ab in abilities
]
attacks = [
{**atk, "effect": compress_text(atk.get("effect", ""))}
for atk in attacks
]
# Trainer cards get a distinct color
if category == "Trainer":
if trainer_type == "Supporter":
color = "#C04010"
elif trainer_type == "Stadium":
color = "#1A7A3A"
else:
color = "#1860A0" # Item / Tool
# Darker shade for header
# We'll just use the type color with opacity
lines = []
lines.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {CARD_W} {CARD_H}" width="{CARD_W}" height="{CARD_H}">')
lines.append(" <defs>")
lines.append(f' <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">')
lines.append(f' <stop offset="0%" stop-color="{color}" stop-opacity="0.3"/>')
lines.append(f' <stop offset="100%" stop-color="{color}" stop-opacity="0.1"/>')
lines.append(f" </linearGradient>")
# Drop shadow filter for body text
lines.append(' <filter id="shadow" x="-2%" y="-2%" width="104%" height="104%">')
lines.append(' <feDropShadow dx="1" dy="1" stdDeviation="0.8" flood-color="#000" flood-opacity="0.35"/>')
lines.append(" </filter>")
# Heavier shadow for title text
lines.append(' <filter id="shadow-title" x="-2%" y="-5%" width="104%" height="110%">')
lines.append(' <feDropShadow dx="1.5" dy="2" stdDeviation="1" flood-color="#000" flood-opacity="0.5"/>')
lines.append(" </filter>")
# Black-white-black sandwich outline for trainer type tag
lines.append(' <filter id="tag-outline" x="-8%" y="-20%" width="116%" height="140%">')
lines.append(' <feMorphology in="SourceAlpha" operator="dilate" radius="4" result="outer"/>')
lines.append(' <feFlood flood-color="#000" flood-opacity="0.8" result="black"/>')
lines.append(' <feComposite in="black" in2="outer" operator="in" result="outer-stroke"/>')
lines.append(' <feMorphology in="SourceAlpha" operator="dilate" radius="2" result="inner"/>')
lines.append(' <feFlood flood-color="white" flood-opacity="0.95" result="white"/>')
lines.append(' <feComposite in="white" in2="inner" operator="in" result="inner-stroke"/>')
lines.append(' <feMerge>')
lines.append(' <feMergeNode in="outer-stroke"/>')
lines.append(' <feMergeNode in="inner-stroke"/>')
lines.append(' <feMergeNode in="SourceGraphic"/>')
lines.append(' </feMerge>')
lines.append(" </filter>")
lines.append(" </defs>")
# Card background — solid white base so transparent areas don't bleed through
lines.append(f' <rect width="{CARD_W}" height="{CARD_H}" rx="25" ry="25" fill="white"/>')
lines.append(f' <rect width="{CARD_W}" height="{CARD_H}" rx="25" ry="25" fill="url(#bg)" stroke="{color}" stroke-width="4"/>')
# Header bar
lines.append(f' <rect x="0" y="0" width="{CARD_W}" height="80" rx="25" ry="25" fill="{color}" opacity="0.85"/>')
lines.append(f' <rect x="0" y="40" width="{CARD_W}" height="40" fill="{color}" opacity="0.85"/>')
# Name and HP / trainer type in header
lines.append(f' <text x="30" y="57" font-family="{FONT_TITLE}" font-size="42" font-weight="900" fill="white" filter="url(#shadow-title)">{name}</text>')
if category == "Trainer":
# Trainer type icon in header
icon_size = 40
icon_x = CARD_W - 30 - icon_size
icon_y = 20
icon_colors = {"Supporter": "#FFD040", "Stadium": "#50E878", "Item": "#60C8FF", "Tool": "#60C8FF"}
icon_fill = icon_colors.get(trainer_type, "#FFD040")
if trainer_type == "Supporter":
# Person silhouette
lines.append(f' <g transform="translate({icon_x},{icon_y})" filter="url(#tag-outline)">')
lines.append(f' <circle cx="{icon_size//2}" cy="{int(icon_size*0.28)}" r="{int(icon_size*0.22)}" fill="{icon_fill}"/>')
lines.append(f' <path d="M{int(icon_size*0.15)},{icon_size} Q{int(icon_size*0.15)},{int(icon_size*0.45)} {icon_size//2},{int(icon_size*0.42)} Q{int(icon_size*0.85)},{int(icon_size*0.45)} {int(icon_size*0.85)},{icon_size} Z" fill="{icon_fill}"/>')
lines.append(f' </g>')
elif trainer_type in ("Item", "Tool"):
# Pokeball icon
r = icon_size // 2
cx = icon_x + r
cy = icon_y + r
lines.append(f' <g filter="url(#tag-outline)">')
lines.append(f' <circle cx="{cx}" cy="{cy}" r="{r}" fill="{icon_fill}" stroke="white" stroke-width="2"/>')
lines.append(f' <rect x="{cx - r}" y="{cy - 2}" width="{icon_size}" height="4" fill="white"/>')
lines.append(f' <circle cx="{cx}" cy="{cy}" r="{int(r*0.3)}" fill="white" stroke="{icon_fill}" stroke-width="2"/>')
lines.append(f' </g>')
elif trainer_type == "Stadium":
# Stadium icon — simple building/columns silhouette
sx = icon_x
sy = icon_y
s = icon_size
lines.append(f' <g filter="url(#tag-outline)">')
# Roof / pediment triangle
lines.append(f' <polygon points="{sx},{sy + int(s*0.4)} {sx + s//2},{sy + int(s*0.08)} {sx + s},{sy + int(s*0.4)}" fill="{icon_fill}"/>')
# Base platform
lines.append(f' <rect x="{sx + int(s*0.05)}" y="{sy + int(s*0.82)}" width="{int(s*0.9)}" height="{int(s*0.12)}" rx="2" fill="{icon_fill}"/>')
# Three columns
cw = int(s * 0.12)
ch = int(s * 0.44)
ctop = sy + int(s * 0.38)
for col_x in [sx + int(s*0.15), sx + s//2 - cw//2, sx + int(s*0.85) - cw]: