#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Icon Generation Script using Gemini 3.1 Pro Preview API
Generates SVG icons via text generation (SVG is XML text format)
Model: gemini-3.1-pro-preview - best thinking, token efficiency, factual consistency
Usage:
python generate.py --prompt "settings gear icon" --style outlined
python generate.py --prompt "shopping cart" --style filled --color "#6366F1"
python generate.py --name "dashboard" --category navigation --style duotone
python generate.py --prompt "cloud upload" --batch 4 --output-dir ./icons
python generate.py --prompt "user profile" --sizes "16,24,32,48"
"""
import argparse
import json
import os
import re
import sys
import time
from pathlib import Path
from datetime import datetime
def load_env():
"""Load .env files in priority order"""
env_paths = [
Path(__file__).parent.parent.parent / ".env",
Path.home() / ".claude" / "skills" / ".env",
Path.home() / ".claude" / ".env"
]
for env_path in env_paths:
if env_path.exists():
with open(env_path) as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
if key not in os.environ:
os.environ[key] = value.strip('"\'')
load_env()
try:
from google import genai
from google.genai import types
except ImportError:
print("Error: google-genai package not installed.")
print("Install with: pip install google-genai")
sys.exit(1)
# ============ CONFIGURATION ============
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
MODEL = "gemini-3.1-pro-preview"
# Icon styles with SVG-specific instructions
ICON_STYLES = {
"outlined": "outlined stroke icons, 2px stroke width, no fill, clean open paths",
"filled": "solid filled icons, no stroke, flat color fills, bold shapes",
"duotone": "duotone style with primary color at full opacity and secondary color at 30% opacity, layered shapes",
"thin": "thin line icons, 1px or 1.5px stroke width, delicate minimalist lines",
"bold": "bold thick line icons, 3px stroke width, heavy weight, impactful",
"rounded": "rounded icons with round line caps and joins, soft corners, friendly feel",
"sharp": "sharp angular icons, square line caps and mitered joins, precise edges",
"flat": "flat design icons, solid fills, no gradients or shadows, geometric simplicity",
"gradient": "linear or radial gradient fills, modern vibrant color transitions",
"glassmorphism": "glassmorphism style with semi-transparent fills, blur backdrop effect simulation, frosted glass",
"pixel": "pixel art style icons on a grid, retro 8-bit aesthetic, crisp edges",
"hand-drawn": "hand-drawn sketch style, slightly irregular strokes, organic feel, imperfect lines",
"isometric": "isometric 3D projection, 30-degree angles, dimensional depth",
"glyph": "simple glyph style, single solid shape, minimal detail, pictogram",
"animated-ready": "animated-ready SVG with named groups and IDs for CSS/JS animation targets",
}
ICON_CATEGORIES = {
"navigation": "arrows, menus, hamburger, chevrons, home, back, forward, breadcrumb",
"action": "edit, delete, save, download, upload, share, copy, paste, print, search",
"communication": "email, chat, phone, video call, notification, bell, message bubble",
"media": "play, pause, stop, skip, volume, microphone, camera, image, gallery",
"file": "document, folder, archive, attachment, cloud, database, storage",
"user": "person, group, avatar, profile, settings, lock, key, shield",
"commerce": "cart, bag, wallet, credit card, receipt, tag, gift, store",
"data": "chart, graph, analytics, dashboard, table, filter, sort, calendar",
"development": "code, terminal, bug, git, API, server, database, deploy",
"social": "heart, star, thumbs up, bookmark, flag, trophy, badge, crown",
"weather": "sun, moon, cloud, rain, snow, wind, thunder, temperature",
"map": "pin, location, compass, globe, route, directions, map marker",
}
# SVG generation prompt template
SVG_PROMPT_TEMPLATE = """Generate a clean, production-ready SVG icon.
Requirements:
- Output ONLY valid SVG code, nothing else
- ViewBox: "0 0 {viewbox} {viewbox}"
- Use currentColor for strokes/fills (inherits CSS color)
- No embedded fonts or text elements unless specifically requested
- No raster images or external references
- Optimized paths with minimal nodes
- Accessible: include
element with icon description
{style_instructions}
{color_instructions}
{size_instructions}
Icon to generate: {prompt}
Output the SVG code only, wrapped in ```svg``` code block."""
SVG_BATCH_PROMPT_TEMPLATE = """Generate {count} distinct SVG icon variations for: {prompt}
Requirements for EACH icon:
- Output ONLY valid SVG code
- ViewBox: "0 0 {viewbox} {viewbox}"
- Use currentColor for strokes/fills (inherits CSS color)
- No embedded fonts, raster images, or external references
- Optimized paths with minimal nodes
- Include element with icon description
{style_instructions}
{color_instructions}
Generate {count} different visual interpretations. Output each SVG in a separate ```svg``` code block.
Label each variation (e.g., "Variation 1: [brief description]")."""
def extract_svgs(text):
"""Extract SVG code blocks from model response"""
svgs = []
# Try ```svg code blocks first
pattern = r'```svg\s*\n(.*?)```'
matches = re.findall(pattern, text, re.DOTALL)
if matches:
svgs.extend(matches)
# Fallback: try ```xml code blocks
if not svgs:
pattern = r'```xml\s*\n(.*?)```'
matches = re.findall(pattern, text, re.DOTALL)
svgs.extend(matches)
# Fallback: try bare