⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
whalechan-image-character
Propose DeepSeek Whale-chan character illustrations, let the user select directions, then separately confirm quantities, visual settings and candidate budget before generating verified PNGs. Use for character portraits and themed illustrations with consistent identity and customizable visuals; default to one image per selected proposal.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
Table of Contents
- Project Overview
- Special Statement and Disclaimer
- Whale-chan Character Profile
- Five Character Form Profiles and Proportions
- Visual Showcase Gallery
- Core Agent Skill Library
- Installation & Environment Setup
- Quickstart Guide
- Local Command-Line Toolchain
- Project Roadmap
- Contributing Guide
- License Information
- Character IP & Fanwork Copyright Attribution
- Friendly Links
📖 Project Overview
Whale-chan originated from spontaneous community creations and emotional resonance with the DeepSeek model's reasoning chain and outputs. A whale-fin maid girl who firmly believes that white rice is the ultimate hard currency for computing power, she is slightly tsundere, warm-hearted, and loves unapologetically slacking off in standby mode. She has sparked countless classic memes, stickers, and creative fanworks across social platforms, becoming a truly beloved community icon.
The DeepSeek Whale-chan project is an open-source character specification and Agent creation suite tailored for Whale-chan derivative content. By establishing unified visual standards, anatomical parameters, and automated toolchains, we empower creators and developers to reliably generate high-quality character illustrations, posters, stickers, and multi-panel comedy comics:
- 🎨 Visual Feature Locking: Standardized reference assets strictly locking hair gradient, whale-fin ears, forward cowlick, whale tail, and classic maid uniform;
- 📐 Quantified Form Proportions: Mathematically defined proportions from 4.0-head standard portraits down to 2.1-head chibi SD forms, verified by skeletal measurement tools;
- 🧠 Character Mindset Engine: Identifies the source's own comedy direction — reversal, exposure, escalation, recognition, or character gag — and preserves its humor and tone through Whale-chan's language, reactions, and timing;
- 🛠️ Full-Stack Toolchain Integration: Out-of-the-box Agent Skills and local scripts supporting multi-model routing and single-prompt delivery.
📢 Special Statement and Disclaimer
- Non-official Community Project: This project is a community-driven derivative fan creation and AI character consistency toolchain experiment, not officially affiliated with DeepSeek (Hangzhou DeepSeek Artificial Intelligence Basic Technology Research Co., Ltd.).
- Trademark and Brand Ownership: DeepSeek and related brand names mentioned in this project belong to their respective trademark holders.
- Safety & Content Ethics: All generated illustrations and comics must adhere to positive, safe, and lawful content standards, strictly prohibiting any unlawful uses, infringement on third-party rights, or violations of model provider terms of service.
📇 Whale-chan Character Profile
📐 Five Character Form Profiles and Proportions
Forms strictly control body proportions and skeletal ratios, without altering character age, identity, costume details, hair color, or cetacean physiology. The built-in skeletal joint fitting and pose neutralization algorithms enforce precise head-to-body ratio acceptance bands:
Form Code (form) | Target Ratio | Strict Acceptance Range | Visual Characteristics & Target Scenarios |
|---|---|---|---|
standard | 4.0 Heads | 3.846 ~ 4.146 | Standard Slender Form: Most elongated posture, natural limbs, clear torso structure. Best for standing displays, official concept sheets, and large posters. |
compact | 3.3 Heads | 3.105 ~ 3.405 | Compact Proportion Form: Moderately shortened limbs, stronger dynamic tension. Best for action poses, seated interactions, and medium-range illustrations. |
semi-chibi | 2.8 Heads | 2.695 ~ 2.995 | Default Baseline Form: Slightly larger head, rounded and compact torso and limbs, blending cuteness and scene adaptability. Default output baseline for all Skills. |
| `ch |
// HOW IT'S BUILT
// FILES
52 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/whalechan-image-character/SKILL.md12 KBb5ed1776a0e5upstream ↗
--- name: whalechan-image-character description: Propose DeepSeek Whale-chan character illustrations, let the user select directions, then separately confirm quantities, visual settings and candidate budget before generating verified PNGs. Use for character portraits and themed illustrations with consistent identity and customizable visuals; default to one image per selected proposal. --- # Whale-chan Image Character Create verified Whale-chan PNGs. Preserve Whale-chan's permanent identity while resolving every visual dimension independently from the user's request, typed reference images, and canonical defaults. A custom value changes only its own field. Workflow: propose → **Gate 1: select directions** → **Gate 2: confirm scope and begin** → expand, validate and freeze → generate, review and deliver. Selection alone is not permission to generate. ## Load guidance as needed - Read `references/proposal-selection.md` before presenting either gate or interpreting replies. - Read `references/assignment-schema.md` whenever normalizing, confirming, or freezing a request. - Read `references/character-spec.md` before building prompts or deciding whether a requested customization preserves Whale-chan identity. - Read `references/form-profiles.md` when resolving or measuring proportions. The five bundled forms are recommended presets, not the only allowed ratios. - Read `references/reference-index.md` when selecting bundled or user-supplied references. - Read `references/provider-routing.md` before any provider call or parallel run. - Read `references/qa-rubric.md` before reviewing or promoting a candidate. - Read `references/gallery.md` before exporting the completed task's preview gallery. - Treat `references/reference-catalog.json` as the machine-readable authority for bundled paths, hashes, preset ratios, and preset acceptance ranges. ## Choose the language Read `references/language-policy.md` before planning. Resolve one task `language`: explicit user instruction → meaningful current-session expression → newest meaningful local session within 24 hours → ask when uncertain. Use `scripts/detect-language.py` for historical evidence, not as an automatic verdict; recent sessions take precedence over aggregate counts. Save the normalized BCP-47 tag, actual resolution evidence and any explicit scoped overrides. Use it for communication, image lettering, HTML UI, drawing prompts and visible run/image titles. Preserve exact locked wording and necessary technical tokens. Keep internal IDs and filenames in English. Propagate the saved language to workers and resume from it; never redetect during execution. Prepare required plan/prompt locale sections before confirmation; use the offline gallery language selector for UI only. Keep generated content in its recorded language. See the language policy for custom dictionaries, display titles, scoped overrides and legacy compatibility. ## Resolve the request Resolve the request field by field while planning; build the complete schema v7 assignment only after Gate 2. Use the user's explicit instructions first, then references only for their declared roles, then canonical defaults for unresolved fields. Do not let a reference silently control unrelated dimensions. Defaults: - Five directions for an open theme; one image per selected proposal. A precisely specified scene uses direct proposals without inventing five alternatives. - `semi-chibi`; canonical style; canonical maid outfit. - Warm ivory-beige solid background `#F5EADD`; transparency off. - No visible text. When text is requested without a language, use the session language (see [Choose the language](#choose-the-language)); do not translate or invent wording without confirmation. - Full-body centered composition, `1:1`, PNG, provider-native resolution, automatic sub-agent execution (up to 10 workers, resolved from actual capacity before Gate 2). Prefer 1024×1024 when the selected provider exposes a compatible size control, but do not treat 1024×1024 as a default acceptance requirement. The user may explicitly request any style, action, outfit, solid/custom/transparent background, exact multilingual text, measurable head ratio greater than 1.0, positive-integer aspect ratio, or exact positive pixel resolution. If the user gives only width and height, derive the aspect ratio; if both are given, require them to agree. Keep extreme but measurable ratios possible; disclose that ratios outside the five presets have no bundled proportion reference and may be harder to satisfy. Provider safety and technical limits still apply. Input screenshots, chat logs, and dialogue supply subject matter only. They do not authorize copying UI, visible source text, avatars, brands, or visual style unless the user explicitly assigns those roles. Give the run an English kebab-case `run_name` and every image a unique English snake_case `name`. Write `run_title` and each image `title` in the resolved titles language. When one request contains several images, freeze a complete image-level configuration for each one rather than asking workers to inherit unstated choices. ## Obtain both user decisions 1. Prepare and review materially different directions for an open theme, or preserve the user's precisely specified scenes in direct mode. Show the seven-column Markdown table from `proposal-selection.md`, explain one image per selected proposal by default, and wait at **Gate 1**. Do not expand unselected alternatives into full image assignments. 2. Record the actual reply, chosen proposals, quantities and explicit changes. Prepare `scope.configurations` for the selected quantities: lock subject/action/composition, visual fields, exact text, output intent and reference permissions; state what execution details may vary. Use separate configurations when approved variants need different locked settings. 3. Show the Gate 2 summary generated by `summarize-selection`: titles, per-proposal counts, total images, adjustments, configurations, output, references, execution request, concrete sub-agent count and candidate budget. Explain a budget above 24 in this same summary. Wait for explicit permission to begin. Never infer it from silence or a recommendation. 4. After **Gate 2**, expand exactly the approved counts, review each execution against its proposal and locked requirements, validate and freeze internally. No third routine approval is required. A change to the core direction returns to Gate 1; changes to selection, counts, locked settings or budget require an updated Gate 2 summary and reply. Defect repairs within the approved scope and reduced runtime parallelism do not. ## Execute the confirmed assignment 1. Write the schema v7 assignment with both actual decision records described in `references/assignment-schema.md`, then validate and initialize it: ```bash python3 scripts/manage-run.py validate-assignment --assignment <assignment.json> python3 scripts/manage-run.py init --assignment <assignment.json> \ --effective-parallelism <current-capacity> --effective-subagents <actual-worker-count> ``` Recheck capacity before initialization and report any reduction. Pass the actual worker count and parallelism explicitly (0 workers and parallelism 1 for main-agent fallback). Never exceed the count confirmed at Gate 2. 2. Build each prompt from the normalized assignment in this order: permanent identity → theme → proportion target → resolved style → expression/action/composition → resolved outfit → props/objects → resolved background and alpha → exact text directive → typed-reference role limits → anatomy/contact constraints → output format, aspect ratio, and resolution intent. Include canonical locks only for fields whose mode is `canonical`. 3. Route providers and references according to `provider-routing.md`. Use one provider call per candidate and stop after the first complete PASS. Codex ImageGen comes first whenever Codex is available: inside Codex, call the built-in tool; in any other agent, run `scripts/generate-codex.py --check`, then generate with `generate-codex.py` while this agent keeps prompting, QA, recording and retries. Save each prompt to a file and run `python3 scripts/manage-run.py build-request --run-dir <run> --image <id> --prompt-file <prompt.txt>`; it writes `<prompt>.request.json` from the frozen references, hashes and output, for `generate-codex.py` and every fallback adapter. Record a failed check as a `codex` provider error and continue in provider order. Record Codex candidates with `--transport cli --provider-audit <output>.codex.json` (or `--transport builtin` inside Codex); an audit with `usable: false` is a failed candidate, and `usable: null` is recorded and reported as unverified. 4. Run deterministic image validation against the frozen resolution mode, inspect the original resolution, measure the frozen proportion, and complete the assignment-aware visual QA in `qa-rubric.md`. Never resize or crop a candidate to make it pass. Promote only when automatic and visual verdicts both pass. 5. Retry with one targeted correction at a time. Use at most 2 candidates per provider by default and 8 candidates per image total. 6. Finalize through `manage-run.py finalize`. Preserve failed numbering gaps and report final paths, provider/model, effective prompt, references, and QA result. If every provider failed only for setup reasons (`unavailable`, `authentication` or `quota`) while images still have unused candidates, leave the run open: a finalized run cannot accept more images. Report what to configure (install and log in to Codex CLI, or set a provider key) so the same run resumes without repeating either gate; close it with `--allow-failures` only when budgets are exhausted or the user asks. After Gate 2 and successful preparation/initialization, **create the confirmed number of sub-agents using the runtime's delegation tool**, reduced only for current capacity. Follow the dispatch and result-collection procedure in `references/provider-routing.md`; writing a parallelism field alone does not start workers. Reuse available workers for remaining images. The main agent alone writes the manifest and promotes finals. Each worker handles one candidate for one image at a time; retries and fallback for that image wait for the coordinator's record. Do not launch generation workers during planning or before the required batch review. The required batch review above is the existing [expansion consistency review](references/proposal-selection.md#expansion-consistency-review), completed during assignment expansion. ## Preview gallery Before final delivery, export the finalized run with `python3 scripts/export-gallery.py --run-dir <run>` and link the returned `gallery` HTML path. For a multi-source batch, keep each independent source group in its own run, with consecutive screenshots together in `input.content`; after all runs finalize, export one gallery using repeated `--run-dir` and an explicit `--output`. Include all proposals, final images and recorded attempts. A gallery is a read-only snapshot, not new QA or permission to generate. If setup failures leave a run open, resume it before exporting. Export errors do not require regeneration. See `references/gallery.md`. ## Hard stops - Do not initialize a formal run, generate, or call a paid image API before both gates for the current scope are complete and the assignment validates. Do not exceed the confirmed budget or fabricate approval. - Do not weaken permanent Whale-chan identity, anatomy/contact checks, or assignment-specific QA merely because another field is custom. - Do not accept missing, misspelled, illegible, additional, or wrong-language text. Source UI, signatures, watermarks, usernames, QR codes, and unconfirmed brand marks always fail. - Do not silently drop a reference, role, alpha requirement, or other confirmed field because a provider lacks the capability; route forward or seek renewed confirmation. - Do not silently resize, crop, or convert a provider-native result, and do not send an exact-resolution assignment to a provider that cannot guarantee its width and height. - Do not route around a safety rejection. Record it as a run-level halt, stop new dispatch, and quarantine uncommitted in-flight results. - Do not promote from automatic checks alone. - Do not overwrite bundled references, prior runs, attempts, staging results, or final files.skills/whalechan-image-character/scripts/detect-language.py7.9 KB8f9d203b324dupstream ↗
#!/usr/bin/env python3 """Summarize the scripts the user typed in recent local agent sessions; read-only. Scans Claude Code (~/.claude/projects) and Codex CLI (~/.codex/sessions) records from the last day, keeps only messages the user typed, and counts them by script. The agent makes the final language decision; this is evidence, not a verdict. """ from __future__ import annotations import argparse from collections import Counter from datetime import datetime, timedelta, timezone import hashlib import json import os from pathlib import Path import re import sys import unicodedata KANA = re.compile(r"[-ヿ]") HANGUL = re.compile(r"[가-]") HAN = re.compile(r"[一-鿿]") CYRILLIC = re.compile(r"[Ѐ-ӿ]") LATIN = re.compile(r"[A-Za-zÀ-ɏ]") # Drop paths, URLs and code so a Chinese request quoting a file path still reads as Chinese. NOISE = re.compile(r"```.*?```|`[^`]*`|https?://\S+|(?:~|\.{0,2})?/[\w.@~/-]+|\$[\w-]+", re.S) SIMPLIFIED = set("这个们说时会对还没为过发后来见问题国学开关门长东车马书图张让应该给实现简写语") TRADITIONAL = set("這個們說時會對還沒為過發後來見問題國學開關門長東車馬書圖張讓應該給實現簡寫語") INJECTED = ("<", "# AGENTS.md instructions", "Caveat:", "[Request interrupted by user") def parse_time(value: str | None) -> datetime | None: if not value: return None try: stamp = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None return stamp if stamp.tzinfo else stamp.replace(tzinfo=timezone.utc) def typed(text: str) -> str | None: text = text.strip() if not text or text.startswith(INJECTED): return None return text def claude_messages(root: Path, since: datetime): for path in root.glob("*/*.jsonl"): if datetime.fromtimestamp(path.stat().st_mtime, timezone.utc) < since: continue with path.open(encoding="utf-8", errors="replace") as handle: for line in handle: try: record = json.loads(line) except json.JSONDecodeError: continue if record.get("type") != "user" or record.get("isMeta") or record.get("isSidechain"): continue stamp = parse_time(record.get("timestamp")) content = (record.get("message") or {}).get("content") parts = [content] if isinstance(content, str) else [ item.get("text", "") for item in content or [] if isinstance(item, dict) and item.get("type") == "text"] for part in parts: if stamp and stamp >= since and (text := typed(part)): yield "claude-code", str(path), stamp, text def codex_messages(root: Path, since: datetime): for path in root.glob("*/*/*/rollout-*.jsonl"): if datetime.fromtimestamp(path.stat().st_mtime, timezone.utc) < since: continue interactive = True with path.open(encoding="utf-8", errors="replace") as handle: for line in handle: try: record = json.loads(line) except json.JSONDecodeError: continue payload = record.get("payload") or {} if record.get("type") == "session_meta": # `codex exec` sessions carry prompts written by tools such as generate-codex.py. source = payload.get("source") interactive = source != "exec" and not isinstance(source, dict) if not interactive or record.get("type") != "response_item" or payload.get("role") != "user": continue stamp = parse_time(record.get("timestamp")) for item in payload.get("content") or []: if stamp and stamp >= since and item.get("type") == "input_text" and (text := typed(item.get("text", ""))): yield "codex", str(path), stamp, text def classify(text: str) -> str | None: clean = NOISE.sub(" ", text) clean = "\n".join(line for line in clean.splitlines() if not line.lstrip().startswith(">")) if len(clean.strip()) < 3 or clean.strip().lower() in {"okay", "yes", "sure", "thanks", "continue"}: return None if KANA.search(clean): return "ja" if HANGUL.search(clean): return "ko" han = HAN.findall(clean) if len(han) >= 2: simplified = sum(char in SIMPLIFIED for char in han) traditional = sum(char in TRADITIONAL for char in han) return "zh-Hant" if traditional > simplified else "zh-Hans" if len(CYRILLIC.findall(clean)) >= 3: return "cyrillic" if len(LATIN.findall(clean)) >= 3: return "latin" if sum(unicodedata.category(char).startswith("L") for char in clean) >= 3: return "other" return None def detect(hours: float, home: Path, samples: int) -> dict: since = datetime.now(timezone.utc) - timedelta(hours=hours) seen, rows = set(), [] stores = {"claude-code": home / ".claude" / "projects", "codex": home / ".codex" / "sessions"} readers = {"claude-code": claude_messages, "codex": codex_messages} for agent, root in stores.items(): if not root.is_dir(): continue for source, session, stamp, text in readers[agent](root, since): # Deduplicate repeated transport records, not later messages with the same wording. key = (session, stamp, hashlib.sha256(text.encode("utf-8")).hexdigest()) if key in seen: continue seen.add(key) if (script := classify(text)): rows.append({"agent": source, "session": session, "time": stamp, "script": script, "text": text}) counts = Counter(row["script"] for row in rows) agents = Counter(row["agent"] for row in rows) leading = counts.most_common(1)[0][0] if counts else None rows.sort(key=lambda row: row["time"], reverse=True) sessions = {} for row in rows: session = sessions.setdefault(row["session"], {"session": row["session"], "agent": row["agent"], "last_user_message": row["time"].isoformat(), "by_script": {}, "latest": []}) script = row["script"] session["by_script"][script] = session["by_script"].get(script, 0) + 1 if len(session["latest"]) < samples: session["latest"].append({"script": script, "excerpt": row["text"][:240]}) if sessions: leading = max(next(iter(sessions.values()))["by_script"], key=next(iter(sessions.values()))["by_script"].get) return { "sessions": list(sessions.values()), "window_hours": hours, "stores": {agent: root.is_dir() for agent, root in stores.items()}, "messages": len(rows), "by_agent": dict(agents), "by_script": dict(counts.most_common()), "leading": leading, "suggested_tag": {"latin": None, "cyrillic": None, "other": None}.get(leading, leading), "latest": [{"agent": row["agent"], "time": row["time"].isoformat(), "script": row["script"], "excerpt": row["text"][:80]} for row in rows[:samples]], "note": "Latin or Cyrillic script does not identify the language; read the excerpts. " "Use current-session expression first; otherwise inspect the newest meaningful session, not global counts. Quoted source material may still require agent exclusion.", } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--hours", type=float, default=24) parser.add_argument("--samples", type=int, default=5) parser.add_argument("--home", default=os.path.expanduser("~"), help=argparse.SUPPRESS) args = parser.parse_args() print(json.dumps(detect(args.hours, Path(args.home), args.samples), ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": sys.exit(main())skills/whalechan-image-character/scripts/export-gallery.py20 KB0a9e1be57d02upstream ↗
#!/usr/bin/env python3 """Export completed runs to an offline gallery; never mutate run records.""" from __future__ import annotations import argparse import importlib.util import hashlib import json from pathlib import Path import shutil import subprocess import sys from datetime import datetime, timezone SKILL_ROOT = Path(__file__).resolve().parents[1] COMIC = SKILL_ROOT.name == "whalechan-image-comic" SPEC = importlib.util.spec_from_file_location("gallery_language", Path(__file__).with_name("language_policy.py")) language_policy = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(language_policy) class GalleryError(ValueError): pass def read_json(path): return json.loads(path.read_text(encoding="utf-8")) def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def tier_info(spec): """Describe the planned exaggeration tier and contrast.""" tier = spec.get("exaggeration") if not tier: return None contrast = spec.get("contrast") if not contrast: return {"tier": tier} tiers_path = SKILL_ROOT / "references" / "exaggeration-tiers.json" labels = ({axis["id"]: {"zh": axis["label_zh"], "en": axis["label"]} for axis in read_json(tiers_path)["axes"]} if tiers_path.is_file() else {}) return {"tier": tier, "lowered_to": contrast["lowered_to"], "axes": [{"id": axis, **labels.get(axis, {"zh": axis, "en": axis})} for axis in contrast["axes"]]} def picture_name(kind, label, language): return language_policy.locale({}, language, "gallery")["pictures"][kind].format(label=label) def localized_warning(warning, words): subject = warning["subject"] if isinstance(subject, dict): subject = words["pictures"][subject["kind"]].format(label=subject["label"]) return words["warnings"][warning["code"]].format(subject=subject, record=words["records"].get(warning.get("record"), "")) def as_text(value): if value is None: return "" return value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, indent=2) class RunReader: def __init__(self, run, assets): self.run = run self.assets = assets self.warnings = [] self.assignment = read_json(run / "assignment.json") self.manifest = read_json(run / "manifest.json") if self.assignment.get("schema_version") not in ((19, 20) if COMIC else (6, 7)): raise GalleryError(f"Unsupported assignment schema: {run.name}") if self.manifest.get("schema_version") != (1 if COMIC else 3): raise GalleryError(f"Unsupported manifest schema: {run.name}") if self.manifest.get("status") not in {"complete", "partial", "complete_with_failures"}: raise GalleryError(f"Finalize the run before exporting: {run.name}") if digest(run / "assignment.json") != self.manifest.get("assignment_sha256"): raise GalleryError(f"Assignment hash mismatch: {run.name}") ids = [item["id"] for item in self.assignment["images"]] if len(ids) != len(set(ids)) or set(ids) != set(self.manifest["images"]): raise GalleryError(f"Image inventory mismatch: {run.name}") def locate(self, value, external=False): if not value: return None path = Path(value) old_root = Path(self.assignment.get("run_dir", str(self.run))) candidates = [] if path.is_absolute() and path.is_relative_to(old_root): candidates.append(self.run / path.relative_to(old_root)) if not path.is_absolute(): candidates.append(self.run / path) if external: candidates.append(path if path.is_absolute() else SKILL_ROOT / path) original = self.assignment.get("source_assignment") if original and not path.is_absolute(): candidates.append(Path(original).parent / path) for candidate in candidates: resolved = candidate.resolve() if (external or resolved.is_relative_to(self.run)) and resolved.is_file(): return resolved return None def picture(self, path, label, expected=None, kind="final"): if path is None: self.warnings.append({"code": "image_missing", "subject": {"kind": kind, "label": label}}) return {"label": label, "kind": kind, "src": None} sha = digest(path) if expected and sha != expected: raise GalleryError(f"Image hash mismatch: {picture_name(kind, label, 'en')}") result = subprocess.run(["magick", "identify", "-ping", "-format", "%m %w %h", f"{path}[0]"], check=True, capture_output=True, text=True, timeout=30) format_name, width, height = result.stdout.split() extension = {"PNG": "png", "JPEG": "jpg", "WEBP": "webp", "GIF": "gif"}.get(format_name) width, height = int(width), int(height) if extension is None and kind == "source" and format_name in {"HEIC", "HEIF"}: native = self.assets / (sha + path.suffix.lower()) if not native.exists(): shutil.copyfile(path, native) preview = self.assets / (".preview-" + sha + ".png") subprocess.run(["magick", f"{path}[0]", str(preview)], check=True, capture_output=True, timeout=60) result = self.picture(preview, label, kind=kind) preview.unlink() return {**result, "original_src": "assets/" + native.name, "original_sha256": sha, "display_conversion": "HEIC/HEIF source to PNG"} if extension is None: raise GalleryError(f"Unsupported image format: {picture_name(kind, label, 'en')}") name = f"{sha}.{extension}" target = self.assets / name if not target.exists(): shutil.copyfile(path, target) return {"label": label, "kind": kind, "src": f"assets/{name}", "width": width, "height": height} def sidecar(self, value, subject, record, json_file=False): if isinstance(value, dict): return value path = self.locate(value) if path is None: self.warnings.append({"code": "record_missing", "subject": subject, "record": record}) return {} if json_file else "" return read_json(path) if json_file else path.read_text(encoding="utf-8") def attempt(self, record): key = record["attempt_id"] if COMIC else str(record["candidate_attempt"]) role = record.get("role", "candidate") qa = self.sidecar(record.get("visual_qa"), key, "visual_qa", True) if record.get("visual_qa") else {} auto = self.sidecar(record.get("automatic_qa"), key, "automatic_qa", True) if record.get("automatic_qa") else {} prompt = ( self.sidecar(record.get("prompt"), key, "prompt") if COMIC else record.get("prompt", "")) try: picture = self.picture(self.locate(record.get("candidate", record.get("candidate_path"))), key, record.get("candidate_sha256"), "candidate") except subprocess.SubprocessError: if not record.get("technical_error"): raise # Preserve undecodable output as a counted technical failure, not a final or a regeneration request. picture = self.picture(None, key, kind="candidate") return {"id": key, "role": role, "picture": picture, "sha256": record.get("candidate_sha256"), "prompt": prompt, "provider": record.get("provider"), "model": record.get("model"), "verdict": record.get("verdict"), "created_at": record.get("created_at"), "defects": qa.get("defects", qa.get("core_defects", [])) or ([record["technical_error"]] if record.get("technical_error") else []), "minor_issues": qa.get("minor_issues", []), "targeted_retry": qa.get("targeted_retry"), "automatic": auto.get("overall"), "visual": qa.get("verdict")} def image(self, spec): state = self.manifest["images"][spec["id"]] records = state.get("attempts", []) attempts = [self.attempt(record) for record in records] final = None if state.get("status") == "passed": final = self.picture(self.locate(state.get("final_path")), spec["id"], state.get("final_sha256")) matches = [item for item in attempts if item["sha256"] and item["sha256"] == state.get("final_sha256") and item["verdict"] == "PASS"] origin = matches[0] if len(matches) == 1 else None if final and not origin: self.warnings.append({"code": "final_ambiguous" if matches else "final_unrecorded", "subject": spec["id"]}) return {"id": spec["id"], "title": spec.get("title"), "name": spec.get("title", spec.get("name", spec["id"])), "note": spec.get("execution_note", ""), "status": state.get("status"), "tier": tier_info(spec) if COMIC else None, "final": final, "final_sha256": state.get("final_sha256"), "origin": origin, "attempts": attempts, "calls": sum(item.get("consumes_candidate_budget", True) is not False for item in state.get("attempts", [])), "errors": [{key: error.get(key) for key in ("provider", "model", "category", "details", "created_at")} for error in state.get("provider_errors", [])]} def gallery_images(self, proposals): pictures = [] for proposal in proposals: for image in proposal["images"]: matched = False for index, attempt in enumerate(image["attempts"]): if not attempt["picture"].get("src"): continue matches_final = bool(image["final"] and attempt["sha256"] and attempt["sha256"] == image["final_sha256"] and attempt["verdict"] == "PASS") matched |= matches_final pictures.append({"image_id": image["id"], "proposal_choice": proposal["choice"], "attempt_index": index, "picture": attempt["picture"], "created_at": attempt["created_at"], "is_final": attempt is image["origin"], "matches_final": matches_final}) if image["final"] and image["final"].get("src") and not matched: origin = image["origin"] pictures.append({"image_id": image["id"], "proposal_choice": proposal["choice"], "attempt_index": image["attempts"].index(origin) if origin else None, "picture": image["final"], "created_at": origin["created_at"] if origin else None, "is_final": True, "matches_final": True}) def recorded_time(item): value = item["created_at"] if value: try: stamp = datetime.fromisoformat(value.replace("Z", "+00:00")) return (0, stamp.replace(tzinfo=stamp.tzinfo or timezone.utc).timestamp()) except ValueError: pass return (1, 0) return sorted(pictures, key=recorded_time) def sources(self): source = self.assignment.get("input", {}) content = source.get("content") originals = [] if source.get("type") in {"image", "screenshot"}: values = content if isinstance(content, list) else [content] for index, value in enumerate(values, 1): archived = sorted((self.run / "source").glob(f"original-{index:02d}.*")) path = archived[0] if archived else None originals.append(self.picture(path, str(index), kind="source")) # A source analysis is an interpretation, never the user's original words. request = "" else: request = "\n".join(as_text(item) for item in content) if isinstance(content, list) else as_text(content) analysis = source.get("source_analysis", {}).get("source_event", "") return request, originals, analysis def build(self): assignment = self.assignment options = assignment.get("proposal", {}).get("options", []) counts = {item["choice"]: item["count"] for item in assignment.get("selection", {}).get("choices", [])} proposals = [] assigned = set() ranked_comic = COMIC for index, option in enumerate(options, 1): choice = str(index) if ranked_comic else option["choice"] specs = [spec for spec in assignment["images"] if (spec.get("idea_id") == option.get("idea_id") if COMIC else spec.get("proposal_choice") == option["choice"])] assigned.update(spec["id"] for spec in specs) proposals.append({"choice": choice, "title": option["title"], "scene": option.get("scene", ""), "detail": option.get("twist", option.get("action_expression", "")), "selected": option["idea_id"] in assignment.get("ranked_ideas", []) if ranked_comic else choice in counts, "planned": 1 if ranked_comic else counts.get(choice, 0), "images": [self.image(spec) for spec in specs]}) if assigned != set(self.manifest["images"]): raise GalleryError(f"Unlinked proposal images: {self.run.name}") if COMIC: included = {option.get("idea_id") for option in options} for candidate in assignment.get("creative_pool", []): if candidate["id"] in included: continue proposals.append({"choice": str(len(proposals) + 1), "title": candidate["premise"], "scene": candidate["scene"], "detail": candidate["punchline"], "selected": False, "planned": 0, "images": []}) references = [] seen = set() for spec in assignment["images"]: for ref in spec.get("references", []): key = (ref.get("sha256") or ref.get("path"), tuple(ref.get("roles", []))) if key in seen: continue seen.add(key) picture = self.picture(self.locate(ref.get("path"), external=True), ref.get("id", ""), ref.get("sha256"), "reference") references.append({**picture, "roles": ref.get("roles", [])}) request, originals, analysis = self.sources() images = [image for proposal in proposals for image in proposal["images"]] group = {"title": assignment.get("run_title", assignment["run_name"]), "status": self.manifest["status"], "date": self.manifest.get("finalized_at", self.manifest.get("completed_at")), "request": request, "originals": originals, "analysis": analysis, "references": references, "proposals": proposals, "planned": len(images), "passed": sum(item["status"] == "passed" for item in images), "calls": sum(item["calls"] for item in images), "errors": sum(len(item["errors"]) for item in images), "warnings": list({json.dumps(item, sort_keys=True): item for item in self.warnings}.values())} if COMIC: group["selection_review"] = assignment["selection_review"] if COMIC: group["gallery_images"] = self.gallery_images(proposals) group["collection_reviews"] = [] for review in self.manifest.get("collection", {}).get("reviews", []): review_path = self.locate(review["path"]) if review_path is None or digest(review_path) != review["sha256"]: raise GalleryError("Collection review is missing or changed") sheet = review_path.with_name("sheet.png") picture = self.picture(sheet if sheet.is_file() else None, str(review["round"] + 1), review["sheet_sha256"], "reference") group["collection_reviews"].append({"picture": picture, "review": read_json(review_path)}) group["task_outcomes"] = {key: value["status"] for key, value in self.manifest["images"].items()} group["stage_events"] = self.manifest.get("events", []) return group def export_gallery(run_dirs, output=None, language=None, locales=None): runs = [Path(path).resolve() for path in run_dirs] if not runs or len(set(runs)) != len(runs): raise GalleryError("Supply distinct run directories") if len(runs) > 1 and output is None: raise GalleryError("Batch export requires --output") assignments = [read_json(run / "assignment.json") for run in runs] language = language or (language_policy.effective(assignments[0], "interface") if assignments[0].get("language") else "zh") strings, names, directions = language_policy.gallery_locales(assignments + [{"language": language}], locales) destination = Path(output).resolve() if output else runs[0] / "gallery" base = destination number = 2 while destination.exists(): destination = base.with_name(f"{base.name}-{number:02d}") number += 1 destination.mkdir(parents=True) try: assets = destination / "assets" assets.mkdir() groups = [RunReader(run, assets).build() for run in runs] data = {"skill": "comic" if COMIC else "character", "language": language, "groups": groups, "exported_at": datetime.now(timezone.utc).isoformat(), "locales": strings, "locale_names": names, "locale_directions": directions, "gallery_id": hashlib.sha256(str(destination).encode()).hexdigest()} template_root = SKILL_ROOT / "assets" / "gallery" template = (template_root / "index.html").read_text(encoding="utf-8") payload = json.dumps(data, ensure_ascii=False).replace("<", "\<").replace( " ", "\ ").replace(" ", "\ ") # Insert data last: user text is never interpreted as HTML or a template token. html = template.replace("/* GALLERY_CSS */", (template_root / "gallery.css").read_text(encoding="utf-8")) html = html.replace("/* GALLERY_JS */", (template_root / "gallery.js").read_text(encoding="utf-8")) html = html.replace('<html lang="zh-CN">', f'<html lang="{language_policy.tag(language)}" dir="{directions[language_policy.tag(language)]}">') html = html.replace("GALLERY_DATA", payload) (destination / "index.html").write_text(html, encoding="utf-8") except Exception: shutil.rmtree(destination) raise return {"gallery": str(destination / "index.html"), "groups": len(groups), "warnings": {str(index + 1): [localized_warning(item, strings[language_policy.tag(language)]) for item in group["warnings"]] for index, group in enumerate(groups) if group["warnings"]}} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--run-dir", action="append", required=True) parser.add_argument("--output") parser.add_argument("--locales", help="JSON locale packs keyed by BCP-47 tag") parser.add_argument("--language", help="Initial page language; defaults to the saved task interface language") args = parser.parse_args() try: print(json.dumps(export_gallery(args.run_dir, args.output, args.language, read_json(Path(args.locales)) if args.locales else None), ensure_ascii=False, indent=2)) except (GalleryError, OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: print(json.dumps({"error": str(error)}, ensure_ascii=False), file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/scripts/generate-codex.py17 KB29b615415a79upstream ↗
#!/usr/bin/env python3 """Generate one Whale-chan candidate through the local Codex CLI's built-in ImageGen.""" from __future__ import annotations import argparse import hashlib import json import os import re import shutil import subprocess import sys import tempfile import time from pathlib import Path from typing import Any IMAGE_MODEL = "gpt-image" REASONING_EFFORT = "low" SAFETY_MARKERS = ("safety", "moderation", "policy", "content_filter", "blocked") QUOTA_MARKERS = ("usage limit", "quota", "insufficient", "billing") RATE_MARKERS = ("rate limit", "rate_limit", "too many requests", "429") # Specific phrases only: a bare "login" also appears in unrelated service errors. AUTH_MARKERS = ("not logged in", "please log in", "login required", "unauthorized", "401", "authentication failed") class AdapterError(RuntimeError): def __init__(self, message: str, category: str = "service") -> None: super().__init__(message) self.category = category REFERENCE_ROLES = { "identity", "style", "pose_action", "composition", "costume", "background", "typography", "proportion", } def load_request(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise AdapterError(f"Cannot read request JSON: {exc}", "capability") from exc if not isinstance(value, dict) or not isinstance(value.get("prompt"), str) or not value["prompt"].strip(): raise AdapterError("request.prompt must be a non-empty string", "capability") if value.keys() - {"prompt", "references", "aspect_ratio", "resolution", "output", "quality"}: raise AdapterError("request contains unsupported fields", "capability") refs = value.get("references") if not isinstance(refs, list) or not refs: raise AdapterError("request.references must contain at least 1 reference", "capability") audited: list[dict[str, Any]] = [] for index, item in enumerate(refs): if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not item["path"].strip(): raise AdapterError(f"request.references[{index}].path must be a non-empty string", "capability") roles = item.get("roles") if ( not isinstance(roles, list) or not roles or any(not isinstance(role, str) for role in roles) or len(set(roles)) != len(roles) or not set(roles) <= REFERENCE_ROLES ): raise AdapterError(f"request.references[{index}].roles contains an invalid or duplicate role", "capability") instruction = item.get("instruction") if instruction is not None and not isinstance(instruction, str): raise AdapterError(f"request.references[{index}].instruction must be a string", "capability") ref = Path(item["path"]) if not ref.is_absolute(): ref = (path.parent / ref).resolve() if not ref.is_file(): raise AdapterError(f"Reference image does not exist: {ref}", "capability") if item.get("sha256") is not None: if item["sha256"].lower() != hashlib.sha256(ref.read_bytes()).hexdigest(): raise AdapterError(f"request.references[{index}].sha256 does not match the reference image", "capability") audited.append({ "id": item.get("id", f"reference-{index + 1}"), "path": str(ref), "roles": roles, "instruction": instruction, "sha256": item.get("sha256"), }) output = value.get("output") if not isinstance(output, dict) or set(output) != {"format", "alpha"} or output.get("format") != "png": raise AdapterError("request.output must contain exactly format png and alpha", "capability") if not isinstance(output.get("alpha"), bool): raise AdapterError("request.output.alpha must be a boolean", "capability") if output["alpha"]: raise AdapterError( "Codex ImageGen transparent output is not verified; alpha needs the next provider", "capability", ) aspect_ratio = value.get("aspect_ratio") if not isinstance(aspect_ratio, str) or re.fullmatch(r"[1-9]\d*:[1-9]\d*", aspect_ratio) is None: raise AdapterError("request.aspect_ratio must be a positive WIDTH:HEIGHT ratio", "capability") resolution = value.get("resolution") if not isinstance(resolution, dict) or set(resolution) != {"mode", "width", "height"}: raise AdapterError("request.resolution must contain exactly mode, width, and height", "capability") if resolution["mode"] == "exact": raise AdapterError( "Codex ImageGen exposes no pixel-size control; exact resolution needs the next provider", "capability", ) if resolution["mode"] != "provider-native" or resolution["width"] is not None or resolution["height"] is not None: raise AdapterError("provider-native resolution requires null width and height", "capability") value["references"] = audited value["requested_output"] = { "aspect_ratio": aspect_ratio, "resolution": resolution, "output": output, } return value def codex_home() -> Path: return Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") def run_quiet(command: list[str], timeout: int) -> subprocess.CompletedProcess[str]: try: return subprocess.run(command, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired as exc: raise AdapterError(f"{' '.join(command[:2])} timed out after {timeout}s", "timeout") from exc except OSError as exc: raise AdapterError(f"Cannot run {command[0]}: {exc}", "unavailable") from exc def check_codex() -> dict[str, Any]: executable = shutil.which("codex") if executable is None: raise AdapterError("Codex CLI is not installed or not on PATH", "unavailable") version = run_quiet([executable, "--version"], 30) status = run_quiet([executable, "login", "status"], 30) detail = (status.stdout + status.stderr).strip() if status.returncode != 0 or "logged in" not in detail.lower() or "not logged in" in detail.lower(): raise AdapterError(f"Codex CLI is not logged in: {detail[:300]}", "authentication") return { "executable": executable, "version": version.stdout.strip() or version.stderr.strip(), "login": detail.splitlines()[0] if detail else "", } def build_instruction(spec: dict[str, Any]) -> str: lines = [ "Call your built-in image generation tool exactly once, passing the text between " "<prompt> tags verbatim as the image prompt and including every attached image. " "Do not run shell commands, edit files, or rewrite the prompt.", "", "Attached images, in order:", ] for index, ref in enumerate(spec["references"], start=1): note = ref["instruction"] or "use only for the declared roles" lines.append(f"- Image {index} ({', '.join(ref['roles'])}): {note}") lines.extend([ "", "After the tool returns, reply with only DONE.", "", "<prompt>", spec["prompt"].strip(), "</prompt>", "", ]) return "\n".join(lines) def codex_command(executable: str, workdir: Path, references: list[dict[str, Any]]) -> list[str]: command = [ executable, "exec", "--skip-git-repo-check", "-s", "read-only", "--json", "-C", str(workdir), "-c", f'model_reasoning_effort="{REASONING_EFFORT}"', ] for ref in references: command.extend(["-i", ref["path"]]) # `-i` accepts several values; `--` stops it from swallowing the stdin marker. command.extend(["--", "-"]) return command def classify_text(text: str, *, image_failure: bool = False) -> str: lowered = text.lower() # Safety is only inferred from an ImageGen failure, never from general CLI noise. if image_failure and any(marker in lowered for marker in SAFETY_MARKERS): return "safety_rejection" for markers, category in ( (QUOTA_MARKERS, "quota"), (RATE_MARKERS, "rate_limit"), (AUTH_MARKERS, "authentication"), ): if any(marker in lowered for marker in markers): return category return "service" def parse_events(stdout: str) -> tuple[str | None, list[str]]: thread_id = None failures: list[str] = [] for line in stdout.splitlines(): try: event = json.loads(line) except json.JSONDecodeError: continue kind = event.get("type") if kind == "thread.started": thread_id = event.get("thread_id") elif kind in {"turn.failed", "error"}: error = event.get("error") or event failures.append(str(error.get("message") or error)) return thread_id, failures def find_rollout(home: Path, thread_id: str) -> Path | None: for _ in range(10): matches = sorted(home.glob(f"sessions/*/*/*/rollout-*{thread_id}.jsonl")) if matches: return matches[-1] time.sleep(0.5) return None def read_rollout(path: Path) -> dict[str, Any]: generations: list[dict[str, Any]] = [] attached = 0 tool_images: int | None = None for line in path.read_text(encoding="utf-8").splitlines(): try: payload = json.loads(line).get("payload", {}) except json.JSONDecodeError: continue item = payload.get("item") or {} if item.get("kind") == "image_gen.generation": generations.append(item) elif payload.get("type") == "message" and payload.get("role") == "user": attached = max(attached, sum( 1 for part in payload.get("content", []) if part.get("type") == "input_image" )) elif payload.get("type") == "custom_tool_call" and "image_gen" in str(payload.get("input")): # ImageGen receives references either as recent attachments or as explicit paths. call = payload["input"] recent = re.search(r"num_last_images_to_include\s*:\s*(\d+)", call) paths = re.search(r"referenced_image_paths\s*:\s*\[(.*?)\]", call, re.S) tool_images = (int(recent.group(1)) if recent else 0) + ( len(re.findall(r'"(?:[^"\\]|\\.)*"', paths.group(1))) if paths else 0 ) return {"generations": generations, "attached_images": attached, "tool_reference_images": tool_images} def usable_verdict(prompt_verbatim: bool | None, tool_images: int | None, expected: int) -> bool | None: """False: prompt rewritten or references dropped. None: the session record could not verify either.""" if prompt_verbatim is False or tool_images not in (None, expected): return False if prompt_verbatim is None or tool_images is None: return None return True def copy_once(source: Path, destination: Path) -> None: if destination.exists(): raise AdapterError(f"Output already exists: {destination}", "capability") destination.parent.mkdir(parents=True, exist_ok=True) fd, temp_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent) os.close(fd) try: shutil.copyfile(source, temp_name) os.replace(temp_name, destination) except Exception: Path(temp_name).unlink(missing_ok=True) raise def write_json_once(path: Path, value: dict[str, Any]) -> None: if path.exists(): raise AdapterError(f"Audit file already exists: {path}", "capability") path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def generate(spec: dict[str, Any], codex: dict[str, Any], output: Path, audit_path: Path, timeout: int) -> dict[str, Any]: instruction = build_instruction(spec) started = time.time() with tempfile.TemporaryDirectory(prefix="whalechan-codex-") as workdir: command = codex_command(codex["executable"], Path(workdir), spec["references"]) try: completed = subprocess.run( command, input=instruction, capture_output=True, text=True, timeout=timeout, cwd=workdir ) except subprocess.TimeoutExpired as exc: raise AdapterError(f"codex exec timed out after {timeout}s", "timeout") from exc thread_id, failures = parse_events(completed.stdout) if thread_id is None: detail = (completed.stderr or completed.stdout).strip()[-1000:] raise AdapterError(f"codex exec did not start a thread: {detail}", classify_text(detail)) home = codex_home() rollout = find_rollout(home, thread_id) evidence = read_rollout(rollout) if rollout else { "generations": [], "attached_images": None, "tool_reference_images": None, } generations = evidence["generations"] for item in generations: if item.get("failure"): raise AdapterError(f"Codex ImageGen failed: {item['failure']}", classify_text(str(item["failure"]), image_failure=True)) saved = [Path(item["savedPath"]) for item in generations if item.get("savedPath")] revised = generations[0].get("revisedPrompt") if generations else None if not saved: # Rollout format is not a public contract; fall back to the thread's image directory. saved = sorted((home / "generated_images" / thread_id).glob("*.png")) if not saved: detail = "; ".join(failures) or (completed.stderr or "").strip()[-1000:] or "no image was produced" raise AdapterError(f"Codex returned no image (thread {thread_id}): {detail}", classify_text(detail)) source = saved[0] if not source.is_file(): raise AdapterError(f"Codex image is missing on disk: {source}", "service") copy_once(source, output) prompt_verbatim = None if revised is None else revised.strip() == spec["prompt"].strip() audit = { "provider": "codex", "transport": "cli", "model": IMAGE_MODEL, "codex_version": codex["version"], "thread_id": thread_id, "rollout_path": str(rollout) if rollout else None, "saved_path": str(source), "generation_count": len(saved), "attached_images": evidence["attached_images"], "tool_reference_images": evidence["tool_reference_images"], "expected_reference_images": len(spec["references"]), "prompt_sha256": hashlib.sha256(spec["prompt"].strip().encode("utf-8")).hexdigest(), "prompt_verbatim": prompt_verbatim, "revised_prompt": revised, "references": spec["references"], "requested_output": spec["requested_output"], "output": str(output), "output_sha256": hashlib.sha256(output.read_bytes()).hexdigest(), "duration_seconds": round(time.time() - started, 1), } audit["usable"] = usable_verdict(prompt_verbatim, audit["tool_reference_images"], len(spec["references"])) write_json_once(audit_path, audit) return audit def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check", action="store_true", help="Only report whether Codex CLI can be used") parser.add_argument("--request") parser.add_argument("--output") parser.add_argument("--audit", help="Audit JSON path; defaults to <output>.codex.json") parser.add_argument("--timeout", type=int, default=420) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() try: if args.check: print(json.dumps({"ok": True, "provider": "codex", "transport": "cli", **check_codex()}, ensure_ascii=False, indent=2)) return 0 if not args.request or not args.output: parser.error("--request and --output are required unless --check is used") spec = load_request(Path(args.request).resolve()) output = Path(args.output).resolve() audit_path = Path(args.audit).resolve() if args.audit else output.with_name(output.name + ".codex.json") if args.dry_run: executable = shutil.which("codex") or "codex" print(json.dumps({ "ok": True, "provider": "codex", "transport": "cli", "model": IMAGE_MODEL, "command": codex_command(executable, Path("<temporary-directory>"), spec["references"]), "instruction": build_instruction(spec), "references": spec["references"], "requested_output": spec["requested_output"], "output": str(output), "audit": str(audit_path), "dry_run": True, }, ensure_ascii=False, indent=2)) return 0 for path in (output, audit_path): if path.exists(): raise AdapterError(f"Output already exists: {path}", "capability") audit = generate(spec, check_codex(), output, audit_path, args.timeout) print(json.dumps({"ok": True, "audit": str(audit_path), **{ key: audit[key] for key in ( "provider", "transport", "model", "thread_id", "prompt_verbatim", "usable", "tool_reference_images", "expected_reference_images", "output", "output_sha256", "duration_seconds", ) }}, ensure_ascii=False, indent=2)) return 0 except AdapterError as exc: print(json.dumps({"ok": False, "category": exc.category, "error": str(exc)}, ensure_ascii=False), file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/scripts/generate-nanobanana.py13 KB0d1f3378e48aupstream ↗
#!/usr/bin/env python3 """Generate one Whale-chan candidate through the Gemini Nano Banana API.""" from __future__ import annotations import argparse import base64 import hashlib import json import os import sys import tempfile import urllib.error import urllib.request from pathlib import Path from typing import Any REFERENCE_ROLES = { "identity", "style", "pose_action", "composition", "costume", "background", "typography", "proportion", } class AdapterError(RuntimeError): def __init__(self, message: str, category: str = "service") -> None: super().__init__(message) self.category = category def load_request(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise AdapterError(f"Cannot read request JSON: {exc}", "capability") from exc allowed_fields = { "prompt", "references", "aspect_ratio", "resolution", "output", "image_size" } if isinstance(value, dict) and value.keys() - allowed_fields: raise AdapterError("request contains unsupported fields", "capability") if not isinstance(value, dict) or not isinstance(value.get("prompt"), str) or not value["prompt"].strip(): raise AdapterError("request.prompt must be a non-empty string", "capability") refs = value.get("references") if not isinstance(refs, list) or not refs: raise AdapterError("request.references must contain at least 1 reference", "capability") normalized: list[dict[str, Any]] = [] for index, item in enumerate(refs): if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not item["path"].strip(): raise AdapterError(f"request.references[{index}].path must be a non-empty string", "capability") raw_roles = item.get("roles") if not isinstance(raw_roles, list) or not raw_roles or any( not isinstance(role, str) or not role.strip() for role in raw_roles ): raise AdapterError(f"request.references[{index}].roles must be a non-empty list of strings", "capability") instruction = item.get("instruction") if instruction is not None and not isinstance(instruction, str): raise AdapterError(f"request.references[{index}].instruction must be a string", "capability") raw_path = item["path"] roles = [role.strip() for role in raw_roles] if len(set(roles)) != len(roles) or not set(roles) <= REFERENCE_ROLES: raise AdapterError( f"request.references[{index}].roles contains an invalid or duplicate role", "capability", ) ref = Path(raw_path) if not ref.is_absolute(): ref = (path.parent / ref).resolve() if not ref.is_file(): raise AdapterError(f"Reference image does not exist: {ref}", "capability") normalized_ref: dict[str, Any] = {"path": ref, "roles": roles} for field in ("id", "sha256"): if field in item: if not isinstance(item[field], str) or not item[field].strip(): raise AdapterError( f"request.references[{index}].{field} must be a non-empty string", "capability", ) normalized_ref[field] = item[field].strip() expected_sha256 = normalized_ref.get("sha256") if expected_sha256 is not None: actual_sha256 = hashlib.sha256(ref.read_bytes()).hexdigest() if expected_sha256.lower() != actual_sha256: raise AdapterError( f"request.references[{index}].sha256 does not match the reference image", "capability", ) if instruction is not None: normalized_ref["instruction"] = instruction normalized.append(normalized_ref) output = value.get("output") if not isinstance(output, dict) or set(output) != {"format", "alpha"}: raise AdapterError("request.output must contain exactly format and alpha", "capability") if output.get("format") != "png": raise AdapterError("request.output.format must be png", "capability") alpha = output.get("alpha") if not isinstance(alpha, bool): raise AdapterError("request.output.alpha must be a boolean", "capability") if alpha: raise AdapterError( "Nano Banana adapter has no verified native transparent-output contract", "capability", ) aspect_ratio = value.get("aspect_ratio") if aspect_ratio not in {"1:1", "9:16"}: raise AdapterError("request.aspect_ratio must be 1:1 or 9:16", "capability") resolution = value.get("resolution") if not isinstance(resolution, dict) or set(resolution) != {"mode", "width", "height"}: raise AdapterError( "request.resolution must contain exactly mode, width, and height", "capability", ) if resolution.get("mode") != "provider-native": raise AdapterError( "Nano Banana cannot guarantee an exact pixel resolution", "capability", ) if resolution.get("width") is not None or resolution.get("height") is not None: raise AdapterError( "provider-native resolution requires null width and height", "capability", ) value["resolution"] = { "mode": "provider-native", "width": None, "height": None, } value["references"] = normalized value["reference_paths"] = [item["path"] for item in normalized] value["output"] = {**output, "alpha": alpha} return value def effective_prompt(spec: dict[str, Any]) -> str: prompt = spec["prompt"] if spec["output"]["alpha"]: return f"{prompt}\n\nOutput requirement: PNG with a genuinely transparent background and clean subject edges." return prompt def reference_summary(spec: dict[str, Any]) -> list[dict[str, Any]]: return [ { "path": str(item["path"]), "roles": item["roles"], **({"id": item["id"]} if "id" in item else {}), **({"sha256": item["sha256"]} if "sha256" in item else {}), **({"instruction": item["instruction"]} if "instruction" in item else {}), } for item in spec["references"] ] def mime(path: Path) -> str: prefix = path.read_bytes()[:12] if prefix.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if prefix.startswith(b"\xff\xd8\xff"): return "image/jpeg" if prefix.startswith((b"GIF87a", b"GIF89a")): return "image/gif" if prefix.startswith(b"RIFF") and prefix[8:12] == b"WEBP": return "image/webp" raise AdapterError(f"Unsupported reference image format: {path}", "capability") def classify_http(status: int, detail: str) -> str: lowered = detail.lower() if status in {401, 403}: return "authentication" if status == 429: return "quota" if "quota" in lowered or "billing" in lowered else "rate_limit" if "safety" in lowered or "blocked" in lowered: return "safety_rejection" if status >= 500: return "service" return "capability" def call_api(url: str, api_key: str, body: dict[str, Any], timeout: int) -> dict[str, Any]: payload = json.dumps(body, ensure_ascii=False).encode("utf-8") request = urllib.request.Request( url, data=payload, headers={"x-goog-api-key": api_key, "Content-Type": "application/json"}, method="POST", ) try: with urllib.request.urlopen(request, timeout=timeout) as response: return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace")[:4000] raise AdapterError(f"HTTP {exc.code}: {detail}", classify_http(exc.code, detail)) from exc except (urllib.error.URLError, TimeoutError) as exc: raise AdapterError(f"Network request failed: {exc}", "timeout") from exc except json.JSONDecodeError as exc: raise AdapterError("Provider returned invalid JSON", "service") from exc def extract_image(response: dict[str, Any]) -> bytes: if isinstance(response.get("error"), dict): error = response["error"] raise AdapterError(str(error.get("message") or error.get("status") or "provider error")) for candidate in response.get("candidates", []): finish_reason = str(candidate.get("finishReason", "")) if finish_reason in {"SAFETY", "PROHIBITED_CONTENT"}: raise AdapterError(f"Generation blocked: {finish_reason}", "safety_rejection") for part in candidate.get("content", {}).get("parts", []): inline = part.get("inlineData") or part.get("inline_data") if isinstance(inline, dict) and inline.get("data"): return base64.b64decode(inline["data"], validate=True) raise AdapterError("Nano Banana response contained no image", "service") def write_once(path: Path, data: bytes) -> None: if path.exists(): raise AdapterError(f"Output already exists: {path}", "capability") path.parent.mkdir(parents=True, exist_ok=True) fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "wb") as handle: handle.write(data) os.replace(temp_name, path) except Exception: Path(temp_name).unlink(missing_ok=True) raise def image_size(spec: dict[str, Any]) -> str: explicit = spec.get("image_size") if explicit in {"512", "1K", "2K", "4K"}: return explicit return "1K" def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--request", required=True) parser.add_argument("--output", required=True) parser.add_argument("--model") parser.add_argument("--timeout", type=int, default=180) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() try: request_path = Path(args.request).resolve() spec = load_request(request_path) model = args.model or os.environ.get("NANO_BANANA_IMAGE_MODEL", "gemini-3.1-flash-image") model = model.removeprefix("models/") base_url = os.environ.get( "GEMINI_BASE_URL", "https://generativelanguage.googleapis.com/v1" ).rstrip("/") output = Path(args.output).resolve() endpoint = f"{base_url}/models/{model}:generateContent" prompt = effective_prompt(spec) references = reference_summary(spec) summary = { "provider": "nano-banana", "model": model, "endpoint": endpoint, "reference_paths": [str(path) for path in spec["reference_paths"]], "references": references, "reference_count": len(references), "reference_roles": [item["roles"] for item in references], "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), "aspect_ratio": spec["aspect_ratio"], "resolution_mode": spec["resolution"]["mode"], "image_size": image_size(spec), "output": str(output), "output_alpha": spec["output"]["alpha"], "transparency_handling": "prompt-only" if spec["output"]["alpha"] else "opaque-default", "dry_run": args.dry_run, } if args.dry_run: print(json.dumps({"ok": True, **summary}, ensure_ascii=False, indent=2)) return 0 api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") if not api_key: raise AdapterError("GEMINI_API_KEY or GOOGLE_API_KEY is not configured", "authentication") parts: list[dict[str, Any]] = [{"text": prompt}] for ref in spec["reference_paths"]: parts.append( { "inlineData": { "mimeType": mime(ref), "data": base64.b64encode(ref.read_bytes()).decode("ascii"), } } ) body = { "contents": [{"role": "user", "parts": parts}], "generationConfig": { "responseModalities": ["IMAGE"], "imageConfig": { "aspectRatio": spec["aspect_ratio"], "imageSize": image_size(spec), }, }, } response = call_api(endpoint, api_key, body, args.timeout) image = extract_image(response) write_once(output, image) print( json.dumps( {"ok": True, **summary, "dry_run": False, "output_sha256": hashlib.sha256(image).hexdigest()}, ensure_ascii=False, indent=2, ) ) return 0 except (AdapterError, ValueError, base64.binascii.Error) as exc: category = exc.category if isinstance(exc, AdapterError) else "service" print(json.dumps({"ok": False, "category": category, "error": str(exc)}, ensure_ascii=False), file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/scripts/generate-openai.py15 KB3133819cd7d1upstream ↗
#!/usr/bin/env python3 """Generate one Whale-chan candidate through the OpenAI Images API.""" from __future__ import annotations import argparse import base64 import hashlib import json import math import os import re import secrets import sys import tempfile import urllib.error import urllib.request from pathlib import Path from typing import Any REFERENCE_ROLES = { "identity", "style", "pose_action", "composition", "costume", "background", "typography", "proportion", } class AdapterError(RuntimeError): def __init__(self, message: str, category: str = "service") -> None: super().__init__(message) self.category = category def resolve_size( resolution: Any, ratio_width: int, ratio_height: int, ) -> tuple[dict[str, Any], str]: if not isinstance(resolution, dict) or set(resolution) != {"mode", "width", "height"}: raise AdapterError( "request.resolution must contain exactly mode, width, and height", "capability", ) mode = resolution.get("mode") width = resolution.get("width") height = resolution.get("height") if mode == "provider-native": if width is not None or height is not None: raise AdapterError( "provider-native resolution requires null width and height", "capability", ) ratio = ratio_width / ratio_height if ratio >= 1: height = 1024 width = round((height * ratio) / 16) * 16 else: width = 1024 height = round((width / ratio) / 16) * 16 elif mode == "exact": if ( isinstance(width, bool) or not isinstance(width, int) or width < 1 or isinstance(height, bool) or not isinstance(height, int) or height < 1 ): raise AdapterError( "exact resolution requires positive width and height", "capability", ) else: raise AdapterError( "request.resolution.mode must be provider-native or exact", "capability", ) if not math.isclose( width / height, ratio_width / ratio_height, rel_tol=0.02, ): raise AdapterError("request.resolution does not match request.aspect_ratio", "capability") if ( width % 16 != 0 or height % 16 != 0 or max(width, height) > 3840 or max(width, height) / min(width, height) > 3 or not 655_360 <= width * height <= 8_294_400 ): raise AdapterError("request resolution violates gpt-image-2 size constraints", "capability") return {"mode": mode, "width": resolution.get("width"), "height": resolution.get("height")}, f"{width}x{height}" def load_request(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise AdapterError(f"Cannot read request JSON: {exc}", "capability") from exc allowed_fields = {"prompt", "references", "aspect_ratio", "resolution", "output", "quality"} if isinstance(value, dict) and value.keys() - allowed_fields: raise AdapterError("request contains unsupported fields", "capability") if not isinstance(value, dict) or not isinstance(value.get("prompt"), str) or not value["prompt"].strip(): raise AdapterError("request.prompt must be a non-empty string", "capability") refs = value.get("references") if not isinstance(refs, list) or not refs: raise AdapterError("request.references must contain at least 1 reference", "capability") normalized: list[dict[str, Any]] = [] for index, item in enumerate(refs): if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not item["path"].strip(): raise AdapterError(f"request.references[{index}].path must be a non-empty string", "capability") raw_roles = item.get("roles") if not isinstance(raw_roles, list) or not raw_roles or any( not isinstance(role, str) or not role.strip() for role in raw_roles ): raise AdapterError(f"request.references[{index}].roles must be a non-empty list of strings", "capability") instruction = item.get("instruction") if instruction is not None and not isinstance(instruction, str): raise AdapterError(f"request.references[{index}].instruction must be a string", "capability") raw_path = item["path"] roles = [role.strip() for role in raw_roles] if len(set(roles)) != len(roles) or not set(roles) <= REFERENCE_ROLES: raise AdapterError( f"request.references[{index}].roles contains an invalid or duplicate role", "capability", ) ref = Path(raw_path) if not ref.is_absolute(): ref = (path.parent / ref).resolve() if not ref.is_file(): raise AdapterError(f"Reference image does not exist: {ref}", "capability") normalized_ref: dict[str, Any] = {"path": ref, "roles": roles} for field in ("id", "sha256"): if field in item: if not isinstance(item[field], str) or not item[field].strip(): raise AdapterError( f"request.references[{index}].{field} must be a non-empty string", "capability", ) normalized_ref[field] = item[field].strip() expected_sha256 = normalized_ref.get("sha256") if expected_sha256 is not None: actual_sha256 = hashlib.sha256(ref.read_bytes()).hexdigest() if expected_sha256.lower() != actual_sha256: raise AdapterError( f"request.references[{index}].sha256 does not match the reference image", "capability", ) if instruction is not None: normalized_ref["instruction"] = instruction normalized.append(normalized_ref) output = value.get("output") if not isinstance(output, dict) or set(output) != {"format", "alpha"}: raise AdapterError("request.output must contain exactly format and alpha", "capability") if output.get("format") != "png": raise AdapterError("request.output.format must be png", "capability") alpha = output.get("alpha") if not isinstance(alpha, bool): raise AdapterError("request.output.alpha must be a boolean", "capability") aspect_ratio = value.get("aspect_ratio") ratio_match = ( re.fullmatch(r"([1-9]\d*):([1-9]\d*)", aspect_ratio) if isinstance(aspect_ratio, str) else None ) if ratio_match is None: raise AdapterError("request.aspect_ratio must be a positive WIDTH:HEIGHT ratio", "capability") ratio_width, ratio_height = (int(item) for item in ratio_match.groups()) resolution, size = resolve_size(value.get("resolution"), ratio_width, ratio_height) value["size"] = size value["resolution"] = resolution value["references"] = normalized value["reference_paths"] = [item["path"] for item in normalized] value["output"] = {**output, "alpha": alpha} return value def effective_prompt(spec: dict[str, Any]) -> str: prompt = spec["prompt"] if spec["output"]["alpha"]: return f"{prompt}\n\nOutput requirement: PNG with a genuinely transparent background and clean subject edges." return prompt def reference_summary(spec: dict[str, Any]) -> list[dict[str, Any]]: return [ { "path": str(item["path"]), "roles": item["roles"], **({"id": item["id"]} if "id" in item else {}), **({"sha256": item["sha256"]} if "sha256" in item else {}), **({"instruction": item["instruction"]} if "instruction" in item else {}), } for item in spec["references"] ] def request_fields(spec: dict[str, Any], model: str) -> list[tuple[str, str]]: fields = [ ("model", model), ("prompt", effective_prompt(spec)), ("size", spec["size"]), ("quality", spec.get("quality", "medium")), ("output_format", "png"), ] if spec["output"]["alpha"]: fields.append(("background", "transparent")) return fields def mime(path: Path) -> str: prefix = path.read_bytes()[:12] if prefix.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if prefix.startswith(b"\xff\xd8\xff"): return "image/jpeg" if prefix.startswith((b"GIF87a", b"GIF89a")): return "image/gif" if prefix.startswith(b"RIFF") and prefix[8:12] == b"WEBP": return "image/webp" raise AdapterError(f"Unsupported reference image format: {path}", "capability") def multipart(fields: list[tuple[str, str]], files: list[Path]) -> tuple[bytes, str]: boundary = f"----whalechan-{secrets.token_hex(12)}" body: list[bytes] = [] for name, value in fields: body.extend( [ f"--{boundary}\r\n".encode(), f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode(), value.encode("utf-8"), b"\r\n", ] ) for path in files: body.extend( [ f"--{boundary}\r\n".encode(), ( f'Content-Disposition: form-data; name="image[]"; filename="{path.name}"\r\n' ).encode(), f"Content-Type: {mime(path)}\r\n\r\n".encode(), path.read_bytes(), b"\r\n", ] ) body.append(f"--{boundary}--\r\n".encode()) return b"".join(body), f"multipart/form-data; boundary={boundary}" def classify_http(status: int, detail: str) -> str: lowered = detail.lower() if status in {401, 403}: return "authentication" if status == 429: return "quota" if "quota" in lowered or "billing" in lowered else "rate_limit" if "moderation_blocked" in lowered or "safety" in lowered: return "safety_rejection" if status >= 500: return "service" return "capability" def post(url: str, headers: dict[str, str], payload: bytes, timeout: int) -> dict[str, Any]: request = urllib.request.Request(url, data=payload, headers=headers, method="POST") try: with urllib.request.urlopen(request, timeout=timeout) as response: return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace")[:4000] raise AdapterError(f"HTTP {exc.code}: {detail}", classify_http(exc.code, detail)) from exc except (urllib.error.URLError, TimeoutError) as exc: raise AdapterError(f"Network request failed: {exc}", "timeout") from exc except json.JSONDecodeError as exc: raise AdapterError("Provider returned invalid JSON", "service") from exc def extract_image(response: dict[str, Any], timeout: int) -> bytes: error = response.get("error") if isinstance(error, dict): message = str(error.get("message") or error.get("code") or "provider error") category = "safety_rejection" if error.get("code") == "moderation_blocked" else "service" raise AdapterError(message, category) for item in response.get("data", []): if item.get("b64_json"): return base64.b64decode(item["b64_json"], validate=True) if item.get("url"): try: with urllib.request.urlopen(item["url"], timeout=timeout) as result: return result.read() except (urllib.error.URLError, TimeoutError) as exc: raise AdapterError(f"Could not download output: {exc}", "service") from exc raise AdapterError("OpenAI response contained no image", "service") def write_once(path: Path, data: bytes) -> None: if path.exists(): raise AdapterError(f"Output already exists: {path}", "capability") path.parent.mkdir(parents=True, exist_ok=True) fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "wb") as handle: handle.write(data) os.replace(temp_name, path) except Exception: Path(temp_name).unlink(missing_ok=True) raise def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--request", required=True) parser.add_argument("--output", required=True) parser.add_argument("--model") parser.add_argument("--timeout", type=int, default=180) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() try: request_path = Path(args.request).resolve() spec = load_request(request_path) model = args.model or os.environ.get("OPENAI_IMAGE_MODEL", "gpt-image-2") base_url = os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1").rstrip("/") output = Path(args.output).resolve() prompt = effective_prompt(spec) references = reference_summary(spec) summary = { "provider": "openai", "model": model, "endpoint": f"{base_url}/images/edits", "reference_paths": [str(path) for path in spec["reference_paths"]], "references": references, "reference_count": len(references), "reference_roles": [item["roles"] for item in references], "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), "size": spec["size"], "resolution_mode": spec["resolution"]["mode"], "quality": spec.get("quality", "medium"), "output": str(output), "output_alpha": spec["output"]["alpha"], "transparency_handling": "native" if spec["output"]["alpha"] else "opaque-default", "dry_run": args.dry_run, } if args.dry_run: print(json.dumps({"ok": True, **summary}, ensure_ascii=False, indent=2)) return 0 api_key = os.environ.get("OPENAI_API_KEY") if not api_key: raise AdapterError("OPENAI_API_KEY is not configured", "authentication") payload, content_type = multipart( request_fields(spec, model), spec["reference_paths"], ) response = post( summary["endpoint"], {"Authorization": f"Bearer {api_key}", "Content-Type": content_type}, payload, args.timeout, ) image = extract_image(response, args.timeout) write_once(output, image) print( json.dumps( {"ok": True, **summary, "dry_run": False, "output_sha256": hashlib.sha256(image).hexdigest()}, ensure_ascii=False, indent=2, ) ) return 0 except (AdapterError, ValueError, base64.binascii.Error) as exc: category = exc.category if isinstance(exc, AdapterError) else "service" print(json.dumps({"ok": False, "category": category, "error": str(exc)}, ensure_ascii=False), file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/scripts/generate-seedream.py13 KB4581d28336baupstream ↗
#!/usr/bin/env python3 """Generate one Whale-chan candidate through the Volcengine Ark Seedream API.""" from __future__ import annotations import argparse import base64 import hashlib import json import os import sys import tempfile import urllib.error import urllib.request from pathlib import Path from typing import Any REFERENCE_ROLES = { "identity", "style", "pose_action", "composition", "costume", "background", "typography", "proportion", } class AdapterError(RuntimeError): def __init__(self, message: str, category: str = "service") -> None: super().__init__(message) self.category = category def load_request(path: Path) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise AdapterError(f"Cannot read request JSON: {exc}", "capability") from exc allowed_fields = {"prompt", "references", "aspect_ratio", "resolution", "output"} if isinstance(value, dict) and value.keys() - allowed_fields: raise AdapterError("request contains unsupported fields", "capability") if not isinstance(value, dict) or not isinstance(value.get("prompt"), str) or not value["prompt"].strip(): raise AdapterError("request.prompt must be a non-empty string", "capability") refs = value.get("references") if not isinstance(refs, list) or not refs: raise AdapterError("request.references must contain at least 1 reference", "capability") normalized: list[dict[str, Any]] = [] for index, item in enumerate(refs): if not isinstance(item, dict) or not isinstance(item.get("path"), str) or not item["path"].strip(): raise AdapterError(f"request.references[{index}].path must be a non-empty string", "capability") raw_roles = item.get("roles") if not isinstance(raw_roles, list) or not raw_roles or any( not isinstance(role, str) or not role.strip() for role in raw_roles ): raise AdapterError(f"request.references[{index}].roles must be a non-empty list of strings", "capability") instruction = item.get("instruction") if instruction is not None and not isinstance(instruction, str): raise AdapterError(f"request.references[{index}].instruction must be a string", "capability") raw_path = item["path"] roles = [role.strip() for role in raw_roles] if len(set(roles)) != len(roles) or not set(roles) <= REFERENCE_ROLES: raise AdapterError( f"request.references[{index}].roles contains an invalid or duplicate role", "capability", ) ref = Path(raw_path) if not ref.is_absolute(): ref = (path.parent / ref).resolve() if not ref.is_file(): raise AdapterError(f"Reference image does not exist: {ref}", "capability") normalized_ref: dict[str, Any] = {"path": ref, "roles": roles} for field in ("id", "sha256"): if field in item: if not isinstance(item[field], str) or not item[field].strip(): raise AdapterError( f"request.references[{index}].{field} must be a non-empty string", "capability", ) normalized_ref[field] = item[field].strip() expected_sha256 = normalized_ref.get("sha256") if expected_sha256 is not None: actual_sha256 = hashlib.sha256(ref.read_bytes()).hexdigest() if expected_sha256.lower() != actual_sha256: raise AdapterError( f"request.references[{index}].sha256 does not match the reference image", "capability", ) if instruction is not None: normalized_ref["instruction"] = instruction normalized.append(normalized_ref) output = value.get("output") if not isinstance(output, dict) or set(output) != {"format", "alpha"}: raise AdapterError("request.output must contain exactly format and alpha", "capability") if output.get("format") != "png": raise AdapterError("request.output.format must be png", "capability") alpha = output.get("alpha") if not isinstance(alpha, bool): raise AdapterError("request.output.alpha must be a boolean", "capability") if alpha: raise AdapterError( "Seedream adapter has no verified native transparent-output contract", "capability", ) aspect_ratio = value.get("aspect_ratio") if aspect_ratio not in {"1:1", "9:16"}: raise AdapterError("request.aspect_ratio must be 1:1 or 9:16", "capability") resolution = value.get("resolution") if not isinstance(resolution, dict) or set(resolution) != {"mode", "width", "height"}: raise AdapterError( "request.resolution must contain exactly mode, width, and height", "capability", ) native_sizes = {"1:1": (1024, 1024), "9:16": (1024, 1792)} mode = resolution.get("mode") width = resolution.get("width") height = resolution.get("height") if mode == "provider-native": if width is not None or height is not None: raise AdapterError( "provider-native resolution requires null width and height", "capability", ) width, height = native_sizes[aspect_ratio] elif mode == "exact": if (width, height) != native_sizes[aspect_ratio]: raise AdapterError( "Seedream exact resolution must match its verified native size for the aspect ratio", "capability", ) else: raise AdapterError( "request.resolution.mode must be provider-native or exact", "capability", ) size = f"{width}x{height}" value["size"] = size value["resolution"] = resolution value["references"] = normalized value["reference_paths"] = [item["path"] for item in normalized] value["output"] = {**output, "alpha": alpha} return value def effective_prompt(spec: dict[str, Any]) -> str: prompt = spec["prompt"] if spec["output"]["alpha"]: return f"{prompt}\n\nOutput requirement: PNG with a genuinely transparent background and clean subject edges." return prompt def reference_summary(spec: dict[str, Any]) -> list[dict[str, Any]]: return [ { "path": str(item["path"]), "roles": item["roles"], **({"id": item["id"]} if "id" in item else {}), **({"sha256": item["sha256"]} if "sha256" in item else {}), **({"instruction": item["instruction"]} if "instruction" in item else {}), } for item in spec["references"] ] def mime(path: Path) -> str: prefix = path.read_bytes()[:12] if prefix.startswith(b"\x89PNG\r\n\x1a\n"): return "image/png" if prefix.startswith(b"\xff\xd8\xff"): return "image/jpeg" if prefix.startswith((b"GIF87a", b"GIF89a")): return "image/gif" if prefix.startswith(b"RIFF") and prefix[8:12] == b"WEBP": return "image/webp" raise AdapterError(f"Unsupported reference image format: {path}", "capability") def data_url(path: Path) -> str: return f"data:{mime(path)};base64,{base64.b64encode(path.read_bytes()).decode('ascii')}" def classify_http(status: int, detail: str) -> str: lowered = detail.lower() if status in {401, 403}: return "authentication" if status == 429: return "quota" if "quota" in lowered or "balance" in lowered else "rate_limit" if "safety" in lowered or "risk" in lowered or "blocked" in lowered: return "safety_rejection" if status >= 500: return "service" return "capability" def call_api(url: str, api_key: str, body: dict[str, Any], timeout: int) -> dict[str, Any]: payload = json.dumps(body, ensure_ascii=False).encode("utf-8") request = urllib.request.Request( url, data=payload, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, method="POST", ) try: with urllib.request.urlopen(request, timeout=timeout) as response: return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace")[:4000] raise AdapterError(f"HTTP {exc.code}: {detail}", classify_http(exc.code, detail)) from exc except (urllib.error.URLError, TimeoutError) as exc: raise AdapterError(f"Network request failed: {exc}", "timeout") from exc except json.JSONDecodeError as exc: raise AdapterError("Provider returned invalid JSON", "service") from exc def extract_image(response: dict[str, Any], timeout: int) -> bytes: if isinstance(response.get("error"), dict): error = response["error"] message = str(error.get("message") or error.get("code") or "provider error") category = "safety_rejection" if "risk" in message.lower() else "service" raise AdapterError(message, category) for item in response.get("data", []): if isinstance(item.get("error"), dict): message = str(item["error"].get("message") or item["error"].get("code")) raise AdapterError(message) if item.get("b64_json"): return base64.b64decode(item["b64_json"], validate=True) if item.get("url"): try: with urllib.request.urlopen(item["url"], timeout=timeout) as result: return result.read() except (urllib.error.URLError, TimeoutError) as exc: raise AdapterError(f"Could not download output: {exc}", "service") from exc raise AdapterError("Seedream response contained no image", "service") def write_once(path: Path, data: bytes) -> None: if path.exists(): raise AdapterError(f"Output already exists: {path}", "capability") path.parent.mkdir(parents=True, exist_ok=True) fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "wb") as handle: handle.write(data) os.replace(temp_name, path) except Exception: Path(temp_name).unlink(missing_ok=True) raise def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--request", required=True) parser.add_argument("--output", required=True) parser.add_argument("--model") parser.add_argument("--timeout", type=int, default=180) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() try: request_path = Path(args.request).resolve() spec = load_request(request_path) model = args.model or os.environ.get( "SEEDREAM_IMAGE_MODEL", "doubao-seedream-5-0-lite-260128" ) base_url = os.environ.get( "SEEDREAM_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3" ).rstrip("/") endpoint = f"{base_url}/images/generations" output = Path(args.output).resolve() prompt = effective_prompt(spec) references = reference_summary(spec) summary = { "provider": "seedream", "model": model, "endpoint": endpoint, "reference_paths": [str(path) for path in spec["reference_paths"]], "references": references, "reference_count": len(references), "reference_roles": [item["roles"] for item in references], "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), "size": spec["size"], "resolution_mode": spec["resolution"]["mode"], "output": str(output), "output_alpha": spec["output"]["alpha"], "transparency_handling": "prompt-only" if spec["output"]["alpha"] else "opaque-default", "dry_run": args.dry_run, } if args.dry_run: print(json.dumps({"ok": True, **summary}, ensure_ascii=False, indent=2)) return 0 api_key = os.environ.get("ARK_API_KEY") if not api_key: raise AdapterError("ARK_API_KEY is not configured", "authentication") references = [data_url(path) for path in spec["reference_paths"]] body = { "model": model, "prompt": prompt, "image": references if len(references) > 1 else references[0], "size": spec["size"], "output_format": "png", "response_format": "b64_json", "watermark": False, } response = call_api(endpoint, api_key, body, args.timeout) image = extract_image(response, args.timeout) write_once(output, image) print( json.dumps( {"ok": True, **summary, "dry_run": False, "output_sha256": hashlib.sha256(image).hexdigest()}, ensure_ascii=False, indent=2, ) ) return 0 except (AdapterError, ValueError, base64.binascii.Error) as exc: category = exc.category if isinstance(exc, AdapterError) else "service" print(json.dumps({"ok": False, "category": category, "error": str(exc)}, ensure_ascii=False), file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/scripts/language_policy.py5.9 KB1bd2fb1d330eupstream ↗
"""Task language contracts and offline locale packs; language inference belongs to the agent.""" import copy import json import re from pathlib import Path from string import Formatter ROOT = Path(__file__).resolve().parents[1] FIELDS = {'language', 'language_overrides', 'language_resolution', 'localizations', 'run_title'} SCOPES = {'communication', 'visible_text', 'interface', 'prompt', 'titles'} ALIASES = {'zh': 'zh-Hans', 'zh-CN': 'zh-Hans', 'zh-SG': 'zh-Hans', 'zh-TW': 'zh-Hant', 'zh-HK': 'zh-Hant'} def tag(value): if not isinstance(value, str) or not re.fullmatch(r'[a-zA-Z]{2,8}(?:-[a-zA-Z0-9]{1,8})*', value): raise ValueError('Use a BCP-47 language tag') parts = value.split('-') value = '-'.join([parts[0].lower()] + [p.title() if len(p) == 4 else p.upper() if len(p) == 2 else p.lower() for p in parts[1:]]) return ALIASES.get(value, value) def effective(value, scope): return tag(value.get('language_overrides', {}).get(scope, value['language'])) def placeholders(value): return {field for _, field, _, _ in Formatter().parse(value) if field is not None} def check_dictionary(actual, expected, path='locale'): if isinstance(expected, dict): if not isinstance(actual, dict) or set(actual) != set(expected): raise ValueError(f'{path}: missing or unexpected translation keys') for key in expected: check_dictionary(actual[key], expected[key], f'{path}.{key}') elif not isinstance(actual, str) or not actual.strip() or placeholders(actual) != placeholders(expected): raise ValueError(f'{path}: empty translation or mismatched placeholders') def locale(value, language, section): language = tag(language) baseline = json.loads((ROOT / 'assets/locales/en.json').read_text()) path = ROOT / 'assets/locales' / f'{language}.json' bundled = json.loads(path.read_text()) if path.is_file() else {} supplied = value.get('localizations', {}).get(language, {}) result = supplied.get(section, bundled.get(section)) if result is None: raise ValueError(f'Missing {language}.{section}; author the complete locale before continuing') check_dictionary(result, baseline[section], f'{language}.{section}') return copy.deepcopy(result) def contract(value): """Only new schemas call this; legacy approval hashes remain unchanged.""" language = tag(value.get('language')) if language != value['language']: raise ValueError('Store the normalized language tag') overrides = value.get('language_overrides', {}) if not isinstance(overrides, dict) or set(overrides) - SCOPES: raise ValueError('Unknown language override scope') for scope, code in overrides.items(): if tag(code) != code: raise ValueError(f'Normalize language_overrides.{scope}') evidence = value.get('language_resolution') if not isinstance(evidence, dict) or evidence.get('source') not in {'explicit', 'current-session', 'recent-session', 'user-answer'} or not evidence.get('reason'): raise ValueError('Record actual language resolution source and reason') if not isinstance(value.get('run_title'), str) or not value['run_title'].strip(): raise ValueError('run_title is required for new tasks') return {k: copy.deepcopy(value[k]) for k in FIELDS if k in value} def validate(value, comic=False, images=True): result = contract(value) if images: for image in value.get('images', []): if not isinstance(image.get('title'), str) or not image['title'].strip(): raise ValueError('Every new image needs a visible title') text = image.get('text') if text and effective(value, 'visible_text') not in [tag(x) for x in text['languages']] and text['content'] not in value['language_resolution'].get('preserved_text', []): raise ValueError('text.languages must include the resolved visible-text language') if comic and tag(value['input']['language']) != effective(value, 'visible_text'): raise ValueError('input.language differs from the resolved visible-text language') return result def gallery_locales(assignments, extra=None): """Merge only UI dictionaries; never translate saved task content.""" merged = {} languages = ['zh-Hans', 'en'] for value in assignments: for code, pack in value.get('localizations', {}).items(): code = tag(code) if 'gallery' in pack: if code in merged and any(merged[code].get(k) != pack.get(k) for k in ('gallery', 'name', 'direction')): raise ValueError(f'Conflicting gallery locale: {code}') merged[code] = pack if value.get('language'): used = [value['language'], *value.get('language_overrides', {}).values()] if value.get('input', {}).get('language'): used.append(value['input']['language']) for image in value.get('images', []): used.extend((image.get('text') or {}).get('languages', [])) for code in used: if tag(code) not in languages: languages.append(tag(code)) for code, pack in (extra or {}).items(): merged[tag(code)] = pack result, names, directions = {}, {}, {} for code in languages: result[code] = locale({'localizations': merged}, code, 'gallery') path = ROOT / 'assets/locales' / f'{code}.json' metadata = merged.get(code) or (json.loads(path.read_text()) if path.is_file() else {}) if not metadata.get('name') or metadata.get('direction') not in {'ltr', 'rtl'}: raise ValueError(f'{code}: locale requires a native name and ltr/rtl direction') names[code], directions[code] = metadata['name'], metadata['direction'] return result, names, directions def overrides_text(value, words): return "; ".join(words["scopes"][scope] + ": " + code for scope, code in value.get("language_overrides", {}).items()) or words["none"]skills/whalechan-image-character/scripts/manage-run.py121 KB6eb8f519aeadupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/scripts/measure-form.py10 KBa828543be2afupstream ↗
#!/usr/bin/env python3 """Create image-bound Whale-chan proportion evidence from reviewed landmarks.""" from __future__ import annotations import argparse import hashlib import json import math import shutil import subprocess import sys from pathlib import Path from typing import Any SKILL_ROOT = Path(__file__).resolve().parents[1] CATALOG_PATH = SKILL_ROOT / "references" / "reference-catalog.json" CATALOG_SCHEMA_VERSION = 4 class MeasurementError(RuntimeError): """Invalid input or unavailable overlay renderer.""" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def load_catalog() -> tuple[dict[str, Any], str]: try: value = json.loads(CATALOG_PATH.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise MeasurementError(f"Cannot read reference catalog: {exc}") from exc if not isinstance(value, dict): raise MeasurementError("Invalid reference catalog") forms = value.get("forms") if ( value.get("schema_version") != CATALOG_SCHEMA_VERSION or not isinstance(forms, dict) or not forms ): raise MeasurementError("Invalid reference catalog") for profile in forms.values(): if not isinstance(profile, dict): raise MeasurementError("Invalid reference catalog") mean = profile.get("mean_head_ratio") acceptance_range = profile.get("acceptance_range") if ( not isinstance(mean, (int, float)) or isinstance(mean, bool) or not math.isfinite(mean) or mean <= 0 or not isinstance(acceptance_range, list) or len(acceptance_range) != 2 or any( not isinstance(item, (int, float)) or isinstance(item, bool) or not math.isfinite(item) for item in acceptance_range ) or not acceptance_range[0] <= mean <= acceptance_range[1] ): raise MeasurementError("Invalid reference catalog") return value, sha256(CATALOG_PATH) def distance(start: list[float], end: list[float]) -> float: return math.hypot(end[0] - start[0], end[1] - start[1]) def target_sha256( mode: str, preset: str | None, mean: float, acceptance_range: list[float], ) -> str: value = { "mode": mode, "preset": preset, "target_head_ratio": float(mean), "acceptance_range": [float(item) for item in acceptance_range], } payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha256(payload).hexdigest() def resolve_target( profile: dict[str, Any], override_mean: float | None, override_range: list[float] | None, ) -> tuple[float, list[float]]: if (override_mean is None) != (override_range is None): raise MeasurementError( "Confirmed mean and acceptance range must be provided together" ) if override_mean is None: return float(profile["mean_head_ratio"]), list(profile["acceptance_range"]) if ( isinstance(override_mean, bool) or not isinstance(override_mean, (int, float)) or not math.isfinite(override_mean) or override_mean <= 1 or not isinstance(override_range, list) or len(override_range) != 2 or any( isinstance(item, bool) or not isinstance(item, (int, float)) or not math.isfinite(item) for item in override_range ) or override_range[0] >= override_range[1] or not override_range[0] <= override_mean <= override_range[1] ): raise MeasurementError("Invalid confirmed proportion target") return float(override_mean), [float(item) for item in override_range] def draw_line(start: list[float], end: list[float]) -> str: return f"line {start[0]:g},{start[1]:g} {end[0]:g},{end[1]:g}" def draw_circle(point: list[float], radius: int = 7) -> str: return ( f"circle {point[0]:g},{point[1]:g} " f"{point[0] + radius:g},{point[1]:g}" ) def render_overlay( image: Path, overlay: Path, head_top: list[float], chin: list[float], pelvis: list[float], knee: list[float], sole: list[float], ) -> None: magick = shutil.which("magick") if not magick: raise MeasurementError("ImageMagick 'magick' is required") overlay.parent.mkdir(parents=True, exist_ok=True) body_points = [chin, pelvis, knee, sole] body_lines = " ".join( draw_line(start, end) for start, end in zip(body_points, body_points[1:]) ) points = " ".join(draw_circle(point) for point in [head_top, *body_points]) command = [ magick, str(image), "-stroke", "#E5484D", "-strokewidth", "5", "-fill", "none", "-draw", draw_line(head_top, chin), "-stroke", "#1677FF", "-draw", body_lines, "-fill", "#FFD60A", "-stroke", "#111827", "-strokewidth", "2", "-draw", points, str(overlay), ] try: subprocess.run(command, check=True, capture_output=True, text=True, timeout=30) except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: detail = getattr(exc, "stderr", "") or str(exc) raise MeasurementError(f"Cannot render measurement overlay: {detail.strip()}") from exc def build_result( image: Path, form: str, overlay: Path, head_top: list[float], chin: list[float], pelvis: list[float], knee: list[float], sole: list[float], override_mean: float | None = None, override_range: list[float] | None = None, ) -> dict[str, Any]: head_height = distance(head_top, chin) if head_height <= 0: raise MeasurementError("Head top and chin must not be the same point") segments = [ {"name": "chin_to_pelvis", "start": chin, "end": pelvis}, {"name": "pelvis_to_knee", "start": pelvis, "end": knee}, {"name": "knee_to_sole", "start": knee, "end": sole}, ] if any(distance(item["start"], item["end"]) <= 0 for item in segments): raise MeasurementError("Every body segment must have positive length") ratio = (head_height + sum(distance(item["start"], item["end"]) for item in segments)) / head_height catalog, catalog_sha256 = load_catalog() profile = catalog["forms"][form] mean_head_ratio, acceptance_range = resolve_target( profile, override_mean, override_range ) target_source = "custom" if override_mean is not None else "preset" target_preset = None if override_mean is not None else form target_digest = target_sha256( target_source, target_preset, mean_head_ratio, acceptance_range ) minimum, maximum = acceptance_range return { "candidate_sha256": sha256(image), "form_evidence": { "measurement_method": "pose-neutralized-skeleton", "head_axis": {"top": head_top, "chin": chin}, "body_segments": segments, "calculated_head_ratio": round(ratio, 3), "measurement_overlay": str(overlay.resolve()), "measurement_overlay_sha256": sha256(overlay), "catalog_sha256": catalog_sha256, "target_source": target_source, "target_sha256": target_digest, "mean_head_ratio": mean_head_ratio, "acceptance_range": acceptance_range, }, "form": form, "catalog_sha256": catalog_sha256, "target_source": target_source, "target_sha256": target_digest, "mean_head_ratio": mean_head_ratio, "acceptance_range": acceptance_range, "within_range": minimum <= ratio <= maximum, } def main() -> int: catalog, _catalog_sha256 = load_catalog() parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image") parser.add_argument("--form", choices=sorted(catalog["forms"]), required=True) parser.add_argument("--head-top", nargs=2, type=float, required=True, metavar=("X", "Y")) parser.add_argument("--chin", nargs=2, type=float, required=True, metavar=("X", "Y")) parser.add_argument("--pelvis", nargs=2, type=float, required=True, metavar=("X", "Y")) parser.add_argument("--knee", nargs=2, type=float, required=True, metavar=("X", "Y")) parser.add_argument("--sole", nargs=2, type=float, required=True, metavar=("X", "Y")) parser.add_argument("--confirmed-mean-head-ratio", type=float) parser.add_argument( "--confirmed-acceptance-range", nargs=2, type=float, metavar=("MIN", "MAX") ) parser.add_argument("--write-overlay", required=True) parser.add_argument("--write-json", required=True) args = parser.parse_args() image = Path(args.image).resolve() overlay = Path(args.write_overlay).resolve() output = Path(args.write_json).resolve() if not image.is_file(): print(json.dumps({"ok": False, "error": f"Image does not exist: {image}"}), file=sys.stderr) return 2 try: render_overlay(image, overlay, args.head_top, args.chin, args.pelvis, args.knee, args.sole) result = build_result( image, args.form, overlay, args.head_top, args.chin, args.pelvis, args.knee, args.sole, args.confirmed_mean_head_ratio, args.confirmed_acceptance_range, ) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") except MeasurementError as exc: print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False), file=sys.stderr) return 2 print(json.dumps({"ok": True, **result}, ensure_ascii=False, indent=2)) return 0 if result["within_range"] else 1 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/scripts/validate-image.py7.8 KB668070590e6bupstream ↗
#!/usr/bin/env python3 """Validate Whale-chan PNG geometry and color mode.""" from __future__ import annotations import argparse import hashlib import json import math import os import re import shutil import subprocess import sys import tempfile from pathlib import Path from typing import Any class ValidationError(RuntimeError): """A file inspection failure.""" def run_magick(arguments: list[str]) -> str: executable = shutil.which("magick") if not executable: raise ValidationError("ImageMagick 'magick' is required") try: completed = subprocess.run( [executable, *arguments], check=True, capture_output=True, text=True, timeout=30, ) except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: detail = getattr(exc, "stderr", "") or str(exc) raise ValidationError(f"ImageMagick failed: {detail.strip()}") from exc return completed.stdout.strip() def inspect_header(path: Path) -> dict[str, Any]: value = run_magick( ["identify", "-quiet", "-format", "%m|%w|%h|%[colorspace]|%[channels]", str(path)] ) parts = value.split("|", 4) if len(parts) != 5: raise ValidationError(f"Unexpected identify output: {value}") return { "format": parts[0], "width": int(parts[1]), "height": int(parts[2]), "colorspace": parts[3], "channels": parts[4], } def inspect_alpha_minimum(path: Path) -> float: value = run_magick( [str(path), "-alpha", "extract", "-format", "%[fx:minima]", "info:"] ) try: return float(value) except ValueError as exc: raise ValidationError(f"Unexpected alpha inspection output: {value}") from exc def inspect_transparent_fraction(path: Path) -> float: value = run_magick( [ str(path), "-alpha", "extract", "-threshold", "5%", "-format", "%[fx:1-mean]", "info:", ] ) try: return float(value) except ValueError as exc: raise ValidationError(f"Unexpected transparency inspection output: {value}") from exc def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def validate( path: Path, aspect_ratio: str = "1:1", resolution_mode: str = "provider-native", width: int | None = None, height: int | None = None, alpha: str = "forbidden", ) -> dict[str, Any]: if not path.is_file(): raise ValidationError(f"Image does not exist: {path}") if path.read_bytes()[:8] != b"\x89PNG\r\n\x1a\n": raise ValidationError("File does not have a PNG signature") ratio_match = re.fullmatch(r"([1-9]\d*):([1-9]\d*)", aspect_ratio) if ratio_match is None: raise ValidationError("aspect_ratio must be a positive WIDTH:HEIGHT ratio") ratio_width, ratio_height = (int(item) for item in ratio_match.groups()) if resolution_mode not in {"provider-native", "exact"}: raise ValidationError("resolution_mode must be provider-native or exact") if resolution_mode == "provider-native": if width is not None or height is not None: raise ValidationError("provider-native resolution must not specify width or height") elif ( isinstance(width, bool) or not isinstance(width, int) or width < 1 or isinstance(height, bool) or not isinstance(height, int) or height < 1 ): raise ValidationError("exact resolution requires positive width and height") header = inspect_header(path) ratio_pass = math.isclose( header["width"] / header["height"], ratio_width / ratio_height, rel_tol=0.02, ) size_pass = resolution_mode == "provider-native" or ( header["width"] == width and header["height"] == height ) t1_pass = ( header["format"].upper() == "PNG" and header["width"] > 0 and header["height"] > 0 and ratio_pass and size_pass ) channels = header["channels"].lower().replace(" ", "") has_alpha = "alpha" in channels or channels.startswith(("rgba", "srgba", "graya", "cmyka")) alpha_minimum = inspect_alpha_minimum(path) if has_alpha else None transparent_fraction = inspect_transparent_fraction(path) if has_alpha else None alpha_pass = ( not has_alpha if alpha == "forbidden" else has_alpha and alpha_minimum is not None and alpha_minimum <= 0.05 and transparent_fraction is not None and transparent_fraction >= 0.01 ) t2_pass = header["colorspace"].lower() in {"rgb", "srgb"} and alpha_pass gates = { "T1": { "verdict": "PASS" if t1_pass else "FAIL", "detail": ( f"{header['format']} {header['width']}x{header['height']}; " f"expected PNG aspect_ratio={aspect_ratio}, " f"resolution={resolution_mode}" + (f" {width}x{height}" if resolution_mode == "exact" else "") ), }, "T2": { "verdict": "PASS" if t2_pass else "FAIL", "detail": ( f"colorspace={header['colorspace']}, channels={header['channels']}, " f"alpha={alpha}, alpha_minimum={alpha_minimum}, " f"transparent_fraction={transparent_fraction}" ), }, } overall = "PASS" if all(item["verdict"] == "PASS" for item in gates.values()) else "FAIL" return { "schema_version": 2, "path": str(path.resolve()), "sha256": sha256(path), "overall": overall, "gates": gates, "metrics": { **header, "alpha_policy": alpha, "resolution_mode": resolution_mode, "expected_aspect_ratio": aspect_ratio, "expected_width": width, "expected_height": height, "alpha_minimum": alpha_minimum, "transparent_fraction": transparent_fraction, }, } def write_json(path: Path, value: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump(value, handle, ensure_ascii=False, indent=2) handle.write("\n") os.replace(temp_name, path) except Exception: Path(temp_name).unlink(missing_ok=True) raise def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image") parser.add_argument("--aspect-ratio", default="1:1") parser.add_argument( "--resolution-mode", choices=("provider-native", "exact"), default="provider-native", ) parser.add_argument("--width", type=int) parser.add_argument("--height", type=int) parser.add_argument("--alpha", choices=("forbidden", "required"), default="forbidden") parser.add_argument("--write-json") args = parser.parse_args() try: result = validate( Path(args.image).resolve(), args.aspect_ratio, args.resolution_mode, args.width, args.height, args.alpha, ) if args.write_json: write_json(Path(args.write_json).resolve(), result) except ValidationError as exc: print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False), file=sys.stderr) return 2 print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if result["overall"] == "PASS" else 1 if __name__ == "__main__": raise SystemExit(main())skills/whalechan-image-character/references/assignment-schema.md15 KB92d8ef5bac58upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/character-spec.md4.8 KB6d191f0b77fbupstream ↗
# Character specification Whale-chan identity is permanent. Style, costume, background, text, action, and proportion are independently resolved fields whose canonical values are defaults rather than universal locks. ## Permanent identity Preserve these traits in every mode: - One recognizable, ageless humanoid Whale-chan with two arms, two legs, paired side whale-fin ears, one forward-curving ahoge, and one coherent whale tail connected naturally to the body. - Broad round face, large expressive eyes, tiny nose, small expressive mouth, rosy cheek placement, and the characteristic deep-ocean-blue hair mass fading toward cyan curled ends when the confirmed style supports color. - Stable face construction, hair silhouette, fin-ear placement, ahoge silhouette, tail construction, and decorative density sufficient to distinguish Whale-chan from a generic blue-haired character. - The requested proportion changes geometry, never apparent age. Do not silently transform the character into a child, giant whale, whale-bodied creature, mermaid, or half-whale. - Correct anatomy, tail attachment, object geometry, grip, support, and contact for the confirmed action. A custom medium may simplify, pixelate, flatten, recolor, or stylize these features, but must preserve their recognizable structure. If a request would remove or replace the permanent identity itself, explain the conflict and seek a revised assignment rather than treating it as a style override. ## Canonical style default When `style.mode` is `canonical`, use the selected preset's bundled primary as style authority: - Bold near-black navy outer contours with finer interior lines. - Clean rounded shapes, restrained soft cel shading, and sparse glossy highlights. - Cool navy, ocean blue, cyan-blue, clean white, warm pale skin, and restrained muted-gold accents. - Moderate saturation and contrast; avoid unintended neon, washed-out, gray, muddy, painterly, or harshly contrasted rendering. When `style.mode` is `custom`, follow the frozen description and references carrying the `style` role. Do not reject an intended watercolor, pixel-art, monochrome, painterly, 3D, print, or other rendering choice merely because it differs from the canonical style. Canonical references may still carry `identity`, but must not control style unless `style` is one of their declared roles. ## Canonical costume default When `costume.mode` is `canonical`, keep the complete navy-and-white ornate maid outfit: white frilled headpiece, navy neck bow with blue gem, dark-navy sleeves and bodice, white frilled collar and apron with the small blue whale emblem, muted-gold piping/embroidery/bows/buttons, white frilled hem and socks, and dark-blue strap shoes. The whale emblem is a graphic, not text. When `costume.mode` is `custom`, render the frozen costume description and any `costume` references. Do not require canonical garments, emblem, palette, or ornaments. A costume change never implicitly changes identity, style, action, or proportion. ## Background and text defaults - Default background: solid warm ivory-beige `#F5EADD`, no alpha. A confirmed custom background may contain a complete environment, landscape, texture, border, gradient, or scene. A confirmed transparent background must produce meaningful alpha and no rendered backdrop. - Default text: none. When enabled, render only the exact frozen content, languages, direction, line breaks, placement, and style. Never inherit source UI or text without authorization. - Always reject unconfirmed signatures, watermarks, usernames, QR codes, and brand marks. ## Dynamic prompt blocks Every provider prompt must contain the permanent identity block and only the defaults still active after normalization. Express the following permanent identity meaning in the saved prompt language. This English example is semantic guidance, not a fixed-language prompt block; preserve exact user-locked visible text separately. ```text DeepSeek Whale-chan, one consistent ageless humanoid character: broad round face, expressive eyes, characteristic deep-ocean-blue-to-cyan curled hair when color is applicable, paired side whale-fin ears, one forward-curving ahoge, and one coherent naturally attached whale tail; two correct arms and two correct legs. Preserve the recognizable face, hair mass, fin-ear placement, ahoge silhouette, and tail construction. Follow the frozen head ratio without changing apparent age. Correct anatomy, contact, and object geometry. ``` Append the canonical style block only for `style.mode: canonical`; otherwise append the complete custom style description and typed style-reference limits. Do the same independently for costume, background, and proportion. Append a strict no-text directive when `text` is null; otherwise append the exact text contract. Add only defect-specific corrections on retries.skills/whalechan-image-character/references/form-profiles.md3.8 KB05575ce9abffupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/gallery.md4.5 KBed4431c23428upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/language-policy.md6.0 KB8247ceb10880upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/proposal-selection.md7.1 KB2f604e036cb5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/provider-routing.md14 KBf0b3a1ede779upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/qa-rubric.md9.5 KB0cfb7de9fe00upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/reference-catalog.json5.3 KB3c02db2edf90upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/references/reference-index.md4.1 KB6113bf14b153upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/gallery/gallery.css18 KBe724ac48cfb1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/gallery/gallery.js34 KB99d36c3ee23dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/gallery/index.html2.5 KB2d3b5ae13f18upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/locales/en.json15 KBb8b68c58b955upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/locales/zh-Hans.json14 KBe6fe5bbd7200upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/chibi/0054_rice_identity_comic_rendered_isolated.webp105 KBdcb45455455aupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/chibi/0057_patting_full_belly_rendered_isolated.webp87 KB8267cb13e2cbupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/chibi/0067_angry_you_are_silly_reply_rendered_isolated.webp109 KB6bda719109e1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/compact/0080_lounging_on_chair_rendered_isolated.webp123 KB978594f07bb5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/compact/0102_intimate_relationship_question_rendered_isolated.webp93 KB5ba070a731e0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/compact/04_light_turn.webp95 KB456a8d143b75upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/semi-chibi/0015_data_still_in_brain_rendered_isolated.webp105 KBd3d3ca890d4bupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/semi-chibi/0076_sitting_ready_on_chair_rendered_isolated.webp96 KBf38cdf7dda63upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/semi-chibi/neutral_standing_front_isolated.webp94 KB060cc59f14dfupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/standard/01_gentle_wave.webp101 KB371e8ea7cd8cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/standard/03_light_turning_step.webp83 KB00866b0ce601upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/standard/05_side_reclining_pose.webp90 KBe87328894ceaupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/super-deformed/0019_literal_love_reply_rendered_isolated.webp82 KB125dcbf42c59upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/super-deformed/0040_kicked_from_chair_rendered_isolated.webp96 KBc169ff3bd9a6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/assets/reference-images/super-deformed/0081_stranded_on_floor_rendered_isolated.webp70 KB0ce61fe32351upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/agents/openai.yaml381 B3d5a0b4653efupstream ↗
interface: display_name: "whalechan-image-character" short_description: "Select, confirm, and generate verified Whale-chan art" default_prompt: "Use $whalechan-image-character to propose illustration directions in a table, let me select, then separately confirm quantities, visual settings and candidate budget before generation; default to one image per selected proposal."skills/whalechan-image-character/tests/helpers.py11 KBf41c3bfb6e2cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_adapters.py5.4 KB292eccedc1f5upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_execution.py3.1 KB59bc79a94844upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_gallery.py14 KB468ac35f2f0fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_gallery_lifecycle.py1.1 KB5fdab5df5b55upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_language.py6.9 KBf4edaef00649upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_manage_run.py13 KBdcab93e6abddupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_selection_contract.py7.5 KB29d11af6abbaupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/whalechan-image-character/tests/test_validate_image.py1.6 KBf30a11eb36e9upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/neko3000-deepseek-whalechan-skills-whalechan-image-character.md