Update image generation and citation management scripts to use 'uv pip install' for package installations. Modify skill versions for infographics and generate-image to reflect recent changes. Enhance error handling and review logic in infographic generation scripts, ensuring better feedback on quality assessments.

This commit is contained in:
Timothy Kassis committed 2026-07-31 10:26:56 -07:00
1 parent 4d5f1d20be
commit bd99c01e3f
81 files changed
+2921 -1492

No files matched your search

+193 -11
View File
@@ -1,21 +1,36 @@
"""Shared tests for the AI schematic generator bundled by three skills.
"""Shared tests for the AI schematic generator bundled by several skills.
`scientific-schematics`, `latex-posters`, and `literature-review` each ship a
byte-identical `scripts/generate_schematic.py` (a thin CLI) and
`scripts/generate_schematic_ai.py` (the generator). Rather than write the same
tests three times, each suite instantiates `schematic_test_case()` against its
own copy; `tests/_meta` separately pins the copies together.
`scientific-schematics`, `latex-posters`, `literature-review`,
`citation-management`, and `scientific-slides` each ship a byte-identical
`scripts/generate_schematic.py` (a thin CLI) and `scripts/generate_schematic_ai.py`
(the generator). Rather than write the same tests five times, each suite
instantiates the factories below against its own copy; `tests/_meta` separately
pins the copies together.
The behaviour worth testing offline is the environment allowlist. The CLI
re-executes the generator as a subprocess, and it deliberately forwards a
named set of variables rather than the whole parent environment -- copying
everything would hand the child every unrelated secret exported in the calling
shell. Nothing here makes a network call or needs an API key.
Two lineages descend from that generator with the same review-parsing code:
`infographics/scripts/generate_infographic_ai.py` and
`scientific-slides/scripts/generate_slide_image_ai.py`. They reuse
`review_parsing_test_case()` and `review_failure_test_case()`.
Three behaviours are worth testing offline:
- **The environment allowlist.** The CLI re-executes the generator as a
subprocess, and it deliberately forwards a named set of variables rather than
the whole parent environment -- copying everything would hand the child every
unrelated secret exported in the calling shell.
- **Review parsing.** The reviewer answers in prose, and the score and verdict
have to survive whatever markdown it wraps them in.
- **Review failure.** The review is a second model call that can fail on its
own; when it does, the run must neither crash nor report a score it never
received.
Nothing here makes a network call or needs an API key.
"""
from __future__ import annotations
import importlib
import importlib.util
import sys
import unittest
from pathlib import Path
@@ -98,5 +113,172 @@ def schematic_test_case(skill_root: Path) -> type[unittest.TestCase]:
def test_the_generator_script_is_shipped_alongside_the_cli(self) -> None:
self.assertTrue((scripts / "generate_schematic_ai.py").is_file())
def test_the_iteration_count_is_rejected_rather_than_clamped(self) -> None:
# Silently clamping an out-of-range value used to send 0 to the
# child, which failed there with a message about the child's own
# flag. The check runs before the credential lookup, so this needs
# no API key.
import subprocess
for value in ("0", "3", "-1"):
with self.subTest(iterations=value):
result = subprocess.run(
[sys.executable, str(scripts / "generate_schematic.py"),
"a diagram", "-o", "out.png", "--iterations", value],
capture_output=True, text=True, timeout=60,
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("--iterations", result.stderr)
SchematicContractTests.__qualname__ = f"SchematicContractTests[{skill_root.name}]"
return SchematicContractTests
def review_parsing_test_case(scripts_dir: Path, module_name: str) -> type[unittest.TestCase]:
"""Build the review-parsing TestCase for one AI generator module.
Parameterised by module name because three lineages of the same generator
ship across six skills -- `generate_schematic_ai` (five skills, byte
identical), `generate_infographic_ai`, and `generate_slide_image_ai`. They
share the parsing helpers, and they shared the bugs.
Everything here is offline: the helpers are pure functions, and the one
test that reaches `review_image` stubs the request out.
"""
requests_available = importlib.util.find_spec("requests") is not None
def load():
if str(scripts_dir) not in sys.path:
sys.path.insert(0, str(scripts_dir))
return importlib.import_module(module_name)
@unittest.skipUnless(requests_available, "requests is not installed")
class ReviewParsingTests(unittest.TestCase):
maxDiff = None
def setUp(self) -> None:
self.module = load()
def test_the_score_survives_the_markdown_the_reviewer_writes_it_in(self) -> None:
# Gemini emits "**SCORE:** 8.5" far more often than the bare form
# the rubric asks for. A pattern that only matched the bare form
# scored every one of those runs at the old hardcoded default.
for text, expected in (
("SCORE: 8.5", 8.5),
("**SCORE:** 8.5", 8.5),
("**SCORE: 8.5**", 8.5),
("__SCORE__: 9.0", 9.0),
("### SCORE: 8", 8.0),
("SCORE: 8/10", 8.0),
("Score: 7", 7.0),
):
with self.subTest(text=text):
self.assertEqual(self.module._parse_score(text), expected)
def test_an_unparseable_score_is_none_rather_than_a_stand_in(self) -> None:
# A default here reaches the review log indistinguishable from a
# number the reviewer actually gave.
for text in ("no number anywhere", "", "SCORE: 85", "SCORE: -1"):
with self.subTest(text=text):
self.assertIsNone(self.module._parse_score(text))
def test_the_verdict_comes_from_the_verdict_line_only(self) -> None:
# The rubric prompt spells out both tokens when it explains the
# response format. A reviewer echoing that back must not be read
# as failing the diagram.
echoed = (
"SCORE: 9.0\n"
"VERDICT: ACCEPTABLE\n"
"Reminder: if score < 8.5, mark as NEEDS_IMPROVEMENT with suggestions."
)
self.assertEqual(self.module._parse_verdict(echoed), "ACCEPTABLE")
self.assertIsNone(
self.module._parse_verdict("someday I might say NEEDS_IMPROVEMENT")
)
def test_a_real_failing_verdict_is_still_recognised(self) -> None:
for text in (
"VERDICT: NEEDS_IMPROVEMENT",
"**VERDICT:** NEEDS_IMPROVEMENT",
"**VERDICT: NEEDS IMPROVEMENT**",
):
with self.subTest(text=text):
self.assertEqual(
self.module._parse_verdict(text), "NEEDS_IMPROVEMENT"
)
def test_the_review_result_carries_whether_the_review_happened(self) -> None:
self.assertEqual(
self.module.ReviewResult._fields,
("critique", "score", "needs_improvement", "reviewed", "error"),
)
ReviewParsingTests.__qualname__ = f"ReviewParsingTests[{module_name}]"
return ReviewParsingTests
def review_failure_test_case(
scripts_dir: Path, module_name: str, class_name: str, review_args: tuple
) -> type[unittest.TestCase]:
"""Build the TestCase covering `review_image`'s failure paths.
Separate from `review_parsing_test_case` because it has to instantiate the
generator, whose class name and `review_image` signature differ between the
three lineages.
"""
requests_available = importlib.util.find_spec("requests") is not None
def load():
if str(scripts_dir) not in sys.path:
sys.path.insert(0, str(scripts_dir))
return importlib.import_module(module_name)
@unittest.skipUnless(requests_available, "requests is not installed")
class ReviewFailureTests(unittest.TestCase):
maxDiff = None
def setUp(self) -> None:
self.module = load()
generator = getattr(self.module, class_name)(api_key="sk-or-test")
generator._image_to_base64 = lambda path: "data:image/png;base64,AAAA"
self.generator = generator
def test_a_response_with_no_choices_does_not_crash_the_run(self) -> None:
# This used to return two values into a three-value unpack, so a
# rate-limited review killed a run whose image was already on disk.
self.generator._make_request = lambda **kwargs: {"choices": []}
review = self.generator.review_image(*review_args)
self.assertIsNone(review.score)
self.assertFalse(review.reviewed)
self.assertFalse(review.needs_improvement)
self.assertTrue(review.error)
def test_a_failed_review_is_not_reported_as_a_passing_one(self) -> None:
def explode(**kwargs):
raise RuntimeError("API request timed out after 120 seconds")
self.generator._make_request = explode
review = self.generator.review_image(*review_args)
self.assertIsNone(review.score)
self.assertFalse(review.reviewed)
# No retry: a reviewer that did not answer says nothing about the
# image, so regenerating would be guesswork.
self.assertFalse(review.needs_improvement)
self.assertIn("timed out", review.error)
def test_a_scored_review_is_reported_verbatim(self) -> None:
self.generator._make_request = lambda **kwargs: {
"choices": [{"message": {"content": "**SCORE:** 9.5\n**VERDICT:** ACCEPTABLE"}}]
}
review = self.generator.review_image(*review_args)
self.assertEqual(review.score, 9.5)
self.assertTrue(review.reviewed)
self.assertIsNone(review.error)
ReviewFailureTests.__qualname__ = f"ReviewFailureTests[{module_name}]"
return ReviewFailureTests
@@ -27,6 +27,13 @@ import format_bibtex # noqa: E402
import validate_citations # noqa: E402
SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)
ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_schematic_ai"
)
ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator",
("diagram.png", "a prompt", 1, "journal", 2),
)
BIBLIOGRAPHY = """\
@article{jumper2021,
+311 -1
View File
@@ -45,7 +45,6 @@ def make_args(**overrides) -> argparse.Namespace:
n=None,
aspect_ratio=None,
resolution=None,
size=None,
quality=None,
output_format=None,
background=None,
@@ -56,6 +55,53 @@ def make_args(**overrides) -> argparse.Namespace:
return argparse.Namespace(**defaults)
# A trimmed stand-in for GET /api/v1/images/models, carrying the shapes that
# matter: enum values, ranges, and a bare capability flag.
CATALOGUE = {
"google/gemini-3.1-flash-image": {
"id": "google/gemini-3.1-flash-image",
"supported_parameters": {
"aspect_ratio": {"type": "enum", "values": ["1:1", "16:9", "21:9"]},
"resolution": {"type": "enum", "values": ["512", "1K", "2K", "4K"]},
"n": {"type": "range", "min": 1, "max": 1},
"input_references": {"type": "range", "min": 0, "max": 14},
},
},
"openai/gpt-image-2": {
"id": "openai/gpt-image-2",
"supported_parameters": {
"background": {"type": "enum", "values": ["auto", "opaque"]},
"quality": {"type": "enum", "values": ["auto", "low", "medium", "high"]},
"n": {"type": "range", "min": 1, "max": 10},
"input_references": {"type": "range", "min": 0, "max": 16},
},
},
"openai/gpt-image-1": {
"id": "openai/gpt-image-1",
"supported_parameters": {
"background": {"type": "enum", "values": ["auto", "transparent", "opaque"]},
"n": {"type": "range", "min": 1, "max": 10},
"input_references": {"type": "range", "min": 0, "max": 16},
},
},
"bytedance-seed/seedream-4.5": {
"id": "bytedance-seed/seedream-4.5",
"supported_parameters": {
"seed": {"type": "boolean"},
"n": {"type": "range", "min": 1, "max": 10},
"input_references": {"type": "range", "min": 0, "max": 14},
},
},
"black-forest-labs/flux.2-pro": {
"id": "black-forest-labs/flux.2-pro",
"supported_parameters": {
"seed": {"type": "boolean"},
"input_references": {"type": "range", "min": 0, "max": 8},
},
},
}
class CliSurfaceTests(unittest.TestCase):
def test_help_exits_zero(self):
completed = subprocess.run(
@@ -73,6 +119,45 @@ class CliSurfaceTests(unittest.TestCase):
self.assertNotEqual(completed.returncode, 0)
self.assertIn("prompt is required", completed.stderr)
def test_dry_run_prints_the_payload_without_network_or_key(self):
completed = subprocess.run(
[sys.executable, "-B", str(SCRIPT), "a cat", "--aspect-ratio", "16:9",
"--no-preflight", "--dry-run"],
text=True, capture_output=True, timeout=20, check=False,
env={**os.environ, "OPENROUTER_API_KEY": ""},
)
self.assertEqual(completed.returncode, 0, completed.stderr)
self.assertIn('"aspect_ratio": "16:9"', completed.stdout)
self.assertIn("nothing billed", completed.stdout)
def test_size_flag_is_gone(self):
"""No catalogue model accepts `size`; offering the flag only invites a 400."""
completed = subprocess.run(
[sys.executable, "-B", str(SCRIPT), "a cat", "--size", "2048x2048",
"--no-preflight", "--dry-run"],
text=True, capture_output=True, timeout=20, check=False,
)
self.assertNotEqual(completed.returncode, 0)
self.assertIn("unrecognized arguments", completed.stderr)
def test_output_format_does_not_offer_svg(self):
completed = subprocess.run(
[sys.executable, "-B", str(SCRIPT), "a cat", "--output-format", "svg",
"--no-preflight", "--dry-run"],
text=True, capture_output=True, timeout=20, check=False,
)
self.assertNotEqual(completed.returncode, 0)
self.assertIn("invalid choice", completed.stderr)
def test_out_of_range_compression_is_rejected_locally(self):
completed = subprocess.run(
[sys.executable, "-B", str(SCRIPT), "a cat", "--output-compression", "150",
"--no-preflight", "--dry-run"],
text=True, capture_output=True, timeout=20, check=False,
)
self.assertNotEqual(completed.returncode, 0)
self.assertIn("between 0 and 100", completed.stderr)
def test_targets_the_images_endpoint_not_chat_completions(self):
self.assertEqual(gi.IMAGES_URL, "https://openrouter.ai/api/v1/images")
self.assertEqual(gi.MODELS_URL, "https://openrouter.ai/api/v1/images/models")
@@ -114,6 +199,19 @@ class ApiKeyResolutionTests(unittest.TestCase):
finally:
os.chdir(previous)
def test_dotenv_export_prefix_is_tolerated(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / ".env").write_text(
"export OPENROUTER_API_KEY=exported-key\n", encoding="utf-8"
)
previous = os.getcwd()
os.chdir(tmp)
try:
os.environ.pop("OPENROUTER_API_KEY", None)
self.assertEqual(gi.find_api_key(None), "exported-key")
finally:
os.chdir(previous)
def test_absent_key_raises_with_guidance(self):
with tempfile.TemporaryDirectory() as tmp:
previous = os.getcwd()
@@ -150,6 +248,163 @@ class PayloadTests(unittest.TestCase):
[{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}],
)
def test_printed_payload_shortens_base64_references(self):
blob = "data:image/png;base64," + "A" * 500
payload = {"model": "m", "prompt": "p",
"input_references": [{"type": "image_url", "image_url": {"url": blob}}]}
shown = gi.redacted_payload(payload)
url = shown["input_references"][0]["image_url"]["url"]
self.assertLess(len(url), 80)
self.assertIn("chars of base64", url)
# The original is untouched, so the request still carries the real bytes.
self.assertEqual(payload["input_references"][0]["image_url"]["url"], blob)
class PreflightTests(unittest.TestCase):
"""The check that turns per-model parameter rules into free local errors."""
def test_valid_request_passes(self):
payload = gi.build_payload(make_args(aspect_ratio="16:9", resolution="2K"))
gi.preflight(payload, CATALOGUE)
def test_unsupported_parameter_is_caught(self):
payload = gi.build_payload(make_args(seed=42))
with self.assertRaises(gi.RequestRejected) as caught:
gi.preflight(payload, CATALOGUE)
self.assertIn("seed is not supported", str(caught.exception))
def test_value_outside_the_model_enum_is_caught(self):
payload = gi.build_payload(
make_args(model="openai/gpt-image-2", background="transparent")
)
with self.assertRaises(gi.RequestRejected) as caught:
gi.preflight(payload, CATALOGUE)
message = str(caught.exception)
self.assertIn("background=transparent is not allowed", message)
self.assertIn("auto, opaque", message)
def test_n_above_the_model_maximum_is_caught(self):
payload = gi.build_payload(make_args(n=4))
with self.assertRaises(gi.RequestRejected) as caught:
gi.preflight(payload, CATALOGUE)
self.assertIn("exceeds this model's maximum of 1", str(caught.exception))
def test_too_many_reference_images_are_caught(self):
payload = gi.build_payload(
make_args(model="black-forest-labs/flux.2-pro",
input=[f"https://e.com/{i}.png" for i in range(9)])
)
with self.assertRaises(gi.RequestRejected) as caught:
gi.preflight(payload, CATALOGUE)
self.assertIn("accepts at most 8", str(caught.exception))
def test_every_problem_is_reported_at_once(self):
payload = gi.build_payload(make_args(aspect_ratio="3:2", seed=1, n=9))
with self.assertRaises(gi.RequestRejected) as caught:
gi.preflight(payload, CATALOGUE)
self.assertIn("3 problems", str(caught.exception))
def test_unknown_model_suggests_close_matches(self):
payload = gi.build_payload(make_args(model="google/gemini-3.1-flash-imag"))
with self.assertRaises(gi.RequestRejected) as caught:
gi.preflight(payload, CATALOGUE)
self.assertIn("google/gemini-3.1-flash-image", str(caught.exception))
def test_suggestions_name_a_model_that_accepts_the_value(self):
payload = gi.build_payload(
make_args(model="openai/gpt-image-2", background="transparent")
)
with self.assertRaises(gi.RequestRejected):
gi.preflight(payload, CATALOGUE)
supporting = gi.models_supporting(CATALOGUE, "background", "transparent")
self.assertIn("openai/gpt-image-1", supporting)
self.assertNotIn("openai/gpt-image-2", supporting)
def test_suggestions_skip_undocumented_families(self):
"""FLUX is in the live catalogue but outside this skill's documented set."""
supporting = gi.models_supporting(CATALOGUE, "seed")
self.assertIn("bytedance-seed/seedream-4.5", supporting)
self.assertNotIn("black-forest-labs/flux.2-pro", supporting)
class SpecDescriptionTests(unittest.TestCase):
def test_enum_lists_its_values(self):
self.assertEqual(
gi.describe_spec({"type": "enum", "values": ["1K", "2K"]}), "1K, 2K"
)
def test_range_shows_its_bounds(self):
self.assertEqual(gi.describe_spec({"type": "range", "min": 0, "max": 16}), "0-16")
def test_bare_capability_reads_as_supported(self):
self.assertEqual(gi.describe_spec({"type": "boolean"}), "supported")
class RetryTests(unittest.TestCase):
def test_retry_after_header_is_honoured(self):
self.assertEqual(gi.retry_delay("7", 0), 7.0)
def test_absurd_retry_after_is_capped(self):
self.assertEqual(gi.retry_delay("99999", 0), 60.0)
def test_unparsable_retry_after_falls_back_to_backoff(self):
self.assertEqual(gi.retry_delay("in a bit", 2), 4.0)
def test_backoff_grows(self):
self.assertEqual([gi.retry_delay(None, i) for i in range(3)], [1.0, 2.0, 4.0])
def test_only_transient_statuses_retry(self):
self.assertIn(429, gi.RETRY_STATUS)
self.assertIn(503, gi.RETRY_STATUS)
self.assertNotIn(400, gi.RETRY_STATUS)
self.assertNotIn(401, gi.RETRY_STATUS)
class ErrorMessageTests(unittest.TestCase):
def test_bad_request_points_at_model_info(self):
detail = gi.error_detail(400, '{"error": {"message": "unsupported parameter"}}')
self.assertIn("unsupported parameter", detail)
self.assertIn("--model-info", detail)
def test_auth_failure_mentions_the_key_and_content_policy(self):
detail = gi.error_detail(403, '{"error": {"message": "forbidden"}}')
self.assertIn("openrouter.ai/keys", detail)
self.assertIn("content-policy", detail)
def test_non_json_body_is_passed_through(self):
self.assertIn("gateway timeout", gi.error_detail(504, "gateway timeout"))
class CostReportingTests(unittest.TestCase):
def test_reports_the_billed_cost(self):
lines = gi.cost_lines({"cost": 0.0672})
self.assertEqual(lines[0], "Cost: $0.0672")
def test_byok_upstream_cost_is_not_reported_as_free(self):
"""usage.cost is 0 on a BYOK key; the real spend is upstream."""
lines = gi.cost_lines(
{"cost": 0, "is_byok": True,
"cost_details": {"upstream_inference_cost": 0.03360275}}
)
self.assertIn("$0.03360275", lines[0])
self.assertIn("BYOK", lines[0])
def test_genuinely_free_generation_says_so(self):
self.assertEqual(gi.cost_lines({"cost": 0}), ["Cost: $0 reported"])
def test_image_tokens_are_reported_when_present(self):
lines = gi.cost_lines(
{"cost": 0.0672, "completion_tokens_details": {"image_tokens": 1120}}
)
self.assertIn("Image tokens: 1120", lines)
def test_missing_usage_reports_nothing(self):
self.assertEqual(gi.cost_lines({}), [])
def test_cost_never_prints_in_scientific_notation(self):
self.assertEqual(gi.format_cost(3e-05), "0.00003")
self.assertEqual(gi.format_cost(0.3), "0.3")
class ReferenceEncodingTests(unittest.TestCase):
def test_urls_and_data_urls_pass_through(self):
@@ -193,6 +448,10 @@ class OutputPathTests(unittest.TestCase):
def test_unknown_media_type_falls_back_to_png(self):
self.assertEqual(gi.output_paths(None, "image/unheard-of", 1), [Path("generated_image.png")])
def test_media_type_parameters_are_ignored(self):
self.assertEqual(gi.output_paths(None, "IMAGE/PNG; charset=binary", 1),
[Path("generated_image.png")])
def test_explicit_output_is_respected(self):
self.assertEqual(gi.output_paths("art.png", "image/png", 1), [Path("art.png")])
@@ -202,6 +461,10 @@ class OutputPathTests(unittest.TestCase):
[Path("out_1.png"), Path("out_2.png"), Path("out_3.png")],
)
def test_jpeg_spelling_is_not_a_mismatch(self):
"""`-o out.jpeg` names an image/jpeg response correctly, so say nothing."""
self.assertEqual(gi.acceptable_suffixes("image/jpeg"), {".jpg", ".jpeg"})
class SaveImageTests(unittest.TestCase):
def test_saves_base64_payload(self):
@@ -221,10 +484,35 @@ class SaveImageTests(unittest.TestCase):
gi.save_images(response, str(target))
self.assertTrue(target.is_file())
def test_numbering_has_no_gaps_when_an_entry_is_empty(self):
good = base64.b64encode(b"x").decode("ascii")
response = {"data": [
{"b64_json": good, "media_type": "image/png"},
{"media_type": "image/png"},
{"b64_json": good, "media_type": "image/png"},
]}
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "out.png"
written = gi.save_images(response, str(target))
self.assertEqual([p.name for p in written], ["out_1.png", "out_2.png"])
def test_empty_data_raises(self):
with self.assertRaises(gi.ApiError):
gi.save_images({"data": []}, None)
def test_entries_without_any_image_data_raise(self):
with self.assertRaises(gi.ApiError):
gi.save_images({"data": [{"media_type": "image/png"}]}, None)
def test_non_https_url_in_a_response_is_refused(self):
"""The URL comes from the response, not the caller, so it is not trusted."""
with self.assertRaises(gi.ApiError) as caught:
gi.image_bytes({"url": "http://evil.example/x.png"}, 5.0)
self.assertIn("non-HTTPS", str(caught.exception))
def test_downloaded_images_are_size_capped(self):
self.assertGreater(gi.MAX_DOWNLOAD_BYTES, 0)
class SkillDocumentTests(unittest.TestCase):
def test_frontmatter_version_matches_expected(self):
@@ -238,6 +526,28 @@ class SkillDocumentTests(unittest.TestCase):
def test_reference_file_is_present(self):
self.assertTrue((SKILL_ROOT / "references" / "models.md").is_file())
def test_documentation_does_not_promise_a_size_parameter(self):
for name in ("SKILL.md", "references/models.md"):
text = (SKILL_ROOT / name).read_text(encoding="utf-8")
self.assertNotIn("--size", text.replace("There is no `--size`", ""))
def test_transparent_background_is_not_offered_on_models_that_refuse_it(self):
"""gpt-image-2 allows only auto and opaque; recommending it wastes a call."""
text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
for line in text.splitlines():
stripped = line.strip()
# `$ ...` lines demonstrate the rejection itself, and prose that says
# the combination is unavailable is the warning, not a recommendation.
if stripped.startswith("$ ") or "not available" in stripped:
continue
if "--background transparent" in stripped:
self.assertNotIn("gpt-image-2", stripped)
def test_text_and_integrity_caveats_are_documented(self):
text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8").lower()
self.assertIn("never evidence", text)
self.assertIn("cannot be trusted with text", text)
if __name__ == "__main__":
unittest.main()
+10
View File
@@ -30,6 +30,16 @@ import generate_infographic # noqa: E402
CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
# `generate_infographic_ai.py` is a fork of the schematic generator and shares
# its review-parsing code, so it reuses the same contract.
ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_infographic_ai"
)
ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_infographic_ai", "InfographicGenerator",
("infographic.png", "a prompt", "statistical", 1, "default", 3),
)
class SubprocessEnvironmentTests(unittest.TestCase):
def test_only_allowlisted_variables_are_forwarded(self) -> None:
+7
View File
@@ -21,6 +21,13 @@ SCRIPTS = SKILL_ROOT / "scripts"
sys.path.insert(0, str(SCRIPTS))
SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)
ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_schematic_ai"
)
ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator",
("diagram.png", "a prompt", 1, "journal", 2),
)
CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
REVIEW_SCRIPT = SCRIPTS / "review_poster.sh"
+7
View File
@@ -28,6 +28,13 @@ sys.path.insert(0, str(SCRIPTS))
import search_databases # noqa: E402
SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)
ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_schematic_ai"
)
ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator",
("diagram.png", "a prompt", 1, "journal", 2),
)
RESULTS = [
{
@@ -20,6 +20,13 @@ SCRIPTS = SKILL_ROOT / "scripts"
sys.path.insert(0, str(SCRIPTS))
SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)
ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_schematic_ai"
)
ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator",
("diagram.png", "a prompt", 1, "journal", 2),
)
CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
+59 -35
View File
@@ -57,6 +57,24 @@ import slides_to_pdf # noqa: E402
import validate_presentation # noqa: E402
SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT)
ReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_schematic_ai"
)
ReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator",
("diagram.png", "a prompt", 1, "journal", 2),
)
# `generate_slide_image_ai.py` is a fork of the schematic generator, not one of
# the byte-identical copies, so it needs its own instantiation of the same
# review-parsing contract.
SlideImageReviewParsingTests = skill_contract.schematic.review_parsing_test_case(
SCRIPTS, "generate_slide_image_ai"
)
SlideImageReviewFailureTests = skill_contract.schematic.review_failure_test_case(
SCRIPTS, "generate_slide_image_ai", "SlideImageGenerator",
("slide.png", "a prompt", 1, False, 2),
)
CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
@@ -822,64 +840,70 @@ class ReviewDecisionTests(SlideGeneratorTestCase):
def test_a_score_at_the_threshold_is_accepted(self) -> None:
# 6.5 is the threshold itself, so it must not trigger another round.
_, score, needs_improvement = self.review(
{"content": "SCORE: 6.5\nVERDICT: ACCEPTABLE"}
)
self.assertEqual(score, 6.5)
self.assertFalse(needs_improvement)
review = self.review({"content": "SCORE: 6.5\nVERDICT: ACCEPTABLE"})
self.assertEqual(review.score, 6.5)
self.assertFalse(review.needs_improvement)
def test_a_score_below_the_threshold_asks_for_another_round(self) -> None:
_, score, needs_improvement = self.review({"content": "SCORE: 6.4"})
self.assertEqual(score, 6.4)
self.assertTrue(needs_improvement)
review = self.review({"content": "SCORE: 6.4"})
self.assertEqual(review.score, 6.4)
self.assertTrue(review.needs_improvement)
def test_an_explicit_verdict_overrides_a_high_score(self) -> None:
# The reviewer's words win: a 9 with NEEDS_IMPROVEMENT is not accepted.
_, score, needs_improvement = self.review(
{"content": "SCORE: 9\nVERDICT: NEEDS_IMPROVEMENT"}
)
self.assertEqual(score, 9.0)
self.assertTrue(needs_improvement)
review = self.review({"content": "SCORE: 9\nVERDICT: NEEDS_IMPROVEMENT"})
self.assertEqual(review.score, 9.0)
self.assertTrue(review.needs_improvement)
def test_a_loosely_worded_score_is_still_read(self) -> None:
_, score, _ = self.review({"content": "Overall quality: 8.5 out of 10"})
self.assertEqual(score, 8.5)
review = self.review({"content": "Overall quality: 8.5 out of 10"})
self.assertEqual(review.score, 8.5)
def test_an_unscored_review_does_not_block_the_pipeline(self) -> None:
# No parseable score: assume acceptable rather than loop pointlessly.
_, score, needs_improvement = self.review({"content": "Looks good to me"})
self.assertEqual(score, 7.0)
self.assertFalse(needs_improvement)
# No parseable score and no verdict: still no extra round, because a
# reviewer that said nothing measurable says nothing about the image.
# The score stays None -- a stand-in number here would reach the review
# log indistinguishable from one the reviewer actually gave.
review = self.review({"content": "Looks good to me"})
self.assertIsNone(review.score)
self.assertFalse(review.needs_improvement)
self.assertTrue(review.error)
def test_a_review_returned_as_content_blocks_is_flattened(self) -> None:
critique, score, _ = self.review(
review = self.review(
{"content": [{"type": "text", "text": "SCORE: 6.0"},
{"type": "text", "text": "ISSUES: crowded"}]}
)
self.assertEqual(score, 6.0)
self.assertIn("crowded", critique)
self.assertEqual(review.score, 6.0)
self.assertIn("crowded", review.critique)
def test_a_reasoning_only_reply_is_used_as_the_critique(self) -> None:
critique, score, _ = self.review({"content": "", "reasoning": "SCORE: 6.0"})
self.assertEqual(score, 6.0)
self.assertIn("SCORE", critique)
review = self.review({"content": "", "reasoning": "SCORE: 6.0"})
self.assertEqual(review.score, 6.0)
self.assertIn("SCORE", review.critique)
def test_a_failed_review_is_not_treated_as_a_bad_image(self) -> None:
with mock.patch.object(
self.generator, "_make_request", side_effect=RuntimeError("API down")
):
critique, score, needs_improvement = self.generator.review_image(
str(self.image_path), "a slide", 1
)
self.assertFalse(needs_improvement)
self.assertEqual(score, 7.0)
self.assertIn("review skipped", critique)
review = self.generator.review_image(str(self.image_path), "a slide", 1)
self.assertFalse(review.needs_improvement)
# Nor as a passing one: the image was never actually measured.
self.assertIsNone(review.score)
self.assertFalse(review.reviewed)
self.assertIn("API down", review.critique)
class RefinementLoopTests(SlideGeneratorTestCase):
PAYLOAD = b"first-image"
BETTER = b"second-image"
def reviewed(self, critique, score, needs_improvement):
"""A completed review, in the shape `review_image` returns."""
return self.module.ReviewResult(
critique, score, needs_improvement, reviewed=True
)
def generate(self, images, reviews, **kwargs):
destination = self.root / "slides" / "01_title.png"
with mock.patch.object(self.generator, "generate_image", side_effect=images) as drew, \
@@ -892,7 +916,7 @@ class RefinementLoopTests(SlideGeneratorTestCase):
def test_a_good_first_image_stops_early_and_is_written(self) -> None:
results, destination, drew = self.generate(
[self.PAYLOAD], [("great", 8.0, False)]
[self.PAYLOAD], [self.reviewed("great", 8.0, False)]
)
self.assertTrue(results["success"])
self.assertTrue(results["early_stop"])
@@ -905,7 +929,7 @@ class RefinementLoopTests(SlideGeneratorTestCase):
def test_a_weak_image_is_regenerated_from_an_improved_prompt(self) -> None:
results, destination, drew = self.generate(
[self.PAYLOAD, self.BETTER],
[("text too small", 5.0, True), ("better", 7.5, False)],
[self.reviewed("text too small", 5.0, True), self.reviewed("better", 7.5, False)],
)
self.assertTrue(results["success"])
self.assertEqual(len(results["iterations"]), 2)
@@ -917,7 +941,7 @@ class RefinementLoopTests(SlideGeneratorTestCase):
def test_the_iteration_ceiling_still_keeps_the_last_image(self) -> None:
results, destination, drew = self.generate(
[self.PAYLOAD, self.BETTER],
[("bad", 3.0, True), ("still bad", 4.0, True)],
[self.reviewed("bad", 3.0, True), self.reviewed("still bad", 4.0, True)],
iterations=2,
)
self.assertEqual(drew.call_count, 2)
@@ -935,7 +959,7 @@ class RefinementLoopTests(SlideGeneratorTestCase):
def test_the_mode_and_threshold_are_recorded_in_the_results(self) -> None:
results, _, _ = self.generate(
[self.PAYLOAD], [("fine", 7.0, False)], visual_only=True
[self.PAYLOAD], [self.reviewed("fine", 7.0, False)], visual_only=True
)
self.assertEqual(results["mode"], "visual_only")
self.assertEqual(results["quality_threshold"], 6.5)
+3 -2
View File
@@ -61,7 +61,8 @@ packages = ["requests", "python-dotenv"]
packages = ["requests", "python-dotenv"]
[skills.generate-image]
packages = ["requests"]
# The bundled CLI is standard-library only, and a test enforces that.
packages = []
[skills.markdown-mermaid-writing]
packages = []
@@ -86,7 +87,7 @@ packages = [
]
[skills.scientific-schematics]
packages = ["schemdraw", "matplotlib", "requests", "python-dotenv"]
packages = ["requests", "python-dotenv"]
[skills.scientific-visualization]
packages = ["matplotlib", "seaborn", "plotly", "pypdf", "pillow", "numpy"]