mirror of
https://github.com/nextlevelbuilder/ui-ux-pro-max-skill.git
synced 2026-11-19 09:00:32 +00:00
fix(design): image extensions, failure exit status and --pro model id (#532)
The logo and CIP scripts wrote whatever image Gemini returned under a .png name. Nano Banana Pro returns JPEG, so --pro produced JPEG files named .png. Both now take the extension from inline_data.mime_type, and logo prints the path it actually wrote. Nothing is re-encoded. The logo, CIP and icon scripts printed an error and exited 0 when a request failed. They now exit 1 when nothing was generated: a failed single request, or a batch, set or size set where every item failed. A partial batch exits 0, since its summary already reports n/m. --pro used gemini-3-pro-image-preview, which is past its listed shutdown date. It now uses gemini-3-pro-image, and the model ids can be overridden with GEMINI_FLASH_IMAGE_MODEL and GEMINI_PRO_IMAGE_MODEL. Fixes #529 Co-authored-by: Jul11us <233702296+Jul11us@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7246805992
commit
616663179c
@ -111,7 +111,7 @@ python3 scripts/cip/generate.py --brand "TopGroup" --logo logo.png --deliverable
|
||||
python3 scripts/cip/generate.py --brand "TechFlow" --deliverable "business card" --no-logo-prompt
|
||||
```
|
||||
|
||||
Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image-preview`)
|
||||
Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image`). Override the ids with `GEMINI_FLASH_IMAGE_MODEL` / `GEMINI_PRO_IMAGE_MODEL`.
|
||||
|
||||
### CIP: Render HTML Presentation
|
||||
|
||||
|
||||
@ -64,7 +64,9 @@ python3 scripts/cip/render-html.py --brand "TopGroup" --industry "consulting" --
|
||||
## Models
|
||||
|
||||
- `flash` (default): `gemini-2.5-flash-image` - Fast, cost-effective
|
||||
- `pro`: `gemini-3-pro-image-preview` - Quality, 4K text rendering
|
||||
- `pro`: `gemini-3-pro-image` - Quality, 4K text rendering
|
||||
|
||||
Set `GEMINI_FLASH_IMAGE_MODEL` or `GEMINI_PRO_IMAGE_MODEL` to use another Gemini model id.
|
||||
|
||||
## Deliverable Categories
|
||||
|
||||
|
||||
@ -7,11 +7,19 @@ Uses Gemini's native image generation (Nano Banana Flash/Pro) for high-quality m
|
||||
Supports text-and-image-to-image generation for using actual brand logos.
|
||||
|
||||
- gemini-2.5-flash-image: Fast generation, cost-effective (default)
|
||||
- gemini-3-pro-image-preview: Pro quality, 4K text rendering
|
||||
- gemini-3-pro-image: Pro quality, 4K text rendering
|
||||
|
||||
Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini
|
||||
model id, for example when Google retires one of these.
|
||||
|
||||
Image Editing (text-and-image-to-image):
|
||||
When --logo is provided, the script uses Gemini's image editing capability
|
||||
to incorporate the actual logo into CIP mockups instead of generating one.
|
||||
|
||||
Each mockup is saved with the extension of the image type Gemini returns
|
||||
(.png, .jpg or .webp). Exit status is 1 when nothing was generated: a failed
|
||||
single deliverable, or a set where every deliverable failed. A set where some
|
||||
deliverables succeed exits 0 and reports how many were generated.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@ -25,13 +33,6 @@ from datetime import datetime
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from core import search, get_cip_brief
|
||||
|
||||
# Model options
|
||||
MODELS = {
|
||||
"flash": "gemini-2.5-flash-image", # Nano Banana Flash - fast, default
|
||||
"pro": "gemini-3-pro-image-preview" # Nano Banana Pro - quality, 4K text
|
||||
}
|
||||
DEFAULT_MODEL = "flash"
|
||||
|
||||
|
||||
def load_logo_image(logo_path):
|
||||
"""Load logo image using PIL for Gemini image editing"""
|
||||
@ -85,6 +86,16 @@ def load_env():
|
||||
|
||||
load_env()
|
||||
|
||||
# Model options (read after load_env so .env files can override the ids)
|
||||
MODELS = {
|
||||
"flash": os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image", # Nano Banana Flash - fast, default
|
||||
"pro": os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image" # Nano Banana Pro - quality, 4K text
|
||||
}
|
||||
DEFAULT_MODEL = "flash"
|
||||
|
||||
# File extensions for the image types Gemini returns as inline data
|
||||
IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
||||
|
||||
|
||||
def build_cip_prompt(deliverable, brand_name, style=None, industry=None, mockup=None, use_logo_image=False):
|
||||
"""Build an optimized prompt for CIP mockup generation
|
||||
@ -192,7 +203,7 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", a
|
||||
|
||||
Models:
|
||||
- flash: gemini-2.5-flash-image (fast, cost-effective) - DEFAULT
|
||||
- pro: gemini-3-pro-image-preview (quality, 4K text rendering)
|
||||
- pro: gemini-3-pro-image (quality, 4K text rendering)
|
||||
|
||||
Args:
|
||||
prompt_data: Dict with prompt, deliverable, brand, etc.
|
||||
@ -265,7 +276,9 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", a
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
brand_slug = prompt_data["brand"].lower().replace(" ", "-")
|
||||
deliverable_slug = prompt_data["deliverable"].lower().replace(" ", "-")
|
||||
filename = f"{brand_slug}-{deliverable_slug}-{timestamp}.png"
|
||||
mime_type = (part.inline_data.mime_type or "").split(";")[0].strip().lower()
|
||||
extension = IMAGE_EXTENSIONS.get(mime_type, ".png")
|
||||
filename = f"{brand_slug}-{deliverable_slug}-{timestamp}{extension}"
|
||||
filepath = output_dir / filename
|
||||
|
||||
image_data = part.inline_data.data
|
||||
@ -390,7 +403,7 @@ Examples:
|
||||
|
||||
Models:
|
||||
flash (default): gemini-2.5-flash-image - Fast, cost-effective
|
||||
pro: gemini-3-pro-image-preview - Quality, 4K text rendering
|
||||
pro: gemini-3-pro-image - Quality, 4K text rendering
|
||||
|
||||
Image Editing Mode:
|
||||
When --logo is provided, uses Gemini's text-and-image-to-image capability
|
||||
@ -464,6 +477,8 @@ Image Editing Mode:
|
||||
print(json.dumps(results, indent=2))
|
||||
else:
|
||||
print(f"\n✅ Generated {len(results)} CIP mockups")
|
||||
if not results:
|
||||
sys.exit(1)
|
||||
else:
|
||||
# Generate single deliverable
|
||||
deliverable = args.deliverable or "business card"
|
||||
@ -481,6 +496,8 @@ Image Editing Mode:
|
||||
)
|
||||
if args.json:
|
||||
print(json.dumps({"filepath": filepath, **prompt_data}, indent=2))
|
||||
if filepath is None:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@ -493,7 +493,7 @@ def main():
|
||||
# Multi-size mode
|
||||
if args.sizes:
|
||||
sizes = [int(s.strip()) for s in args.sizes.split(",")]
|
||||
generate_sizes(
|
||||
generated = generate_sizes(
|
||||
prompt=prompt,
|
||||
sizes=sizes,
|
||||
style=args.style,
|
||||
@ -504,7 +504,7 @@ def main():
|
||||
# Batch mode
|
||||
elif args.batch:
|
||||
output_dir = args.output_dir or "./icons"
|
||||
generate_batch(
|
||||
generated = generate_batch(
|
||||
prompt=prompt,
|
||||
count=args.batch,
|
||||
output_dir=output_dir,
|
||||
@ -515,7 +515,7 @@ def main():
|
||||
)
|
||||
# Single icon
|
||||
else:
|
||||
generate_icon(
|
||||
generated = generate_icon(
|
||||
prompt=prompt,
|
||||
style=args.style,
|
||||
category=args.category,
|
||||
@ -526,6 +526,10 @@ def main():
|
||||
viewbox=args.viewbox
|
||||
)
|
||||
|
||||
# Exit 1 when nothing was generated; a partly generated batch or size set exits 0
|
||||
if not generated:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -8,9 +8,20 @@ with the selected model's prompt/aspect-ratio contract.
|
||||
|
||||
Models:
|
||||
- Nano Banana (default): gemini-2.5-flash-image - fast, high-volume, low-latency
|
||||
- Nano Banana Pro (--pro): gemini-3-pro-image-preview - professional quality, advanced reasoning
|
||||
- Nano Banana Pro (--pro): gemini-3-pro-image - professional quality, advanced reasoning
|
||||
- MuAPI Nano Banana (--provider muapi): nano-banana - hosted asynchronous image generation
|
||||
|
||||
Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini
|
||||
model id, for example when Google retires one of these.
|
||||
|
||||
Gemini returns PNG or JPEG data. The file gets the extension of the returned
|
||||
type, so ``--output logo.png`` can be saved as ``logo.jpg``; the path actually
|
||||
written is printed.
|
||||
|
||||
Exit status is 1 when nothing was generated: a failed single request, or a
|
||||
batch where every variant failed. A batch where some variants succeed exits 0
|
||||
and reports how many were generated.
|
||||
|
||||
Usage:
|
||||
python generate.py --prompt "tech startup logo minimalist blue"
|
||||
python generate.py --prompt "coffee shop vintage badge" --style vintage --output logo.png
|
||||
@ -28,6 +39,7 @@ import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@ -65,8 +77,15 @@ ATLASCLOUD_API_KEY = os.environ.get("ATLASCLOUD_API_KEY")
|
||||
MUAPI_API_KEY = os.environ.get("MUAPI_API_KEY")
|
||||
|
||||
# Gemini "Nano Banana" model configurations for image generation
|
||||
GEMINI_FLASH = "gemini-2.5-flash-image" # Nano Banana: fast, high-volume, low-latency
|
||||
GEMINI_PRO = "gemini-3-pro-image-preview" # Nano Banana Pro: professional quality, advanced reasoning
|
||||
GEMINI_FLASH = (
|
||||
os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image"
|
||||
) # Nano Banana: fast, high-volume, low-latency
|
||||
GEMINI_PRO = (
|
||||
os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image"
|
||||
) # Nano Banana Pro: professional quality, advanced reasoning
|
||||
|
||||
# File extensions for the image types Gemini returns as inline data
|
||||
IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
||||
|
||||
# Atlas Cloud model validated against the live model catalog and schema.
|
||||
ATLAS_MODEL = "google/nano-banana-2-lite/text-to-image"
|
||||
@ -431,7 +450,21 @@ def _generate_with_muapi(prompt, output_path, aspect_ratio, api_key, model):
|
||||
raise RuntimeError("MuAPI prediction timed out while polling")
|
||||
|
||||
|
||||
def _path_for_image_type(output_path, mime_type):
|
||||
"""Return output_path with the extension of the returned image type.
|
||||
|
||||
An unknown image type keeps the requested path.
|
||||
"""
|
||||
extension = IMAGE_EXTENSIONS.get(mime_type.split(";")[0].strip().lower())
|
||||
path = Path(output_path)
|
||||
suffix = path.suffix.lower()
|
||||
if extension is None or suffix == extension or (suffix, extension) == (".jpeg", ".jpg"):
|
||||
return output_path
|
||||
return str(path.with_suffix(extension))
|
||||
|
||||
|
||||
def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):
|
||||
"""Generate with Gemini and return the path the image was saved to."""
|
||||
if not GEMINI_API_KEY:
|
||||
raise RuntimeError("GEMINI_API_KEY not set")
|
||||
|
||||
@ -478,9 +511,15 @@ def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):
|
||||
and part.inline_data
|
||||
and part.inline_data.mime_type.startswith("image/")
|
||||
):
|
||||
with open(output_path, "wb") as output_file:
|
||||
saved_path = _path_for_image_type(output_path, part.inline_data.mime_type)
|
||||
if saved_path != output_path:
|
||||
print(
|
||||
f"Gemini returned {part.inline_data.mime_type}, "
|
||||
f"so saving as {saved_path} instead of {output_path}"
|
||||
)
|
||||
with open(saved_path, "wb") as output_file:
|
||||
output_file.write(part.inline_data.data)
|
||||
return
|
||||
return saved_path
|
||||
raise RuntimeError("Gemini did not return an image")
|
||||
|
||||
|
||||
@ -520,9 +559,9 @@ def generate_logo(
|
||||
model_label = f"MuAPI ({muapi_model})"
|
||||
else:
|
||||
model_label = (
|
||||
"Nano Banana Pro (gemini-3-pro-image-preview)"
|
||||
f"Nano Banana Pro ({GEMINI_PRO})"
|
||||
if use_pro
|
||||
else "Nano Banana (gemini-2.5-flash-image)"
|
||||
else f"Nano Banana ({GEMINI_FLASH})"
|
||||
)
|
||||
|
||||
print(f"Generating logo with {model_label}...")
|
||||
@ -548,7 +587,7 @@ def generate_logo(
|
||||
muapi_model,
|
||||
)
|
||||
else:
|
||||
_generate_with_gemini(full_prompt, output_path, ratio, use_pro)
|
||||
output_path = _generate_with_gemini(full_prompt, output_path, ratio, use_pro)
|
||||
|
||||
print(f"Logo saved to: {output_path}")
|
||||
return output_path
|
||||
@ -635,7 +674,7 @@ def generate_batch(
|
||||
|
||||
if result:
|
||||
results.append(result)
|
||||
print(f" ✓ Saved: {filename}\n")
|
||||
print(f" ✓ Saved: {os.path.basename(result)}\n")
|
||||
else:
|
||||
print(f" ✗ Failed: {style_key}\n")
|
||||
|
||||
@ -675,7 +714,7 @@ def main():
|
||||
parser.add_argument(
|
||||
"--pro",
|
||||
action="store_true",
|
||||
help="Use Nano Banana Pro (gemini-3-pro-image-preview) for professional quality",
|
||||
help=f"Use Nano Banana Pro ({GEMINI_PRO}) for professional quality",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--provider",
|
||||
@ -738,7 +777,7 @@ def main():
|
||||
output_dir = (
|
||||
args.output_dir or f"./{args.brand.lower().replace(' ', '_')}_logos"
|
||||
)
|
||||
generate_batch(
|
||||
results = generate_batch(
|
||||
prompt=prompt,
|
||||
brand_name=args.brand or "Logo",
|
||||
count=args.batch,
|
||||
@ -750,8 +789,10 @@ def main():
|
||||
atlas_model=args.atlas_model,
|
||||
muapi_model=args.muapi_model,
|
||||
)
|
||||
if not results:
|
||||
sys.exit(1)
|
||||
else:
|
||||
generate_logo(
|
||||
saved_path = generate_logo(
|
||||
prompt=prompt,
|
||||
style=args.style,
|
||||
industry=args.industry,
|
||||
@ -763,6 +804,8 @@ def main():
|
||||
atlas_model=args.atlas_model,
|
||||
muapi_model=args.muapi_model,
|
||||
)
|
||||
if saved_path is None:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@ -1,13 +1,46 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import call, patch
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock, call, patch
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[1] / "generate.py"
|
||||
SPEC = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)
|
||||
logo_generate = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(logo_generate)
|
||||
|
||||
|
||||
def _load_module():
|
||||
spec = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
logo_generate = _load_module()
|
||||
|
||||
JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"
|
||||
PNG = b"\x89PNG\r\n\x1a\npng-bytes"
|
||||
|
||||
|
||||
def _image_response(mime_type, data):
|
||||
part = SimpleNamespace(inline_data=SimpleNamespace(mime_type=mime_type, data=data))
|
||||
return SimpleNamespace(
|
||||
candidates=[SimpleNamespace(content=SimpleNamespace(parts=[part]))]
|
||||
)
|
||||
|
||||
|
||||
def _fake_genai(client):
|
||||
"""sys.modules entries for an offline google.genai whose Client is client."""
|
||||
types = ModuleType("google.genai.types")
|
||||
types.GenerateContentConfig = types.ImageConfig = types.SafetySetting = dict
|
||||
genai = ModuleType("google.genai")
|
||||
genai.Client = lambda api_key: client
|
||||
genai.types = types
|
||||
google = ModuleType("google")
|
||||
google.genai = genai
|
||||
return {"google": google, "google.genai": genai, "google.genai.types": types}
|
||||
|
||||
|
||||
class AtlasGenerationTests(unittest.TestCase):
|
||||
@ -284,5 +317,138 @@ class MuapiGenerationTests(unittest.TestCase):
|
||||
json_request.assert_called_once()
|
||||
|
||||
|
||||
class GeminiImageTypeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Mock()
|
||||
for patcher in (
|
||||
patch.dict(sys.modules, _fake_genai(self.client)),
|
||||
patch.object(logo_generate, "GEMINI_API_KEY", "test-key"),
|
||||
):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp_dir.cleanup)
|
||||
self.dir = Path(temp_dir.name)
|
||||
|
||||
def _generate(self, mime_type, data, requested_name):
|
||||
self.client.models.generate_content.return_value = _image_response(
|
||||
mime_type, data
|
||||
)
|
||||
return logo_generate._generate_with_gemini(
|
||||
"logo prompt", str(self.dir / requested_name), "1:1", use_pro=True
|
||||
)
|
||||
|
||||
def test_jpeg_is_saved_with_jpg_extension(self):
|
||||
with patch("sys.stdout", new_callable=io.StringIO):
|
||||
saved = self._generate("image/jpeg", JPEG, "logo.png")
|
||||
|
||||
self.assertEqual(saved, str(self.dir / "logo.jpg"))
|
||||
self.assertEqual(Path(saved).read_bytes(), JPEG)
|
||||
self.assertFalse((self.dir / "logo.png").exists())
|
||||
|
||||
def test_matching_extension_keeps_requested_path(self):
|
||||
for mime_type, data, name in (
|
||||
("image/png", PNG, "logo.png"),
|
||||
("image/jpeg", JPEG, "logo.jpeg"),
|
||||
("image/jpeg", JPEG, "logo.JPG"),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
saved = self._generate(mime_type, data, name)
|
||||
self.assertEqual(saved, str(self.dir / name))
|
||||
self.assertEqual(Path(saved).read_bytes(), data)
|
||||
|
||||
def test_unknown_image_type_keeps_requested_path(self):
|
||||
self.assertEqual(
|
||||
logo_generate._path_for_image_type("logo.png", "image/heic"), "logo.png"
|
||||
)
|
||||
|
||||
def test_generate_logo_prints_and_returns_the_saved_path(self):
|
||||
self.client.models.generate_content.return_value = _image_response(
|
||||
"image/jpeg", JPEG
|
||||
)
|
||||
with patch("sys.stdout", new_callable=io.StringIO) as stdout:
|
||||
saved = logo_generate.generate_logo(
|
||||
"test mark", output_path=str(self.dir / "logo.png"), use_pro=True
|
||||
)
|
||||
|
||||
self.assertEqual(saved, str(self.dir / "logo.jpg"))
|
||||
self.assertIn(f"Logo saved to: {saved}", stdout.getvalue())
|
||||
|
||||
def test_pro_requests_the_configured_pro_model(self):
|
||||
self._generate("image/png", PNG, "logo.png")
|
||||
|
||||
self.assertEqual(
|
||||
self.client.models.generate_content.call_args.kwargs["model"],
|
||||
logo_generate.GEMINI_PRO,
|
||||
)
|
||||
|
||||
|
||||
class GeminiModelIdTests(unittest.TestCase):
|
||||
def test_pro_defaults_to_the_ga_model(self):
|
||||
with patch.dict(os.environ):
|
||||
os.environ.pop("GEMINI_PRO_IMAGE_MODEL", None)
|
||||
module = _load_module()
|
||||
|
||||
self.assertEqual(module.GEMINI_PRO, "gemini-3-pro-image")
|
||||
|
||||
def test_model_ids_can_be_overridden_from_the_environment(self):
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"GEMINI_FLASH_IMAGE_MODEL": "flash-next", "GEMINI_PRO_IMAGE_MODEL": "pro-next"},
|
||||
):
|
||||
module = _load_module()
|
||||
|
||||
self.assertEqual(module.GEMINI_FLASH, "flash-next")
|
||||
self.assertEqual(module.GEMINI_PRO, "pro-next")
|
||||
|
||||
|
||||
class ExitStatusTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp_dir.cleanup)
|
||||
self.dir = Path(temp_dir.name)
|
||||
|
||||
def _run_main(self, *args):
|
||||
with patch.object(sys, "argv", ["generate.py", *args]), patch(
|
||||
"sys.stdout", new_callable=io.StringIO
|
||||
):
|
||||
logo_generate.main()
|
||||
|
||||
def test_failed_single_request_exits_1(self):
|
||||
client = Mock()
|
||||
client.models.generate_content.side_effect = RuntimeError(
|
||||
"429 RESOURCE_EXHAUSTED"
|
||||
)
|
||||
with patch.dict(sys.modules, _fake_genai(client)), patch.object(
|
||||
logo_generate, "GEMINI_API_KEY", "test-key"
|
||||
), self.assertRaises(SystemExit) as raised:
|
||||
self._run_main("--prompt", "test mark", "--output", str(self.dir / "logo.png"))
|
||||
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
|
||||
@patch.object(logo_generate.time, "sleep")
|
||||
@patch.object(logo_generate, "generate_logo", return_value=None)
|
||||
def test_batch_with_no_logos_exits_1(self, generate_logo, sleep):
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self._run_main(
|
||||
"--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir)
|
||||
)
|
||||
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
self.assertEqual(generate_logo.call_count, 2)
|
||||
|
||||
@patch.object(logo_generate.time, "sleep")
|
||||
@patch.object(
|
||||
logo_generate, "generate_logo", side_effect=[None, "demo_modern_02.png"]
|
||||
)
|
||||
def test_partial_batch_exits_0(self, generate_logo, sleep):
|
||||
self._run_main("--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir))
|
||||
|
||||
self.assertEqual(generate_logo.call_count, 2)
|
||||
|
||||
def test_list_styles_exits_0(self):
|
||||
self._run_main("--list-styles")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
134
.claude/skills/design/scripts/tests/test_cip_generate.py
Normal file
134
.claude/skills/design/scripts/tests/test_cip_generate.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""Offline regression tests for cip/generate.py (no network, stubbed genai)."""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import types as pytypes
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parent.parent / "cip" / "generate.py"
|
||||
|
||||
JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"
|
||||
PNG = b"\x89PNG\r\n\x1a\npng-bytes"
|
||||
|
||||
PROMPT_DATA = {
|
||||
"prompt": "business card mockup",
|
||||
"deliverable": "Business Card",
|
||||
"brand": "Demo",
|
||||
"style": "Corporate Minimal",
|
||||
"mockup_context": "desk",
|
||||
}
|
||||
|
||||
|
||||
class _Config:
|
||||
def __init__(self, **kwargs):
|
||||
self.__dict__.update(kwargs)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def load_cip(monkeypatch):
|
||||
"""Return a loader for a fresh cip/generate.py with google.genai stubbed.
|
||||
|
||||
cip/generate.py imports its own `core` module, which shares a name with the
|
||||
ui-ux-pro-max search core, so sys.modules and sys.path are restored afterwards.
|
||||
"""
|
||||
monkeypatch.setattr(sys, "path", list(sys.path))
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "test-key")
|
||||
monkeypatch.delenv("GEMINI_FLASH_IMAGE_MODEL", raising=False)
|
||||
monkeypatch.delenv("GEMINI_PRO_IMAGE_MODEL", raising=False)
|
||||
|
||||
with mock.patch.dict(sys.modules):
|
||||
sys.modules.pop("core", None)
|
||||
google = pytypes.ModuleType("google")
|
||||
genai = pytypes.ModuleType("google.genai")
|
||||
types = pytypes.ModuleType("google.genai.types")
|
||||
types.GenerateContentConfig = types.ImageConfig = _Config
|
||||
genai.Client = mock.MagicMock()
|
||||
genai.types = types
|
||||
google.genai = genai
|
||||
sys.modules.update(
|
||||
{"google": google, "google.genai": genai, "google.genai.types": types}
|
||||
)
|
||||
|
||||
def load():
|
||||
spec = importlib.util.spec_from_file_location("cip_generate_under_test", SCRIPT)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
mod.client = genai.Client.return_value
|
||||
return mod
|
||||
|
||||
yield load
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cip(load_cip):
|
||||
return load_cip()
|
||||
|
||||
|
||||
def _image_response(mime_type, data):
|
||||
part = pytypes.SimpleNamespace(
|
||||
inline_data=pytypes.SimpleNamespace(mime_type=mime_type, data=data))
|
||||
return pytypes.SimpleNamespace(
|
||||
candidates=[pytypes.SimpleNamespace(content=pytypes.SimpleNamespace(parts=[part]))])
|
||||
|
||||
|
||||
def _run_main(cip, monkeypatch, *args):
|
||||
monkeypatch.setattr(sys, "argv", ["generate.py", "--brand", "Demo", *args])
|
||||
cip.main()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime_type, data, extension", [
|
||||
("image/jpeg", JPEG, ".jpg"),
|
||||
("image/png", PNG, ".png"),
|
||||
("image/webp", b"RIFFwebp", ".webp"),
|
||||
])
|
||||
def test_mockup_extension_follows_returned_image_type(cip, tmp_path, mime_type, data, extension):
|
||||
cip.client.models.generate_content.return_value = _image_response(mime_type, data)
|
||||
filepath = cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")
|
||||
assert Path(filepath).suffix == extension
|
||||
assert Path(filepath).read_bytes() == data
|
||||
|
||||
|
||||
def test_pro_uses_the_ga_model(cip, tmp_path):
|
||||
cip.client.models.generate_content.return_value = _image_response("image/png", PNG)
|
||||
cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")
|
||||
assert cip.client.models.generate_content.call_args.kwargs["model"] == "gemini-3-pro-image"
|
||||
|
||||
|
||||
def test_model_ids_can_be_overridden_from_the_environment(load_cip, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_FLASH_IMAGE_MODEL", "flash-next")
|
||||
monkeypatch.setenv("GEMINI_PRO_IMAGE_MODEL", "pro-next")
|
||||
assert load_cip().MODELS == {"flash": "flash-next", "pro": "pro-next"}
|
||||
|
||||
|
||||
def test_main_exits_1_when_single_deliverable_fails(cip, monkeypatch, tmp_path):
|
||||
cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(cip, monkeypatch, "--deliverable", "business card", "--no-logo-prompt",
|
||||
"--output", str(tmp_path))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_1_when_every_deliverable_in_a_set_fails(cip, monkeypatch, tmp_path):
|
||||
cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",
|
||||
"--no-logo-prompt", "--output", str(tmp_path))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_0_when_part_of_a_set_is_generated(cip, monkeypatch, tmp_path):
|
||||
cip.client.models.generate_content.side_effect = [
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED"),
|
||||
_image_response("image/png", PNG),
|
||||
]
|
||||
_run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",
|
||||
"--no-logo-prompt", "--output", str(tmp_path))
|
||||
assert len(list(tmp_path.glob("*.png"))) == 1
|
||||
|
||||
|
||||
def test_main_prompt_only_exits_0(cip, monkeypatch):
|
||||
_run_main(cip, monkeypatch, "--deliverable", "business card", "--prompt-only")
|
||||
cip.client.models.generate_content.assert_not_called()
|
||||
@ -140,3 +140,39 @@ def test_generate_batch_warns_when_truncated_after_some_icons(gen, tmp_path, cap
|
||||
'<svg viewBox="0 0 24 24"><path d="M 15 14 H 19', "MAX_TOKENS")
|
||||
assert len(gen.generate_batch("crane", 2, str(tmp_path))) == 1
|
||||
assert "MAX_TOKENS" in capsys.readouterr().out
|
||||
|
||||
|
||||
def _run_main(gen, monkeypatch, *args):
|
||||
monkeypatch.setattr(sys, "argv", ["generate.py", *args])
|
||||
gen.main()
|
||||
|
||||
|
||||
def test_main_exits_1_when_icon_request_fails(gen, monkeypatch, tmp_path):
|
||||
client = gen.genai.Client.return_value
|
||||
client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_1_when_batch_generates_nothing(gen, monkeypatch, tmp_path):
|
||||
client = gen.genai.Client.return_value
|
||||
resp = _response(None, "SAFETY")
|
||||
resp.candidates = []
|
||||
client.models.generate_content.return_value = resp
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(gen, monkeypatch, "--prompt", "crane", "--batch", "2",
|
||||
"--output-dir", str(tmp_path))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_0_when_icon_is_saved(gen, monkeypatch, tmp_path):
|
||||
client = gen.genai.Client.return_value
|
||||
client.models.generate_content.return_value = _response(
|
||||
'<svg viewBox="0 0 24 24"><path d="M0 0"/></svg>')
|
||||
_run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))
|
||||
assert (tmp_path / "a.svg").exists()
|
||||
|
||||
|
||||
def test_main_list_styles_exits_0(gen, monkeypatch):
|
||||
_run_main(gen, monkeypatch, "--list-styles")
|
||||
|
||||
@ -111,7 +111,7 @@ python3 scripts/cip/generate.py --brand "TopGroup" --logo logo.png --deliverable
|
||||
python3 scripts/cip/generate.py --brand "TechFlow" --deliverable "business card" --no-logo-prompt
|
||||
```
|
||||
|
||||
Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image-preview`)
|
||||
Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image`). Override the ids with `GEMINI_FLASH_IMAGE_MODEL` / `GEMINI_PRO_IMAGE_MODEL`.
|
||||
|
||||
### CIP: Render HTML Presentation
|
||||
|
||||
|
||||
@ -64,7 +64,9 @@ python3 scripts/cip/render-html.py --brand "TopGroup" --industry "consulting" --
|
||||
## Models
|
||||
|
||||
- `flash` (default): `gemini-2.5-flash-image` - Fast, cost-effective
|
||||
- `pro`: `gemini-3-pro-image-preview` - Quality, 4K text rendering
|
||||
- `pro`: `gemini-3-pro-image` - Quality, 4K text rendering
|
||||
|
||||
Set `GEMINI_FLASH_IMAGE_MODEL` or `GEMINI_PRO_IMAGE_MODEL` to use another Gemini model id.
|
||||
|
||||
## Deliverable Categories
|
||||
|
||||
|
||||
@ -7,11 +7,19 @@ Uses Gemini's native image generation (Nano Banana Flash/Pro) for high-quality m
|
||||
Supports text-and-image-to-image generation for using actual brand logos.
|
||||
|
||||
- gemini-2.5-flash-image: Fast generation, cost-effective (default)
|
||||
- gemini-3-pro-image-preview: Pro quality, 4K text rendering
|
||||
- gemini-3-pro-image: Pro quality, 4K text rendering
|
||||
|
||||
Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini
|
||||
model id, for example when Google retires one of these.
|
||||
|
||||
Image Editing (text-and-image-to-image):
|
||||
When --logo is provided, the script uses Gemini's image editing capability
|
||||
to incorporate the actual logo into CIP mockups instead of generating one.
|
||||
|
||||
Each mockup is saved with the extension of the image type Gemini returns
|
||||
(.png, .jpg or .webp). Exit status is 1 when nothing was generated: a failed
|
||||
single deliverable, or a set where every deliverable failed. A set where some
|
||||
deliverables succeed exits 0 and reports how many were generated.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@ -25,13 +33,6 @@ from datetime import datetime
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from core import search, get_cip_brief
|
||||
|
||||
# Model options
|
||||
MODELS = {
|
||||
"flash": "gemini-2.5-flash-image", # Nano Banana Flash - fast, default
|
||||
"pro": "gemini-3-pro-image-preview" # Nano Banana Pro - quality, 4K text
|
||||
}
|
||||
DEFAULT_MODEL = "flash"
|
||||
|
||||
|
||||
def load_logo_image(logo_path):
|
||||
"""Load logo image using PIL for Gemini image editing"""
|
||||
@ -85,6 +86,16 @@ def load_env():
|
||||
|
||||
load_env()
|
||||
|
||||
# Model options (read after load_env so .env files can override the ids)
|
||||
MODELS = {
|
||||
"flash": os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image", # Nano Banana Flash - fast, default
|
||||
"pro": os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image" # Nano Banana Pro - quality, 4K text
|
||||
}
|
||||
DEFAULT_MODEL = "flash"
|
||||
|
||||
# File extensions for the image types Gemini returns as inline data
|
||||
IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
||||
|
||||
|
||||
def build_cip_prompt(deliverable, brand_name, style=None, industry=None, mockup=None, use_logo_image=False):
|
||||
"""Build an optimized prompt for CIP mockup generation
|
||||
@ -192,7 +203,7 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", a
|
||||
|
||||
Models:
|
||||
- flash: gemini-2.5-flash-image (fast, cost-effective) - DEFAULT
|
||||
- pro: gemini-3-pro-image-preview (quality, 4K text rendering)
|
||||
- pro: gemini-3-pro-image (quality, 4K text rendering)
|
||||
|
||||
Args:
|
||||
prompt_data: Dict with prompt, deliverable, brand, etc.
|
||||
@ -265,7 +276,9 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", a
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
brand_slug = prompt_data["brand"].lower().replace(" ", "-")
|
||||
deliverable_slug = prompt_data["deliverable"].lower().replace(" ", "-")
|
||||
filename = f"{brand_slug}-{deliverable_slug}-{timestamp}.png"
|
||||
mime_type = (part.inline_data.mime_type or "").split(";")[0].strip().lower()
|
||||
extension = IMAGE_EXTENSIONS.get(mime_type, ".png")
|
||||
filename = f"{brand_slug}-{deliverable_slug}-{timestamp}{extension}"
|
||||
filepath = output_dir / filename
|
||||
|
||||
image_data = part.inline_data.data
|
||||
@ -390,7 +403,7 @@ Examples:
|
||||
|
||||
Models:
|
||||
flash (default): gemini-2.5-flash-image - Fast, cost-effective
|
||||
pro: gemini-3-pro-image-preview - Quality, 4K text rendering
|
||||
pro: gemini-3-pro-image - Quality, 4K text rendering
|
||||
|
||||
Image Editing Mode:
|
||||
When --logo is provided, uses Gemini's text-and-image-to-image capability
|
||||
@ -464,6 +477,8 @@ Image Editing Mode:
|
||||
print(json.dumps(results, indent=2))
|
||||
else:
|
||||
print(f"\n✅ Generated {len(results)} CIP mockups")
|
||||
if not results:
|
||||
sys.exit(1)
|
||||
else:
|
||||
# Generate single deliverable
|
||||
deliverable = args.deliverable or "business card"
|
||||
@ -481,6 +496,8 @@ Image Editing Mode:
|
||||
)
|
||||
if args.json:
|
||||
print(json.dumps({"filepath": filepath, **prompt_data}, indent=2))
|
||||
if filepath is None:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@ -493,7 +493,7 @@ def main():
|
||||
# Multi-size mode
|
||||
if args.sizes:
|
||||
sizes = [int(s.strip()) for s in args.sizes.split(",")]
|
||||
generate_sizes(
|
||||
generated = generate_sizes(
|
||||
prompt=prompt,
|
||||
sizes=sizes,
|
||||
style=args.style,
|
||||
@ -504,7 +504,7 @@ def main():
|
||||
# Batch mode
|
||||
elif args.batch:
|
||||
output_dir = args.output_dir or "./icons"
|
||||
generate_batch(
|
||||
generated = generate_batch(
|
||||
prompt=prompt,
|
||||
count=args.batch,
|
||||
output_dir=output_dir,
|
||||
@ -515,7 +515,7 @@ def main():
|
||||
)
|
||||
# Single icon
|
||||
else:
|
||||
generate_icon(
|
||||
generated = generate_icon(
|
||||
prompt=prompt,
|
||||
style=args.style,
|
||||
category=args.category,
|
||||
@ -526,6 +526,10 @@ def main():
|
||||
viewbox=args.viewbox
|
||||
)
|
||||
|
||||
# Exit 1 when nothing was generated; a partly generated batch or size set exits 0
|
||||
if not generated:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@ -8,9 +8,20 @@ with the selected model's prompt/aspect-ratio contract.
|
||||
|
||||
Models:
|
||||
- Nano Banana (default): gemini-2.5-flash-image - fast, high-volume, low-latency
|
||||
- Nano Banana Pro (--pro): gemini-3-pro-image-preview - professional quality, advanced reasoning
|
||||
- Nano Banana Pro (--pro): gemini-3-pro-image - professional quality, advanced reasoning
|
||||
- MuAPI Nano Banana (--provider muapi): nano-banana - hosted asynchronous image generation
|
||||
|
||||
Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini
|
||||
model id, for example when Google retires one of these.
|
||||
|
||||
Gemini returns PNG or JPEG data. The file gets the extension of the returned
|
||||
type, so ``--output logo.png`` can be saved as ``logo.jpg``; the path actually
|
||||
written is printed.
|
||||
|
||||
Exit status is 1 when nothing was generated: a failed single request, or a
|
||||
batch where every variant failed. A batch where some variants succeed exits 0
|
||||
and reports how many were generated.
|
||||
|
||||
Usage:
|
||||
python generate.py --prompt "tech startup logo minimalist blue"
|
||||
python generate.py --prompt "coffee shop vintage badge" --style vintage --output logo.png
|
||||
@ -28,6 +39,7 @@ import argparse
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@ -65,8 +77,15 @@ ATLASCLOUD_API_KEY = os.environ.get("ATLASCLOUD_API_KEY")
|
||||
MUAPI_API_KEY = os.environ.get("MUAPI_API_KEY")
|
||||
|
||||
# Gemini "Nano Banana" model configurations for image generation
|
||||
GEMINI_FLASH = "gemini-2.5-flash-image" # Nano Banana: fast, high-volume, low-latency
|
||||
GEMINI_PRO = "gemini-3-pro-image-preview" # Nano Banana Pro: professional quality, advanced reasoning
|
||||
GEMINI_FLASH = (
|
||||
os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image"
|
||||
) # Nano Banana: fast, high-volume, low-latency
|
||||
GEMINI_PRO = (
|
||||
os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image"
|
||||
) # Nano Banana Pro: professional quality, advanced reasoning
|
||||
|
||||
# File extensions for the image types Gemini returns as inline data
|
||||
IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
||||
|
||||
# Atlas Cloud model validated against the live model catalog and schema.
|
||||
ATLAS_MODEL = "google/nano-banana-2-lite/text-to-image"
|
||||
@ -431,7 +450,21 @@ def _generate_with_muapi(prompt, output_path, aspect_ratio, api_key, model):
|
||||
raise RuntimeError("MuAPI prediction timed out while polling")
|
||||
|
||||
|
||||
def _path_for_image_type(output_path, mime_type):
|
||||
"""Return output_path with the extension of the returned image type.
|
||||
|
||||
An unknown image type keeps the requested path.
|
||||
"""
|
||||
extension = IMAGE_EXTENSIONS.get(mime_type.split(";")[0].strip().lower())
|
||||
path = Path(output_path)
|
||||
suffix = path.suffix.lower()
|
||||
if extension is None or suffix == extension or (suffix, extension) == (".jpeg", ".jpg"):
|
||||
return output_path
|
||||
return str(path.with_suffix(extension))
|
||||
|
||||
|
||||
def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):
|
||||
"""Generate with Gemini and return the path the image was saved to."""
|
||||
if not GEMINI_API_KEY:
|
||||
raise RuntimeError("GEMINI_API_KEY not set")
|
||||
|
||||
@ -478,9 +511,15 @@ def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):
|
||||
and part.inline_data
|
||||
and part.inline_data.mime_type.startswith("image/")
|
||||
):
|
||||
with open(output_path, "wb") as output_file:
|
||||
saved_path = _path_for_image_type(output_path, part.inline_data.mime_type)
|
||||
if saved_path != output_path:
|
||||
print(
|
||||
f"Gemini returned {part.inline_data.mime_type}, "
|
||||
f"so saving as {saved_path} instead of {output_path}"
|
||||
)
|
||||
with open(saved_path, "wb") as output_file:
|
||||
output_file.write(part.inline_data.data)
|
||||
return
|
||||
return saved_path
|
||||
raise RuntimeError("Gemini did not return an image")
|
||||
|
||||
|
||||
@ -520,9 +559,9 @@ def generate_logo(
|
||||
model_label = f"MuAPI ({muapi_model})"
|
||||
else:
|
||||
model_label = (
|
||||
"Nano Banana Pro (gemini-3-pro-image-preview)"
|
||||
f"Nano Banana Pro ({GEMINI_PRO})"
|
||||
if use_pro
|
||||
else "Nano Banana (gemini-2.5-flash-image)"
|
||||
else f"Nano Banana ({GEMINI_FLASH})"
|
||||
)
|
||||
|
||||
print(f"Generating logo with {model_label}...")
|
||||
@ -548,7 +587,7 @@ def generate_logo(
|
||||
muapi_model,
|
||||
)
|
||||
else:
|
||||
_generate_with_gemini(full_prompt, output_path, ratio, use_pro)
|
||||
output_path = _generate_with_gemini(full_prompt, output_path, ratio, use_pro)
|
||||
|
||||
print(f"Logo saved to: {output_path}")
|
||||
return output_path
|
||||
@ -635,7 +674,7 @@ def generate_batch(
|
||||
|
||||
if result:
|
||||
results.append(result)
|
||||
print(f" ✓ Saved: {filename}\n")
|
||||
print(f" ✓ Saved: {os.path.basename(result)}\n")
|
||||
else:
|
||||
print(f" ✗ Failed: {style_key}\n")
|
||||
|
||||
@ -675,7 +714,7 @@ def main():
|
||||
parser.add_argument(
|
||||
"--pro",
|
||||
action="store_true",
|
||||
help="Use Nano Banana Pro (gemini-3-pro-image-preview) for professional quality",
|
||||
help=f"Use Nano Banana Pro ({GEMINI_PRO}) for professional quality",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--provider",
|
||||
@ -738,7 +777,7 @@ def main():
|
||||
output_dir = (
|
||||
args.output_dir or f"./{args.brand.lower().replace(' ', '_')}_logos"
|
||||
)
|
||||
generate_batch(
|
||||
results = generate_batch(
|
||||
prompt=prompt,
|
||||
brand_name=args.brand or "Logo",
|
||||
count=args.batch,
|
||||
@ -750,8 +789,10 @@ def main():
|
||||
atlas_model=args.atlas_model,
|
||||
muapi_model=args.muapi_model,
|
||||
)
|
||||
if not results:
|
||||
sys.exit(1)
|
||||
else:
|
||||
generate_logo(
|
||||
saved_path = generate_logo(
|
||||
prompt=prompt,
|
||||
style=args.style,
|
||||
industry=args.industry,
|
||||
@ -763,6 +804,8 @@ def main():
|
||||
atlas_model=args.atlas_model,
|
||||
muapi_model=args.muapi_model,
|
||||
)
|
||||
if saved_path is None:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@ -1,13 +1,46 @@
|
||||
import importlib.util
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import call, patch
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock, call, patch
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[1] / "generate.py"
|
||||
SPEC = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)
|
||||
logo_generate = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(logo_generate)
|
||||
|
||||
|
||||
def _load_module():
|
||||
spec = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
logo_generate = _load_module()
|
||||
|
||||
JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"
|
||||
PNG = b"\x89PNG\r\n\x1a\npng-bytes"
|
||||
|
||||
|
||||
def _image_response(mime_type, data):
|
||||
part = SimpleNamespace(inline_data=SimpleNamespace(mime_type=mime_type, data=data))
|
||||
return SimpleNamespace(
|
||||
candidates=[SimpleNamespace(content=SimpleNamespace(parts=[part]))]
|
||||
)
|
||||
|
||||
|
||||
def _fake_genai(client):
|
||||
"""sys.modules entries for an offline google.genai whose Client is client."""
|
||||
types = ModuleType("google.genai.types")
|
||||
types.GenerateContentConfig = types.ImageConfig = types.SafetySetting = dict
|
||||
genai = ModuleType("google.genai")
|
||||
genai.Client = lambda api_key: client
|
||||
genai.types = types
|
||||
google = ModuleType("google")
|
||||
google.genai = genai
|
||||
return {"google": google, "google.genai": genai, "google.genai.types": types}
|
||||
|
||||
|
||||
class AtlasGenerationTests(unittest.TestCase):
|
||||
@ -284,5 +317,138 @@ class MuapiGenerationTests(unittest.TestCase):
|
||||
json_request.assert_called_once()
|
||||
|
||||
|
||||
class GeminiImageTypeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Mock()
|
||||
for patcher in (
|
||||
patch.dict(sys.modules, _fake_genai(self.client)),
|
||||
patch.object(logo_generate, "GEMINI_API_KEY", "test-key"),
|
||||
):
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp_dir.cleanup)
|
||||
self.dir = Path(temp_dir.name)
|
||||
|
||||
def _generate(self, mime_type, data, requested_name):
|
||||
self.client.models.generate_content.return_value = _image_response(
|
||||
mime_type, data
|
||||
)
|
||||
return logo_generate._generate_with_gemini(
|
||||
"logo prompt", str(self.dir / requested_name), "1:1", use_pro=True
|
||||
)
|
||||
|
||||
def test_jpeg_is_saved_with_jpg_extension(self):
|
||||
with patch("sys.stdout", new_callable=io.StringIO):
|
||||
saved = self._generate("image/jpeg", JPEG, "logo.png")
|
||||
|
||||
self.assertEqual(saved, str(self.dir / "logo.jpg"))
|
||||
self.assertEqual(Path(saved).read_bytes(), JPEG)
|
||||
self.assertFalse((self.dir / "logo.png").exists())
|
||||
|
||||
def test_matching_extension_keeps_requested_path(self):
|
||||
for mime_type, data, name in (
|
||||
("image/png", PNG, "logo.png"),
|
||||
("image/jpeg", JPEG, "logo.jpeg"),
|
||||
("image/jpeg", JPEG, "logo.JPG"),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
saved = self._generate(mime_type, data, name)
|
||||
self.assertEqual(saved, str(self.dir / name))
|
||||
self.assertEqual(Path(saved).read_bytes(), data)
|
||||
|
||||
def test_unknown_image_type_keeps_requested_path(self):
|
||||
self.assertEqual(
|
||||
logo_generate._path_for_image_type("logo.png", "image/heic"), "logo.png"
|
||||
)
|
||||
|
||||
def test_generate_logo_prints_and_returns_the_saved_path(self):
|
||||
self.client.models.generate_content.return_value = _image_response(
|
||||
"image/jpeg", JPEG
|
||||
)
|
||||
with patch("sys.stdout", new_callable=io.StringIO) as stdout:
|
||||
saved = logo_generate.generate_logo(
|
||||
"test mark", output_path=str(self.dir / "logo.png"), use_pro=True
|
||||
)
|
||||
|
||||
self.assertEqual(saved, str(self.dir / "logo.jpg"))
|
||||
self.assertIn(f"Logo saved to: {saved}", stdout.getvalue())
|
||||
|
||||
def test_pro_requests_the_configured_pro_model(self):
|
||||
self._generate("image/png", PNG, "logo.png")
|
||||
|
||||
self.assertEqual(
|
||||
self.client.models.generate_content.call_args.kwargs["model"],
|
||||
logo_generate.GEMINI_PRO,
|
||||
)
|
||||
|
||||
|
||||
class GeminiModelIdTests(unittest.TestCase):
|
||||
def test_pro_defaults_to_the_ga_model(self):
|
||||
with patch.dict(os.environ):
|
||||
os.environ.pop("GEMINI_PRO_IMAGE_MODEL", None)
|
||||
module = _load_module()
|
||||
|
||||
self.assertEqual(module.GEMINI_PRO, "gemini-3-pro-image")
|
||||
|
||||
def test_model_ids_can_be_overridden_from_the_environment(self):
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"GEMINI_FLASH_IMAGE_MODEL": "flash-next", "GEMINI_PRO_IMAGE_MODEL": "pro-next"},
|
||||
):
|
||||
module = _load_module()
|
||||
|
||||
self.assertEqual(module.GEMINI_FLASH, "flash-next")
|
||||
self.assertEqual(module.GEMINI_PRO, "pro-next")
|
||||
|
||||
|
||||
class ExitStatusTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp_dir.cleanup)
|
||||
self.dir = Path(temp_dir.name)
|
||||
|
||||
def _run_main(self, *args):
|
||||
with patch.object(sys, "argv", ["generate.py", *args]), patch(
|
||||
"sys.stdout", new_callable=io.StringIO
|
||||
):
|
||||
logo_generate.main()
|
||||
|
||||
def test_failed_single_request_exits_1(self):
|
||||
client = Mock()
|
||||
client.models.generate_content.side_effect = RuntimeError(
|
||||
"429 RESOURCE_EXHAUSTED"
|
||||
)
|
||||
with patch.dict(sys.modules, _fake_genai(client)), patch.object(
|
||||
logo_generate, "GEMINI_API_KEY", "test-key"
|
||||
), self.assertRaises(SystemExit) as raised:
|
||||
self._run_main("--prompt", "test mark", "--output", str(self.dir / "logo.png"))
|
||||
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
|
||||
@patch.object(logo_generate.time, "sleep")
|
||||
@patch.object(logo_generate, "generate_logo", return_value=None)
|
||||
def test_batch_with_no_logos_exits_1(self, generate_logo, sleep):
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
self._run_main(
|
||||
"--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir)
|
||||
)
|
||||
|
||||
self.assertEqual(raised.exception.code, 1)
|
||||
self.assertEqual(generate_logo.call_count, 2)
|
||||
|
||||
@patch.object(logo_generate.time, "sleep")
|
||||
@patch.object(
|
||||
logo_generate, "generate_logo", side_effect=[None, "demo_modern_02.png"]
|
||||
)
|
||||
def test_partial_batch_exits_0(self, generate_logo, sleep):
|
||||
self._run_main("--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir))
|
||||
|
||||
self.assertEqual(generate_logo.call_count, 2)
|
||||
|
||||
def test_list_styles_exits_0(self):
|
||||
self._run_main("--list-styles")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
134
cli/assets/skills/design/scripts/tests/test_cip_generate.py
Normal file
134
cli/assets/skills/design/scripts/tests/test_cip_generate.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""Offline regression tests for cip/generate.py (no network, stubbed genai)."""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import types as pytypes
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parent.parent / "cip" / "generate.py"
|
||||
|
||||
JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"
|
||||
PNG = b"\x89PNG\r\n\x1a\npng-bytes"
|
||||
|
||||
PROMPT_DATA = {
|
||||
"prompt": "business card mockup",
|
||||
"deliverable": "Business Card",
|
||||
"brand": "Demo",
|
||||
"style": "Corporate Minimal",
|
||||
"mockup_context": "desk",
|
||||
}
|
||||
|
||||
|
||||
class _Config:
|
||||
def __init__(self, **kwargs):
|
||||
self.__dict__.update(kwargs)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def load_cip(monkeypatch):
|
||||
"""Return a loader for a fresh cip/generate.py with google.genai stubbed.
|
||||
|
||||
cip/generate.py imports its own `core` module, which shares a name with the
|
||||
ui-ux-pro-max search core, so sys.modules and sys.path are restored afterwards.
|
||||
"""
|
||||
monkeypatch.setattr(sys, "path", list(sys.path))
|
||||
monkeypatch.setenv("GEMINI_API_KEY", "test-key")
|
||||
monkeypatch.delenv("GEMINI_FLASH_IMAGE_MODEL", raising=False)
|
||||
monkeypatch.delenv("GEMINI_PRO_IMAGE_MODEL", raising=False)
|
||||
|
||||
with mock.patch.dict(sys.modules):
|
||||
sys.modules.pop("core", None)
|
||||
google = pytypes.ModuleType("google")
|
||||
genai = pytypes.ModuleType("google.genai")
|
||||
types = pytypes.ModuleType("google.genai.types")
|
||||
types.GenerateContentConfig = types.ImageConfig = _Config
|
||||
genai.Client = mock.MagicMock()
|
||||
genai.types = types
|
||||
google.genai = genai
|
||||
sys.modules.update(
|
||||
{"google": google, "google.genai": genai, "google.genai.types": types}
|
||||
)
|
||||
|
||||
def load():
|
||||
spec = importlib.util.spec_from_file_location("cip_generate_under_test", SCRIPT)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
mod.client = genai.Client.return_value
|
||||
return mod
|
||||
|
||||
yield load
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cip(load_cip):
|
||||
return load_cip()
|
||||
|
||||
|
||||
def _image_response(mime_type, data):
|
||||
part = pytypes.SimpleNamespace(
|
||||
inline_data=pytypes.SimpleNamespace(mime_type=mime_type, data=data))
|
||||
return pytypes.SimpleNamespace(
|
||||
candidates=[pytypes.SimpleNamespace(content=pytypes.SimpleNamespace(parts=[part]))])
|
||||
|
||||
|
||||
def _run_main(cip, monkeypatch, *args):
|
||||
monkeypatch.setattr(sys, "argv", ["generate.py", "--brand", "Demo", *args])
|
||||
cip.main()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime_type, data, extension", [
|
||||
("image/jpeg", JPEG, ".jpg"),
|
||||
("image/png", PNG, ".png"),
|
||||
("image/webp", b"RIFFwebp", ".webp"),
|
||||
])
|
||||
def test_mockup_extension_follows_returned_image_type(cip, tmp_path, mime_type, data, extension):
|
||||
cip.client.models.generate_content.return_value = _image_response(mime_type, data)
|
||||
filepath = cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")
|
||||
assert Path(filepath).suffix == extension
|
||||
assert Path(filepath).read_bytes() == data
|
||||
|
||||
|
||||
def test_pro_uses_the_ga_model(cip, tmp_path):
|
||||
cip.client.models.generate_content.return_value = _image_response("image/png", PNG)
|
||||
cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")
|
||||
assert cip.client.models.generate_content.call_args.kwargs["model"] == "gemini-3-pro-image"
|
||||
|
||||
|
||||
def test_model_ids_can_be_overridden_from_the_environment(load_cip, monkeypatch):
|
||||
monkeypatch.setenv("GEMINI_FLASH_IMAGE_MODEL", "flash-next")
|
||||
monkeypatch.setenv("GEMINI_PRO_IMAGE_MODEL", "pro-next")
|
||||
assert load_cip().MODELS == {"flash": "flash-next", "pro": "pro-next"}
|
||||
|
||||
|
||||
def test_main_exits_1_when_single_deliverable_fails(cip, monkeypatch, tmp_path):
|
||||
cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(cip, monkeypatch, "--deliverable", "business card", "--no-logo-prompt",
|
||||
"--output", str(tmp_path))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_1_when_every_deliverable_in_a_set_fails(cip, monkeypatch, tmp_path):
|
||||
cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",
|
||||
"--no-logo-prompt", "--output", str(tmp_path))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_0_when_part_of_a_set_is_generated(cip, monkeypatch, tmp_path):
|
||||
cip.client.models.generate_content.side_effect = [
|
||||
RuntimeError("429 RESOURCE_EXHAUSTED"),
|
||||
_image_response("image/png", PNG),
|
||||
]
|
||||
_run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",
|
||||
"--no-logo-prompt", "--output", str(tmp_path))
|
||||
assert len(list(tmp_path.glob("*.png"))) == 1
|
||||
|
||||
|
||||
def test_main_prompt_only_exits_0(cip, monkeypatch):
|
||||
_run_main(cip, monkeypatch, "--deliverable", "business card", "--prompt-only")
|
||||
cip.client.models.generate_content.assert_not_called()
|
||||
@ -140,3 +140,39 @@ def test_generate_batch_warns_when_truncated_after_some_icons(gen, tmp_path, cap
|
||||
'<svg viewBox="0 0 24 24"><path d="M 15 14 H 19', "MAX_TOKENS")
|
||||
assert len(gen.generate_batch("crane", 2, str(tmp_path))) == 1
|
||||
assert "MAX_TOKENS" in capsys.readouterr().out
|
||||
|
||||
|
||||
def _run_main(gen, monkeypatch, *args):
|
||||
monkeypatch.setattr(sys, "argv", ["generate.py", *args])
|
||||
gen.main()
|
||||
|
||||
|
||||
def test_main_exits_1_when_icon_request_fails(gen, monkeypatch, tmp_path):
|
||||
client = gen.genai.Client.return_value
|
||||
client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_1_when_batch_generates_nothing(gen, monkeypatch, tmp_path):
|
||||
client = gen.genai.Client.return_value
|
||||
resp = _response(None, "SAFETY")
|
||||
resp.candidates = []
|
||||
client.models.generate_content.return_value = resp
|
||||
with pytest.raises(SystemExit) as raised:
|
||||
_run_main(gen, monkeypatch, "--prompt", "crane", "--batch", "2",
|
||||
"--output-dir", str(tmp_path))
|
||||
assert raised.value.code == 1
|
||||
|
||||
|
||||
def test_main_exits_0_when_icon_is_saved(gen, monkeypatch, tmp_path):
|
||||
client = gen.genai.Client.return_value
|
||||
client.models.generate_content.return_value = _response(
|
||||
'<svg viewBox="0 0 24 24"><path d="M0 0"/></svg>')
|
||||
_run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))
|
||||
assert (tmp_path / "a.svg").exists()
|
||||
|
||||
|
||||
def test_main_list_styles_exits_0(gen, monkeypatch):
|
||||
_run_main(gen, monkeypatch, "--list-styles")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user