Files
lucioandClaude Fable 5 472c983287 Commit build outputs via LFS; right-click markers, inline edit box, panel pin
Make a fresh clone servable after `git lfs pull` alone, and rebuildable with
`tools/build.py` without re-rendering unchanged PSDs:

- Track build/ (rendered base PNGs, previews, world composites), web/tiles/,
  web/tiles-trimmed/, web/data/world.json and web/data/markers/. Large PNGs
  and the tile pyramids go through Git LFS (.gitattributes); JSON stays plain.
- build.py: decide PSD re-export from build/<id>/base.stamp.json (PSD size,
  mtime, SHA-256 recorded at export time) instead of file mtimes, which are
  meaningless after an LFS checkout. Same size + new mtime hashes once and
  refreshes the stamp; --stamp-only writes stamps for existing base.pngs.
- Ignore .DS_Store and .env files; track sources/**/*.jpg through LFS.

Viewer:
- Right-click (long-press) the map for a category menu that drops a draft
  marker under the pointer and enters marker edit mode for that map.
- Marker editing moves out of the side panel into a box anchored next to the
  marker: Enter or a left click anywhere else saves, Esc cancels, Delete
  inside the box; drags save position plus the box contents.
- Maps panel expands on hover, header click pins/unpins (status shown in the
  header), unpinned collapses 2 s after the pointer leaves; Overview is the
  first list entry instead of a separate button. Only the panel scrolls; the
  page never grows past the viewport. Hover tooltips render above markers.

Also includes the pending source additions (overall square base, skirt
textures, AI regeneration tooling and notes), service worker, Caddyfile and
map config updates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-22 09:46:02 -07:00

126 lines
4.2 KiB
Python

"""Gemini AI Image API client wrapper for text-to-image and image-to-image editing.
Usage:
from tools.ai.gemini import edit_image, generate
img = generate("Top-down satellite terrain...")
edited = edit_image([crop_img, mask_img], "Outpaint the transparent regions...")
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import Sequence
from PIL import Image
try:
from google import genai
from google.genai import types
except ImportError:
genai = None
types = None
# Must be an image-output model. Override with GEMINI_IMAGE_MODEL; list what your
# key can reach with: python -c "from tools.ai.gemini import get_client; \
# print([m.name for m in get_client().models.list() if 'image' in m.name])"
DEFAULT_MODEL = os.environ.get("GEMINI_IMAGE_MODEL", "gemini-3.1-flash-image")
def _load_env_key() -> str | None:
"""Load GEMINI_API_KEY or GOOGLE_API_KEY from environment or .env file."""
key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
if key:
return key
# Look for .env in project root
root = Path(__file__).resolve().parent.parent.parent
env_file = root / ".env"
if env_file.exists():
for line in env_file.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k, v = k.strip(), v.strip().strip('"\'')
if k in ("GEMINI_API_KEY", "GOOGLE_API_KEY") and v:
os.environ[k] = v
return v
return None
def get_client(api_key: str | None = None) -> genai.Client:
"""Return an initialized google-genai Client."""
if genai is None:
raise ImportError(
"google-genai is not installed. Install with: pip install -r tools/requirements-ai.txt"
)
key = api_key or _load_env_key()
if not key:
raise ValueError(
"No Gemini API key found. Set GEMINI_API_KEY or GOOGLE_API_KEY in environment or .env file."
)
return genai.Client(api_key=key)
def _extract_image(response) -> Image.Image:
"""Extract the first PIL Image part from a GenerateContentResponse."""
for candidate in getattr(response, "candidates", []):
content = getattr(candidate, "content", None)
if not content:
continue
for part in getattr(content, "parts", []):
if hasattr(part, "inline_data") and part.inline_data is not None:
if hasattr(part, "as_image"):
return part.as_image()
import io
return Image.open(io.BytesIO(part.inline_data.data))
for part in getattr(response, "parts", []):
if hasattr(part, "inline_data") and part.inline_data is not None:
if hasattr(part, "as_image"):
return part.as_image()
import io
return Image.open(io.BytesIO(part.inline_data.data))
raise RuntimeError("No image found in Gemini response.")
def generate(
prompt: str,
*,
model: str = DEFAULT_MODEL,
seed: int | None = None,
client: genai.Client | None = None,
) -> Image.Image:
"""Generate an image from a text prompt."""
cli = client or get_client()
config = types.GenerateContentConfig(seed=seed) if seed is not None and types else None
kwargs = {"config": config} if config else {}
response = cli.models.generate_content(
model=model,
contents=[prompt],
**kwargs,
)
return _extract_image(response)
def edit_image(
images: Sequence[Image.Image],
prompt: str,
*,
model: str = DEFAULT_MODEL,
seed: int | None = None,
client: genai.Client | None = None,
) -> Image.Image:
"""Perform image-to-image generation / editing with input images and prompt."""
cli = client or get_client()
contents: list[types.Part | Image.Image | str] = list(images) + [prompt]
config = types.GenerateContentConfig(seed=seed) if seed is not None and types else None
kwargs = {"config": config} if config else {}
response = cli.models.generate_content(
model=model,
contents=contents,
**kwargs,
)
return _extract_image(response)