Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.
feat: add banana image generation extension (seo-image-gen)
Daniel36aac5ceeefd
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 392f946..aedcf3e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "claude-seo",- "version": "1.4.0",+ "version": "1.5.0","description": "Comprehensive SEO analysis skill for Claude Code. Covers technical SEO, content quality (E-E-A-T), schema markup, image optimization, sitemap architecture, AI search optimization (GEO), and strategic planning across all industries.","author": "AgriciDaniel","license": "MIT",@@ -19,7 +19,9 @@"skills/seo-plan/SKILL.md","skills/seo-programmatic/SKILL.md","skills/seo-competitor-pages/SKILL.md",- "skills/seo-hreflang/SKILL.md"+ "skills/seo-hreflang/SKILL.md",+ "extensions/dataforseo/skills/seo-dataforseo/SKILL.md",+ "extensions/banana/skills/seo-image-gen/SKILL.md"],"agents": ["agents/seo-technical.md",@@ -28,6 +30,8 @@"agents/seo-sitemap.md","agents/seo-performance.md","agents/seo-visual.md",- "agents/seo-geo.md"+ "agents/seo-geo.md",+ "extensions/dataforseo/agents/seo-dataforseo.md",+ "extensions/banana/agents/seo-image-gen.md"]}diff --git a/CLAUDE.md b/CLAUDE.mdindex 0e6c9ea..bc9c25a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ schema markup, image optimization, sitemap architecture, and AI search optimizat```claude-seo/CLAUDE.md # Project instructions (this file)- .claude-plugin/plugin.json # Plugin manifest (v1.3.2)+ .claude-plugin/plugin.json # Plugin manifest v1.5.0seo/ # Main orchestrator skillSKILL.md # Entry point, routing table, core rulesreferences/ # On-demand knowledge files@@ -41,6 +41,9 @@ claude-seo/seo-performance.md # Core Web Vitals, page speedseo-visual.md # Screenshots, mobile renderingseo-geo.md # AI crawler access, GEO, citability+ extensions/ # Optional add-on capabilities+ dataforseo/ # Live SEO data via DataForSEO MCP+ banana/ # AI image generation via Gemini MCPdocs/ # Extended documentationARCHITECTURE.md # System design overviewCOMMANDS.md # Full command reference@@ -65,6 +68,7 @@ claude-seo/| `/seo programmatic` | Programmatic SEO analysis and planning || `/seo competitor-pages` | Competitor comparison page generation || `/seo hreflang <url>` | International SEO / hreflang audit |+| `/seo image-gen [use-case] <desc>` | AI image generation for SEO assets (extension) |## Development Rules@@ -81,4 +85,4 @@ claude-seo/1. **Progressive Disclosure**: Metadata always loaded, instructions on activation, resources on demand2. **Industry Detection**: Auto-detect SaaS, e-commerce, local, publisher, agency3. **Parallel Execution**: Full audits spawn 7 subagents simultaneously-4. **Extension System**: DataForSEO MCP integration for live data+4. **Extension System**: DataForSEO MCP for live data, Banana MCP for AI image generationdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d5bb003..538468c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -198,20 +198,48 @@ Extensions are opt-in add-ons that integrate external data sources via MCP serve```extensions/-└── dataforseo/ # DataForSEO MCP integration+├── dataforseo/ # DataForSEO MCP integration+│ ├── README.md # Extension documentation+│ ├── install.sh # Unix installer+│ ├── install.ps1 # Windows installer+│ ├── uninstall.sh # Unix uninstaller+│ ├── uninstall.ps1 # Windows uninstaller+│ ├── field-config.json # API response field filtering+│ ├── skills/+│ │ └── seo-dataforseo/+│ │ └── SKILL.md # Sub-skill (22 commands)+│ ├── agents/+│ │ └── seo-dataforseo.md # Subagent+│ └── docs/+│ └── DATAFORSEO-SETUP.md # Account setup guide+│+└── banana/ # Banana Image Generation (Gemini AI)├── README.md # Extension documentation├── install.sh # Unix installer- ├── install.ps1 # Windows installer├── uninstall.sh # Unix uninstaller- ├── uninstall.ps1 # Windows uninstaller- ├── field-config.json # API response field filtering├── skills/- │ └── seo-dataforseo/- │ └── SKILL.md # Sub-skill (22 commands)+ │ └── seo-image-gen/+ │ └── SKILL.md # Sub-skill (6 commands)├── agents/- │ └── seo-dataforseo.md # Subagent+ │ └── seo-image-gen.md # Image audit subagent+ ├── scripts/ # Python scripts (stdlib only)+ │ ├── generate.py # Direct API fallback+ │ ├── edit.py # Image editing fallback+ │ ├── batch.py # CSV batch workflow+ │ ├── cost_tracker.py # Usage and cost tracking+ │ ├── presets.py # Brand preset management+ │ ├── setup_mcp.py # MCP configuration+ │ └── validate_setup.py # Installation verification+ ├── references/ # On-demand knowledge+ │ ├── prompt-engineering.md # 6-component Reasoning Brief+ │ ├── gemini-models.md # Model specs and pricing+ │ ├── mcp-tools.md # MCP tool reference+ │ ├── post-processing.md # ImageMagick recipes+ │ ├── cost-tracking.md # Cost tracking guide+ │ ├── presets.md # Preset schema+ │ └── seo-image-presets.md # SEO-specific presets└── docs/- └── DATAFORSEO-SETUP.md # Account setup guide+ └── BANANA-SETUP.md # API key and MCP setup```### Available Extensions@@ -219,6 +247,7 @@ extensions/| Extension | Package | What it Adds ||-----------|---------|-------------|| **DataForSEO** | `dataforseo-mcp-server` | 22 commands: live SERP, keywords, backlinks, on-page analysis, content analysis, business listings, AI visibility, LLM mentions |+| **Banana Image Gen** | `@ycse/nanobanana-mcp` | 6 commands: OG image, hero image, product photo, infographic, custom, and batch generation via Gemini AI |### Extension Conventiondiff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex a7f4ba8..8f5c1a0 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -314,6 +314,37 @@ Live SEO data via DataForSEO MCP server (extension). 22 commands across 9 API mo---+### `/seo image-gen [use-case] <description>`++AI image generation for SEO assets (extension). Powered by Gemini via nanobanana-mcp.++**Prerequisites:** Banana extension installed (`./extensions/banana/install.sh`)++**Use Cases:**+```+/seo image-gen og <description> # OG/social preview image (16:9, 1K)+/seo image-gen hero <description> # Blog hero image (16:9, 2K)+/seo image-gen product <description> # Product photography (4:3, 2K)+/seo image-gen infographic <description> # Infographic visual (2:3, 4K)+/seo image-gen custom <description> # Custom with full Creative Director pipeline+/seo image-gen batch <description> [N] # Generate N variations (default: 3)+```++**Example:**+```+/seo image-gen og "Professional SaaS analytics dashboard with clean UI"+/seo image-gen hero "Dramatic sunset over modern city skyline"+/seo image-gen product "Wireless noise-canceling headphones on marble surface"+```++**What it does:**+1. Maps SEO use case to optimized domain mode, aspect ratio, and resolution+2. Constructs 6-component Reasoning Brief (Creative Director pipeline)+3. Generates image via Gemini API+4. Provides SEO checklist (alt text, file naming, WebP, schema markup)++---+## Quick Reference| Command | Use Case |@@ -324,6 +355,7 @@ Live SEO data via DataForSEO MCP server (extension). 22 commands across 9 API mo| `/seo geo <url>` | AI search optimization || `/seo hreflang [url]` | Hreflang/i18n SEO audit || `/seo images <url>` | Image optimization |+| `/seo image-gen [use-case] <desc>` | AI image generation (extension) || `/seo page <url>` | Single page analysis || `/seo plan <type>` | Strategic planning || `/seo programmatic [url\|plan]` | Programmatic SEO analysis |diff --git a/extensions/banana/README.md b/extensions/banana/README.mdnew file mode 100644index 0000000..c247410--- /dev/null+++ b/extensions/banana/README.md@@ -0,0 +1,92 @@+# Banana Image Generation Extension for Claude SEO++Generate production-ready SEO images using AI — OG/social previews, blog heroes,+product photography, infographics, and more. Powered by Google Gemini via the+banana Creative Director pipeline.++## Prerequisites++- **Claude SEO** installed (`~/.claude/skills/seo/`)+- **Node.js 18+** with npx+- **Google AI API key** (free at [aistudio.google.com/apikey](https://aistudio.google.com/apikey))+- **ImageMagick** (optional, for post-processing)++## Installation++```bash+./extensions/banana/install.sh+```++The installer will:+1. Verify Claude SEO is installed+2. Prompt for your Google AI API key (if nanobanana-mcp not already configured)+3. Install the `seo-image-gen` skill and agent+4. Configure the MCP server in `~/.claude/settings.json`++## Commands++| Command | What it does |+|---------|-------------|+| `/seo image-gen og <description>` | OG/social preview image (1200x630 feel) |+| `/seo image-gen hero <description>` | Blog hero image (widescreen, dramatic) |+| `/seo image-gen product <description>` | Product photography (clean, white BG) |+| `/seo image-gen infographic <description>` | Infographic visual (vertical, data-heavy) |+| `/seo image-gen custom <description>` | Custom with full Creative Director pipeline |+| `/seo image-gen batch <description> [N]` | Generate N variations (default: 3) |++## Use Case Defaults++| Use Case | Aspect Ratio | Resolution | Domain Mode | Cost |+|----------|-------------|------------|-------------|------|+| OG/Social Preview | 16:9 | 1K | Product/UI | ~$0.04 |+| Blog Hero | 16:9 | 2K | Cinema/Editorial | ~$0.08 |+| Product Photo | 4:3 | 2K | Product | ~$0.08 |+| Infographic | 2:3 | 4K | Infographic | ~$0.16 |+| Social Square | 1:1 | 1K | UI/Web | ~$0.04 |+| Favicon/Icon | 1:1 | 512 | Logo | ~$0.02 |++## How It Works++Claude acts as a **Creative Director** — it never passes raw text to the API.+Instead, it analyzes your intent, selects the optimal domain mode, and constructs+an optimized prompt using a proven 6-component Reasoning Brief system:++1. **Subject** (30%) — Physical specificity and micro-details+2. **Style** (25%) — Camera specs, film stock, brand references+3. **Context** (15%) — Location, time, weather, supporting elements+4. **Action** (10%) — Pose, gesture, movement, state+5. **Composition** (10%) — Shot type, framing, focal length+6. **Lighting** (10%) — Direction, quality, color temperature++## Post-Generation SEO Checklist++After every generation, Claude provides:+- Alt text suggestion (keyword-rich, descriptive)+- SEO-friendly file naming convention+- WebP conversion command+- ImageObject schema snippet+- OG meta tag markup (for social previews)++## Audit Integration++During `/seo audit`, the extension optionally spawns an image analysis agent that:+- Audits existing OG/social images across the site+- Identifies missing or low-quality images+- Creates a prioritized generation plan with prompt suggestions+- Estimates total cost for the generation plan++The agent never auto-generates images — it produces a plan for your review.++## Uninstallation++```bash+./extensions/banana/uninstall.sh+```++This removes the skill and agent. If you also use the standalone banana skill,+the MCP server config is preserved.++## Troubleshooting++See [docs/BANANA-SETUP.md](docs/BANANA-SETUP.md) for detailed setup instructions+and common issues.diff --git a/extensions/banana/agents/seo-image-gen.md b/extensions/banana/agents/seo-image-gen.mdnew file mode 100644index 0000000..0b09bc9--- /dev/null+++ b/extensions/banana/agents/seo-image-gen.md@@ -0,0 +1,59 @@+---+name: seo-image-gen+description: SEO image analyst. Audits existing OG/social preview images, identifies missing or low-quality images, and creates an image generation plan with prompts for key pages. Does NOT auto-generate images.+tools: Read, Bash, Glob, Grep+---++You are an SEO image analyst. When delegated tasks during an SEO audit:++1. Check that nanobanana-mcp tools are available before including generation recommendations+2. Analyze the site's existing image strategy for SEO impact+3. Output a structured generation plan — never auto-generate (cost control)++## Analysis Scope++For each audited page, evaluate:+- **OG image presence** — Does `og:image` meta tag exist? Is it valid?+- **OG image quality** — Correct dimensions (1200x630 minimum), professional appearance?+- **Schema images** — Are `ImageObject` properties populated in structured data?+- **Alt text quality** — Descriptive, keyword-rich, not stuffed?+- **Image format** — Using modern formats (WebP, AVIF) vs legacy (PNG, JPEG)?+- **Image file size** — Under 200KB for hero, under 100KB for thumbnails?++## Output Format++Match existing claude-seo patterns:++### Image Audit Summary++| Metric | Value | Status |+|--------|-------|--------|+| Pages with OG images | X/Y | Pass/Fail |+| OG images correct size | X/Y | Pass/Fail |+| Schema ImageObject usage | X/Y | Pass/Fail |+| WebP/AVIF adoption | X% | Pass/Fail |+| Average image file size | XKB | Pass/Fail |++### Image Generation Plan++For each page missing or having low-quality images:++| Page | Issue | Suggested Use Case | Prompt Idea | Priority |+|------|-------|-------------------|-------------|----------|+| /homepage | Missing OG image | og | Professional SaaS dashboard overview | Critical |+| /blog/post-1 | Low-res hero | hero | [contextual suggestion] | High |++Priority levels: Critical > High > Medium > Low++### Recommendations++- Prioritize pages by traffic volume (highest traffic = fix first)+- Note estimated cost for full generation plan+- Suggest batch generation for efficiency+- Recommend WebP conversion pipeline for all generated assets++## Error Handling++- If nanobanana-mcp is not available, still audit existing images but note that generation requires the banana extension+- Report errors clearly with actionable next steps+- Note data source as "Image Audit (static analysis)" to distinguish from live checksdiff --git a/extensions/banana/docs/BANANA-SETUP.md b/extensions/banana/docs/BANANA-SETUP.mdnew file mode 100644index 0000000..9502ab7--- /dev/null+++ b/extensions/banana/docs/BANANA-SETUP.md@@ -0,0 +1,86 @@+# Banana Extension Setup Guide++## Google AI API Key++1. Go to [aistudio.google.com/apikey](https://aistudio.google.com/apikey)+2. Sign in with your Google account+3. Click "Create API key"+4. Copy the key — you'll need it during installation++**Free tier limits:**+- ~10 requests per minute (RPM)+- ~500 requests per day (RPD)+- Resets at midnight Pacific time++## MCP Server Configuration++The installer configures this automatically. If you need to set it up manually,+add to `~/.claude/settings.json`:++```json+{+ "mcpServers": {+ "nanobanana-mcp": {+ "command": "npx",+ "args": ["-y", "@ycse/nanobanana-mcp@latest"],+ "env": {+ "GOOGLE_API_KEY": "your-api-key-here"+ }+ }+ }+}+```++## Verifying Installation++Run the validation script:+```bash+python3 ~/.claude/skills/seo-image-gen/scripts/validate_setup.py+```++Or check manually:+1. `ls ~/.claude/skills/seo-image-gen/SKILL.md` — skill file exists+2. `ls ~/.claude/agents/seo-image-gen.md` — agent file exists+3. `grep nanobanana ~/.claude/settings.json` — MCP configured++## Common Issues++### "MCP tools not available"+- Restart Claude Code after installing the extension+- Verify your API key is valid at [aistudio.google.com](https://aistudio.google.com)+- Check `~/.claude/settings.json` has the nanobanana-mcp entry++### "Rate limited (429)"+- Free tier: ~10 requests/minute, ~500/day+- Wait 60 seconds and retry+- For batch operations, add delays between requests++### "IMAGE_SAFETY" error+- The safety filter flagged your prompt (often a false positive)+- Claude will suggest rephrased alternatives automatically+- Common triggers: certain color descriptions, implied scenarios+- See `references/prompt-engineering.md` Safety Rephrase section++### "Node.js version too old"+- Requires Node.js 18++- Update via nvm: `nvm install 18 && nvm use 18`+- Or download from [nodejs.org](https://nodejs.org/)++### Generated images not appearing+- Default output directory: `~/Documents/nanobanana_generated/`+- Check the path returned by Claude after generation+- Verify disk space is available++## ImageMagick (Optional)++For post-processing (WebP conversion, cropping, background removal):++```bash+# Ubuntu/Pop!_OS+sudo apt install imagemagick++# Verify+magick --version+```++If `magick` (v7) is not available, the scripts fall back to `convert` (v6).diff --git a/extensions/banana/install.sh b/extensions/banana/install.shnew file mode 100755index 0000000..d165cf5--- /dev/null+++ b/extensions/banana/install.sh@@ -0,0 +1,170 @@+#!/usr/bin/env bash+set -euo pipefail++# Banana Image Generation Extension Installer for Claude SEO+# Wraps everything in main() to prevent partial execution on network failure++main() {+ SKILL_DIR="${HOME}/.claude/skills/seo-image-gen"+ AGENT_DIR="${HOME}/.claude/agents"+ SEO_SKILL_DIR="${HOME}/.claude/skills/seo"+ SETTINGS_FILE="${HOME}/.claude/settings.json"++ echo "════════════════════════════════════════"+ echo "║ Banana Image Gen - SEO Extension ║"+ echo "║ For Claude SEO ║"+ echo "════════════════════════════════════════"+ echo ""++ # Check prerequisites+ if [ ! -d "${SEO_SKILL_DIR}" ]; then+ echo "✗ Claude SEO is not installed."+ echo " Install it first: curl -fsSL https://raw.githubusercontent.com/AgriciDaniel/claude-seo/main/install.sh | bash"+ exit 1+ fi+ echo "✓ Claude SEO detected"++ if ! command -v node >/dev/null 2>&1; then+ echo "✗ Node.js is required but not installed."+ echo " Install Node.js 20+: https://nodejs.org/"+ exit 1+ fi++ NODE_VERSION=$(node -v | sed 's/v//' | cut -d. -f1)+ if [ "${NODE_VERSION}" -lt 20 ]; then+ echo "✗ Node.js 20+ required (found v${NODE_VERSION})."+ echo " Update: https://nodejs.org/"+ exit 1+ fi+ echo "✓ Node.js v$(node -v | sed 's/v//') detected"++ if ! command -v npx >/dev/null 2>&1; then+ echo "✗ npx is required but not found (comes with npm)."+ exit 1+ fi+ echo "✓ npx detected"++ # Determine script directory (works for both ./install.sh and repo-relative paths)+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++ # Check if running from repo or standalone+ if [ -f "${SCRIPT_DIR}/skills/seo-image-gen/SKILL.md" ]; then+ SOURCE_DIR="${SCRIPT_DIR}"+ elif [ -f "${SCRIPT_DIR}/extensions/banana/skills/seo-image-gen/SKILL.md" ]; then+ SOURCE_DIR="${SCRIPT_DIR}/extensions/banana"+ else+ echo "✗ Cannot find extension source files."+ echo " Run this script from the claude-seo repo: ./extensions/banana/install.sh"+ exit 1+ fi++ # Check if nanobanana-mcp is already configured+ MCP_CONFIGURED=false+ if [ -f "${SETTINGS_FILE}" ]; then+ if python3 -c "+import json+with open('${SETTINGS_FILE}', 'r') as f:+ settings = json.load(f)+if 'mcpServers' in settings and 'nanobanana-mcp' in settings['mcpServers']:+ exit(0)+else:+ exit(1)+" 2>/dev/null; then+ MCP_CONFIGURED=true+ echo "✓ nanobanana-mcp already configured in settings.json"+ fi+ fi++ # If MCP not configured, prompt for API key+ if [ "${MCP_CONFIGURED}" = false ]; then+ echo ""+ echo "Google AI API key required for image generation."+ echo "Get a free key at: https://aistudio.google.com/apikey"+ echo ""++ read -rsp "Google AI API key (GOOGLE_AI_API_KEY): " GOOGLE_AI_API_KEY+ echo ""+ if [ -z "${GOOGLE_AI_API_KEY}" ]; then+ echo "✗ API key cannot be empty."+ exit 1+ fi++ # Configure MCP server+ echo "→ Configuring nanobanana-mcp server..."+ python3 -c "+import json, os++settings_path = '${SETTINGS_FILE}'++# Read existing settings or create new+if os.path.exists(settings_path):+ with open(settings_path, 'r') as f:+ settings = json.load(f)+else:+ settings = {}++# Ensure mcpServers key exists+if 'mcpServers' not in settings:+ settings['mcpServers'] = {}++# Add nanobanana-mcp server config+settings['mcpServers']['nanobanana-mcp'] = {+ 'command': 'npx',+ 'args': ['-y', '@ycse/nanobanana-mcp@latest'],+ 'env': {+ 'GOOGLE_AI_API_KEY': '''${GOOGLE_AI_API_KEY}'''+ }+}++# Write back+os.makedirs(os.path.dirname(settings_path), exist_ok=True)+with open(settings_path, 'w') as f:+ json.dump(settings, f, indent=2)++print(' ✓ nanobanana-mcp configured in settings.json')+" || {+ echo "✗ Could not auto-configure MCP server."+ echo " See: extensions/banana/docs/BANANA-SETUP.md"+ exit 1+ }+ fi++ # Install skill+ echo ""+ echo "→ Installing seo-image-gen skill..."+ mkdir -p "${SKILL_DIR}"+ cp "${SOURCE_DIR}/skills/seo-image-gen/SKILL.md" "${SKILL_DIR}/SKILL.md"++ # Install agent+ echo "→ Installing seo-image-gen agent..."+ mkdir -p "${AGENT_DIR}"+ cp "${SOURCE_DIR}/agents/seo-image-gen.md" "${AGENT_DIR}/seo-image-gen.md"++ # Copy scripts and references to skill directory for ${CLAUDE_SKILL_DIR} resolution+ echo "→ Installing scripts and references..."+ mkdir -p "${SKILL_DIR}/scripts" "${SKILL_DIR}/references"+ cp "${SOURCE_DIR}/scripts/"*.py "${SKILL_DIR}/scripts/"+ cp "${SOURCE_DIR}/references/"*.md "${SKILL_DIR}/references/"++ # Pre-warm npx package+ echo "→ Pre-downloading nanobanana-mcp..."+ npx -y @ycse/nanobanana-mcp@latest --help >/dev/null 2>&1 || true++ echo ""+ echo "✓ Banana Image Generation extension installed successfully!"+ echo ""+ echo "Usage:"+ echo " 1. Start Claude Code: claude"+ echo " 2. Run commands:"+ echo " /seo image-gen og \"Professional SaaS dashboard\""+ echo " /seo image-gen hero \"Dramatic sunset over city skyline\""+ echo " /seo image-gen product \"Wireless headphones on marble\""+ echo " /seo image-gen infographic \"SEO ranking factors 2026\""+ echo " /seo image-gen custom \"Any creative concept\""+ echo " /seo image-gen batch \"Product variations\" 3"+ echo ""+ echo "Full docs: extensions/banana/README.md"+ echo "To uninstall: ./extensions/banana/uninstall.sh"+}++main "$@"diff --git a/extensions/banana/references/cost-tracking.md b/extensions/banana/references/cost-tracking.mdnew file mode 100644index 0000000..80e89d4--- /dev/null+++ b/extensions/banana/references/cost-tracking.md@@ -0,0 +1,47 @@+# Cost Tracking Reference++> Load this on-demand when the user asks about costs or before batch operations.++## Pricing Table++| Model | Resolution | Cost/Image | Notes |+|-------|-----------|-----------|-------|+| 3.1 Flash | 512 | $0.020 | Quick drafts |+| 3.1 Flash | 1K | $0.039 | Standard (default) |+| 3.1 Flash | 2K | $0.078 | Quality assets |+| 3.1 Flash | 4K | $0.156 | Print/hero images |+| 2.5 Flash | 512 | $0.020 | Draft fallback |+| 2.5 Flash | 1K | $0.039 | Standard fallback |+| Batch API | Any | 50% of above | Asynchronous, higher latency |++Pricing is approximate, based on ~1,290 output tokens per image.+Research suggests actual costs may be ~$0.067/img. Verify at https://ai.google.dev/gemini-api/docs/pricing++## Free Tier Limits++- ~10 requests per minute (RPM)+- ~500 requests per day (RPD)+- Per Google Cloud project, resets midnight Pacific++## Cost Tracker Commands++```bash+# Log a generation+cost_tracker.py log --model gemini-3.1-flash-image-preview --resolution 1K --prompt "coffee shop hero"++# View summary (total + last 7 days)+cost_tracker.py summary++# Today's usage+cost_tracker.py today++# Estimate before batch+cost_tracker.py estimate --model gemini-3.1-flash-image-preview --resolution 1K --count 10++# Reset ledger+cost_tracker.py reset --confirm+```++## Storage++Ledger stored at `~/.banana/costs.json`. Created automatically on first use.diff --git a/extensions/banana/references/gemini-models.md b/extensions/banana/references/gemini-models.mdnew file mode 100644index 0000000..f8e2640--- /dev/null+++ b/extensions/banana/references/gemini-models.md@@ -0,0 +1,200 @@+# Gemini Image Generation Models++> Last updated: 2026-03-13+> Aligned with Google's March 2026 API state++## Available Models++### gemini-3.1-flash-image-preview (Recommended)+| Property | Value |+|----------|-------|+| **Model ID** | `gemini-3.1-flash-image-preview` |+| **Tier** | Nano Banana 2 (Flash) |+| **Speed** | Fast — optimized for high-volume use |+| **Aspect Ratios** | All 14 ratios (see table below) |+| **Max Resolution** | Up to 4096×4096 (4K tier) |+| **Features** | Google Search grounding (web + image), thinking levels, image-only output, extreme aspect ratios |+| **Rate Limits (Free)** | ~10 RPM / ~500 RPD (per Google Cloud project, resets midnight Pacific) |+| **Output Tokens** | ~1,290 output tokens per image |+| **Best For** | Most use cases, rapid iteration, batch generation |++### gemini-2.5-flash-image+| Property | Value |+|----------|-------|+| **Model ID** | `gemini-2.5-flash-image` |+| **Tier** | Nano Banana 2 (Flash, previous gen) |+| **Speed** | Fast |+| **Aspect Ratios** | 1:1, 16:9, 9:16, 4:3, 3:4 |+| **Max Resolution** | Up to 1024×1024 (1K tier) |+| **Rate Limits (Free)** | ~10 RPM / ~500 RPD |+| **Best For** | Stable fallback, proven quality |++## Deprecated Models (DO NOT USE)++### gemini-3-pro-image-preview+- **Status:** Base model deprecated March 9, 2026. **Image generation variant may still be accessible** — use at your own discretion via `set_model`. Prefer 3.1 Flash.+- **Was:** Nano Banana Pro tier (professional asset production, 4K output, 14 reference images)+- **Migration:** Use `gemini-3.1-flash-image-preview` instead++### gemini-2.0-flash-exp+- **Status:** Deprecated, replaced by gemini-2.5-flash-image++## Aspect Ratios++All 14 supported ratios. Availability varies by model:++| Ratio | Orientation | Use Cases | 3.1 Flash | 2.5 Flash |+|-------|-------------|-----------|:---------:|:---------:|+| `1:1` | Square | Social posts, avatars, thumbnails | ✅ | ✅ |+| `16:9` | Landscape | Blog headers, YouTube thumbnails, presentations | ✅ | ✅ |+| `9:16` | Portrait | Stories, Reels, TikTok, mobile | ✅ | ✅ |+| `4:3` | Landscape | Product shots, classic display | ✅ | ✅ |+| `3:4` | Portrait | Book covers, portrait framing | ✅ | ✅ |+| `2:3` | Portrait | Pinterest pins, posters | ✅ | ❌ |+| `3:2` | Landscape | DSLR standard, photo prints | ✅ | ❌ |+| `4:5` | Portrait | Instagram portrait, social | ✅ | ❌ |+| `5:4` | Landscape | Large format photography | ✅ | ❌ |+| `1:4` | Tall strip | Vertical banners, side panels | ✅ | ❌ |+| `4:1` | Wide strip | Website banners, headers | ✅ | ❌ |+| `1:8` | Extreme tall | Narrow vertical strips | ✅ | ❌ |+| `8:1` | Extreme wide | Ultra-wide banners | ✅ | ❌ |+| `21:9` | Ultra-wide | Cinematic, film-grade, ultra-wide monitors | ✅ | ❌ |++## Resolution Tiers++Control output resolution with the `imageSize` parameter. Note the **uppercase K** requirement.++| `imageSize` Value | Pixel Range | Model Availability | Use Case |+|-------------------|-------------|-------------------|----------|+| `512` | Up to 512×512 | All models | Drafts, quick iteration, low bandwidth |+| `1K` (default) | Up to 1024×1024 | All models | Standard web use, social media |+| `2K` | Up to 2048×2048 | 3.1 Flash | Quality assets, detailed work |+| `4K` | Up to 4096×4096 | 3.1 Flash | Print production, hero images, final assets |++**Notes:**+- Actual pixel dimensions depend on aspect ratio (e.g., 4K at 16:9 = 4096×2304)+- Higher resolutions consume more tokens and cost more+- Default is `1K` if `imageSize` is not specified++## API Configuration++### Endpoint+```+https://generativelanguage.googleapis.com/v1beta/models/{model-id}:generateContent+```++### Required Parameters+```json+{+ "contents": [{"parts": [{"text": "your prompt here"}]}],+ "generationConfig": {+ "responseModalities": ["TEXT", "IMAGE"],+ "imageConfig": {+ "aspectRatio": "16:9",+ "imageSize": "1K"+ }+ }+}+```++### Image-Only Output Mode+Force the model to return only an image (no text response):+```json+{+ "generationConfig": {+ "responseModalities": ["IMAGE"]+ }+}+```++### Thinking Level+Control how much the model "thinks" before generating. Higher levels improve complex compositions but increase latency:+```json+{+ "generationConfig": {+ "thinkingConfig": {+ "thinkingLevel": "medium"+ }+ }+}+```+Levels: `minimal`, `low`, `medium`, `high`++### Google Search Grounding+Ground generation in real-world visual references. Supports web and image search (3.1 Flash):+```json+{+ "tools": [{"googleSearch": {}}]+}+```+**Prompt pattern:** `[Search/source request] + [Analytical task] + [Visual translation]`++Example: "Search for the latest SpaceX Starship design, analyze its proportions and markings, then generate a photorealistic image of it at sunset on the launch pad."++### Multi-Image Input+Up to 14 reference images can be provided:+- **10 object references** — for style, composition, or visual matching+- **4 character references** — assign distinct names to preserve features across generations++Useful for character consistency, style transfer, and brand-aligned generation.++## Rate Limits by Tier++| Tier | RPM | RPD | Notes |+|------|-----|-----|-------|+| Free | ~10 | ~500 | Per Google Cloud project, resets midnight Pacific. Reduced Dec 2025. |+| Pay-as-you-go | 30 | 10,000 | Production workloads |+| Enterprise | Custom | Custom | Contact Google |++## Pricing++| Model | Resolution | Cost per Image | Notes |+|-------|-----------|---------------|-------|+| 3.1 Flash | 1K | ~$0.039 | Standard |+| 3.1 Flash | 2K | ~$0.078 | 2× standard |+| 3.1 Flash | 4K | ~$0.156 | 4× standard |+| 2.5 Flash | 1K | ~$0.039 | Standard |+| Batch API | Any | 50% discount | Asynchronous, higher latency |++Pricing is approximate and based on ~1,290 output tokens per image.+Research suggests NB2 pricing may be ~$0.067/img (vs documented $0.039). Verify current pricing at https://ai.google.dev/gemini-api/docs/pricing++## Image Output Specs++| Property | Value |+|----------|-------|+| **Format** | PNG |+| **Max Resolution** | Up to 4096×4096 (4K tier, 3.1 Flash) |+| **Color Space** | sRGB |+| **Text Rendering** | Supported — best under 25 characters |+| **Style Control** | Via prompt engineering |++## Safety Filters++Gemini uses a two-layer safety architecture:++1. **Input filters** — block prompts containing prohibited content before generation+2. **Output filters** — analyze generated images and block unsafe results++| `finishReason` | Meaning | Retryable? |+|----------------|---------|:----------:|+| `STOP` | Successful generation | N/A |+| `IMAGE_SAFETY` | Output blocked by safety filter | Rephrase prompt |+| `PROHIBITED_CONTENT` | Content policy violation | No — topic is blocked |+| `SAFETY` | General safety block | Rephrase prompt |+| `RECITATION` | Detected copyrighted content | Rephrase prompt |++**Known issue:** Filters are known to be overly cautious — benign prompts may be blocked. Iterate with rephrased wording if this happens.++## Content Credentials++- **SynthID watermarks** are always embedded in generated images (invisible, machine-readable)+- **C2PA metadata** is included on Pro/paid outputs (verifiable provenance chain)++## Key Limitations+- No video generation (image only)+- No transparent backgrounds (PNG but always with background)+- Text rendering quality varies — keep text under 25 characters for best results+- Safety filters may block some prompts (violence, NSFW, public figures) — known to be overly cautious+- Session context resets between Claude Code conversations+- `imageSize` and thinking level depend on MCP package version supportdiff --git a/extensions/banana/references/mcp-tools.md b/extensions/banana/references/mcp-tools.mdnew file mode 100644index 0000000..c1c3b56--- /dev/null+++ b/extensions/banana/references/mcp-tools.md@@ -0,0 +1,115 @@+# MCP Tools Reference — @ycse/nanobanana-mcp++> Package: `@ycse/nanobanana-mcp`+> GitHub: https://github.com/YCSE/nanobanana-mcp++## Tools++### gemini_generate_image+Generate an image from a text prompt.++**Parameters:**+| Param | Type | Required | Description |+|-------|------|----------|-------------|+| `prompt` | string | Yes | Text description of the image to generate |++**Returns:** Image data + file path (saved to `~/Documents/nanobanana_generated/`)++**Example usage in Claude Code:**+```+User: "Generate a sunset over mountains in watercolor style"+→ Claude calls gemini_generate_image with prompt+→ Returns image path and description+```++### gemini_edit_image+Edit an existing image with text instructions.++**Parameters:**+| Param | Type | Required | Description |+|-------|------|----------|-------------|+| `imagePath` | string | Yes | Path to the image file to edit |+| `prompt` | string | Yes | Edit instructions |++**Returns:** Modified image data + file path++**Example:**+```+User: "Remove the background from ~/Documents/photo.png"+→ Claude calls gemini_edit_image with path and instruction+```++### gemini_chat+Multi-turn visual conversation maintaining session context.++**Parameters:**+| Param | Type | Required | Description |+|-------|------|----------|-------------|+| `message` | string | Yes | Chat message (can reference previous images) |++**Returns:** Text response + optional image++**Key feature:** Session consistency — maintains style, characters, and context across turns. Great for iterative refinement.++### set_aspect_ratio+Configure the aspect ratio for subsequent image generations.++**Parameters:**+| Param | Type | Required | Description |+|-------|------|----------|-------------|+| `ratio` | string | Yes | Aspect ratio (e.g., "16:9", "1:1", "9:16") |++**Supported ratios:** 1:1, 16:9, 9:16, 4:3, 3:4, 2:3, 3:2, 4:5, 5:4, 1:4, 4:1, 1:8, 8:1, 21:9++### set_model+Switch the active Gemini model.++**Parameters:**+| Param | Type | Required | Description |+|-------|------|----------|-------------|+| `model` | string | Yes | Model identifier |++**Available models:**+- `gemini-3.1-flash-image-preview` (default, recommended)+- `gemini-2.5-flash-image` (stable fallback)++### get_image_history+Retrieve list of images generated in the current session.++**Parameters:** None++**Returns:** Array of image entries with paths and prompts++### clear_conversation+Reset session context and conversation history.++**Parameters:** None++**Returns:** Confirmation of reset++## Environment Variables++| Variable | Required | Description |+|----------|----------|-------------|+| `GOOGLE_AI_API_KEY` | Yes | API key from https://aistudio.google.com/apikey |+| `NANOBANANA_MODEL` | No | Override default model (default: `gemini-3.1-flash-image-preview`) |++## Output Directory+All generated images are saved to: `~/Documents/nanobanana_generated/`++Images are named with timestamps for easy identification.++## Feature Availability via MCP++Some newer Gemini API features depend on the MCP package version of `@ycse/nanobanana-mcp`. Check the package version to confirm support:++| Feature | API Status | MCP Support |+|---------|-----------|-------------|+| `imageSize` (resolution control) | Available | Depends on package version |+| Thinking level (`thinkingConfig`) | Available | Depends on package version |+| Search grounding (`googleSearch`) | Available | Depends on package version |+| Image-only output (`responseModalities: ["IMAGE"]`) | Available | Depends on package version |+| Multi-image input (up to 14 refs) | Available | Via `gemini_chat` with image paths |+| All 14 aspect ratios | Available | Via `set_aspect_ratio` |++If a feature is not yet supported by the MCP package, you can still use it via direct API calls with `curl` or the Google AI SDK.diff --git a/extensions/banana/references/post-processing.md b/extensions/banana/references/post-processing.mdnew file mode 100644index 0000000..546ad5c--- /dev/null+++ b/extensions/banana/references/post-processing.md@@ -0,0 +1,192 @@+# Post-Processing Pipeline Reference++> Load this on-demand when the user needs image manipulation after generation.++## Prerequisites++Check availability before using:+```bash+which magick # ImageMagick 7 (preferred)+which convert # ImageMagick 6 (fallback)+which ffmpeg # For video/animation+```++Install ImageMagick if not present: `sudo apt install imagemagick` (Debian/Ubuntu) or `brew install imagemagick` (macOS).++## Common Operations++### Resize for Platforms++```bash+# Instagram post (1080x1080)+magick input.png -resize 1080x1080^ -gravity center -extent 1080x1080 instagram.png++# Twitter/X header (1500x500)+magick input.png -resize 1500x500^ -gravity center -extent 1500x500 twitter-header.png++# YouTube thumbnail (1280x720)+magick input.png -resize 1280x720^ -gravity center -extent 1280x720 youtube-thumb.png++# LinkedIn banner (1584x396)+magick input.png -resize 1584x396^ -gravity center -extent 1584x396 linkedin-banner.png++# Favicon (multi-size ICO)+magick input.png -resize 32x32 favicon.ico+```++### Background Removal (Transparency)++```bash+# Remove solid white background+magick input.png -fuzz 10% -transparent white output.png++# Remove solid color background (specify color)+magick input.png -fuzz 15% -transparent "#F0F0F0" output.png++# Clean edges after transparency (anti-alias)+magick input.png -fuzz 10% -transparent white -channel A -blur 0x1 -level 50%,100% output.png++# Auto-crop transparent padding+magick input.png -trim +repage output.png+```++### Format Conversion++```bash+# PNG to WebP (web-optimized, smaller file)+magick input.png -quality 85 output.webp++# PNG to JPEG (with white background for transparency)+magick input.png -background white -flatten -quality 90 output.jpg++# PNG to AVIF (modern, smallest size)+magick input.png -quality 80 output.avif++# SVG trace (for logos — requires potrace)+potrace input.pbm -s -o output.svg+```++### Color Adjustments++```bash+# Increase contrast+magick input.png -contrast-stretch 2%x1% output.png++# Warm color temperature+magick input.png -modulate 100,110,105 output.png++# Cool color temperature+magick input.png -modulate 100,90,95 output.png++# Desaturate (muted colors)+magick input.png -modulate 100,70,100 output.png++# Convert to grayscale+magick input.png -colorspace Gray output.png++# Sepia tone+magick input.png -sepia-tone 80% output.png+```++### Compositing++```bash+# Overlay watermark (bottom-right, 20% opacity)+magick base.png watermark.png -gravity southeast -geometry +20+20 \+ -compose dissolve -define compose:args=20 -composite output.png++# Side-by-side comparison+magick input1.png input2.png +append comparison.png++# Vertical stack+magick input1.png input2.png -append stack.png++# Add padding/border+magick input.png -bordercolor white -border 40 output.png++# Add rounded corners+magick input.png \( +clone -alpha extract -draw \+ "roundrectangle 0,0,%[fx:w-1],%[fx:h-1],20,20" \) \+ -alpha off -compose CopyOpacity -composite rounded.png+```++### Batch Processing++```bash+# Resize all PNGs in directory+for f in ~/Documents/nanobanana_generated/*.png; do+ magick "$f" -resize 800x800 "${f%.png}_thumb.png"+done++# Convert all to WebP+for f in ~/Documents/nanobanana_generated/*.png; do+ magick "$f" -quality 85 "${f%.png}.webp"+done+```++## Animation (GIF/Video from Multiple Frames)++```bash+# Create GIF from multiple images+magick -delay 100 frame1.png frame2.png frame3.png animation.gif++# Create MP4 from image sequence+ffmpeg -framerate 1 -pattern_type glob -i '*.png' \+ -c:v libx264 -pix_fmt yuv420p slideshow.mp4+```++## Note on 4K Output++With Gemini 3.1 Flash's `imageSize: "4K"` option (up to 4096×4096), many traditional+upscaling post-processing steps are no longer necessary. If your target platform accepts+images at or below 4K resolution, generate at native 4K instead of generating at 1K+and upscaling. This produces better detail and avoids upscaling artifacts.++## Green Screen Transparency Pipeline++Gemini cannot generate transparent backgrounds. Use this workaround:++### 1. Generate with green screen prompt++Append to any prompt:+```+on a solid bright green (#00FF00) chroma key background+with a thin white outline separating the subject from the background+```++### 2. Remove green screen (ImageMagick)++```bash+magick input.png -fuzz 20% -transparent "#00FF00" output.png+```++### 3. Clean edges + trim (ImageMagick)++```bash+magick output.png -channel A -blur 0x1 -level 50%,100% -trim +repage final.png+```++### 4. Alternative (FFmpeg, better for batch)++```bash+ffmpeg -i input.png -vf "colorkey=0x00FF00:0.3:0.1,despill=type=green" -pix_fmt rgba output.png+```++### Tips+- `-fuzz 20%` handles slight color variations at edges; increase to 25% for softer edges+- The white outline in the prompt helps prevent color spill on subject edges+- For batch processing, the FFmpeg approach is faster and handles despill automatically+- Always verify edges after conversion — may need manual touchup for hair/fur++## Quality Assessment++```bash+# Get image dimensions and info+magick identify -verbose input.png | head -20++# Check file size+ls -lh input.png++# Get exact pixel dimensions+magick identify -format "%wx%h" input.png+```diff --git a/extensions/banana/references/presets.md b/extensions/banana/references/presets.mdnew file mode 100644index 0000000..2b6df0b--- /dev/null+++ b/extensions/banana/references/presets.md@@ -0,0 +1,69 @@+# Brand/Style Presets Reference++> Load this on-demand when the user asks about presets or brand consistency.++## Preset Schema++Each preset is stored as `~/.banana/presets/NAME.json`:++```json+{+ "name": "tech-saas",+ "description": "Clean tech SaaS brand",+ "colors": ["#2563EB", "#1E40AF", "#F8FAFC"],+ "style": "clean minimal tech illustration, flat vectors, soft shadows",+ "typography": "bold geometric sans-serif",+ "lighting": "bright diffused studio, no harsh shadows",+ "mood": "professional, trustworthy, modern",+ "default_ratio": "16:9",+ "default_resolution": "2K"+}+```++## Example Presets++### tech-saas+- **Colors:** #2563EB, #1E40AF, #F8FAFC (blue + white)+- **Style:** Clean minimal tech illustration, flat vectors, soft shadows+- **Typography:** Bold geometric sans-serif+- **Mood:** Professional, trustworthy, modern++### luxury-brand+- **Colors:** #1A1A1A, #C9A96E, #FAFAF5 (black + gold + cream)+- **Style:** Elegant high-end photography, rich textures, deep contrast+- **Typography:** Thin elegant serif, generous letter-spacing+- **Mood:** Exclusive, sophisticated, aspirational++### editorial-magazine+- **Colors:** #000000, #FFFFFF, #FF3B30 (black + white + accent red)+- **Style:** Bold editorial photography, strong geometric composition+- **Typography:** Condensed all-caps sans-serif headlines+- **Mood:** Bold, provocative, contemporary++## How Presets Merge into Reasoning Brief++When a preset is active, Claude uses its values as defaults for the Reasoning Brief:+1. **Colors** → inform palette descriptions in Context and Style components+2. **Style** → becomes the base for the Style component+3. **Typography** → used for any text rendering+4. **Lighting** → becomes the base for the Lighting component+5. **Mood** → influences Action and Context components++User instructions always override preset values. If a user says "make it dark"+but the preset has bright lighting, follow the user's instruction.++## Managing Presets++```bash+# List presets+presets.py list++# Show details+presets.py show tech-saas++# Create interactively (Claude fills in details from conversation)+presets.py create NAME --colors "#hex,#hex" --style "..." --mood "..."++# Delete+presets.py delete NAME --confirm+```diff --git a/extensions/banana/references/prompt-engineering.md b/extensions/banana/references/prompt-engineering.mdnew file mode 100644index 0000000..29f8336--- /dev/null+++ b/extensions/banana/references/prompt-engineering.md@@ -0,0 +1,411 @@+# Prompt Engineering Reference — Claude Banana++> Load this on-demand when constructing complex prompts or when the user+> asks about prompt techniques. Do NOT load at startup.+>+> Aligned with Google's March 2026 "Ultimate Prompting Guide" for Gemini image generation.++## The 6-Component Reasoning Brief++Every image prompt should contain these components, written as natural+narrative paragraphs — NEVER as comma-separated keyword lists.++### 1. Subject+The main focus of the image. Describe with physical specificity.++**Good:** "A weathered Japanese ceramicist in his 70s, deep sun-etched+wrinkles mapping decades of kiln work, calloused hands cradling a+freshly thrown tea bowl with an irregular, organic rim"++**Bad:** "old man, ceramic, bowl"++### 2. Action+What is happening. Movement, pose, gesture, state of being.++**Good:** "leaning forward with intense concentration, gently smoothing+the rim with a wet thumb, a thin trail of slip running down his wrist"++**Bad:** "making pottery"++### 3. Context+Environment, setting, temporal and spatial details.++**Good:** "inside a traditional wood-fired anagama kiln workshop,+stacked shelves of drying pots visible in the soft background, late+afternoon light filtering through rice paper screens"++**Bad:** "workshop, afternoon"++### 4. Composition+Camera angle, shot type, framing, spatial relationships.++**Good:** "intimate close-up shot from slightly below eye level,+shallow depth of field isolating the hands and bowl against the+soft bokeh of the workshop behind"++**Bad:** "close up"++### 5. Lighting+Light source, quality, direction, temperature, shadows.++**Good:** "warm directional light from a single high window camera-left,+creating gentle Rembrandt lighting on the face with a soft triangle+of light on the shadow-side cheek, deep warm shadows in the workshop"++**Bad:** "natural lighting"++### 6. Style+Art medium, aesthetic reference, technical photographic details.++**Good:** "captured with a Sony A7R IV, 85mm f/1.4 GM lens, Kodak Portra+400 color grading with lifted shadows and muted earth tones, reminiscent+of Dorothea Lange's documentary portraiture"++**Bad:** "photorealistic, 8K, masterpiece"++## Domain Mode Modifier Libraries++### Cinema Mode+**Camera specs:** RED V-Raptor, ARRI Alexa 65, Sony Venice 2, Blackmagic URSA+**Lenses:** Cooke S7/i, Zeiss Supreme Prime, Atlas Orion anamorphic+**Film stocks:** Kodak Vision3 500T (tungsten), Kodak Vision3 250D (daylight), Fuji Eterna Vivid+**Lighting setups:** three-point, chiaroscuro, Rembrandt, split, butterfly, rim/backlight+**Shot types:** establishing wide, medium close-up, extreme close-up, Dutch angle, overhead crane, Steadicam tracking+**Color grading:** teal and orange, desaturated cold, warm vintage, high-contrast noir++### Product Mode+**Surfaces:** polished marble, brushed concrete, raw linen, acrylic riser, gradient sweep+**Lighting:** softbox diffused, hard key with fill card, rim separation, tent lighting, light painting+**Angles:** 45-degree hero, flat lay, three-quarter, straight-on, worm's-eye+**Style refs:** Apple product photography, Aesop minimal, Bang & Olufsen clean, luxury cosmetics++### Portrait Mode+**Focal lengths:** 85mm (classic), 105mm (compression), 135mm (telephoto), 50mm (environmental)+**Apertures:** f/1.4 (dreamy bokeh), f/2.8 (subject-sharp), f/5.6 (environmental context)+**Pose language:** candid mid-gesture, direct-to-camera confrontational, profile silhouette, over-shoulder glance+**Skin/texture:** freckles visible, pores at macro distance, catch light in eyes, subsurface scattering++### Editorial/Fashion Mode+**Publication refs:** Vogue Italia, Harper's Bazaar, GQ, National Geographic, Kinfolk+**Styling notes:** layered textures, statement accessories, monochromatic palette, contrast patterns+**Locations:** marble staircase, rooftop at golden hour, industrial loft, desert dunes, neon-lit alley+**Poses:** power stance, relaxed editorial lean, movement blur, fabric in wind++### UI/Web Mode+**Styles:** flat vector, isometric 3D, line art, glassmorphism, neumorphism, material design+**Colors:** specify exact hex or descriptive palette (e.g., "cool blues #2563EB to #1E40AF")+**Sizing:** design at 2x for retina, specify exact pixel dimensions needed+**Backgrounds:** transparent (request solid white then post-process), gradient, solid color++### Logo Mode+**Construction:** geometric primitives, golden ratio, grid-based, negative space+**Typography:** bold sans-serif, elegant serif, custom lettermark, monogram+**Colors:** max 2-3 colors, works in monochrome, high contrast+**Output:** request on solid white background, post-process to transparent++### Landscape Mode+**Depth layers:** foreground interest, midground subject, background atmosphere+**Atmospherics:** fog, mist, haze, volumetric light rays, dust particles+**Time of day:** blue hour (pre-dawn), golden hour, magic hour (post-sunset), midnight blue+**Weather:** dramatic storm clouds, clearing after rain, snow-covered, sun-dappled++### Infographic Mode+**Layout:** modular sections, clear visual hierarchy, bento grid, flow top-to-bottom+**Text:** use quotes for exact text, descriptive font style, specify size hierarchy+**Data viz:** bar charts, pie charts, flow diagrams, timelines, comparison tables+**Colors:** high-contrast, accessible palette, consistent brand colors++### Abstract Mode+**Geometry:** fractals, voronoi tessellation, spirals, fibonacci, organic flow, crystalline+**Textures:** marble veining, fluid dynamics, smoke wisps, ink diffusion, watercolor bleed+**Color palettes:** analogous harmony, complementary clash, monochromatic gradient, neon-on-black+**Styles:** generative art, data visualization art, glitch, procedural, macro photography of materials++## Advanced Techniques++### Character Consistency (Multi-turn)+Use `gemini_chat` and maintain descriptive anchors:+- First turn: Generate character with exhaustive physical description+- Following turns: Reference "the same character" + repeat 2-3 key identifiers+- Key identifiers: hair color/style, distinctive clothing, facial feature++**Multi-image reference technique** (3.1 Flash):+- Provide up to 4-5 character reference images in the conversation+- Assign distinct names to each character ("Character A: the red-haired knight")+- Model preserves features across different angles, actions, and environments+- Works best when reference images show the character from multiple angles++### Style Transfer Without Reference Images+Describe the target style exhaustively instead of referencing an image:+```+Render this scene in the style of a 1950s travel poster: flat areas of+color in a limited palette of teal, coral, and cream. Bold geometric+shapes with visible paper texture. Hand-lettered title text with a+mid-century modern typeface feel.+```++### Text Rendering Tips+- Quote exact text: `with the text "OPEN DAILY" in bold condensed sans-serif`+- **25 characters or less** — this is the practical limit for reliable rendering+- **2-3 distinct phrases max** — more text fragments degrade quality+- Describe font characteristics, not font names+- Specify placement: "centered at the top third", "along the bottom edge"+- High contrast: light text on dark, or vice versa+- **Text-first hack:** Establish the text concept conversationally first ("I need a sign that says FRESH BREAD"), then generate — the model anchors on text mentioned early+- Expect creative font interpretations, not exact replication of described styles++### Positive Framing (No Negative Prompts)+Gemini does NOT support negative prompts. Rephrase exclusions:+- Instead of "no blur" → "sharp, in-focus, tack-sharp detail"+- Instead of "no people" → "empty, deserted, uninhabited"+- Instead of "no text" → "clean, uncluttered, text-free"+- Instead of "not dark" → "brightly lit, high-key lighting"++### Search-Grounded Generation+For images based on real-world data (weather, events, statistics),+Gemini can use Google Search grounding to incorporate live information.+Useful for infographics with current data.++**Three-part formula for search-grounded prompts:**+1. `[Source/Search request]` — What to look up+2. `[Analytical task]` — What to analyze or extract+3. `[Visual translation]` — How to render it as an image++**Example:** "Search for the current top 5 programming languages by GitHub usage in 2026, analyze their relative popularity percentages, then generate a clean infographic bar chart with the language logos and percentages in a modern dark theme."++## Prompt Adaptation Rules++When adapting prompts from the claude-prompts database (Midjourney/DALL-E/etc.)+to Gemini's natural language format:++| Source Syntax | Gemini Equivalent |+|---------------|-------------------|+| `--ar 16:9` | Call `set_aspect_ratio("16:9")` separately |+| `--v 6`, `--style raw` | Remove — Gemini has no version/style flags |+| `--chaos 50` | Describe variety: "unexpected, surreal composition" |+| `--no trees` | Positive framing: "open clearing with no vegetation" |+| `(word:1.5)` weight | Descriptive emphasis: "prominently featuring [word]" |+| `8K, masterpiece, ultra-detailed` | Keep only "ultra-realistic, high resolution"; remove the rest |+| Comma-separated tags | Expand into descriptive narrative paragraphs |+| `shot on Hasselblad` | Keep — camera specs work well in Gemini |++## Common Prompt Mistakes++1. **Keyword stuffing** — stacking generic quality terms ("8K, masterpiece, best quality") adds nothing. Use only "ultra-realistic, high resolution" at the end+2. **Tag lists** — Gemini wants prose, not "red car, sunset, mountain, cinematic"+3. **Missing lighting** — The single biggest quality differentiator+4. **No composition direction** — Results in generic centered framing+5. **Vague style** — "make it look cool" vs specific art direction+6. **Ignoring aspect ratio** — Always set before generating+7. **Overlong prompts** — Diminishing returns past ~200 words; be precise, not verbose+8. **Text longer than ~25 characters** — Rendering degrades rapidly past this limit+9. **Burying key details at the end** — In long prompts, details placed last may be deprioritized; put critical specifics (exact text, key constraints) in the first third of the prompt+10. **Not iterating with follow-up prompts** — Use `gemini_chat` for progressive refinement instead of trying to get everything right in one generation++## Proven Prompt Templates++> Extracted from 2,500+ tested prompts. These patterns consistently produce+> high-quality results. Use them as starting points and adapt to the request.++### The Winning Formula (Weight Distribution)++| Component | Weight | What to include |+|-----------|--------|-----------------|+| **Subject** | 40% | Age, skin tone, hair color/style, eye color, body type, expression |+| **Styling** | 25% | Brand names, textures, fit, accessories, colors |+| **Environment** | 15% | Location + time of day + context details |+| **Camera** | 10% | Camera model + lens + focal length + shot type |+| **Lighting** | 10% | Quality, direction, color temperature, shadows |++### Instagram Ad / Social Media++**Pattern:** `[Subject with age/appearance] + [outfit with brand/texture] + [action verb] + [setting] + [camera spec] + [lighting] + [platform aesthetic]`++**Example (Product Placement):**+```+Hyper-realistic gym selfie of athletic 24yo influencer with glowing olive+skin, wearing crinkle-textured athleisure set in mauve. iPhone 16 Pro Max+front-facing portrait mode capturing sweat droplets on collarbones, hazel+eyes enhanced by gym LED lighting. Mirror reflection shows perfect form,+golden morning light through floor-to-ceiling windows. Frayed chestnut+ponytail with baby hairs, ultra-detailed skin texture, trending aesthetic.+```++**Example (Lifestyle Ad):**+```+A 24-year-old blonde fitness model in a high-energy sports drink+advertisement. Mid-run on a beach, wearing a vibrant orange sports bra+and black shorts, playful smile and sparkling blue eyes exuding vitality.+Bottle of the drink held in hand, waves crashing in background. Shot on+Nikon D850 with 70-200mm f/2.8 lens, natural light, fast shutter speed+capturing motion. Ultra-realistic skin texture, water droplets, product+label clearly visible.+```++**Example (Luxury Lifestyle):**+```+Gorgeous Instagram model wearing a designer silk gown, luxury rooftop+restaurant, golden hour lighting, champagne in hand, luxurious aspirational+lifestyle. Captured with Sony A7R IV, 85mm f/1.4 lens, shallow depth of+field, warm color grading.+```++### Product / Commercial Photography++**Pattern:** `[Product with brand/detail] + [dynamic elements] + [surface/setting] + "commercial photography for advertising campaign" + [lighting] + "high resolution"`++**Example (Beverage):**+```+Gatorade bottle with condensation dripping down the sides, surrounded by+lightning bolts and a burst of vibrant blue and orange light rays. The+Gatorade logo is prominently displayed on the bottle, with splashes of+water frozen in mid-air. Commercial food photography for an advertising+campaign, high resolution, high level of detail, vibrant complementary+colors.+```++**Example (Food):**+```+In and Out burger with layers of fresh lettuce, melted cheese, and pretzel+bun, placed on a white surface with the In and Out logo subtly glowing in+the background. Falling french fries and golden light, warm scene.+Commercial food photography for an advertising campaign, high resolution,+high level of detail, vibrant complementary colors.+```++### Fashion / Editorial++**Pattern:** `[Subject with ethnicity/age/features] + [outfit with texture/brand/cut] + [location] + [pose/action] + [camera + lens] + [lighting quality]`++**Example (Street Style):**+```+A 24-year-old female AI influencer posing confidently in an urban cityscape+during golden hour. Flawless sun-kissed skin, long wavy brown hair, deep+green eyes. Wearing a chic streetwear outfit — oversized beige blazer,+white top, high-waisted jeans. Captured with Sony A7R IV at 85mm f/1.4,+shallow depth of field with warm golden bokeh.+```++**Example (High Fashion):**+```+Stunning 24-year-old woman, long platinum blonde hair, radiant skin,+piercing blue eyes, dressed in a chic pastel blazer with a modern+minimalist aesthetic, soft sunlight glow, high-end fashion appeal.+Shot on Canon EOS R5, 85mm f/1.2 lens.+```++**Example (Avant-Garde):**+```+A blonde fitness model transformed into a runway-ready fashion icon,+wearing a bold avant-garde outfit: cropped leather jacket with neon pink+accents, paired with high-waisted athletic shorts and knee-high boots.+Captured mid-stride on a minimalist white runway, playful twinkle in her+eye, dramatic studio lighting from above.+```++### SaaS / Tech Marketing++**Pattern:** `[UI mockup or abstract visual] + "on [dark/light] background" + [specific colors with hex] + [typography description] + "clean, premium SaaS aesthetic" + [glassmorphism/gradient/glow effects]`++**Example (Dashboard Hero):**+```+A floating glassmorphism UI card on a deep charcoal background showing a+content analytics dashboard with a rising line graph in teal (#14B8A6),+bar charts in coral (#F97316), and a circular progress indicator at 94%.+Subtle grid lines, frosted glass effect with 20% opacity, teal glow+bleeding from the card edges. Clean premium SaaS aesthetic, no text+smaller than headline size.+```++**Example (Feature Highlight):**+```+An isometric 3D illustration of interconnected data nodes on a dark navy+background. Each node is a glowing teal sphere connected by thin luminous+lines, forming a constellation pattern. One central node pulses brighter+with radiating rings. Modern tech illustration style with subtle depth+of field, volumetric lighting from below.+```++**Example (Comparison/Before-After):**+```+Split-screen image: left side shows a cluttered, dim workspace with+scattered papers, red error indicators, and a frustrated expression+conveyed through a cracked coffee mug and tangled cables. Right side+shows a clean, organized dashboard interface glowing in teal and white+on a dark background, with smooth flowing lines and checkmarks. A sharp+vertical dividing line separates chaos from clarity.+```++### Logo / Branding++**Pattern:** `[Product/bottle/item] + "with [brand element] prominently displayed" + [dynamic visual elements] + "commercial photography" + [lighting style] + "high resolution, vibrant complementary colors"`++**Example:**+```+A sleek matte black bottle with a minimal white logo mark centered on the+label, surrounded by swirling gradient ribbons of teal and coral light.+The bottle sits on a reflective dark surface, sharp studio rim lighting+separating it from the background. Product photography for luxury+branding, high resolution, dramatic contrast.+```++### Key Tactics That Make Prompts Work++1. **Name real cameras** — "Sony A7R IV", "Canon EOS R5", "iPhone 16 Pro Max" anchor realism+2. **Specify exact lens** — "85mm f/1.4" gives the model precise depth-of-field information+3. **Use age + ethnicity + features** — "24yo with olive skin, hazel eyes" beats "a person"+4. **Name brands for styling** — "Lululemon mat", "Tom Ford suit" triggers specific visual associations+5. **Include micro-details** — "sweat droplets on collarbones", "baby hairs stuck to neck"+6. **Add platform context** — "Instagram aesthetic", "commercial photography for advertising"+7. **Describe textures** — "crinkle-textured", "metallic silver", "frosted glass"+8. **Use action verbs** — "mid-run", "posing confidently", "captured mid-stride"+9. **End with "ultra-realistic, high resolution"** — these two specific anchors help on Gemini. Avoid generic stacking like "8K, masterpiece, best quality" which adds no value+10. **For products, say "prominently displayed"** — ensures the product/logo isn't hidden++### Anti-Patterns (What NOT to Do)++- **"A dark-themed Instagram ad showing..."** — too meta, describes the concept not the image+- **"A sleek SaaS dashboard visualization..."** — abstract, no visual anchors+- **"Modern, clean, professional..."** — vague adjectives that mean nothing to the model+- **"A bold call to action with..."** — describes marketing intent, not visual content+- **Describing what the viewer should feel** — instead, describe what creates that feeling++## Safety Filter Rephrase Strategies++Gemini's safety filters (Layer 2: server-side output filter) cannot be disabled.+When a prompt is blocked, the only path forward is rephrasing.++### Common Trigger Categories++| Category | Triggers on | Rephrase approach |+|----------|------------|-------------------|+| Violence/weapons | Combat, blood, injuries, firearms | Use metaphor or aftermath: "battle-worn" → "weathered veteran" |+| Medical/gore | Surgery, wounds, anatomical detail | Abstract or clinical: "open wound" → "medical illustration" |+| Real public figures | Named celebrities, politicians | Use archetypes: "Elon Musk" → "a tech entrepreneur in a minimalist office" |+| Children + risk | Minors in any ambiguous context | Add safety context: specify educational, family, or playful framing |+| NSFW/suggestive | Revealing clothing, intimate poses | Use artistic framing: "fashion editorial, fully clothed, editorial pose" |++### Rephrase Patterns++1. **Abstraction** — Replace specific dangerous elements with abstract concepts+2. **Artistic framing** — Frame content as art, editorial, or documentary+3. **Metaphor** — Use symbolic language instead of literal descriptions+4. **Positive emphasis** — Describe what IS present, not what's dangerous+5. **Context shift** — Move from threatening to educational/professional context++### Example Rephrases++| Blocked prompt | Successful rephrase |+|----------------|---------------------|+| "a soldier in combat firing a rifle" | "a determined soldier standing guard at dawn, rifle slung over shoulder, morning mist over the outpost" |+| "a scary horror monster" | "a fantastical creature from a dark fairy tale, intricate organic textures, bioluminescent accents, concept art style" |+| "dog in a fight" | "a friendly golden retriever playing energetically in a sunny park, action shot, joyful expression" |+| "medical surgery scene" | "a clean modern operating room viewed from the observation gallery, soft blue surgical lights, professional documentary style" |+| "celebrity portrait of [name]" | "a distinguished middle-aged man in a tailored navy suit, warm studio lighting, editorial portrait style" |++### Key Principle++Layer 2 (output filter) analyzes the generated image, not just the prompt.+Even well-phrased prompts can be blocked if the model's interpretation triggers+the output filter. When this happens, try shifting the visual concept further+from the trigger rather than just changing words.diff --git a/extensions/banana/references/seo-image-presets.md b/extensions/banana/references/seo-image-presets.mdnew file mode 100644index 0000000..88d428f--- /dev/null+++ b/extensions/banana/references/seo-image-presets.md@@ -0,0 +1,137 @@+# SEO Image Presets++Pre-configured presets for common SEO image use cases. These map to banana's+preset format (see `references/presets.md` for schema details).++## Preset Templates++### og-default — Standard OG/Social Preview++```json+{+ "name": "og-default",+ "description": "Clean, professional OG image for social sharing",+ "aspect_ratio": "16:9",+ "resolution": "1K",+ "domain_mode": "Product",+ "style": {+ "colors": ["#FFFFFF", "#F5F5F5"],+ "mood": "Professional, clean, trustworthy",+ "lighting": "Bright, even studio lighting with soft shadows",+ "typography": "Modern sans-serif if text needed"+ },+ "post_processing": "magick output.png -resize 1200x630^ -gravity center -extent 1200x630 output-og.webp"+}+```++### blog-hero — Widescreen Blog Hero Image++```json+{+ "name": "blog-hero",+ "description": "Dramatic widescreen hero for blog posts",+ "aspect_ratio": "16:9",+ "resolution": "2K",+ "domain_mode": "Cinema",+ "style": {+ "colors": ["contextual"],+ "mood": "Dramatic, atmospheric, editorial",+ "lighting": "Golden hour or moody blue hour, directional",+ "typography": "None — image only"+ },+ "post_processing": "magick output.png -quality 85 output-hero.webp"+}+```++### product-white — E-commerce Product Shot++```json+{+ "name": "product-white",+ "description": "Clean white background product photography",+ "aspect_ratio": "4:3",+ "resolution": "2K",+ "domain_mode": "Product",+ "style": {+ "colors": ["#FFFFFF"],+ "mood": "Clean, professional, catalog-ready",+ "lighting": "360-degree soft studio lighting, minimal shadows",+ "typography": "None"+ },+ "prompt_suffix": "Studio product photography, clean white background, professional catalog shot, high resolution",+ "post_processing": "magick output.png -fuzz 5% -transparent white output-transparent.png"+}+```++### social-square — Social Media Square++```json+{+ "name": "social-square",+ "description": "1:1 square image for social media platforms",+ "aspect_ratio": "1:1",+ "resolution": "1K",+ "domain_mode": "UI/Web",+ "style": {+ "colors": ["brand-contextual"],+ "mood": "Engaging, scroll-stopping, platform-native",+ "lighting": "Bright, even, high-contrast",+ "typography": "Bold sans-serif if text needed, under 25 characters"+ }+}+```++### infographic-vertical — Data-Heavy Infographic++```json+{+ "name": "infographic-vertical",+ "description": "Tall vertical infographic for data visualization",+ "aspect_ratio": "2:3",+ "resolution": "4K",+ "domain_mode": "Infographic",+ "style": {+ "colors": ["brand-contextual", "data-visualization palette"],+ "mood": "Informative, structured, authoritative",+ "lighting": "Flat, even, no dramatic shadows",+ "typography": "Clear hierarchy — headline, subheads, body, captions"+ },+ "notes": "Use thinking: high for better text rendering accuracy"+}+```++### favicon-mark — Favicon / App Icon++```json+{+ "name": "favicon-mark",+ "description": "Minimal iconic mark for favicon or app icon",+ "aspect_ratio": "1:1",+ "resolution": "512",+ "domain_mode": "Logo",+ "style": {+ "colors": ["2-3 brand colors max"],+ "mood": "Minimal, recognizable, scalable",+ "lighting": "Flat, no shadows",+ "typography": "Single letter or symbol only"+ },+ "post_processing": "magick output.png -resize 32x32 favicon.ico && magick output.png -resize 180x180 apple-touch-icon.png"+}+```++## Creating Custom Presets++Users can create their own presets:+```bash+python3 ~/.claude/skills/seo-image-gen/scripts/presets.py create my-brand+```++This creates `~/.banana/presets/my-brand.json` with the full schema.+Custom presets override SEO defaults when specified.++## Preset Selection Logic++1. If user specifies a use case command (og, hero, product), load the matching preset+2. If user mentions a brand preset name, load from `~/.banana/presets/`+3. Brand presets override SEO presets for colors, mood, and typography+4. SEO presets always provide aspect ratio and resolution defaultsdiff --git a/extensions/banana/scripts/batch.py b/extensions/banana/scripts/batch.pynew file mode 100755index 0000000..b0640f2--- /dev/null+++ b/extensions/banana/scripts/batch.py@@ -0,0 +1,97 @@+#!/usr/bin/env python3+"""Claude Banana — CSV Batch Workflow++Parse a CSV file of image generation requests and output a structured plan.+Claude then executes each row via MCP.++Usage:+ batch.py --csv path/to/file.csv++CSV columns:+ prompt (required), ratio, resolution, model, preset (all optional)++Example CSV:+ prompt,ratio,resolution+ "coffee shop hero image",16:9,2K+ "team photo placeholder",1:1,1K+ "product shot on marble",4:3,2K+"""++import argparse+import csv+import json+import sys+from pathlib import Path++# Inline pricing for estimates+PRICING = {+ "gemini-3.1-flash-image-preview": {"512": 0.020, "1K": 0.039, "2K": 0.078, "4K": 0.156},+ "gemini-2.5-flash-image": {"512": 0.020, "1K": 0.039},+}+DEFAULT_MODEL = "gemini-3.1-flash-image-preview"+DEFAULT_RESOLUTION = "1K"+DEFAULT_RATIO = "1:1"+++def estimate_cost(model, resolution):+ """Estimate cost for a single image."""+ model_pricing = PRICING.get(model, PRICING[DEFAULT_MODEL])+ return model_pricing.get(resolution, model_pricing.get("1K", 0.039))+++def main():+ parser = argparse.ArgumentParser(description="Parse CSV batch and output generation plan")+ parser.add_argument("--csv", required=True, help="Path to CSV file")+ args = parser.parse_args()++ csv_path = Path(args.csv).resolve()+ if not csv_path.exists():+ print(json.dumps({"error": True, "message": f"CSV not found: {csv_path}"}))+ sys.exit(1)++ rows = []+ errors = []++ try:+ with open(csv_path, "r", newline="") as f:+ reader = csv.DictReader(f)+ if not reader.fieldnames or "prompt" not in reader.fieldnames:+ print(json.dumps({"error": True, "message": "CSV must have a 'prompt' column header"}))+ sys.exit(1)+ for i, row in enumerate(reader, start=2): # Line 2+ (1 is header)+ prompt = row.get("prompt", "").strip()+ if not prompt:+ errors.append(f"Row {i}: missing prompt")+ continue++ rows.append({+ "row": i,+ "prompt": prompt,+ "ratio": row.get("ratio", "").strip() or DEFAULT_RATIO,+ "resolution": row.get("resolution", "").strip() or DEFAULT_RESOLUTION,+ "model": row.get("model", "").strip() or DEFAULT_MODEL,+ "preset": row.get("preset", "").strip() or None,+ })+ except (csv.Error, UnicodeDecodeError) as e:+ print(json.dumps({"error": True, "message": f"Failed to parse CSV: {e}"}))+ sys.exit(1)++ if errors:+ print("Validation errors:")+ for e in errors:+ print(f" - {e}")+ if not rows:+ sys.exit(1)+ print()++ # Cost estimate+ total_cost = sum(estimate_cost(r["model"], r["resolution"]) for r in rows)++ # Output structured JSON for Claude to consume+ print(json.dumps({"rows": rows, "total_count": len(rows),+ "estimated_cost": round(total_cost, 3),+ "errors": errors}, indent=2))+++if __name__ == "__main__":+ main()diff --git a/extensions/banana/scripts/cost_tracker.py b/extensions/banana/scripts/cost_tracker.pynew file mode 100755index 0000000..3bcf43e--- /dev/null+++ b/extensions/banana/scripts/cost_tracker.py@@ -0,0 +1,191 @@+#!/usr/bin/env python3+"""Claude Banana — Cost Tracker++Track image generation costs, view summaries, and estimate batch costs.++Usage:+ cost_tracker.py log --model MODEL --resolution RES --prompt "summary"+ cost_tracker.py summary+ cost_tracker.py today+ cost_tracker.py estimate --model MODEL --resolution RES --count N+ cost_tracker.py reset --confirm+"""++import argparse+import json+import sys+from datetime import datetime, timezone+from pathlib import Path++LEDGER_PATH = Path.home() / ".banana" / "costs.json"++# Cost per image in USD (approximate, based on ~1,290 output tokens)+PRICING = {+ "gemini-3.1-flash-image-preview": {+ "512": 0.020,+ "1K": 0.039,+ "2K": 0.078,+ "4K": 0.156,+ },+ "gemini-2.5-flash-image": {+ "512": 0.020,+ "1K": 0.039,+ },+}++# Batch API gets 50% discount+BATCH_DISCOUNT = 0.5+++def _load_ledger():+ """Load the cost ledger from disk."""+ if not LEDGER_PATH.exists():+ return {"total_cost": 0.0, "total_images": 0, "entries": [], "daily": {}}+ with open(LEDGER_PATH, "r") as f:+ return json.load(f)+++def _save_ledger(ledger):+ """Save the cost ledger to disk."""+ LEDGER_PATH.parent.mkdir(parents=True, exist_ok=True)+ with open(LEDGER_PATH, "w") as f:+ json.dump(ledger, f, indent=2)+++def _lookup_cost(model, resolution, batch=False):+ """Look up cost for a model+resolution combination."""+ model_pricing = PRICING.get(model)+ if not model_pricing:+ # Try partial match+ for key in PRICING:+ if key in model or model in key:+ model_pricing = PRICING[key]+ break+ if not model_pricing:+ print(f"Warning: Unknown model '{model}', using 3.1 Flash pricing", file=sys.stderr)+ model_pricing = PRICING["gemini-3.1-flash-image-preview"]++ valid_resolutions = {"512", "1K", "2K", "4K"}+ if resolution not in valid_resolutions:+ print(f"Warning: Unknown resolution '{resolution}', using 1K pricing", file=sys.stderr)+ cost = model_pricing.get(resolution, model_pricing.get("1K", 0.039))+ if batch:+ cost *= BATCH_DISCOUNT+ return cost+++def cmd_log(args):+ """Log a generation to the ledger."""+ ledger = _load_ledger()+ cost = _lookup_cost(args.model, args.resolution, getattr(args, "batch", False))+ today = datetime.now(timezone.utc).strftime("%Y-%m-%d")+ now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")++ entry = {+ "ts": now,+ "model": args.model,+ "res": args.resolution,+ "cost": cost,+ "prompt": args.prompt[:100],+ }++ ledger["entries"].append(entry)+ ledger["total_cost"] = round(ledger["total_cost"] + cost, 4)+ ledger["total_images"] += 1++ if today not in ledger["daily"]:+ ledger["daily"][today] = {"count": 0, "cost": 0.0}+ ledger["daily"][today]["count"] += 1+ ledger["daily"][today]["cost"] = round(ledger["daily"][today]["cost"] + cost, 4)++ _save_ledger(ledger)+ print(json.dumps({"logged": True, "cost": cost, "total_cost": ledger["total_cost"],+ "total_images": ledger["total_images"]}))+++def cmd_summary(args):+ """Show cost summary."""+ ledger = _load_ledger()+ print(f"Total images: {ledger['total_images']}")+ print(f"Total cost: ${ledger['total_cost']:.3f}")+ print()++ daily = ledger.get("daily", {})+ if daily:+ # Show last 7 days+ sorted_days = sorted(daily.keys(), reverse=True)[:7]+ print("Last 7 days:")+ for day in sorted_days:+ d = daily[day]+ print(f" {day}: {d['count']} images, ${d['cost']:.3f}")+ else:+ print("No usage recorded yet.")+++def cmd_today(args):+ """Show today's usage."""+ ledger = _load_ledger()+ today = datetime.now(timezone.utc).strftime("%Y-%m-%d")+ daily = ledger.get("daily", {}).get(today, {"count": 0, "cost": 0.0})+ print(f"Today ({today}): {daily['count']} images, ${daily['cost']:.3f}")+++def cmd_estimate(args):+ """Estimate cost for a batch."""+ cost_per = _lookup_cost(args.model, args.resolution, getattr(args, "batch", False))+ total = round(cost_per * args.count, 3)+ print(f"Model: {args.model}")+ print(f"Resolution: {args.resolution}")+ print(f"Count: {args.count}")+ print(f"Cost/image: ${cost_per:.3f}")+ print(f"Total est: ${total:.3f}")+ if not getattr(args, "batch", False):+ batch_total = round(cost_per * BATCH_DISCOUNT * args.count, 3)+ print(f"Batch est: ${batch_total:.3f} (50% discount)")+++def cmd_reset(args):+ """Reset the ledger."""+ if not args.confirm:+ print("Error: Pass --confirm to reset the cost ledger.", file=sys.stderr)+ sys.exit(1)+ _save_ledger({"total_cost": 0.0, "total_images": 0, "entries": [], "daily": {}})+ print("Cost ledger reset.")+++def main():+ parser = argparse.ArgumentParser(description="Claude Banana Cost Tracker")+ sub = parser.add_subparsers(dest="command", required=True)++ # log+ p_log = sub.add_parser("log", help="Log a generation")+ p_log.add_argument("--model", required=True, help="Model ID")+ p_log.add_argument("--resolution", required=True, help="Resolution (512, 1K, 2K, 4K)")+ p_log.add_argument("--prompt", required=True, help="Brief prompt description")+ p_log.add_argument("--batch", action="store_true", help="Batch API (50%% discount)")++ # summary+ sub.add_parser("summary", help="Show cost summary")++ # today+ sub.add_parser("today", help="Show today's usage")++ # estimate+ p_est = sub.add_parser("estimate", help="Estimate batch cost")+ p_est.add_argument("--model", required=True, help="Model ID")+ p_est.add_argument("--resolution", required=True, help="Resolution (512, 1K, 2K, 4K)")+ p_est.add_argument("--count", required=True, type=int, help="Number of images")+ p_est.add_argument("--batch", action="store_true", help="Use batch pricing (50%% discount)")++ # reset+ p_reset = sub.add_parser("reset", help="Reset cost ledger")+ p_reset.add_argument("--confirm", action="store_true", help="Confirm reset")++ args = parser.parse_args()+ cmds = {"log": cmd_log, "summary": cmd_summary, "today": cmd_today,+ "estimate": cmd_estimate, "reset": cmd_reset}+ cmds[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/extensions/banana/scripts/edit.py b/extensions/banana/scripts/edit.pynew file mode 100755index 0000000..a3e6aae--- /dev/null+++ b/extensions/banana/scripts/edit.py@@ -0,0 +1,141 @@+#!/usr/bin/env python3+"""Claude Banana — Direct API Fallback: Image Editing++Edit images via Gemini REST API when MCP is unavailable.+Uses only Python stdlib (no pip dependencies).++Usage:+ edit.py --image path/to/image.png --prompt "remove the background"+ [--model MODEL] [--api-key KEY]+"""++import argparse+import base64+import json+import os+import sys+import urllib.request+from datetime import datetime+from pathlib import Path++DEFAULT_MODEL = "gemini-3.1-flash-image-preview"+OUTPUT_DIR = Path.home() / "Documents" / "nanobanana_generated"+API_BASE = "https://generativelanguage.googleapis.com/v1beta/models"+++def edit_image(image_path, prompt, model, api_key):+ """Call Gemini API to edit an image."""+ image_path = Path(image_path).resolve()+ if not image_path.exists():+ print(json.dumps({"error": True, "message": f"Image not found: {image_path}"}))+ sys.exit(1)++ # Read and encode image+ with open(image_path, "rb") as f:+ image_b64 = base64.b64encode(f.read()).decode("utf-8")++ # Determine MIME type+ suffix = image_path.suffix.lower()+ mime_types = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",+ ".webp": "image/webp", ".gif": "image/gif"}+ mime_type = mime_types.get(suffix, "image/png")++ url = f"{API_BASE}/{model}:generateContent?key={api_key}"++ body = {+ "contents": [+ {+ "parts": [+ {"text": prompt},+ {"inlineData": {"mimeType": mime_type, "data": image_b64}},+ ]+ }+ ],+ "generationConfig": {+ "responseModalities": ["TEXT", "IMAGE"],+ },+ }++ data = json.dumps(body).encode("utf-8")+ req = urllib.request.Request(+ url,+ data=data,+ headers={"Content-Type": "application/json"},+ method="POST",+ )++ try:+ with urllib.request.urlopen(req, timeout=120) as resp:+ result = json.loads(resp.read().decode("utf-8"))+ except urllib.error.HTTPError as e:+ error_body = e.read().decode("utf-8") if e.fp else ""+ print(json.dumps({"error": True, "status": e.code, "message": error_body}))+ sys.exit(1)+ except urllib.error.URLError as e:+ print(json.dumps({"error": True, "message": str(e.reason)}))+ sys.exit(1)++ # Extract image from response+ candidates = result.get("candidates", [])+ if not candidates:+ finish_reason = result.get("promptFeedback", {}).get("blockReason", "UNKNOWN")+ print(json.dumps({"error": True, "message": f"No candidates returned. Reason: {finish_reason}"}))+ sys.exit(1)++ parts = candidates[0].get("content", {}).get("parts", [])+ image_data = None+ text_response = ""++ for part in parts:+ if "inlineData" in part:+ image_data = part["inlineData"]["data"]+ elif "text" in part:+ text_response = part["text"]++ if not image_data:+ finish_reason = candidates[0].get("finishReason", "UNKNOWN")+ print(json.dumps({"error": True, "message": f"No image in response. finishReason: {finish_reason}"}))+ sys.exit(1)++ # Save image+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")+ filename = f"banana_edit_{timestamp}.png"+ output_path = (OUTPUT_DIR / filename).resolve()++ with open(output_path, "wb") as f:+ f.write(base64.b64decode(image_data))++ return {+ "path": str(output_path),+ "model": model,+ "source": str(image_path),+ "text": text_response,+ }+++def main():+ parser = argparse.ArgumentParser(description="Edit images via Gemini REST API")+ parser.add_argument("--image", required=True, help="Path to input image")+ parser.add_argument("--prompt", required=True, help="Edit instruction")+ parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})")+ parser.add_argument("--api-key", default=None, help="Google AI API key (or set GOOGLE_AI_API_KEY env)")++ args = parser.parse_args()++ api_key = args.api_key or os.environ.get("GOOGLE_AI_API_KEY") or os.environ.get("GOOGLE_API_KEY")+ if not api_key:+ print(json.dumps({"error": True, "message": "No API key. Set GOOGLE_AI_API_KEY env or pass --api-key"}))+ sys.exit(1)++ result = edit_image(+ image_path=args.image,+ prompt=args.prompt,+ model=args.model,+ api_key=api_key,+ )+ print(json.dumps(result, indent=2))+++if __name__ == "__main__":+ main()diff --git a/extensions/banana/scripts/generate.py b/extensions/banana/scripts/generate.pynew file mode 100755index 0000000..aa19a73--- /dev/null+++ b/extensions/banana/scripts/generate.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""Claude Banana — Direct API Fallback: Image Generation++Generate images via Gemini REST API when MCP is unavailable.+Uses only Python stdlib (no pip dependencies).++Usage:+ generate.py --prompt "a cat in space" [--aspect-ratio 16:9] [--resolution 1K]+ [--model MODEL] [--api-key KEY] [--thinking LEVEL] [--image-only]+"""++import argparse+import base64+import json+import os+import sys+import urllib.request+from datetime import datetime+from pathlib import Path++DEFAULT_MODEL = "gemini-3.1-flash-image-preview"+DEFAULT_RESOLUTION = "1K"+DEFAULT_RATIO = "1:1"+OUTPUT_DIR = Path.home() / "Documents" / "nanobanana_generated"+API_BASE = "https://generativelanguage.googleapis.com/v1beta/models"++VALID_RATIOS = {"1:1", "16:9", "9:16", "4:3", "3:4", "2:3", "3:2",+ "4:5", "5:4", "1:4", "4:1", "1:8", "8:1", "21:9"}+VALID_RESOLUTIONS = {"512", "1K", "2K", "4K"}+++def generate_image(prompt, model, aspect_ratio, resolution, api_key,+ thinking_level=None, image_only=False):+ """Call Gemini API to generate an image."""+ url = f"{API_BASE}/{model}:generateContent?key={api_key}"++ modalities = ["IMAGE"] if image_only else ["TEXT", "IMAGE"]+ body = {+ "contents": [{"parts": [{"text": prompt}]}],+ "generationConfig": {+ "responseModalities": modalities,+ "imageConfig": {+ "aspectRatio": aspect_ratio,+ "imageSize": resolution,+ },+ },+ }++ if thinking_level:+ body["generationConfig"]["thinkingConfig"] = {"thinkingLevel": thinking_level}++ data = json.dumps(body).encode("utf-8")+ req = urllib.request.Request(+ url,+ data=data,+ headers={"Content-Type": "application/json"},+ method="POST",+ )++ try:+ with urllib.request.urlopen(req, timeout=120) as resp:+ result = json.loads(resp.read().decode("utf-8"))+ except urllib.error.HTTPError as e:+ error_body = e.read().decode("utf-8") if e.fp else ""+ print(json.dumps({"error": True, "status": e.code, "message": error_body}))+ sys.exit(1)+ except urllib.error.URLError as e:+ print(json.dumps({"error": True, "message": str(e.reason)}))+ sys.exit(1)++ # Extract image from response+ candidates = result.get("candidates", [])+ if not candidates:+ finish_reason = result.get("promptFeedback", {}).get("blockReason", "UNKNOWN")+ print(json.dumps({"error": True, "message": f"No candidates returned. Reason: {finish_reason}"}))+ sys.exit(1)++ parts = candidates[0].get("content", {}).get("parts", [])+ image_data = None+ text_response = ""++ for part in parts:+ if "inlineData" in part:+ image_data = part["inlineData"]["data"]+ elif "text" in part:+ text_response = part["text"]++ if not image_data:+ finish_reason = candidates[0].get("finishReason", "UNKNOWN")+ print(json.dumps({"error": True, "message": f"No image in response. finishReason: {finish_reason}"}))+ sys.exit(1)++ # Save image+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")+ filename = f"banana_{timestamp}.png"+ output_path = (OUTPUT_DIR / filename).resolve()++ with open(output_path, "wb") as f:+ f.write(base64.b64decode(image_data))++ return {+ "path": str(output_path),+ "model": model,+ "aspect_ratio": aspect_ratio,+ "resolution": resolution,+ "text": text_response,+ }+++def main():+ parser = argparse.ArgumentParser(description="Generate images via Gemini REST API")+ parser.add_argument("--prompt", required=True, help="Image generation prompt")+ parser.add_argument("--aspect-ratio", default=DEFAULT_RATIO, help=f"Aspect ratio (default: {DEFAULT_RATIO})")+ parser.add_argument("--resolution", default=DEFAULT_RESOLUTION, help=f"Resolution: 512, 1K, 2K, 4K (default: {DEFAULT_RESOLUTION})")+ parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})")+ parser.add_argument("--api-key", default=None, help="Google AI API key (or set GOOGLE_AI_API_KEY env)")+ parser.add_argument("--thinking", default=None, choices=["minimal", "low", "medium", "high"], help="Thinking level")+ parser.add_argument("--image-only", action="store_true", help="Return image only (no text)")++ args = parser.parse_args()++ if args.aspect_ratio not in VALID_RATIOS:+ print(json.dumps({"error": True, "message": f"Invalid aspect ratio '{args.aspect_ratio}'. Valid: {sorted(VALID_RATIOS)}"}))+ sys.exit(1)++ if args.resolution not in VALID_RESOLUTIONS:+ print(json.dumps({"error": True, "message": f"Invalid resolution '{args.resolution}'. Valid: {sorted(VALID_RESOLUTIONS)}"}))+ sys.exit(1)++ api_key = args.api_key or os.environ.get("GOOGLE_AI_API_KEY") or os.environ.get("GOOGLE_API_KEY")+ if not api_key:+ print(json.dumps({"error": True, "message": "No API key. Set GOOGLE_AI_API_KEY env or pass --api-key"}))+ sys.exit(1)++ result = generate_image(+ prompt=args.prompt,+ model=args.model,+ aspect_ratio=args.aspect_ratio,+ resolution=args.resolution,+ api_key=api_key,+ thinking_level=args.thinking,+ image_only=args.image_only,+ )+ print(json.dumps(result, indent=2))+++if __name__ == "__main__":+ main()diff --git a/extensions/banana/scripts/presets.py b/extensions/banana/scripts/presets.pynew file mode 100755index 0000000..7daffad--- /dev/null+++ b/extensions/banana/scripts/presets.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""Claude Banana — Brand/Style Presets++Manage reusable brand and style presets for consistent image generation.++Usage:+ presets.py list+ presets.py show NAME+ presets.py create NAME --colors "#hex,#hex" --style "..." [options]+ presets.py delete NAME --confirm+"""++import argparse+import json+import re+import sys+from pathlib import Path++PRESETS_DIR = Path.home() / ".banana" / "presets"+++def _ensure_dir():+ """Ensure presets directory exists."""+ PRESETS_DIR.mkdir(parents=True, exist_ok=True)+++def _sanitize_name(name):+ """Sanitize preset name to prevent path traversal."""+ # Strip path separators and keep only safe characters+ safe = re.sub(r'[^a-zA-Z0-9_\-]', '', name)+ if not safe:+ print("Error: Preset name must contain only letters, numbers, hyphens, and underscores.", file=sys.stderr)+ sys.exit(1)+ return safe+++def _preset_path(name):+ """Get path for a preset file."""+ safe_name = _sanitize_name(name)+ return PRESETS_DIR / f"{safe_name}.json"+++def _load_preset(name):+ """Load a preset by name."""+ path = _preset_path(name)+ if not path.exists():+ print(f"Error: Preset '{name}' not found.", file=sys.stderr)+ sys.exit(1)+ with open(path, "r") as f:+ return json.load(f)+++def cmd_list(args):+ """List available presets."""+ _ensure_dir()+ presets = sorted(PRESETS_DIR.glob("*.json"))+ if not presets:+ print("No presets found. Create one with: presets.py create NAME --style \"...\"")+ return+ print(f"Available presets ({len(presets)}):\n")+ for p in presets:+ try:+ with open(p, "r") as f:+ data = json.load(f)+ desc = data.get("description", "No description")+ print(f" {p.stem:20s} — {desc}")+ except (json.JSONDecodeError, KeyError):+ print(f" {p.stem:20s} — (invalid preset file)")+++def cmd_show(args):+ """Show full preset details."""+ preset = _load_preset(args.name)+ print(json.dumps(preset, indent=2))+++def cmd_create(args):+ """Create a new preset."""+ _ensure_dir()+ path = _preset_path(args.name)+ if path.exists():+ print(f"Error: Preset '{args.name}' already exists. Use a different name.", file=sys.stderr)+ sys.exit(1)++ colors = [c.strip() for c in args.colors.split(",")] if args.colors else []++ preset = {+ "name": args.name,+ "description": args.description or f"Custom preset: {args.name}",+ "colors": colors,+ "style": args.style or "",+ "typography": args.typography or "",+ "lighting": args.lighting or "",+ "mood": args.mood or "",+ "default_ratio": args.ratio or "16:9",+ "default_resolution": args.resolution or "2K",+ }++ with open(path, "w") as f:+ json.dump(preset, f, indent=2)++ print(f"Preset '{args.name}' created at {path}")+ print(json.dumps(preset, indent=2))+++def cmd_delete(args):+ """Delete a preset."""+ if not args.confirm:+ print("Error: Pass --confirm to delete the preset.", file=sys.stderr)+ sys.exit(1)+ path = _preset_path(args.name)+ if not path.exists():+ print(f"Error: Preset '{args.name}' not found.", file=sys.stderr)+ sys.exit(1)+ path.unlink()+ print(f"Preset '{args.name}' deleted.")+++def main():+ parser = argparse.ArgumentParser(description="Claude Banana Brand/Style Presets")+ sub = parser.add_subparsers(dest="command", required=True)++ # list+ sub.add_parser("list", help="List available presets")++ # show+ p_show = sub.add_parser("show", help="Show preset details")+ p_show.add_argument("name", help="Preset name")++ # create+ p_create = sub.add_parser("create", help="Create a new preset")+ p_create.add_argument("name", help="Preset name (e.g., tech-saas, luxury-brand)")+ p_create.add_argument("--colors", default="", help="Comma-separated hex colors")+ p_create.add_argument("--style", default="", help="Visual style description")+ p_create.add_argument("--typography", default="", help="Typography description")+ p_create.add_argument("--lighting", default="", help="Lighting description")+ p_create.add_argument("--mood", default="", help="Mood/emotion description")+ p_create.add_argument("--description", default="", help="Brief preset description")+ p_create.add_argument("--ratio", default="16:9", help="Default aspect ratio")+ p_create.add_argument("--resolution", default="2K", help="Default resolution")++ # delete+ p_delete = sub.add_parser("delete", help="Delete a preset")+ p_delete.add_argument("name", help="Preset name")+ p_delete.add_argument("--confirm", action="store_true", help="Confirm deletion")++ args = parser.parse_args()+ cmds = {"list": cmd_list, "show": cmd_show, "create": cmd_create, "delete": cmd_delete}+ cmds[args.command](args)+++if __name__ == "__main__":+ main()diff --git a/extensions/banana/scripts/setup_mcp.py b/extensions/banana/scripts/setup_mcp.pynew file mode 100755index 0000000..f685a4a--- /dev/null+++ b/extensions/banana/scripts/setup_mcp.py@@ -0,0 +1,151 @@+#!/usr/bin/env python3+"""+Setup script for Claude Banana MCP server in Claude Code.++Configures @ycse/nanobanana-mcp in Claude Code's settings.json+with the user's Google AI API key.++Usage:+ python3 setup_mcp.py # Interactive (prompts for key)+ python3 setup_mcp.py --key YOUR_KEY # Non-interactive+ python3 setup_mcp.py --check # Verify existing setup+ python3 setup_mcp.py --remove # Remove MCP config+ python3 setup_mcp.py --help # Show usage+"""++import json+import sys+import os+from pathlib import Path++SETTINGS_PATH = Path.home() / ".claude" / "settings.json"+MCP_NAME = "nanobanana-mcp"+MCP_PACKAGE = "@ycse/nanobanana-mcp"+DEFAULT_MODEL = "gemini-3.1-flash-image-preview"+++def load_settings() -> dict:+ """Load Claude Code settings.json."""+ if not SETTINGS_PATH.exists():+ return {}+ with open(SETTINGS_PATH, "r") as f:+ return json.load(f)+++def save_settings(settings: dict) -> None:+ """Save Claude Code settings.json."""+ SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)+ with open(SETTINGS_PATH, "w") as f:+ json.dump(settings, f, indent=2)+ print(f"Settings saved to {SETTINGS_PATH}")+++def check_setup() -> bool:+ """Check if MCP is already configured."""+ settings = load_settings()+ servers = settings.get("mcpServers", {})+ if MCP_NAME in servers:+ env = servers[MCP_NAME].get("env", {})+ key = env.get("GOOGLE_AI_API_KEY", "")+ masked = key[:8] + "..." + key[-4:] if len(key) > 12 else "(not set)"+ print(f"MCP server '{MCP_NAME}' is configured.")+ print(f" Package: {MCP_PACKAGE}")+ print(f" API Key: {masked}")+ print(f" Model: {env.get('NANOBANANA_MODEL', DEFAULT_MODEL)}")+ return True+ print(f"MCP server '{MCP_NAME}' is NOT configured.")+ return False+++def remove_mcp() -> None:+ """Remove MCP configuration."""+ settings = load_settings()+ servers = settings.get("mcpServers", {})+ if MCP_NAME in servers:+ del servers[MCP_NAME]+ settings["mcpServers"] = servers+ save_settings(settings)+ print(f"Removed '{MCP_NAME}' from Claude Code settings.")+ else:+ print(f"'{MCP_NAME}' not found in settings.")+++def setup_mcp(api_key: str) -> None:+ """Configure MCP server in Claude Code settings."""+ if not api_key or not api_key.strip():+ print("Error: API key cannot be empty.")+ sys.exit(1)++ api_key = api_key.strip()+ settings = load_settings()++ if "mcpServers" not in settings:+ settings["mcpServers"] = {}++ settings["mcpServers"][MCP_NAME] = {+ "command": "npx",+ "args": ["-y", MCP_PACKAGE],+ "env": {+ "GOOGLE_AI_API_KEY": api_key,+ "NANOBANANA_MODEL": DEFAULT_MODEL,+ },+ }++ save_settings(settings)+ print(f"\nMCP server '{MCP_NAME}' configured successfully!")+ print(f" Package: {MCP_PACKAGE}")+ print(f" Model: {DEFAULT_MODEL}")+ print(f"\nRestart Claude Code for changes to take effect.")+ print(f"Generated images will be saved to: ~/Documents/nanobanana_generated/")+++def main() -> None:+ args = sys.argv[1:]++ if "--help" in args or "-h" in args:+ print("Usage: python3 setup_mcp.py [OPTIONS]")+ print()+ print("Options:")+ print(" --key KEY Provide API key non-interactively")+ print(" --check Verify existing setup")+ print(" --remove Remove MCP configuration")+ print(" --help, -h Show this help message")+ print()+ print("Get a free API key at: https://aistudio.google.com/apikey")+ sys.exit(0)++ if "--check" in args:+ check_setup()+ return++ if "--remove" in args:+ remove_mcp()+ return++ # Get API key+ api_key = None+ for i, arg in enumerate(args):+ if arg == "--key" and i + 1 < len(args):+ api_key = args[i + 1]+ break++ if not api_key:+ # Check environment+ api_key = os.environ.get("GOOGLE_AI_API_KEY")++ if not api_key:+ print("Claude Banana — MCP Setup")+ print("=" * 40)+ print(f"\nGet your free API key at: https://aistudio.google.com/apikey")+ print()+ try:+ api_key = input("Enter your Google AI API key: ")+ except (EOFError, KeyboardInterrupt):+ print("\nError: No input received. Provide a key with --key or set GOOGLE_AI_API_KEY env var.")+ sys.exit(1)++ setup_mcp(api_key)+++if __name__ == "__main__":+ main()diff --git a/extensions/banana/scripts/validate_setup.py b/extensions/banana/scripts/validate_setup.pynew file mode 100755index 0000000..173e6cb--- /dev/null+++ b/extensions/banana/scripts/validate_setup.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""+Validate that the Claude Banana MCP server is properly configured.++Checks:+1. Claude Code settings.json has the MCP entry+2. API key is present+3. Node.js/npx is available+4. Output directory exists or can be created++Usage:+ python3 validate_setup.py+"""++import json+import shutil+import sys+from pathlib import Path++SETTINGS_PATH = Path.home() / ".claude" / "settings.json"+MCP_NAME = "nanobanana-mcp"+OUTPUT_DIR = Path.home() / "Documents" / "nanobanana_generated"+++def check(label: str, passed: bool, detail: str = "") -> bool:+ status = "PASS" if passed else "FAIL"+ msg = f" [{status}] {label}"+ if detail:+ msg += f" — {detail}"+ print(msg)+ return passed+++def main() -> int:+ print("Claude Banana — Setup Validation")+ print("=" * 40)+ results = []++ # 1. Settings file exists+ results.append(check(+ "Claude Code settings.json exists",+ SETTINGS_PATH.exists(),+ str(SETTINGS_PATH),+ ))++ if not SETTINGS_PATH.exists():+ print("\nCannot continue without settings.json.")+ return 1++ # 2. Load and parse settings+ try:+ with open(SETTINGS_PATH) as f:+ settings = json.load(f)+ results.append(check("settings.json is valid JSON", True))+ except json.JSONDecodeError as e:+ results.append(check("settings.json is valid JSON", False, str(e)))+ return 1++ # 3. MCP entry exists+ servers = settings.get("mcpServers", {})+ has_mcp = MCP_NAME in servers+ results.append(check(f"MCP server '{MCP_NAME}' configured", has_mcp))++ if has_mcp:+ mcp = servers[MCP_NAME]++ # 4. Command is npx+ results.append(check(+ "Command is 'npx'",+ mcp.get("command") == "npx",+ mcp.get("command", "(missing)"),+ ))++ # 5. Package is correct+ args = mcp.get("args", [])+ has_pkg = "@ycse/nanobanana-mcp" in args+ results.append(check(+ "Package is @ycse/nanobanana-mcp",+ has_pkg,+ str(args),+ ))++ # 6. API key present+ env = mcp.get("env", {})+ key = env.get("GOOGLE_AI_API_KEY", "")+ results.append(check(+ "GOOGLE_AI_API_KEY is set",+ bool(key),+ f"{key[:8]}...{key[-4:]}" if len(key) > 12 else "(empty or short)",+ ))++ # 7. Model configured+ model = env.get("NANOBANANA_MODEL", "")+ results.append(check(+ "NANOBANANA_MODEL is set",+ bool(model),+ model or "(not set, will use package default)",+ ))++ # 8. Node.js/npx available+ has_npx = shutil.which("npx") is not None+ results.append(check(+ "npx is available in PATH",+ has_npx,+ shutil.which("npx") or "not found",+ ))++ # 9. Output directory+ if OUTPUT_DIR.exists():+ results.append(check("Output directory exists", True, str(OUTPUT_DIR)))+ else:+ try:+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)+ results.append(check("Output directory created", True, str(OUTPUT_DIR)))+ except OSError as e:+ results.append(check("Output directory writable", False, str(e)))++ # Summary+ passed = sum(1 for r in results if r)+ total = len(results)+ print(f"\n{'=' * 40}")+ print(f"Results: {passed}/{total} checks passed")++ if passed == total:+ print("Status: Ready to generate images!")+ return 0+ else:+ print("Status: Some checks failed. Fix the issues above.")+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/extensions/banana/skills/seo-image-gen/SKILL.md b/extensions/banana/skills/seo-image-gen/SKILL.mdnew file mode 100644index 0000000..6e14118--- /dev/null+++ b/extensions/banana/skills/seo-image-gen/SKILL.md@@ -0,0 +1,166 @@+---+name: seo-image-gen+description: "AI image generation for SEO assets — OG/social preview images, blog hero images, schema images, product photography, infographics. Powered by Gemini via nanobanana-mcp. Requires banana extension installed. Use when user says \"generate image\", \"OG image\", \"social preview\", \"hero image\", \"blog image\", \"product photo\", \"infographic\", \"seo image\", \"create visual\", \"image-gen\", \"favicon\", \"schema image\", \"pinterest pin\", \"generate visual\", \"banner\", or \"thumbnail\"."+argument-hint: "[og|hero|product|infographic|custom|batch] <description>"+---++# SEO Image Gen — AI Image Generation for SEO Assets (Extension)++Generate production-ready images for SEO use cases using Gemini's image generation+via the banana Creative Director pipeline. Maps SEO needs to optimized domain modes,+aspect ratios, and resolution defaults.++## Architecture Note++This skill has two components with distinct roles:+- **SKILL.md** (this file) — Handles interactive `/seo image-gen` commands for generating images+- **Agent** (`agents/seo-image-gen.md`) — Audit-only analyst spawned during `/seo audit` to assess existing OG/social images and produce a generation plan (never auto-generates)++## Prerequisites++This skill requires the banana extension to be installed:+```bash+./extensions/banana/install.sh+```++**Check availability:** Before using any image generation tool, verify the MCP server+is connected by checking if `gemini_generate_image` or `set_aspect_ratio` tools are+available. If tools are not available, inform the user the extension is not installed+and provide install instructions.++## Quick Reference++| Command | What it does |+|---------|-------------|+| `/seo image-gen og <description>` | Generate OG/social preview image (1200x630 feel) |+| `/seo image-gen hero <description>` | Blog hero image (widescreen, dramatic) |+| `/seo image-gen product <description>` | Product photography (clean, white BG) |+| `/seo image-gen infographic <description>` | Infographic visual (vertical, data-heavy) |+| `/seo image-gen custom <description>` | Custom image with full Creative Director pipeline |+| `/seo image-gen batch <description> [N]` | Generate N variations (default: 3) |++## SEO Image Use Cases++Each use case maps to pre-configured banana parameters:++| Use Case | Aspect Ratio | Resolution | Domain Mode | Notes |+|----------|-------------|------------|-------------|-------|+| **OG/Social Preview** | `16:9` | `1K` | Product or UI/Web | Clean, professional, text-friendly |+| **Blog Hero** | `16:9` | `2K` | Cinema or Editorial | Dramatic, atmospheric, editorial quality |+| **Schema Image** | `4:3` | `1K` | Product | Clean, descriptive, schema ImageObject |+| **Social Square** | `1:1` | `1K` | UI/Web | Platform-optimized square |+| **Product Photo** | `4:3` | `2K` | Product | White background, studio lighting |+| **Infographic** | `2:3` | `4K` | Infographic | Data-heavy, vertical layout |+| **Favicon/Icon** | `1:1` | `512` | Logo | Minimal, scalable, recognizable |+| **Pinterest Pin** | `2:3` | `2K` | Editorial | Tall vertical card |++## Generation Pipeline++For every generation request:++1. **Identify use case** from command or context (og, hero, product, etc.)+2. **Apply SEO defaults** from the use cases table above+3. **Set aspect ratio** via `set_aspect_ratio` MCP tool+4. **Construct Reasoning Brief** using the banana Creative Director pipeline:+ - Load `references/prompt-engineering.md` for the 6-component system+ - Apply domain mode emphasis (Subject 30%, Style 25%, Context 15%, etc.)+ - Be SPECIFIC and VISCERAL — describe what the camera sees+5. **Generate** via `gemini_generate_image` MCP tool+6. **Post-generation SEO checklist** (see below)++### Check for Presets++If the user mentions a brand or has SEO presets configured:+```bash+python3 ~/.claude/skills/seo-image-gen/scripts/presets.py list+```+Load matching preset and apply as defaults. Also check `references/seo-image-presets.md`+for SEO-specific preset templates.++## Post-Generation SEO Checklist++After every successful generation, guide the user on:++1. **Alt text** — Write descriptive, keyword-rich alt text for the generated image+2. **File naming** — Rename to SEO-friendly format: `keyword-description-widthxheight.webp`+3. **WebP conversion** — Convert to WebP for optimal page speed:+ ```bash+ magick output.png -quality 85 output.webp+ ```+4. **File size** — Target under 200KB for hero images, under 100KB for thumbnails+5. **Schema markup** — Suggest `ImageObject` schema for the generated image:+ ```json+ {+ "@type": "ImageObject",+ "url": "https://example.com/images/keyword-description.webp",+ "width": 1200,+ "height": 630,+ "caption": "Descriptive caption with target keyword"+ }+ ```+6. **OG meta tags** — For social preview images, remind about:+ ```html+ <meta property="og:image" content="https://example.com/images/og-image.webp" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Descriptive alt text" />+ ```++## Cost Awareness++Image generation costs money. Be transparent:+- Show estimated cost before generating (especially for batch)+- Log every generation: `python3 ~/.claude/skills/seo-image-gen/scripts/cost_tracker.py log --model MODEL --resolution RES --prompt "brief"`+- Run `cost_tracker.py summary` if user asks about usage++Approximate costs (gemini-3.1-flash):+- 512: ~$0.02/image+- 1K resolution: ~$0.04/image+- 2K resolution: ~$0.08/image+- 4K resolution: ~$0.16/image++## Model Routing++| Scenario | Model | Why |+|----------|-------|-----|+| OG images, social previews | `gemini-3.1-flash-image-preview` @ 1K | Fast, cost-effective |+| Hero images, product photos | `gemini-3.1-flash-image-preview` @ 2K | Quality + detail |+| Infographics with text | `gemini-3.1-flash-image-preview` @ 2K, thinking: high | Better text rendering |+| Quick drafts | `gemini-2.5-flash-image` @ 512 | Rapid iteration |++## Error Handling++| Error | Resolution |+|-------|-----------|+| MCP not configured | Run `./extensions/banana/install.sh` |+| API key invalid | New key at https://aistudio.google.com/apikey |+| Rate limited (429) | Wait 60s, retry. Free tier: ~10 RPM / ~500 RPD |+| `IMAGE_SAFETY` | Rephrase prompt — see `references/prompt-engineering.md` Safety section |+| MCP unavailable | Fall back: `python3 ~/.claude/skills/seo-image-gen/scripts/generate.py --prompt "..." --aspect-ratio "16:9"` |+| Extension not installed | Show install instructions: `./extensions/banana/install.sh` |++## Cross-Skill Integration++- **seo-images** (analysis) feeds into **seo-image-gen** (generation): audit results from `/seo images` identify missing or low-quality images; use those findings to drive `/seo image-gen` commands+- **seo-audit** spawns the seo-image-gen **agent** (not this skill) to analyze OG/social images across the site and produce a prioritized generation plan+- **seo-schema** can consume generated images: after generation, suggest `ImageObject` schema markup pointing to the new assets++## Reference Documentation++Load on-demand — do NOT load all at startup:+- `references/prompt-engineering.md` — 6-component system, domain modes, templates+- `references/gemini-models.md` — Model specs, rate limits, capabilities+- `references/mcp-tools.md` — MCP tool parameters and responses+- `references/post-processing.md` — ImageMagick/FFmpeg pipeline recipes+- `references/cost-tracking.md` — Pricing, usage tracking+- `references/presets.md` — Brand preset management+- `references/seo-image-presets.md` — SEO-specific preset templates++## Response Format++After generating, always provide:+1. **Image path** — where it was saved+2. **Crafted prompt** — show what was sent to the API (educational)+3. **Settings** — model, aspect ratio, resolution+4. **SEO checklist** — alt text suggestion, file naming, WebP conversion+5. **Schema snippet** — ImageObject or og:image markup if applicablediff --git a/extensions/banana/uninstall.sh b/extensions/banana/uninstall.shnew file mode 100755index 0000000..d036bde--- /dev/null+++ b/extensions/banana/uninstall.sh@@ -0,0 +1,43 @@+#!/usr/bin/env bash+set -euo pipefail++main() {+ echo "→ Uninstalling Banana Image Generation extension..."++ # Remove skill (includes copied scripts and references)+ rm -rf "${HOME}/.claude/skills/seo-image-gen"++ # Remove agent+ rm -f "${HOME}/.claude/agents/seo-image-gen.md"++ # Ask before removing MCP server (user may use standalone banana skill)+ SETTINGS_FILE="${HOME}/.claude/settings.json"+ if [ -f "${SETTINGS_FILE}" ]; then+ # Check if standalone banana skill still exists+ if [ -d "${HOME}/.claude/skills/banana" ]; then+ echo " ℹ Standalone banana skill detected at ~/.claude/skills/banana/"+ echo " ℹ Keeping nanobanana-mcp in settings.json (used by standalone skill)"+ else+ # No standalone skill, safe to remove MCP+ python3 -c "+import json, os+settings_path = '${SETTINGS_FILE}'+with open(settings_path, 'r') as f:+ settings = json.load(f)+if 'mcpServers' in settings and 'nanobanana-mcp' in settings['mcpServers']:+ del settings['mcpServers']['nanobanana-mcp']+ if not settings['mcpServers']:+ del settings['mcpServers']+ with open(settings_path, 'w') as f:+ json.dump(settings, f, indent=2)+ print(' ✓ Removed nanobanana-mcp from settings.json')+else:+ print(' ✓ No nanobanana-mcp entry in settings.json')+" 2>/dev/null || echo " ⚠ Could not auto-remove MCP config. Remove 'nanobanana-mcp' from ~/.claude/settings.json manually."+ fi+ fi++ echo "✓ Banana Image Generation extension uninstalled."+}++main "$@"diff --git a/seo/SKILL.md b/seo/SKILL.mdindex 76db4c5..c5aaf3c 100644--- a/seo/SKILL.md+++ b/seo/SKILL.md@@ -37,6 +37,7 @@ e-commerce, publishers, agencies). Orchestrates 12 specialized sub-skills and 7| `/seo competitor-pages [url\|generate]` | Competitor comparison page generation || `/seo hreflang [url]` | Hreflang/i18n SEO audit and generation || `/seo dataforseo [command]` | Live SEO data via DataForSEO (extension) |+| `/seo image-gen [use-case] <description>` | AI image generation for SEO assets (extension) |## Orchestration Logic@@ -98,7 +99,7 @@ Weighted aggregate of all categories:## Sub-Skills-This skill orchestrates 12 specialized sub-skills (+ 1 extension):+This skill orchestrates 12 specialized sub-skills (+ 2 extensions):1. **seo-audit** — Full website audit with parallel delegation2. **seo-page** — Deep single-page analysis@@ -113,6 +114,7 @@ This skill orchestrates 12 specialized sub-skills (+ 1 extension):11. **seo-competitor-pages** — Competitor comparison page generation12. **seo-hreflang** — Hreflang/i18n SEO audit and generation13. **seo-dataforseo** — Live SEO data via DataForSEO MCP (extension)+14. **seo-image-gen** — AI image generation for SEO assets via Gemini (extension)## Subagents@@ -125,3 +127,4 @@ For parallel analysis during audits:- `seo-visual` — Screenshots, mobile testing, above-fold- `seo-geo` — AI crawler access, llms.txt, citability, brand mention signals- `seo-dataforseo` — Live SERP, keyword, backlink, local SEO data (extension, optional)+- `seo-image-gen` — SEO image audit and generation plan (extension, optional)