⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
holo-card
Create interactive holographic cards from supplied images with colored layers, repaired scenery, signed parallax and contour glow. Use Codex native image tools with local assembly, or an explicitly selected independent API workflow.
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
Holo Card
A Codex skill and optional local API service for turning supplied artwork into interactive holographic cards with foreground parallax, a moving background, and adjustable contour glow.
Creative inspiration: @乌托邦的香蕉 — the same handle on Xiaohongshu (小红书) and Bilibili (B站). This project is an independent implementation; attribution does not imply endorsement.
Demo
Watch or download the demo recording. The recording is a user-provided demonstration; artwork belongs to its respective owners.
Quick start: trigger the skill
After installing, start a new Codex task, attach your card image, and send:
$holo-card Turn this image into an interactive holographic card.
Chinese prompt (also supported):
$holo-card 把这张图做成光栅卡
$holo-card invokes the installed skill. Attach the actual image in the same task. If it is not found, check ~/.codex/skills/holo-card/SKILL.md and start a fresh task. Installation instructions follow.
Install the skill
Use the current installation package, or clone the current main branch (update an existing clone with git pull --ff-only):
git clone https://github.com/LerSent001/holo-card.git
python3 holo-card/scripts/install-skill.py
python3 -m pip install Pillow
The installer replaces the existing holo-card package, removes obsolete packaged files, and verifies every installed file. It does not create nested skill directories or retain discoverable backup versions. Treat the installation as managed files; keep your own card outputs elsewhere. Run the same installer after pulling updates. Start a fresh Codex task after installation so already-loaded instructions are refreshed. Attach your image and ask:
$holo-card Turn this image into an interactive holographic card.
Codex uses its built-in image tool; no Gemini key or API server is required. The runtime must provide image generation, Python/Pillow, filesystem access and a browser preview. Availability depends on your Codex environment.
What happens
- Save the original and normalize orientation without cropping.
- Generate a continuous colored foreground, repairing artwork hidden by lettering.
- Reconstruct a complete opaque background, including areas hidden by the foreground and border.
- Extract text, symbols and the decorative frame together as one colored UI layer.
- Expect colored checkerboard-matte outputs, prepare their local alpha masks, and repair only confirmed matte regions; do not mask every element or erase white artwork globally.
- Generate aligned structural contours, assemble an offline HTML card and ZIP, and inspect the result in a local browser.
The local helper does not generate or segment images by itself. It saves jobs, validates/imports layers, optionally applies a supplied alpha correction and assembles them. Source pixels hidden by overlays cannot be recovered exactly; inpainting is an approximation. Generated lettering, shape alignment and alpha edges still need visual review.
Controls
- Drag to rotate; click or press Enter/Space to flip.
- Arrow keys adjust the card angle.
- Depth: -3 to +3, default 0 at the center. Negative/positive changes foreground parallax direction. Text and frame always remain above the foreground.
- Contour glow: 0 to 3, default 0.15. Zero disables contour light. Emission and bloom are restricted to structural contour coverage; glow does not spill into the background.
- Background texture moves independently of the card's CSS rotation.
Local commands
python3 skills/holo-card/scripts/native.py prepare --source /path/card.png --output /path/new-job --name 'My Card'
# Use the native image tool, inspect its outputs, then import each layer:
python3 skills/holo-card/scripts/native.py add --job /path/new-job --kind character --image /path/character.png
# Repeat for background, ui and structure.
python3 skills/holo-card/scripts/native.py assemble --job /path/new-job
python3 -m http.server 8795 --bind 127.0.0.1 --directory /path/new-job
Open the loopback URL printed by your server. index.html is also self-contained for offline use. card.zip contains the HTML, layers and provenance. Use status --job ... before reading a saved job’s prompts: it refreshes them from the current helper. Old mask-only native jobs are rejected instead of silently using legacy extraction. Successful assembly is not proof of visual fidelity.
Edge cases
| Situation | Handling |
|---|---|
| Native image safety refusal | Stop the refused generation and record the error. Do not rephrase or switch providers to bypass it. Contact provider support for an apparent false positive, or use different permitted material. |
| No native image capability | An independently selected API workflow is available; see below. This is not a safety-refusal bypass. |
| Baked checkerboard instead of Alpha | Inspect alpha values, then clean only confirmed contaminated background regions. Protect white clothing, highlights and glyphs. Local code does not automatically solve this. |
| Existing valid transparency | Preserve it; no additional full-element mask is needed. |
| Text overlaps foreground | Remove it from the foreground and repair underlying artwork. Keep typography only in the combined UI layer. |
| Frame and text overlap | Keep both in one UI layer, above the foreground at every depth. |
| Missing background | Inpaint the full opaque plate before parallax. No holes or retained glyphs. |
| Layer moved or changed scale | Align explicitly or reject it. Do not silently crop/stretch or claim an exact extraction. |
| Glow obscures details | Reduce glow and inspect without emission; fix alignment rather than hiding defects. |
| Paid API timeout or uncertain submission | Reuse the existing idempotency key and inspect status. Never automatically start another paid job. |
Optional API service
API setup · Agent/client workflow · OpenAPI
The service requires Node.js 24+, pnpm, a provider key and explicit paid-call authorization. Keep keys in private local files, not chat or generated artifacts. Configuration and upload do not start generation. It binds to loopback by default; no hosted endpoint is supplied.
Current limitation: the API uses legacy four-mask extraction and does not implement the native colored-layer inpainting workflow. Its tests use a mock provider; they do not prove live provider availability, billing, or visual quality. Do not treat it as an automatic fallback for a native refusal.
Verification
python3 -m unittest discover -s skills/holo-card/tests
cd packages/holo-card-api
pnpm install --frozen-lockfile
node --test test/*.test.mjs
Scope and rights
The package contains code and a navy-and-gold card back generated from a user-supplied visual reference. See the bundled artwork notice for provenance and rights. Source card images, credentials, caches and job histories are excluded; the user-provided demo recording is included. Use artwork you are entitled to process and share. This is a layered 2D parallax renderer, not reconstructed 3D geometry. The project is provided under the MIT license; third-party dependencies retain their own licenses.
Mobile preview and immersive mode
Generated cards support touch dragging, tap-to-flip, optional motion controls, and recentering. Enable motion requests browser permission on supported phones; device orientation is preferred, with gravity-based tilt as a fallback. Depth and contour glow remain independent on each device. The eye icon at the top right hides the controls and e
// HOW IT'S BUILT
// FILES
19 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/holo-card/SKILL.md13 KBc59cf6419752upstream ↗
--- name: holo-card description: Create interactive holographic cards from supplied images with colored layers, repaired scenery, signed parallax and contour glow. Use Codex native image tools with local assembly, or an explicitly selected independent API workflow. --- # Holo Card ## Execution paths **Codex default:** built-in image tool → inspect/repair layers → local `native.py` assembly. No API key, server or paid API request is required. Never run API setup as a prerequisite. **Independent API mode:** for agents without native image tools or an explicitly selected API workflow, read [API instructions](references/api.md). The included service currently uses legacy four-mask extraction without hidden-region repair. Do not claim native/API visual parity. A safety refusal is not a missing-alpha error. Preserve the actual refusal and stop that generation; never rewrite prompts or switch providers to bypass it. API mode is not a workaround for a blocked image. For apparent false positives, use the provider's support process or different permitted material. API failures and uncertain submissions must not trigger automatic paid retries. ## Current instructions and resuming Use this installed entrypoint and `scripts/native.py` as the current native workflow. Do not load prompts from old output ZIPs, copied examples or prior conversation snippets. For a saved job, run `native.py status --job ...` **before** reading `prompts.json`: it refreshes that working prompt file from the current helper without changing the existing images or generation references. Obsolete native mask-only jobs are rejected; prepare a new colored-layer job instead. The explicit API service is a separate implementation, never a source of native prompts. ## Native workflow 1. Inspect the actual supplied image with `view_image`. Do not identify/name illustrated characters unless needed. Do not substitute an example. 2. Prepare a persistent job: ```sh python3 <skill-dir>/scripts/native.py prepare --source /absolute/card.png --output /absolute/new-job --name 'Holo Card' ``` The helper requires Pillow. It saves the original, normalized source, state and prompts without network access. Read the newly prepared or refreshed `prompts.json` before generation. 3. Generate separate **colored** layers with the built-in image tool: - **Character:** continuous colored foreground, preserving clothing, anatomy and dark details. Remove overlaid text and repair the concealed artwork coherently. Use a regular neutral checkerboard matte outside the silhouette; convert it locally to an alpha mask before final import. - **Background:** identify scenery and reconstruct every area hidden by subjects, typography and frame. Produce a complete opaque plate, without holes, glyphs or frame fragments, with room for moving crops. - **UI:** combine original text, numbers, symbols, panels and the entire decorative frame at one depth. Preserve glyphs, colors and layout. Use the same checkerboard-matte workflow outside actual UI shapes. - **Structure:** derive thin white structural contours on black from the final repaired character layer, on exactly the same canvas. No filled regions, text, frame or scenery. Use the source card for the first three layers and the final character for contours. Preserve canvas, position and scale; do not independently recenter or fit layers. Inpainting is inferred repair, not recovery of unknown original pixels. The first three layers stay colored; only structure is a luminance mask. 4. Treat colored generation and alpha preparation as separate stages. In this native workflow, expect RGB/checkerboard output; do not require the image generator to emit an alpha channel, and do not repeatedly request "transparent PNG" to resolve this. If an input already has valid alpha, preserve it. For character/UI, inspect the actual returned image, identify its checkerboard matte, and prepare the aligned local mask described below. Then import each finished layer: ```sh python3 <skill-dir>/scripts/native.py add --job /absolute/job --kind character --image /actual/output.png --tool-reference 'Actual generation or repair record' ``` Repeat for `background`, `ui`, and `structure`. Raw inputs and hashes are retained. Use `--replace` only for an authorized replacement. Aspect errors require review, not silent cropping. 5. Assemble, inspect, and deliver: ```sh python3 <skill-dir>/scripts/native.py assemble --job /absolute/job python3 <skill-dir>/scripts/native.py status --job /absolute/job ``` Outputs include four RGBA assets, self-contained HTML, ZIP and provenance. Assembly completion is not visual approval. Inspect actual results before claiming fidelity. No automatic publishing is performed. ## Required matte-to-mask stage: affected regions only A checkerboard preview is not a file alpha channel. Read actual pixel alpha to distinguish them. Native generation need not provide alpha: for an RGB/checkerboard character or UI output, local matte removal is a normal required stage, not a missing capability or a terminal failure. `add` saves such an input as `needs_alpha_mask` and returns the next action. Continue preparing its mask and applying it; do not end with "no transparency, cannot import" or ask the user to fix it. This helper stages the work; it does not automatically infer a correct mask. Use correctly transparent inputs directly. Do not ask the generator for another full-element mask by default. Build the local mask for the actual retained artwork, adjusting only contaminated background regions. An opaque image containing ordinary scenery rather than checkerboard needs actual subject separation first; never pretend that scenery is checkerboard. If a colored output contains baked checkerboard pixels, first verify the artwork is otherwise usable. Identify only the contaminated background regions and remove that checkerboard locally, preserving existing valid alpha, clothing, skin, white highlights, text and frame. Never globally erase gray/white colors or derive subject alpha from artwork brightness. Use spatially constrained selections and connected matte regions, not global color thresholding. Include enclosed background gaps between hair, limbs, accessories and clothing. Preserve white hair/fur, dark clothes, skin, metallic reflections and small lettering. For ambiguous edges, inspect at full size and use small auxiliary selections; write the complete aligned mask locally (0 background, 255 retained artwork, intermediate edge coverage). Check black and white composites; repair edge RGB contamination as well as alpha. Local repair cannot fix changed pose or layout. An optional helper applies an independently prepared, aligned grayscale correction mask without altering RGB. It does **not** predict masks or remove checkerboards automatically: ```sh python3 <skill-dir>/scripts/native.py apply-alpha --job /absolute/job --kind character --color /absolute/color.png --mask /absolute/correction.png --tool-reference 'Exact local correction method' ``` The mask must match image dimensions, use L/1 mode and contain opaque/transparent coverage. Supply the complete desired alpha with unaffected areas preserved. The helper saves input hashes and black/white review images. For UI, retain original colored pixels where possible rather than regenerating typography. Do not use alpha repair to bypass a refused generation. ## Repair matte selection errors When matte removal damages light artwork or detached details, read [matte region selection](references/layer-repair.md). Its optional `scripts/matte_regions.py` removes only explicitly seeded candidate components, respects protected artwork, and preserves existing alpha elsewhere. Never infer background from region size, keep only the largest foreground component, or reuse previous-card coordinates. Candidate selection and edge quality still require visual inspection. ## Layer acceptance before rendering Judge all four layers separately before enabling foil or glow. Complexity is a reason for careful local selection, not permission to substitute these steps: - Character: retain the main figure and attached hair, tails, clothes and accessories; exclude typography, scenery, poster portraits and unrelated decorative creatures. Identify the roles from the actual composition. Preserve original canvas and placement instead of fitting the cutout to its bounding box. - Background: remove the main figure and overlays and reconstruct the concealed scene. Never use the original image enlarged, blurred or dimmed as the completed plate; it creates a second figure under parallax. A fully opaque file alone does not prove successful inpainting. - UI: keep text, panels, decorative frame and editorial inset portraits together when appropriate. Preserve their original pixels/layout where possible. Do not transfer inset faces or poster text into the main-character layer. - Structure: derive from the final repaired character, at the identical size and position. Restrict to selected structural contours; discard checkerboard edges, text, scenery, inset-panel boundaries and dense texture noise. Subject alpha removes outside contamination but cannot by itself distinguish hair/fabric texture from useful structural lines. Inspect an overlay on the character before rendering; never align independently normalized bounding boxes. - First inspect the color composite with contour glow OFF, then tilt both ways. Reject repeated people, retained background silhouettes, missing interiors, displaced text and checkerboard remnants before glow testing. Bloom must not disguise extraction errors. Record actual inspection and remaining defects; `completed` only means assembly succeeded. ## Rendering contract - English controls: **Depth** and **Contour glow**. Depth defaults to 0 at the midpoint of -3…+3; no left/right direction captions. - Signed depth changes foreground parallax: negative inward, positive outward. It NEVER changes stacking: **background → character → combined text/frame UI** at every value. UI also occludes emission and bloom. - Background moves independently with view, including when depth is 0. Reference mapping: `b=(p-.5)*.5+.5-view*.25` (2× background crop). Foreground and its contour use the same coordinates. - Use supplied decorative frame; do not overlay an invented procedural rim. Preserve HDR/RGBM bloom and backside isolation. Default contour glow is 0.15; zero disables contour light without removing foil lighting. - Check -3, 0 and +3 at the same tilted view, glow zero/modest, black/white alpha composites, and front/back. Reject holes, checkerboard residue, doubled/moving text, misaligned anatomy and contour drift. Do not hide defects under bloom. ## Local browser preview Serve the output folder on loopback with a persistent static server and open its real `http://127.0.0.1:PORT/index.html` URL. Inspect the browser and retain the preview tab. A queued file panel does not prove a browser loaded. This does not authorize public website deployment. ## Attribution Creative inspiration: **@乌托邦的香蕉**, using the same name on **Xiaohongshu (小红书)** and **Bilibili (B站)**. This acknowledges inspiration, not authorship of this implementation or endorsement. No profile URL is asserted without verification. - Contour glow is restricted to the structural line coverage multiplied by foreground alpha and UI exclusion. Mask the final blurred bloom by that same line coverage; no halo may spill into scenery or flat subject interiors. Compare glow 0 and maximum at a fixed view; only contour-covered pixels may change. Background foil lighting is independent. ## Phone preview Every generated viewer supports optional device orientation, touch drag, tap-to-flip and Recenter. Motion starts only after the viewer clicks Enable motion; iOS permission is requested inside that gesture. HTTPS is required. Drag temporarily overrides motion. Each device keeps its own depth and glow values; no synchronization service is used. Verify permission denial, missing sensors, calibration and screen rotation separately from actual phone sensor testing. When the user requests a phone-accessible preview, host the generated HTML on an authorized HTTPS destination. With its exact URL, add an offline QR entry using the optional `qrcode` Python dependency: ```sh python3 <skill-dir>/scripts/native.py assemble --job /absolute/job --preview-url https://actual-host.example/card ``` Publish the updated HTML containing the QR entry to that same URL. This argument generates a link and QR only; it does not upload or establish availability. Preserve the target access policy and state if the link requires login. Do not claim real phone verification from synthetic orientation events. ## Signed depth and clipping Positive depth lets character and combined text/frame layers extend outside the background card boundary on an oversized transparent rendering surface. Keep the background clipped to its rounded card boundary. Text/frame depth is clamped to zero for negative slider values; its own rounded clipping boundary moves with the layer. Negative character depth uses the original 0.06 view-offset coefficient and remains clipped to the card. Positive character and text offsets use 0.08 and 0.14 respectively. Do not simulate depth by scaling artwork. Preserve UI stacking, aligned character/contour coordinates, and hide the whole front surface when the back is visible.skills/holo-card/scripts/api.py11 KB67bd02cd023cupstream ↗
#!/usr/bin/env python3 """Standard-library client for Holo Card API. Never prints the API credential.""" import argparse import hashlib import json import os from pathlib import Path import stat import sys import time import urllib.error import urllib.parse import urllib.request import uuid import zipfile class ClientError(Exception): def __init__(self, code, message): self.code, self.message = code, message super().__init__(message) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def config_path(): return Path(os.environ.get('HOLO_CONFIG', Path.home() / '.config/holo-card/client.json')).expanduser() def private_json(path, value): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp') fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, 'w') as out: json.dump(value, out, ensure_ascii=False, indent=2) out.write('\n') os.replace(temporary, path) def valid_url(value): parsed = urllib.parse.urlsplit(value) if parsed.username or parsed.password or parsed.query or parsed.fragment: raise ClientError('INVALID_API_URL', 'Use an API base URL without credentials, query or fragment.') if parsed.scheme != 'https' and not (parsed.scheme == 'http' and parsed.hostname in ('127.0.0.1', 'localhost', '::1')): raise ClientError('HTTPS_REQUIRED', 'Remote API URLs must use HTTPS; HTTP is allowed only on loopback.') if not parsed.hostname: raise ClientError('INVALID_API_URL', 'A hostname is required.') return value.rstrip('/') def configuration(): path = config_path() try: if os.name != 'nt' and stat.S_IMODE(path.stat().st_mode) & 0o077: raise ClientError('INSECURE_CONFIG_PERMISSIONS', 'Set the client credential file permissions to 600.') data = json.loads(path.read_text()) except FileNotFoundError: raise ClientError('NOT_CONFIGURED', 'Configure an API URL and token file first. No generation was submitted.') data['api_url'] = valid_url(data['api_url']) if not isinstance(data.get('api_token'), str) or not data['api_token']: raise ClientError('TOKEN_MISSING', 'The client credential file has no API token.') return data class Client: def __init__(self, config=None): self.config = config or configuration() handlers = [NoRedirect()] if urllib.parse.urlsplit(self.config['api_url']).hostname in ('127.0.0.1','localhost','::1'): handlers.append(urllib.request.ProxyHandler({})) self.opener = urllib.request.build_opener(*handlers) def request(self, path, method='GET', data=None, headers=None, binary=False, timeout=30): if not path.startswith('/') or path.startswith('//'): raise ClientError('INVALID_API_PATH', 'Expected an API-relative path.') h = {'Authorization': 'Bearer ' + self.config['api_token'], **(headers or {})} if isinstance(data, dict): data = json.dumps(data).encode() h['Content-Type'] = 'application/json' req = urllib.request.Request(self.config['api_url'] + path, data=data, method=method, headers=h) try: with self.opener.open(req, timeout=timeout) as response: payload = response.read() return payload if binary else json.loads(payload) except urllib.error.HTTPError as error: try: detail = json.loads(error.read()).get('error', {}) raise ClientError(detail.get('code', 'HTTP_' + str(error.code)), detail.get('message', 'API request failed.')) except (ValueError, AttributeError): raise ClientError('HTTP_' + str(error.code), 'API request failed; no automatic resubmission was attempted.') except (urllib.error.URLError, TimeoutError, ConnectionError): raise ClientError('CONNECTION_UNAVAILABLE', 'API connection failed. For generation, keep the same card and request key and query the saved job before resubmitting.') def upload(self, path, name=None): file = Path(path).expanduser().resolve() if not file.is_file() or not 0 < file.stat().st_size <= 8*1024*1024: raise ClientError('INVALID_FILE', 'Choose an image file up to 8 MiB.') boundary = 'holo-' + uuid.uuid4().hex filename = file.name.replace('"', '').replace('\r','').replace('\n','') payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode() + file.read_bytes() + b'\r\n' if name: payload += (f'--{boundary}\r\nContent-Disposition: form-data; name="name"\r\n\r\n{name}\r\n').encode() payload += f'--{boundary}--\r\n'.encode() return self.request('/v1/cards', 'POST', payload, {'Content-Type': 'multipart/form-data; boundary=' + boundary}) def segment(value): return urllib.parse.quote(value, safe='') def request_key(card_id, supplied=None): # Save a stable key before any network operation. Client restarts reuse it. directory = config_path().parent / 'requests' name = hashlib.sha256(card_id.encode()).hexdigest() + '.json' path = directory / name if path.exists(): saved = json.loads(path.read_text()) if supplied and supplied != saved['key']: raise ClientError('REQUEST_KEY_CONFLICT', 'A saved key already exists for this card. Reuse it to avoid duplicate work.') return saved['key'] key = supplied or str(uuid.uuid4()) # Atomically link a fully written record; another CLI never reads partial JSON. directory.mkdir(parents=True, exist_ok=True, mode=0o700) temporary = directory / (name + '.' + uuid.uuid4().hex + '.tmp') fd = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(fd, 'w') as out: json.dump({'card_id':card_id,'key':key},out) try: os.link(temporary,path) except FileExistsError: return request_key(card_id,supplied) finally: temporary.unlink(missing_ok=True) return key def emit(value): print(json.dumps(value, ensure_ascii=False), flush=True) def main(): parser=argparse.ArgumentParser(description=__doc__) subs=parser.add_subparsers(dest='command',required=True) p=subs.add_parser('configure');p.add_argument('--url',required=True);p.add_argument('--token-file',required=True) subs.add_parser('doctor') p=subs.add_parser('upload');p.add_argument('file');p.add_argument('--name') p=subs.add_parser('generate');p.add_argument('card_id');p.add_argument('--max-image-calls',required=True,type=int,choices=[4]);p.add_argument('--request-key') p=subs.add_parser('status');p.add_argument('job_id') p=subs.add_parser('wait');p.add_argument('job_id');p.add_argument('--timeout',type=float,default=50);p.add_argument('--interval',type=float,default=5) p=subs.add_parser('card');p.add_argument('card_id') p=subs.add_parser('list');p.add_argument('--limit',type=int,default=50) p=subs.add_parser('preview');p.add_argument('card_id') p=subs.add_parser('download');p.add_argument('card_id');p.add_argument('--output',required=True);p.add_argument('--extract',action='store_true') p=subs.add_parser('openapi');p.add_argument('--output',required=True) args=parser.parse_args() if args.command=='configure': content=Path(args.token_file).expanduser().read_text().strip() try: secret=json.loads(content)['api_token'] except (ValueError,TypeError,KeyError): secret=content private_json(config_path(),{'api_url':valid_url(args.url),'api_token':secret}) emit({'configured':True,'api_url':valid_url(args.url),'config_file':str(config_path())});return client=Client() if args.command=='doctor': emit({'api_url':client.config['api_url'],**client.request('/v1/status')}) elif args.command=='upload': emit(client.upload(args.file,args.name)) elif args.command=='generate': key=request_key(args.card_id,args.request_key) emit(client.request('/v1/cards/'+segment(args.card_id)+'/generations','POST',{'max_image_calls':args.max_image_calls},{'Idempotency-Key':key})) elif args.command=='status': emit(client.request('/v1/jobs/'+segment(args.job_id))) elif args.command=='card': emit(client.request('/v1/cards/'+segment(args.card_id))) elif args.command=='list': emit(client.request('/v1/cards?limit='+str(max(1,min(100,args.limit))))) elif args.command=='preview': emit(client.request('/v1/cards/'+segment(args.card_id)+'/preview-links','POST')) elif args.command=='wait': deadline=time.monotonic()+max(0,min(55,args.timeout));previous=None while True: value=client.request('/v1/jobs/'+segment(args.job_id),timeout=min(10,max(1,deadline-time.monotonic()))) fingerprint=json.dumps([value['status'],value['layers']],sort_keys=True) if previous!=fingerprint: emit(value);previous=fingerprint if value['status'] in ('completed','failed','uncertain'): break if time.monotonic()>=deadline: emit({'waiting':True,'job_id':args.job_id,'status':value['status']});break time.sleep(min(max(1,args.interval),max(0,deadline-time.monotonic()))) elif args.command=='download': target=Path(args.output).expanduser().resolve() if target.exists(): raise ClientError('OUTPUT_EXISTS','Choose a new output path; existing results are not overwritten.') target.parent.mkdir(parents=True,exist_ok=True) data=client.request('/v1/cards/'+segment(args.card_id)+'/bundle',binary=True) fd=os.open(target,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600) with os.fdopen(fd,'wb') as out: out.write(data) result={'archive':str(target),'sha256':hashlib.sha256(data).hexdigest()} if args.extract: destination=target.with_suffix('') if destination.exists(): raise ClientError('OUTPUT_EXISTS','Archive saved, but extraction directory already exists.') with zipfile.ZipFile(target) as archive: for entry in archive.infolist(): candidate=(destination/entry.filename).resolve() if not candidate.is_relative_to(destination) or stat.S_ISLNK(entry.external_attr>>16): raise ClientError('UNSAFE_ARCHIVE','Archive contains an unsafe path; it was not extracted.') destination.mkdir(mode=0o700) archive.extractall(destination) result['html']=str(destination/'index.html') emit(result) elif args.command=='openapi': output=Path(args.output).expanduser().resolve();private_json(output,client.request('/openapi.json'));emit({'openapi':str(output)}) if __name__=='__main__': try: main() except ClientError as error: emit({'error':{'code':error.code,'message':error.message}});sys.exit(1) except (OSError,ValueError,KeyError): emit({'error':{'code':'LOCAL_CONFIGURATION_ERROR','message':'Check the local configuration, input and output paths. No credentials are printed.'}});sys.exit(1)skills/holo-card/scripts/matte_regions.py2.2 KB308eba8085f8upstream ↗
#!/usr/bin/env python3 """Remove explicitly seeded candidate matte regions; never infer candidates from color.""" import argparse from collections import deque from pathlib import Path from PIL import Image def selection(candidate, seeds, existing_alpha=None, protect=None): if candidate.mode not in ('1','L'):raise ValueError('Candidate must be a grayscale mask.') size=candidate.size;w,h=size for image in (existing_alpha,protect): if image is not None and (image.size!=size or image.mode not in ('1','L')): raise ValueError('All masks must be aligned grayscale images of identical size.') values=bytearray(candidate.convert('L').tobytes()) protected=protect.convert('L').tobytes() if protect else bytes(w*h) alpha=bytearray(existing_alpha.convert('L').tobytes()) if existing_alpha else bytearray([255])*(w*h) queue=deque();seen=bytearray(w*h) if not seeds:raise ValueError('At least one inspected matte seed is required.') for x,y in seeds: if not (0<=x<w and 0<=y<h):raise ValueError('Seed outside canvas.') i=y*w+x if values[i]!=255 or protected[i]:raise ValueError('Seed must be inside a confirmed unprotected matte candidate.') if not seen[i]:seen[i]=1;queue.append(i) while queue: i=queue.popleft();alpha[i]=0;x=i%w;y=i//w for j in ([i-1] if x else [])+([i+1] if x+1<w else [])+([i-w] if y else [])+([i+w] if y+1<h else []): if not seen[j] and values[j]==255 and not protected[j]:seen[j]=1;queue.append(j) return Image.frombytes('L',size,bytes(alpha)) if __name__=='__main__': p=argparse.ArgumentParser(description=__doc__) p.add_argument('--candidate',required=True);p.add_argument('--seed',action='append',required=True,help='Inspected x,y matte point; repeat for separate gaps') p.add_argument('--existing-alpha');p.add_argument('--protect');p.add_argument('--output',required=True) a=p.parse_args() result=selection(Image.open(a.candidate),[tuple(map(int,s.split(','))) for s in a.seed],Image.open(a.existing_alpha) if a.existing_alpha else None,Image.open(a.protect) if a.protect else None) output=Path(a.output) if output.exists():raise ValueError('Output exists; choose a new correction mask.') result.save(output)skills/holo-card/scripts/native.py18 KB82c19ffce047upstream ↗
#!/usr/bin/env python3 """Local preparation and assembly for Codex built-in image generation. No API or network calls.""" import argparse import base64 import hashlib import json from pathlib import Path import shutil import sys import time import zipfile from PIL import Image, ImageOps, ImageChops KINDS=('character','background','ui','structure') ROOT=Path(__file__).resolve().parents[1] TEMPLATES=ROOT/'assets/renderer' def prompt(kind): common=('Keep the entire original canvas, aspect ratio, exact positions and scale. Do not crop, recenter, redesign, ' 'change visible geometry. No new text or added glow. ') if kind=='structure': return common+'Output a black background with thin white visible structural contour lines of the main illustrated subjects, including selected internal shape boundaries. Exclude dense hair/fabric texture, checkerboard edges and editorial inset boundaries. No filled regions, text, UI or scenery lines. Use the final repaired subject layer as the reference so contours match its repaired anatomy exactly.' targets={ 'character':'Extract only the main foreground subject and its attached hair, clothing, tails and accessories in their original COLORS. Exclude editorial inset portraits and unrelated decorative creatures. Keep those editorial panels in the UI layer. Preserve the main subject on a regular neutral gray checkerboard matte, with no checkerboard inside the retained artwork. Remove scenery, printed text, symbols, UI and frame. Where any typography, numerals, icons or UI overlap the subject, remove the entire overlay and inpaint the concealed subject with coherent neighboring colors, shading, texture and contours. These interior repaired areas must contain continuous artwork, never checkerboard holes. Preserve original anatomy, silhouette, scale and position. No residual glyphs or duplicated text. The checkerboard matte belongs only outside the subject silhouette. Keep eyes, mouth interiors, black ink, dark colors and shadows opaque; never classify dark subject pixels as background. The output must be a continuous independently usable colored subject, not disconnected pieces of the source card.', 'background':'Automatically distinguish background scenery from foreground subjects and the combined typography/frame overlay. Produce a complete opaque COLOR background plate covering the entire canvas, including beneath the decorative border. Remove all subjects, printed text, UI and frame, and reconstruct ALL areas they concealed using the surrounding scenery, colors and directional strokes. No transparent gaps, unfilled cutout silhouettes or residual glyphs. Naturally black scenery remains black. Never substitute an enlarged, blurred or dimmed source image containing the subject. Preserve visible scenery alignment.', 'ui':'Extract the original colored typography, numerals, symbols, information bars AND the entire original decorative border/card frame together as ONE combined UI layer at the same depth, on a regular neutral gray checkerboard matte, with no checkerboard inside the retained artwork. Keep frame and typography together, never as separate depth layers. Preserve glyphs and panel colors exactly at their original positions. Retain editorial inset panels including their images as UI, while excluding the main foreground subject and scenery. Prefer original source pixels for typography when local extraction can preserve them; reject changed lettering. Do not redraw or rearrange text.'} return common+targets[kind]+' Output a full-color image, NOT a black-and-white mask or grayscale image. For character and UI, the local workflow converts the checkerboard matte to an alpha mask afterward; native transparent output is not required.' def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest() def save(path,value): temporary=path.with_suffix(path.suffix+'.tmp') temporary.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n') temporary.replace(path) def current_prompts():return {k:prompt(k) for k in KINDS} def prompt_digest():return hashlib.sha256(json.dumps(current_prompts(),sort_keys=True).encode()).hexdigest() def load(job): state=json.loads((job/'task.json').read_text()) if state.get('layer_mode')!='direct_rgba': raise ValueError('Obsolete native mask job. Prepare a new colored-layer job; legacy prompts and extraction are no longer supported by native.py.') # Saved prompts are working instructions, not the generation audit trail. # Actual generation references and raw images remain untouched. expected=current_prompts() try:existing=json.loads((job/'prompts.json').read_text()) except (OSError,ValueError):existing=None if existing!=expected:save(job/'prompts.json',expected) if state.get('prompt_digest')!=prompt_digest(): state['prompt_digest']=prompt_digest();save(job/'task.json',state) return state def summary(job,state): return {'job_directory':str(job),'execution':state['execution'],'status':state['status'], 'completed_layers':sum(l['status']=='imported' for l in state['layers'].values()),'total_layers':4, 'layers':{k:{'status':v['status'],'error':v.get('error')} for k,v in state['layers'].items()}, 'prompts':str(job/'prompts.json'),'prompt_digest':state.get('prompt_digest'), 'html':str(job/'index.html') if state['status']=='completed' else None, 'archive':str(job/'card.zip') if state['status']=='completed' else None} def prepare(source,job,name): if job.exists():raise ValueError('Output directory exists. Use status to resume it or choose a new directory.') with Image.open(source) as image: if image.format not in ('PNG','JPEG','WEBP') or getattr(image,'n_frames',1)!=1 or image.width*image.height>24_000_000: raise ValueError('Expected one PNG/JPEG/WebP frame up to 24 megapixels.') normalized=ImageOps.exif_transpose(image).convert('RGBA') normalized.thumbnail((1600,1600),Image.Resampling.LANCZOS) job.mkdir(parents=True,mode=0o700);(job/'masks').mkdir();(job/'raw').mkdir();(job/'assets').mkdir() original_name='original'+Path(source).suffix.lower();shutil.copyfile(source,job/original_name) normalized.save(job/'source.png') state={'version':3,'prompt_digest':prompt_digest(),'layer_mode':'direct_rgba','execution':'codex_builtin_image_gen','name':name or source.stem,'status':'awaiting_images','created_at':int(time.time()*1000), 'source':{'original':original_name,'sha256':sha(source),'normalized_sha256':sha(job/'source.png'),'width':normalized.width,'height':normalized.height}, 'layers':{k:{'status':'pending','error':None} for k in KINDS},'repairs':{'background_inpainting':True,'subject_text_cleanup':True}} save(job/'task.json',state);save(job/'prompts.json',current_prompts()) return {**summary(job,state),'edit_target':str(job/'source.png'),'prompts':str(job/'prompts.json'), 'next':'Use the Codex built-in image_gen tool once per layer, then import its actual returned image path with add. No API setup is needed.'} def add(job,kind,path,tool_reference,replace=False): state=load(job) if state['layers'][kind]['status']=='imported' and not replace:raise ValueError('This layer is already imported. Use --replace only for an explicitly selected replacement image.') with Image.open(path) as image: if image.width*image.height>16_000_000 or getattr(image,'n_frames',1)!=1:raise ValueError('Mask image is too large or animated.') suffix={'JPEG':'.jpg','WEBP':'.webp'}.get(image.format,'.png');raw='raw/'+kind+suffix if Path(path).resolve()!=(job/raw).resolve():shutil.copyfile(path,job/raw) if abs((image.width/image.height)/(state['source']['width']/state['source']['height'])-1)>.025: state['layers'][kind]={'status':'needs_review','error':'MASK_ASPECT_MISMATCH','raw':raw,'sha256':sha(path)} state['status']='needs_review';save(job/'task.json',state) raise ValueError('Mask aspect ratio differs from the source. Its raw output is saved; no crop or regeneration was performed.') rgba=image.convert('RGBA') if kind!='structure': if kind != 'background' and rgba.getchannel('A').getextrema()[0]==255: state['layers'][kind]={'status':'needs_alpha_mask','error':None,'raw':raw,'sha256':sha(path),'tool_reference':tool_reference} state['status']='needs_alpha_mask';save(job/'task.json',state) return {**summary(job,state),'repair_input':str(job/raw), 'next_action':'Inspect the matte, prepare an aligned grayscale alpha mask for confirmed checkerboard regions, preserve artwork, then run apply-alpha. Continue locally; this is an intermediate state, not generation failure.', 'mask_convention':'0 removes confirmed background; 255 retains artwork; intermediate values are antialiased edges. Do not threshold artwork brightness or assume opaque pixels are checkerboard.'} if kind == 'background' and rgba.getchannel('A').getextrema()[0] < 255: state['layers'][kind]={'status':'needs_review','error':'BACKGROUND_HAS_HOLES','raw':raw,'sha256':sha(path)} state['status']='needs_review';save(job/'task.json',state) raise ValueError('Background must be fully opaque and inpainted. Raw output saved for review.') else: mask=ImageChops.multiply(rgba.convert('L'),rgba.getchannel('A'));mask.save(job/'masks'/f'{kind}.png') state['layers'][kind]={'status':'imported','error':None,'raw':raw,'sha256':sha(path),'format':('rgba' if kind!='structure' else 'mask'),'imported_at':int(time.time()*1000),'tool_reference':tool_reference} state['status']='ready_to_assemble' if all(v['status']=='imported' for v in state['layers'].values()) else 'awaiting_images' save(job/'task.json',state);return summary(job,state) def html_document(job,state): data_url=lambda path:'data:image/png;base64,'+base64.b64encode(path.read_bytes()).decode() manifest={'name':state['name'],'width':state['source']['width'],'height':state['source']['height'], 'assets':{k:data_url(job/'assets'/f'{k}.png') for k in KINDS},'back':data_url(TEMPLATES/'back.png')} if state.get('preview_url'): manifest['previewUrl']=state['preview_url'] manifest['previewQr']=data_url(job/'mobile-qr.png') data=json.dumps(manifest,ensure_ascii=True).replace('<','\<') renderer=(TEMPLATES/'renderer.js').read_text().replace('export async function createCardRenderer','async function createCardRenderer') script='globalThis.HOLO_MANIFEST='+data+';\n'+renderer+'\nglobalThis.HOLO_CREATE_RENDERER=createCardRenderer;\n'+(TEMPLATES/'viewer.js').read_text() html=(TEMPLATES/'index.html').read_text() html=html.replace('<link rel="stylesheet" href="viewer.css?access=__ACCESS__">','<style>'+(TEMPLATES/'viewer.css').read_text()+'</style>') return html.replace('<script type="module" src="viewer.js?access=__ACCESS__"></script>','<script type="module">'+script+'</script>') def assemble(job,preview_url=None): state=load(job) if preview_url is not None: from urllib.parse import urlsplit parsed=urlsplit(preview_url) if parsed.scheme!='https' or not parsed.hostname or parsed.username or parsed.password: raise ValueError('Mobile preview URL must be an HTTPS address without embedded credentials.') try: import qrcode except ImportError: raise ValueError('Mobile QR generation requires the optional qrcode package: pip install qrcode') qrcode.make(preview_url).save(job/'mobile-qr.png') state['preview_url']=preview_url if any(layer['status']!='imported' for layer in state['layers'].values()):raise ValueError('All four actual image-tool outputs must be imported before assembly.') source=Image.open(job/'source.png').convert('RGBA');warnings=[] lut=[round(max(0,min(1,(v-24)/207))*255) for v in range(256)] for kind in KINDS: if kind!='structure': layer=Image.open(job/state['layers'][kind]['raw']).convert('RGBA').resize(source.size,Image.Resampling.LANCZOS) layer.save(job/'assets'/f'{kind}.png') if not layer.getchannel('A').getbbox():warnings.append(kind.upper()+'_EMPTY_LAYER') continue mask=Image.open(job/'masks'/f'{kind}.png').convert('L').resize(source.size,Image.Resampling.LANCZOS).point(lut) character_alpha=Image.open(job/'assets/character.png').getchannel('A') alpha=ImageChops.multiply(character_alpha,mask) layer=Image.new('RGBA',source.size,'white') layer.putalpha(alpha);layer.save(job/'assets'/f'{kind}.png') if not alpha.getbbox():warnings.append(kind.upper()+'_EMPTY_SELECTION') (job/'index.html').write_text(html_document(job,state)) state['status']='completed';state['completed_at']=int(time.time()*1000);state['warnings']=warnings state['quality_review']='not_automatically_verified';save(job/'task.json',state) provenance={k:v for k,v in state.items() if k!='layers'} provenance['layers']={k:{key:value for key,value in layer.items() if key!='tool_reference'} for k,layer in state['layers'].items()} provenance['renderer']={'emission':40,'rgbm_range':64,'bloom_scales':[.5,.25]} save(job/'provenance.json',provenance) shutil.copyfile(TEMPLATES/'THIRD_PARTY_NOTICES.md',job/'THIRD_PARTY_NOTICES.md') names=['index.html','source.png',state['source']['original'],'provenance.json','prompts.json','THIRD_PARTY_NOTICES.md'] if state.get('preview_url'):names.append('mobile-qr.png') names += [f'assets/{k}.png' for k in KINDS]+[f'masks/{k}.png' for k in KINDS if (job/'masks'/f'{k}.png').exists()] with zipfile.ZipFile(job/'card.zip','w',zipfile.ZIP_DEFLATED) as archive: for name in names:archive.write(job/name,name) return summary(job,state) def apply_alpha(job,kind,color_path,mask_path,reference,replace=False): """Apply an independently authored selection; never derive alpha from color.""" state=load(job) if state.get('layer_mode')!='direct_rgba':raise ValueError('Requires a direct_rgba job.') if state['layers'][kind]['status']=='imported' and not replace:raise ValueError('Layer already imported; select --replace explicitly.') with Image.open(color_path) as color, Image.open(mask_path) as mask_image: if color.width*color.height>16_000_000:raise ValueError('Color image too large.') if color.size!=mask_image.size:raise ValueError('Color and mask must have identical dimensions; align explicitly first.') if abs((color.width/color.height)/(state['source']['width']/state['source']['height'])-1)>.025:raise ValueError('Color aspect ratio differs from card canvas.') if mask_image.mode not in ('1','L'):raise ValueError('Selection must be an explicit grayscale L or 1 mask, not a color image.') mask=mask_image.convert('L') low,high=mask.getextrema() if low!=0 or high!=255:raise ValueError('Selection must contain both fully transparent and fully opaque pixels.') rgba=color.convert('RGBA');rgba.putalpha(mask) folder=job/'alpha-inputs'/kind;folder.mkdir(parents=True,exist_ok=True) stamp=str(time.time_ns()) color_copy=folder/(stamp+'-color.png');mask_copy=folder/(stamp+'-mask.png');out=folder/(stamp+'-rgba.png') color.convert('RGBA').save(color_copy);mask.save(mask_copy);rgba.save(out) for name,bg in [('black','black'),('white','white')]: plate=Image.new('RGBA',rgba.size,bg);plate.alpha_composite(rgba);plate.convert('RGB').save(folder/(stamp+'-review-'+name+'.png')) result=add(job,kind,out,reference,replace) state=load(job);state['layers'][kind]['alpha_method']='independent_selection' state['layers'][kind]['alpha_inputs']={'color':str(color_copy.relative_to(job)),'color_sha256':sha(color_copy),'mask':str(mask_copy.relative_to(job)),'mask_sha256':sha(mask_copy)} state['layers'][kind]['visual_review']='required: alignment, edge contamination, interior holes, text residue' save(job/'task.json',state) return {**summary(job,state),'review_directory':str(folder),'visual_review':'required'} def main(): parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='command',required=True) p=sub.add_parser('prepare');p.add_argument('--source',required=True);p.add_argument('--output',required=True);p.add_argument('--name') p=sub.add_parser('add');p.add_argument('--job',required=True);p.add_argument('--kind',choices=KINDS,required=True);p.add_argument('--image',required=True);p.add_argument('--tool-reference');p.add_argument('--replace',action='store_true') p=sub.add_parser('apply-alpha');p.add_argument('--job',required=True);p.add_argument('--kind',choices=('character','ui'),required=True);p.add_argument('--color',required=True);p.add_argument('--mask',required=True);p.add_argument('--tool-reference',required=True);p.add_argument('--replace',action='store_true') for command in ('assemble','status'): p=sub.add_parser(command);p.add_argument('--job',required=True) if command=='assemble':p.add_argument('--preview-url') args=parser.parse_args() if args.command=='prepare':result=prepare(Path(args.source).expanduser().resolve(),Path(args.output).expanduser().resolve(),args.name) else: job=Path(args.job).expanduser().resolve() if args.command=='add':result=add(job,args.kind,Path(args.image).expanduser().resolve(),args.tool_reference,args.replace) elif args.command=='apply-alpha':result=apply_alpha(job,args.kind,Path(args.color),Path(args.mask),args.tool_reference,args.replace) elif args.command=='assemble':result=assemble(job,args.preview_url) else:result=summary(job,load(job)) print(json.dumps(result,ensure_ascii=False)) if __name__=='__main__': try:main() except (ValueError,OSError,KeyError) as error: print(json.dumps({'error':str(error),'api_called':False,'generation_started_by_script':False},ensure_ascii=False));sys.exit(1)skills/holo-card/scripts/service.py3.9 KB2f794ed9a6adupstream ↗
#!/usr/bin/env python3 """Manage the separately configured local Holo API process; never invokes generation.""" import argparse import json import os from pathlib import Path import signal import socket import subprocess import sys import time import urllib.request ROOT=Path(os.environ.get('HOLO_CONFIG_DIR',Path.home()/'.config/holo-card')).expanduser() CONFIG=ROOT/'service.json' STATE=ROOT/'service-state.json' def emit(value): print(json.dumps(value,ensure_ascii=False),flush=True) def probe(url): try: opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) with opener.open(url+'/healthz',timeout=1) as response: return json.loads(response.read()).get('service')=='holo-card-api' except Exception:return False def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('command',choices=['start','status','stop']);args=parser.parse_args() config=json.loads(CONFIG.read_text());host=config.get('host','127.0.0.1');port=int(config.get('port',8787));url=f'http://{host}:{port}' if args.command=='status':emit({'running':probe(url),'api_url':url});return if args.command=='start': if probe(url):emit({'running':True,'api_url':url,'started':False});return if host not in ('127.0.0.1','localhost','::1'):raise ValueError('This helper starts loopback services only. Use the service deployment configuration for remote hosting.') environment=os.environ.copy() if config.get('env_file'): for line in Path(config['env_file']).expanduser().read_text().splitlines(): if line.startswith('GEMINI_API_KEY='):environment['GEMINI_API_KEY']=line.split('=',1)[1].strip().strip('"\'') environment.update({'HOLO_DATA_DIR':config['data_dir'],'HOST':host,'PORT':str(port)}) root=Path(config['api_root']);entry=root/'src/server.mjs';node=Path(config['node_executable']) if not entry.is_file() or not node.is_file():raise ValueError('Configured API installation or Node runtime is unavailable.') ROOT.mkdir(parents=True,exist_ok=True,mode=0o700) fd=os.open(ROOT/'service.log',os.O_WRONLY|os.O_CREAT|os.O_APPEND,0o600) with os.fdopen(fd,'ab') as log: process=subprocess.Popen([str(node),str(entry)],cwd=root,env=environment,stdin=subprocess.DEVNULL,stdout=log,stderr=log,start_new_session=True) for _ in range(50): if process.poll() is not None:raise ValueError('API exited during startup. Check the private service log.') if probe(url): fd=os.open(STATE,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600) with os.fdopen(fd,'w') as out:json.dump({'pid':process.pid,'api_url':url,'entry':str(entry)},out) emit({'running':True,'started':True,'api_url':url});return time.sleep(.1) process.terminate();raise ValueError('API did not become ready. No generation was submitted.') if args.command=='stop': if not STATE.exists():emit({'stopped':False,'reason':'No managed process record'});return state=json.loads(STATE.read_text());pid=int(state['pid']) # Match the exact managed script to avoid signalling a recycled process ID. actual=subprocess.run(['ps','-p',str(pid),'-o','args='],capture_output=True,text=True).stdout if state['entry'] not in actual:emit({'stopped':False,'reason':'Managed process is no longer running'});return os.kill(pid,signal.SIGTERM) for _ in range(100): if not probe(url): STATE.unlink(missing_ok=True);emit({'stopped':True});return time.sleep(.1) emit({'stopping':True,'pid':pid}) if __name__=='__main__': try:main() except Exception as error: emit({'error':{'code':'LOCAL_SERVICE_UNAVAILABLE','message':str(error) if isinstance(error,ValueError) else 'Run the local API installer or check its private configuration.'}});sys.exit(1)skills/holo-card/references/api.md4.1 KB2e87366b9911upstream ↗
# API connection and agent contract The separately running **Holo Card API** is required. Its OpenAPI 3.1 document is served at `/openapi.json`. The skill works with localhost or a remote HTTPS deployment; it does not depend on the earlier Sites website or its browser login. ## Configure a client Use a protected file supplied by the API operator. It can contain a plain API token or JSON with `api_token`: ```sh python3 <skill-dir>/scripts/api.py configure --url https://YOUR_API_ORIGIN --token-file /private/path/token.json ``` Do not request that the user paste their Gemini key into chat. The Gemini key belongs only to the service process. Local configuration defaults to `~/.config/holo-card/client.json` (mode 600). Different agents can select different client files with `HOLO_CONFIG`. If a local service installation exists, its non-secret paths live in `~/.config/holo-card/service.json`. The installer is in the separately distributed API package. Do not guess paths, install random dependencies, publish a website or expose a localhost port just to configure this skill. ## Direct calls for other agents Use `Authorization: Bearer <API_TOKEN>` for all `/v1` endpoints. API tokens have `cards:read`, `cards:write` and/or `generations:create` scopes. Cards and jobs are isolated by token owner. Creating a new token defaults to a separate owner; the operator can explicitly give another token the same owner to share a library. | Operation | Request | Result | |---|---|---| | Upload | `POST /v1/cards`, multipart `file`, optional `name` | Card ID and stored source, no generation | | Start | `POST /v1/cards/{id}/generations`, `Idempotency-Key`, JSON `{"max_image_calls":4}` | Durable job ID, HTTP 202; same key replays the job | | Progress | `GET /v1/jobs/{id}` | Actual layer states, timestamps, errors and completion count | | Result | `GET /v1/cards/{id}` | Protected RGBA/mask asset URLs, ZIP and preview-link endpoint | | Bundle | `GET /v1/cards/{id}/bundle` | Self-contained HTML and material ZIP | | Preview | `POST /v1/cards/{id}/preview-links` | Scoped 15-minute browser URL | Do not create a fresh idempotency key after a network timeout. Query the card for its existing job, or replay the original request with the **same** key. The server also enforces one job per card, so a different key cannot silently start another paid generation. A new upload followed by generation is new paid work and needs the user's authorization. Important errors: `PROVIDER_NOT_CONFIGURED`, `PROVIDER_AUTH_OR_BILLING`, `PROVIDER_QUOTA_OR_RATE_LIMIT`, `SUBMISSION_OUTCOME_UNKNOWN`, `PROVIDER_NO_IMAGE`, `MASK_ASPECT_MISMATCH`, `ASSEMBLY_FAILED`. None justifies automatic paid retry. Read-only polling failures can recover on a later read. The service normalizes image orientation and limits the longest edge to 1600 px without cropping; original uploaded bytes remain separately available. AI masks are resized to the normalized canvas only after an aspect-ratio check. RGBA colors come from this normalized source; hidden regions are not repaired. A successful generation response does not itself prove high-quality segmentation. ## API-only client workflow This section is for agents without built-in image generation, or when the user explicitly requests API mode. Codex normally uses `native.py` and its built-in image tool instead. ```sh python3 <skill-dir>/scripts/api.py doctor python3 <skill-dir>/scripts/api.py upload /absolute/path/card.png python3 <skill-dir>/scripts/api.py generate CARD_ID --max-image-calls 4 python3 <skill-dir>/scripts/api.py wait JOB_ID --timeout 50 python3 <skill-dir>/scripts/api.py download CARD_ID --output /absolute/path/card.zip --extract python3 <skill-dir>/scripts/api.py preview CARD_ID ``` Before the `generate` command, require authorization for the supplied image and at most four 1K image calls. Reuse existing authorization; configuration, upload, or a refusal of a test image does not grant permission for paid generation. The client saves an idempotency key before submission. `wait` reports real states and returns within a bounded interval. A configured local API can be started using `service.py start`; this is never needed for native Codex mode.skills/holo-card/references/layer-repair.md2.1 KBead57b84e5a4upstream ↗
# Select matte regions without erasing artwork Use this procedure when checkerboard removal damages pale artwork or removes detached foreground details. Select candidates and seeds from the current image; never reuse another card’s coordinates or thresholds. This helper does not solve geometric alignment, text extraction or contour registration. ## Matte selection without erasing artwork Color resemblance is only a candidate signal. Gray cuffs, white hair, highlights and pale lettering may match the matte. A large region is not proof of background, and being connected to the canvas edge is insufficient when the subject touches that edge. Inspect the actual checker pattern and silhouette first. Build an aligned grayscale candidate mask with 255 only where matte connectivity is eligible. Add protected subject regions and break candidate bridges where matte leaks into artwork. Remove only components reached from explicitly inspected matte seeds. Enclosed gaps require their own inspected seeds; never remove every enclosed neutral region. Do not keep only the largest foreground component: detached accessories, particles and separate subjects may be intentional. The optional Pillow-only helper performs this deterministic connectivity operation. It does not detect a checkerboard, choose seeds, or produce soft edges: ```sh python3 <skill-dir>/scripts/matte_regions.py --candidate /path/candidate.png --seed X,Y --seed GAP_X,GAP_Y --existing-alpha /path/current-alpha.png --protect /path/protected-artwork.png --output /path/new-selection.png ``` Seed coordinates above are placeholders chosen by inspecting the current image. Omit existing-alpha only for fully opaque input; omit protect only when candidates cannot leak into artwork. Candidate/protection/alpha masks must share the actual full canvas. Only candidate value 255 is traversable. The helper preserves all alpha outside selected matte components, including partially transparent edges. Inspect and refine edge coverage locally afterward; do not blur the whole mask. Composite over both black and white, check interior holes and colored fringes, then use `native.py apply-alpha`.skills/holo-card/assets/renderer/back.png2.5 MBb05ec17db410upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
skills/holo-card/assets/renderer/index.html2.1 KB67b91345bc37upstream ↗
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Holo Card</title><link rel="stylesheet" href="viewer.css?access=__ACCESS__"></head><body><main class="room"><button id="immersive" class="immersive-toggle" type="button" aria-label="Enter immersive mode" aria-pressed="false" title="Immersive mode"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/><path class="eye-slash" d="m4 4 16 16"/></svg></button><div class="stage"><div class="card" tabindex="0" role="button" aria-label="Click to flip, drag to rotate, or use arrow keys"><div class="face front"><canvas></canvas></div><div class="face back"><img alt="Card back" draggable="false"></div></div></div><aside class="controls" aria-label="Card effects"><label for="depth">Depth</label><div class="depth-track"><input id="depth" type="range" min="-3" max="3" step="0.05" value="0"><span class="depth-ticks" aria-hidden="true"><span></span><span>0</span><span></span></span></div><output for="depth">0.00×</output><label for="brightness">Contour glow</label><input id="brightness" type="range" min="0" max="3" step="0.05" value="0.15"><output for="brightness">0.15×</output><div class="interaction"><button id="motion" type="button" aria-pressed="false">Enable motion</button><button id="mobile" type="button" hidden>Phone preview</button><button id="reset" type="button">Recenter</button></div><p id="motion-hint" aria-live="polite">Drag to rotate · Tap to flip</p></aside><dialog id="mobile-dialog"><form method="dialog"><button aria-label="Close" class="close">×</button></form><h2>Open on your phone</h2><img id="mobile-qr" alt="Scan to preview this card on your phone"><a id="mobile-link" target="_blank" rel="noopener">Open preview</a><p>Each device has its own controls.</p></dialog><p class="status" role="status">Loading card…</p></main><script type="module" src="viewer.js?access=__ACCESS__"></script></body></html>skills/holo-card/assets/renderer/renderer.js12 KBa07e908797f5upstream ↗
// Snapshot of the shared HDR card renderer; input textures are materialized RGBA layers. // Lightweight, view-dependent layered card. No 3D engine or video textures. const vertex = `attribute vec2 position; varying vec2 uv; void main(){uv=position*.5+.5;gl_Position=vec4(position,0.,1.);}`; const fragment = `precision highp float; varying vec2 uv; uniform sampler2D art,bg,uiTex,bloomNear,bloomWide,structureTex; uniform float extracted, cardAspect; uniform vec2 view; uniform float depth, contourBrightness, power, glowPass, pixelWidth; vec4 encodeHDR(vec3 c){float m=clamp(ceil(max(max(c.r,c.g),c.b)/64.*255.)/255.,1./255.,1.);return vec4(c/(64.*m),m);} vec3 decodeHDR(vec4 c){return c.rgb*c.a*64.;} vec3 hsv(vec3 c){vec4 K=vec4(0.,-1./3.,2./3.,-1.);vec4 p=mix(vec4(c.bg,K.wz),vec4(c.gb,K.xy),step(c.b,c.g));vec4 q=mix(vec4(p.xyw,c.r),vec4(c.r,p.yzx),step(p.x,c.r));float d=q.x-min(q.w,q.y);return vec3(abs(q.z+(q.w-q.y)/(6.*d+.00001)),d/(q.x+.00001),q.x);} float ink(vec2 p){vec4 c=texture2D(art,p);vec3 h=hsv(pow(c.rgb,vec3(2.2)));return smoothstep(.035,.065,h.x)*(1.-smoothstep(.17,.21,h.x))*smoothstep(.4,.67,h.y)*smoothstep(.065,.25,h.z)*c.a;} float structure(vec2 p){if(extracted>.5)return texture2D(structureTex,p).a;float a=ink(p);float b=min(min(ink(p+vec2(.0025,0.)),ink(p-vec2(.0025,0.))),min(ink(p+vec2(0.,.0018)),ink(p-vec2(0.,.0018))));return smoothstep(.025,.22,max(0.,a-b));} vec3 rainbow(float t){return .52+.48*cos(6.28318*(t+vec3(0.,.33,.67)));} float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);} float band(vec2 p){float f=p.x*.65+p.y*.4+view.x*1.9+view.y*.85;return pow(max(0.,1.-abs(fract(f+.16)-.5)*2.),3.);} void main(){ vec2 p=(uv-.5)*1.6+.5;vec2 u=p; vec2 edge=abs((p-.5)*vec2(1.,cardAspect))-(vec2(.5,cardAspect*.5)-vec2(.045)); float edgeDistance=length(max(edge,0.))+min(max(edge.x,edge.y),0.)-.045; float cardMask=1.-smoothstep(-pixelWidth,pixelWidth,edgeDistance); float foregroundMask=depth>0.?1.:cardMask;vec2 a=(p-.5)*1.25+.5+view*.40;vec2 b=(p-.5)*.5+.5-view*.25; if(extracted>.5){a=p-view*(depth<0.?.06:.08)*depth;u=p-view*.14*max(depth,0.);b=(p-.5)*.5+.5-view*.25;} vec4 ch=texture2D(art,a);ch.a*=step(0.,a.x)*step(a.x,1.)*step(0.,a.y)*step(a.y,1.); ch.a*=foregroundMask; vec4 background=texture2D(bg,b);background.a*=cardMask;background.a*=step(0.,b.x)*step(b.x,1.)*step(0.,b.y)*step(b.y,1.); float baseAlpha=cardMask+(1.-cardMask)*ch.a; vec3 base=mix(background.rgb*cardMask,ch.rgb,ch.a); vec3 ui=texture2D(uiTex,u).rgb;vec3 uh=hsv(ui);float um=max(smoothstep(.105,.23,uh.y),1.-smoothstep(.35,.62,uh.z)); if(extracted>.5)um=texture2D(uiTex,u).a*step(0.,u.x)*step(u.x,1.)*step(0.,u.y)*step(u.y,1.); // The text/frame plate has its own rounded boundary, moving with its UVs. vec2 uiEdge=abs((u-.5)*vec2(1.,cardAspect))-(vec2(.5,cardAspect*.5)-vec2(.045)); float uiDistance=length(max(uiEdge,0.))+min(max(uiEdge.x,uiEdge.y),0.)-.045; float uiMask=1.-smoothstep(-pixelWidth,pixelWidth,uiDistance); um*=uiMask*foregroundMask; float finalAlpha=clamp(baseAlpha+(1.-baseAlpha)*um,0.,1.); // Transparent overscan must contain zero RGB, including on Safari/Metal. if(finalAlpha<=0.){gl_FragColor=glowPass>.5?encodeHDR(vec3(0.)):vec4(0.);return;} float phase=p.x*.62+p.y*.36+view.x*1.9+view.y*.8; vec3 spectrum=rainbow(phase*2.2);float light=band(p); float micro=pow(hash(floor(p*vec2(620.,868.))),28.); base=mix(base,base*(.64+spectrum*.7)+spectrum*.07*baseAlpha,light*.48*power); float line=structure(a)*ch.a; float envelope=smoothstep(.025,.42,light); vec3 emission=(spectrum*.85+vec3(.15))*line*envelope*power*40.*contourBrightness; vec2 cell=fract(p*vec2(24.,34.))-.5;float seed=hash(floor(p*vec2(24.,34.)));float star=pow(max(0.,1.-abs(cell.x)*18.),14.)*pow(max(0.,1.-abs(cell.y)*2.),6.)+pow(max(0.,1.-abs(cell.y)*18.),14.)*pow(max(0.,1.-abs(cell.x)*2.),6.); base+=spectrum*(star*step(.965,seed)*light*.65+micro*light*.12)*power*(1.-ch.a)*cardMask; base=mix(base,ui,um); float glare=pow(max(0.,1.-length((p-vec2(.5+view.x,.6+view.y))*vec2(1.,.75))),5.); base+=vec3(glare*.12*power)*finalAlpha; base/=max(finalAlpha,.0001); // Concentric rounded border in card-width units, matching the CSS outer radius. // Outer radius .045, uniform inset .015, inner radius .030. vec2 corner=abs((p-.5)*vec2(1.,cardAspect))-(vec2(.485,cardAspect*.5-.015)-vec2(.030)); float distanceToInner=length(max(corner,0.))+min(max(corner.x,corner.y),0.)-.030; float inside=1.-smoothstep(-pixelWidth,pixelWidth,distanceToInner); float rim=(1.-inside)*(1.-extracted); base=mix(base,mix(vec3(.76,.67,.32),spectrum*.5+.5,.35*power)+glare*.15,rim); emission*=(1.-um)*foregroundMask; if(glowPass>.5){gl_FragColor=encodeHDR(max(emission-vec3(1.),vec3(0.)));return;} vec3 bloom=decodeHDR(texture2D(bloomNear,uv))*.55+decodeHDR(texture2D(bloomWide,uv))*.8; bloom*=foregroundMask*(1.-um)*line; // Display mapping is applied AFTER the HDR light and two-scale bloom are composed. vec3 linear=pow(clamp(base,0.,1.),vec3(2.2)); vec3 combined=1.-(1.-linear)*exp(-(emission*.38+bloom*.85)); gl_FragColor=vec4(pow(clamp(combined,0.,1.),vec3(1./2.2))*finalAlpha,finalAlpha); }`; const blurFragment = `precision highp float; varying vec2 uv;uniform sampler2D source;uniform vec2 stepSize; vec3 decodeHDR(vec4 c){return c.rgb*c.a*64.;} vec4 encodeHDR(vec3 c){float m=clamp(ceil(max(max(c.r,c.g),c.b)/64.*255.)/255.,1./255.,1.);return vec4(c/(64.*m),m);} void main(){vec3 c=vec3(0.);float total=0.;for(int i=-4;i<=4;i++){float f=float(i);float w=exp(-f*f/8.);c+=decodeHDR(texture2D(source,uv+stepSize*f))*w;total+=w;}gl_FragColor=encodeHDR(c/total);}`; export async function createCardRenderer(canvas, assets) { const gl = canvas.getContext('webgl', { alpha: true, premultipliedAlpha: true, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: true, }); if (!gl) throw new Error('WebGL unavailable'); const shaders = [], programs = [], textures = [], frames = []; const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW, ); function compile(type, source) { const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader) || 'Shader error'); shaders.push(shader); return shader; } function program(source) { const p = gl.createProgram(); gl.attachShader(p, compile(gl.VERTEX_SHADER, vertex)); gl.attachShader(p, compile(gl.FRAGMENT_SHADER, source)); gl.linkProgram(p); if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error('Shader link error'); programs.push(p); return p; } const scene = program(fragment), blur = program(blurFragment); function use(p) { gl.useProgram(p); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); const a = gl.getAttribLocation(p, 'position'); gl.enableVertexAttribArray(a); gl.vertexAttribPointer(a, 2, gl.FLOAT, false, 0, 0); } function texture(filter) { const t = gl.createTexture(); textures.push(t); gl.bindTexture(gl.TEXTURE_2D, t); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); return t; } const images = await Promise.all( ['character', 'background', 'ui', 'structure'].map( (name) => new Promise((resolve, reject) => { const image = new Image(); image.onload = () => resolve(image); image.onerror = () => reject(new Error('Asset unavailable')); image.src = assets[name]; }), ), ); const artTextures = images.map((image) => { const t = texture(gl.LINEAR); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return t; }); // Full-resolution artwork and line core; bloom only is computed at half/quarter resolution. canvas.width = window.innerWidth < 640 ? 1036 : 1408; canvas.height = Math.round( canvas.width * (assets ? images[0].height / images[0].width : 1.4), ); function target(scale) { const w = Math.round(canvas.width * scale), h = Math.round(canvas.height * scale); const t = texture(gl.NEAREST); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null, ); const f = gl.createFramebuffer(); frames.push(f); gl.bindFramebuffer(gl.FRAMEBUFFER, f); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0, ); if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('Bloom framebuffer unavailable'); return { t, f, w, h }; } const emission = target(0.5), temp = target(0.5), near = target(0.5), wideTemp = target(0.25), wide = target(0.25); const sceneU = { view: gl.getUniformLocation(scene, 'view'), power: gl.getUniformLocation(scene, 'power'), depth: gl.getUniformLocation(scene, 'depth'), contourBrightness: gl.getUniformLocation(scene, 'contourBrightness'), pass: gl.getUniformLocation(scene, 'glowPass'), }; use(scene); gl.uniform1f( gl.getUniformLocation(scene, 'cardAspect'), canvas.height / canvas.width, ); gl.uniform1f(gl.getUniformLocation(scene, 'extracted'), assets ? 1 : 0); gl.uniform1i(gl.getUniformLocation(scene, 'structureTex'), 5); gl.uniform1f(gl.getUniformLocation(scene, 'pixelWidth'), 1 / canvas.width); ['art', 'bg', 'uiTex', 'bloomNear', 'bloomWide'].forEach((name, i) => gl.uniform1i(gl.getUniformLocation(scene, name), i), ); use(blur); gl.uniform1i(gl.getUniformLocation(blur, 'source'), 0); const step = gl.getUniformLocation(blur, 'stepSize'); function bind(t, unit = 0) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, t); } function blurPass(src, dst, x, y) { use(blur); bind(src.t); gl.bindFramebuffer(gl.FRAMEBUFFER, dst.f); gl.viewport(0, 0, dst.w, dst.h); gl.uniform2f(step, x / src.w, y / src.h); gl.drawArrays(gl.TRIANGLES, 0, 6); } return { draw(x, y, strength, depth = 0, contourBrightness = 0.15) { use(scene); artTextures.forEach((t, i) => bind(t, i === 3 ? 5 : i)); bind(near.t, 3); bind(wide.t, 4); gl.uniform2f( sceneU.view, Math.sin((y * Math.PI) / 180) * 0.65, Math.sin((x * Math.PI) / 180) * 0.65, ); gl.uniform1f(sceneU.power, strength); gl.uniform1f(sceneU.depth, depth); gl.uniform1f(sceneU.contourBrightness, contourBrightness); gl.uniform1f(sceneU.pass, 1); gl.bindFramebuffer(gl.FRAMEBUFFER, emission.f); gl.viewport(0, 0, emission.w, emission.h); gl.drawArrays(gl.TRIANGLES, 0, 6); blurPass(emission, temp, 1.2, 0); blurPass(temp, near, 0, 1.2); blurPass(near, wideTemp, 5, 0); blurPass(wideTemp, wide, 0, 2.5); use(scene); artTextures.forEach((t, i) => bind(t, i === 3 ? 5 : i)); bind(near.t, 3); bind(wide.t, 4); gl.uniform1f(sceneU.pass, 0); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, canvas.width, canvas.height); gl.drawArrays(gl.TRIANGLES, 0, 6); }, dispose() { frames.forEach((f) => gl.deleteFramebuffer(f)); textures.forEach((t) => gl.deleteTexture(t)); shaders.forEach((s) => gl.deleteShader(s)); programs.forEach((p) => gl.deleteProgram(p)); gl.deleteBuffer(buffer); }, }; }skills/holo-card/assets/renderer/THIRD_PARTY_NOTICES.md583 B82815f998436upstream ↗
# Artwork and dependencies The default navy-and-gold witch-hat card back was generated with an image-generation tool from a user-supplied visual reference, at the user's request. It is a recreation, not a claim of an independently originated design. Rights in the reference artwork remain with their respective holders; the code's MIT license does not grant rights to underlying third-party artwork. The original reference upload is not bundled. User-supplied card artwork remains subject to its original rights. Third-party Python and Node dependencies retain their own licenses.skills/holo-card/assets/renderer/viewer.css4.9 KB451608f05ebbupstream ↗
*{box-sizing:border-box}html,body{margin:0;width:100%;height:100%;background:#101113;color:#dfe6ee;font-family:system-ui,sans-serif;overflow:hidden}.room{height:100svh;background:radial-gradient(ellipse at 50% 45%,#25282b,#101113 80%)}.stage{position:relative;width:100%;height:100%;display:grid;place-items:center;perspective:1400px;isolation:isolate}.card{position:relative;width:min(79vw,440px,calc(74svh / 1.4));aspect-ratio:5/7;transform-style:preserve-3d;will-change:transform;cursor:grab;touch-action:none;user-select:none;transform:rotateX(-5deg) rotateY(-12deg)}.card:active{cursor:grabbing}.card:focus-visible{outline:2px solid #d6ef9d;outline-offset:12px;border-radius:18px}.face{position:absolute;inset:0;border-radius:4.5%/3.2%;backface-visibility:hidden;-webkit-backface-visibility:hidden;box-shadow:0 0 0 1px #202329,0 30px 65px #000b;overflow:hidden}.front{transform:translateZ(.2px);background:#101318}.front canvas{display:block;width:100%;height:100%}.back{visibility:hidden;transform:rotateY(180deg) translateZ(.2px);background:#13216a}.back img{width:100%;height:100%;object-fit:fill;display:block}.status{position:absolute;bottom:24px;left:20px;right:20px;text-align:center;font-size:14px;line-height:1.5}.status[hidden]{display:none} .controls{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);width:min(380px,90vw);display:grid;grid-template-columns:90px 1fr 48px;gap:12px;align-items:center;padding:16px 18px;background:#1b1e22e8;border:1px solid #ffffff18;border-radius:16px;font-size:13px}.controls input{width:100%;accent-color:#d6ef9d}.controls output{text-align:right;font-variant-numeric:tabular-nums}.stage{height:calc(100% - 105px)} .depth-track{position:relative;min-width:0}.depth-track:before{content:"";position:absolute;left:50%;top:5px;width:1px;height:15px;background:#dfe6ee88;pointer-events:none}.depth-ticks{display:flex;justify-content:space-between;font-size:10px;color:#a4acb5;margin-top:3px}.depth-ticks span:nth-child(2){position:absolute;left:50%;transform:translateX(-50%)} .controls{bottom:max(12px,env(safe-area-inset-bottom));gap:9px}.interaction{grid-column:1/-1;display:flex;gap:8px}.interaction button{flex:1;min-height:38px;border:1px solid #ffffff25;border-radius:9px;background:#2b3036;color:inherit;font:inherit;cursor:pointer}.interaction button[aria-pressed=true]{background:#d6ef9d;color:#182017}.interaction button:focus-visible{outline:2px solid #d6ef9d;outline-offset:2px}.interaction button:disabled{opacity:.6}#motion-hint{grid-column:1/-1;margin:0;font-size:11px;line-height:1.4;color:#b9c1ca;text-align:center;min-height:16px}.stage{height:calc(100% - 200px);padding-top:env(safe-area-inset-top)}.card{max-height:calc(100svh - 230px);max-width:calc((100svh - 230px) / var(--card-aspect,1.4))}@media (max-height:500px) and (orientation:landscape){.stage{width:60%;height:100%;padding:20px}.card{max-height:88svh;max-width:calc(88svh / var(--card-aspect,1.4))}.controls{left:auto;right:12px;top:50%;bottom:auto;transform:translateY(-50%);width:37%;grid-template-columns:75px 1fr 40px;padding:12px;gap:8px;font-size:11px}} [hidden]{display:none!important}dialog{width:min(340px,90vw);border:1px solid #ffffff25;border-radius:18px;background:#202429;color:#dfe6ee;text-align:center;padding:24px}dialog::backdrop{background:#0009}dialog h2{font-size:18px}dialog img{display:block;width:220px;max-width:100%;margin:20px auto;border-radius:8px}dialog a{color:#d6ef9d}dialog p{font-size:12px;color:#b9c1ca}.close{position:absolute;right:10px;top:8px;border:0;background:none;color:inherit;font-size:26px;cursor:pointer}.interaction button{font-size:12px} /* Spacious controls and a card-only immersive view. */ .controls{row-gap:24px;padding:22px 18px}.interaction{margin-top:2px}#motion-hint{display:none}.stage{height:calc(100% - 220px)}.card{max-height:calc(100svh - 250px);max-width:calc((100svh - 250px) / var(--card-aspect,1.4))}.immersive-toggle{position:fixed;z-index:20;top:calc(16px + env(safe-area-inset-top));right:calc(16px + env(safe-area-inset-right));width:42px;height:42px;display:grid;place-items:center;border:1px solid #ffffff20;border-radius:50%;color:#dfe6ee;background:#202429b3;cursor:pointer;touch-action:manipulation}.immersive-toggle:focus-visible{outline:2px solid #d6ef9d;outline-offset:3px}.eye-slash{display:none}.immersive .eye-slash{display:block}.immersive .controls,.immersive .status{display:none}.immersive .stage{height:100%;width:100%;padding:0}.immersive .card{width:min(88vw,calc(84svh / var(--card-aspect,1.4)))!important;max-width:none;max-height:none}@media (max-height:500px) and (orientation:landscape){.controls{row-gap:18px}.stage{height:100%}.card{max-height:88svh;max-width:calc(88svh / var(--card-aspect,1.4))}} /* Oversized transparent foreground surface; background clipping is done in the shader. */ .front{overflow:visible;background:transparent}.front canvas{position:absolute;width:160%;height:160%;max-width:none;left:-30%;top:-30%;border-radius:0;pointer-events:none}skills/holo-card/assets/renderer/viewer.js9.9 KBa4a6f0647001upstream ↗
const canvas = document.querySelector('canvas'), card = document.querySelector('.card'), front = document.querySelector('.front'), back = document.querySelector('.back'), status = document.querySelector('.status'); const immersiveButton = document.querySelector('#immersive'); function setImmersive(active) { document.body.classList.toggle('immersive', active); immersiveButton.setAttribute('aria-pressed', String(active)); immersiveButton.setAttribute('aria-label', active ? 'Exit immersive mode' : 'Enter immersive mode'); immersiveButton.title = active ? 'Exit immersive mode' : 'Immersive mode'; } immersiveButton.addEventListener('click', () => setImmersive(!document.body.classList.contains('immersive'))); document.addEventListener('keydown', e => { if (e.key === 'Escape') setImmersive(false); }); let renderer, raf; let depth = 0, contourBrightness = 0.15, dirty = true; for (const input of document.querySelectorAll(".controls input")) { input.addEventListener("input", () => { if(input.id === "depth") depth = Number(input.value); else contourBrightness = Number(input.value); document.querySelector(`output[for="${input.id}"]`).value = (input.id === "depth" && Number(input.value) > 0 ? "+" : "") + Number(input.value).toFixed(2) + "×"; dirty = true; }); } try { const query = location.search; const factory = globalThis.HOLO_CREATE_RENDERER ?? (await import('./renderer.js' + query)).createCardRenderer; const manifest = globalThis.HOLO_MANIFEST ?? (await fetch('manifest.json' + query).then((r) => { if (!r.ok) throw new Error('Preview expired'); return r.json(); })); const mobileButton = document.querySelector('#mobile'); if (manifest.previewUrl && manifest.previewQr) { const url = new URL(manifest.previewUrl); if (url.protocol === 'https:') { mobileButton.hidden = false; document.querySelector('#mobile-qr').src = manifest.previewQr; document.querySelector('#mobile-link').href = url.href; mobileButton.addEventListener('click', () => document.querySelector('#mobile-dialog').showModal()); } } document.title = manifest.name + ' · Holo Card'; back.querySelector('img').src = manifest.back ?? 'back.png' + query; renderer = await factory(canvas, manifest.assets); const aspect = manifest.height / manifest.width; card.style.setProperty('--card-aspect', aspect); card.style.aspectRatio = `1 / ${aspect}`; card.style.width = `min(79vw,440px,calc(74svh / ${aspect}))`; status.hidden = true; const m = { x: -5, y: -12, tx: -5, ty: -12, base: 0, down: false, px: 0, py: 0, moved: false, pointer: null, startX: 0, startY: 0, }; const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches; const motionButton = document.querySelector('#motion'); const resetButton = document.querySelector('#reset'); const hint = document.querySelector('#motion-hint'); let motionEnabled = false, origin = null, sensorX = 0, sensorY = 0, sensorTimer, orientationSeen = false; const wrap = v => ((v + 180) % 360 + 360) % 360 - 180; const clamp = v => Math.max(-28, Math.min(28, v)); function calibrate() { origin = null; sensorX = sensorY = 0; m.tx = 0; m.ty = m.base; } function stopMotion(message = 'Drag to rotate · Tap to flip') { motionEnabled = false; clearTimeout(sensorTimer); removeEventListener('deviceorientation', onOrientation); removeEventListener('devicemotion', onMotion); motionButton.textContent = 'Enable motion'; motionButton.setAttribute('aria-pressed', 'false'); hint.textContent = message; } function onOrientation(e) { if (!motionEnabled || document.hidden || !Number.isFinite(e.beta) || !Number.isFinite(e.gamma)) return; orientationSeen = true; clearTimeout(sensorTimer); if (!origin) origin = { beta: e.beta, gamma: e.gamma }; const b = wrap(e.beta - origin.beta), g = wrap(e.gamma - origin.gamma); const a = (screen.orientation?.angle ?? window.orientation ?? 0) * Math.PI / 180; sensorX = clamp(-(b * Math.cos(a) + g * Math.sin(a)) * 0.85); sensorY = clamp((g * Math.cos(a) - b * Math.sin(a)) * 0.85); hint.textContent = 'Motion active · Tilt your phone · Drag anytime'; } function onMotion(e) { if (orientationSeen || !motionEnabled || document.hidden) return; const g = e.accelerationIncludingGravity; if (!g || ![g.x, g.y, g.z].every(Number.isFinite) || Math.hypot(g.x, g.y, g.z) < 1) return; // Gravity provides stable relative tilt when orientation events are unavailable. onOrientation({ beta: Math.atan2(-g.y, Math.hypot(g.x, g.z)) * 180 / Math.PI, gamma: Math.atan2(g.x, -g.z) * 180 / Math.PI }); orientationSeen = false; } motionButton.addEventListener('click', async () => { if (motionEnabled) { stopMotion(); return; } if (!isSecureContext) { hint.textContent = 'Open the HTTPS preview link to enable motion. Drag is available.'; return; } if (!globalThis.DeviceOrientationEvent && !globalThis.DeviceMotionEvent) { hint.textContent = 'Motion is unavailable on this device. Drag to rotate.'; return; } motionButton.disabled = true; try { // Start both requests synchronously within the tap, before awaiting either. const requests = [globalThis.DeviceOrientationEvent, globalThis.DeviceMotionEvent] .filter(Boolean).map(api => typeof api.requestPermission === 'function' ? api.requestPermission() : Promise.resolve('granted')); const permissions = await Promise.allSettled(requests); if (!permissions.some(result => result.status === 'fulfilled' && result.value === 'granted')) { hint.textContent = 'Motion permission was not granted. Allow Motion & Orientation in Safari settings, then reload. Drag still works.'; return; } orientationSeen = false; calibrate(); motionEnabled = true; motionButton.textContent = 'Disable motion'; motionButton.setAttribute('aria-pressed', 'true'); hint.textContent = 'Hold comfortably, then tilt your phone…'; addEventListener('deviceorientation', onOrientation); addEventListener('devicemotion', onMotion); sensorTimer = setTimeout(() => stopMotion('No sensor data. Open in Safari or Chrome directly, allow Motion & Orientation, then retry. Drag still works.'), 5000); } catch { stopMotion('Motion could not start. Check browser permissions, or drag.'); } finally { motionButton.disabled = false; } }); resetButton.addEventListener('click', calibrate); screen.orientation?.addEventListener('change', calibrate); addEventListener('orientationchange', calibrate); document.addEventListener('visibilitychange', () => { if (!document.hidden) calibrate(); }); const flip = () => { m.base += 180; m.tx = 0; m.ty = m.base; }; card.addEventListener('keydown', (e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); flip(); } if (e.key.startsWith('Arrow')) { e.preventDefault(); if (e.key === 'ArrowLeft') m.ty -= 8; if (e.key === 'ArrowRight') m.ty += 8; if (e.key === 'ArrowUp') m.tx = Math.min(45, m.tx + 8); if (e.key === 'ArrowDown') m.tx = Math.max(-45, m.tx - 8); } }); card.addEventListener('pointerdown', (e) => { if (m.pointer !== null || (e.pointerType === 'mouse' && e.button !== 0)) return; m.pointer = e.pointerId; m.startX = e.clientX; m.startY = e.clientY; m.down = true; m.px = e.clientX; m.py = e.clientY; m.moved = false; card.setPointerCapture(e.pointerId); }); card.addEventListener('pointermove', (e) => { if (m.down && m.pointer === e.pointerId) { const dx = e.clientX - m.px, dy = e.clientY - m.py; if (Math.hypot(e.clientX - m.startX, e.clientY - m.startY) > 5) m.moved = true; m.ty += dx * 0.62; m.tx = Math.max(-50, Math.min(50, m.tx - dy * 0.3)); m.px = e.clientX; m.py = e.clientY; } else if (!m.down && !motionEnabled && e.pointerType === 'mouse') { m.tx = (-(e.clientY - innerHeight / 2) / innerHeight) * 30; m.ty = m.base + ((e.clientX - innerWidth / 2) / innerWidth) * 40; } }); card.addEventListener('pointerup', (e) => { if (m.pointer !== e.pointerId) return; m.pointer = null; m.down = false; if (card.hasPointerCapture(e.pointerId)) card.releasePointerCapture(e.pointerId); if (!m.moved) flip(); else m.base = Math.round(m.ty / 180) * 180; }); const cancelDrag = () => { m.pointer = null; m.down = false; m.base = Math.round(m.ty / 180) * 180; }; card.addEventListener('pointercancel', cancelDrag); card.addEventListener('lostpointercapture', () => { if (m.down) cancelDrag(); }); card.addEventListener('pointerleave', () => { if (!m.down && !motionEnabled) { m.tx = 0; m.ty = m.base; } }); let lastX = 999, lastY = 999; function frame() { if (motionEnabled && !m.down) { m.tx = sensorX; m.ty = m.base + sensorY; } const ease = motionEnabled ? 0.115 : reduced ? 1 : 0.115; m.x += (m.tx - m.x) * ease; m.y += (m.ty - m.y) * ease; card.style.transform = `rotateX(${m.x}deg) rotateY(${m.y}deg)`; const visible = Math.cos((m.y * Math.PI) / 180) * Math.cos((m.x * Math.PI) / 180) > 0.001; front.style.visibility = visible ? 'visible' : 'hidden'; back.style.visibility = visible ? 'hidden' : 'visible'; if ( !document.hidden && visible && (dirty || Math.abs(m.x - lastX) > 0.015 || Math.abs(m.y - lastY) > 0.015) ) { renderer.draw(m.x, m.y, 1, depth, contourBrightness); dirty = false; lastX = m.x; lastY = m.y; } raf = requestAnimationFrame(frame); } raf = requestAnimationFrame(frame); addEventListener( 'pagehide', () => { cancelAnimationFrame(raf); stopMotion(); renderer.dispose(); }, { once: true }, ); } catch { status.hidden = false; status.textContent = 'Unable to load the card. Refresh the preview link or open the downloaded HTML file.'; }skills/holo-card/.gitignore19 B7a60b85e148fupstream ↗
__pycache__/ *.pycskills/holo-card/agents/openai.yaml322 Bc3545dceac76upstream ↗
interface: display_name: "Holo Card" short_description: "Create layered holographic cards with native image tools and local assembly" default_prompt: "Use $holo-card to turn my supplied image into an interactive holographic card. Repair occluded artwork, preserve typography, and verify transparency and alignment."skills/holo-card/tests/test_matte_regions.py1.3 KBe50d43ecf2bfupstream ↗
import importlib.util from pathlib import Path import unittest from PIL import Image spec=importlib.util.spec_from_file_location('matte',Path(__file__).resolve().parents[1]/'scripts/matte_regions.py') m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) class MatteTests(unittest.TestCase): def test_unseeded_gray_clothing_and_detached_artwork_survive(self): c=Image.new('L',(9,9),255) # Dark silhouette encloses a gray interior that also matches the candidate color. for x in range(2,7):c.putpixel((x,2),0);c.putpixel((x,6),0) for y in range(2,7):c.putpixel((2,y),0);c.putpixel((6,y),0) c.putpixel((8,8),0) a=m.selection(c,[(0,0)]) self.assertEqual(a.getpixel((0,0)),0);self.assertEqual(a.getpixel((4,4)),255);self.assertEqual(a.getpixel((8,8)),255) b=m.selection(c,[(0,0),(4,4)]);self.assertEqual(b.getpixel((4,4)),0) def test_protection_stops_leak_and_preserves_existing_alpha(self): c=Image.new('L',(5,5),255);protect=Image.new('L',c.size,0) for y in range(5):protect.putpixel((2,y),255) original=Image.new('L',c.size,255);original.putpixel((4,4),87) out=m.selection(c,[(0,0)],original,protect) self.assertEqual(out.getpixel((1,1)),0);self.assertEqual(out.getpixel((3,1)),255);self.assertEqual(out.getpixel((4,4)),87) with self.assertRaises(ValueError):m.selection(c,[(2,0)],original,protect) if __name__=='__main__':unittest.main()skills/holo-card/tests/test_motion.mjs3.4 KBaec0e4a309aaupstream ↗
import {readFileSync} from 'node:fs'; import vm from 'node:vm'; import assert from 'node:assert/strict'; const source=readFileSync(new URL('../assets/renderer/viewer.js',import.meta.url),'utf8'); async function boot({permission='granted',secure=true,supported=true}={}) { const nodes=new Map(), events=new Map(); let frame, timer; function node(key) { if(!nodes.has(key)) nodes.set(key,{hidden:false,style:{setProperty(){}},value:'0',listeners:{},addEventListener(k,f){this.listeners[k]=f},setAttribute(k,v){this[k]=v},querySelector(k){return node(key+k)},setPointerCapture(){},hasPointerCapture(){return false}}); return nodes.get(key); } const context={console,URL,location:{search:''},document:{hidden:false,querySelector:node,querySelectorAll:()=>[],addEventListener:(k,f)=>events.set(k,f)},screen:{orientation:{angle:0,addEventListener(){}}},matchMedia:()=>({matches:false}),innerWidth:400,innerHeight:800,isSecureContext:secure,requestAnimationFrame:f=>(frame=f,1),cancelAnimationFrame(){},setTimeout:f=>(timer=f,1),clearTimeout(){},addEventListener:(k,f)=>events.set(k,f),removeEventListener:k=>events.delete(k),HOLO_MANIFEST:{name:'Test',height:829,width:569,assets:{}},HOLO_CREATE_RENDERER:async()=>({draw(){},dispose(){}})}; if(supported) context.DeviceOrientationEvent={requestPermission:async()=>permission}; context.window=context;vm.createContext(context);await vm.runInContext(`(async()=>{${source}\n})()`,context); return {node,events,context,tick:()=>frame(),timeout:()=>timer(),enable:()=>node('#motion').listeners.click(),orient:(beta,gamma)=>events.get('deviceorientation')?.({beta,gamma})}; } let a=await boot();await a.enable();assert.equal(a.node('#motion')['aria-pressed'],'true');a.orient(40,0);a.orient(50,10);a.tick();const before=a.node('.card').style.transform;assert.match(before,/rotateX/); const card=a.node('.card');card.listeners.pointerdown({pointerId:1,pointerType:'touch',clientX:0,clientY:0});card.listeners.pointermove({pointerId:1,pointerType:'touch',clientX:40,clientY:20});a.tick();assert.notEqual(card.style.transform,before);card.listeners.pointerup({pointerId:1});a.tick(); a.node('#reset').listeners.click();a.orient(50,10);a.context.screen.orientation.angle=90;a.orient(60,20);a.tick();assert.ok(!card.style.transform.includes('NaN')); await a.enable();assert.equal(a.events.has('deviceorientation'),false); a=await boot({permission:'denied'});await a.enable();assert.match(a.node('#motion-hint').textContent,/not granted/);assert.equal(a.events.has('deviceorientation'),false); a=await boot({secure:false});await a.enable();assert.match(a.node('#motion-hint').textContent,/HTTPS/); a=await boot({supported:false});await a.enable();assert.match(a.node('#motion-hint').textContent,/unavailable/); a=await boot();await a.enable();a.orient(null,null);a.timeout();assert.equal(a.events.has('deviceorientation'),false);assert.match(a.node('#motion-hint').textContent,/No sensor data/); console.log('Motion: permission, calibration, drag takeover, landscape, disable, denied, insecure, unsupported and no-data paths passed.'); a=await boot();a.context.DeviceMotionEvent={requestPermission:async()=> 'granted'};await a.enable();a.events.get('devicemotion')({accelerationIncludingGravity:{x:0,y:-5,z:-8}});a.events.get('devicemotion')({accelerationIncludingGravity:{x:3,y:-6,z:-7}});a.tick();assert.match(a.node('#motion-hint').textContent,/Motion active/);assert.ok(!a.node('.card').style.transform.includes('NaN'));console.log('Gravity fallback passed.');skills/holo-card/tests/test_native.py6.9 KB5363302e3250upstream ↗
import importlib.util import json from pathlib import Path import socket import tempfile import unittest from unittest.mock import patch import zipfile from PIL import Image spec=importlib.util.spec_from_file_location('native',Path(__file__).resolve().parents[1]/'scripts/native.py') native=importlib.util.module_from_spec(spec);spec.loader.exec_module(native) class NativeTests(unittest.TestCase): def test_native_build_without_api_or_network(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);source=root/'source.png';Image.new('RGBA',(70,98),(20,130,210,255)).save(source) mask=root/'mask.png';Image.new('L',(70,98),255).save(mask);job=root/'task';colored=root/'colored.png';im=Image.new('RGBA',(70,98),(200,40,10,128));im.putpixel((0,0),(0,0,0,0));im.save(colored) with patch.object(socket,'create_connection',side_effect=AssertionError('Network forbidden')): result=native.prepare(source,job,'Safe </script> card');self.assertEqual(result['execution'],'codex_builtin_image_gen') self.assertEqual(result['completed_layers'],0) with self.assertRaises(ValueError):native.assemble(job) for kind in native.KINDS:native.add(job,kind,mask if kind=='structure' else source if kind=='background' else colored,'test-local-fixture') result=native.assemble(job);self.assertEqual(result['status'],'completed') self.assertEqual(Image.open(job/'assets/character.png').getpixel((1,1)),(200,40,10,128)) html=(job/'index.html').read_text();self.assertIn('globalThis.HOLO_MANIFEST',html);self.assertIn('Safe \</script> card',html);self.assertNotIn('src="viewer.js',html) with zipfile.ZipFile(job/'card.zip') as archive:self.assertIsNone(archive.testzip());self.assertIn('provenance.json',archive.namelist()) def test_background_plate_must_be_complete(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);source=root/'source.png';Image.new('RGBA',(70,98),(20,130,210,255)).save(source) hole=root/'hole.png';im=Image.open(source);im.putpixel((30,40),(0,0,0,0));im.save(hole) job=root/'task';native.prepare(source,job,None) with self.assertRaisesRegex(ValueError,'fully opaque'):native.add(job,'background',hole,None) self.assertEqual(native.load(job)['layers']['background']['error'],'BACKGROUND_HAS_HOLES') native.add(job,'background',source,None) self.assertEqual(native.load(job)['layers']['background']['status'],'imported') def test_independent_alpha_preserves_dark_and_light_rgb(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);color=root/'color.png';im=Image.new('RGB',(70,98),'white');im.putpixel((20,20),(0,0,0));im.save(color) mask=root/'mask.png';m=Image.new('L',im.size,255);m.putpixel((0,0),0);m.putpixel((1,0),128);m.save(mask) job=root/'job';native.prepare(color,job,None) native.apply_alpha(job,'character',color,mask,'local test selection') state=native.load(job);out=Image.open(job/state['layers']['character']['raw']) self.assertEqual(out.getpixel((20,20)),(0,0,0,255));self.assertEqual(out.getpixel((1,0)),(255,255,255,128));self.assertEqual(out.getpixel((0,0)),(255,255,255,0)) self.assertEqual(state['layers']['character']['alpha_method'],'independent_selection') bad=root/'bad.png';Image.new('L',(10,10),255).save(bad) with self.assertRaisesRegex(ValueError,'identical dimensions'):native.apply_alpha(job,'ui',color,bad,'test') def test_opaque_layer_stages_mask_work_and_can_resume(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);color=root/'color.png';im=Image.new('RGB',(70,98),(180,180,180));im.putpixel((30,40),(255,255,255));im.putpixel((31,40),(0,0,0));im.save(color) job=root/'job';native.prepare(color,job,None) result=native.add(job,'character',color,'actual image output') self.assertEqual(result['status'],'needs_alpha_mask');self.assertEqual(result['completed_layers'],0) state=native.load(job);self.assertIsNone(state['layers']['character']['error']) self.assertTrue(Path(result['repair_input']).is_file()) with self.assertRaises(ValueError):native.assemble(job) mask=root/'selection.png';m=Image.new('L',(70,98),0);m.putpixel((30,40),255);m.putpixel((31,40),255);m.save(mask) native.apply_alpha(job,'character',color,mask,'local spatial selection') state=native.load(job);self.assertEqual(state['layers']['character']['status'],'imported') out=Image.open(job/state['layers']['character']['raw']) self.assertEqual(out.getpixel((0,0))[3],0);self.assertEqual(out.getpixel((30,40)),(255,255,255,255));self.assertEqual(out.getpixel((31,40)),(0,0,0,255)) def test_mismatched_mask_preserved_for_review(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);source=root/'source.png';Image.new('RGB',(70,98)).save(source);mask=root/'mask.png';Image.new('L',(100,100),255).save(mask) native.prepare(source,root/'task',None) with self.assertRaisesRegex(ValueError,'aspect ratio'):native.add(root/'task','structure',mask,None) state=native.load(root/'task');self.assertEqual(state['status'],'needs_review');self.assertTrue((root/'task'/state['layers']['structure']['raw']).is_file()) def test_resume_refreshes_prompts_without_changing_generation_evidence(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);source=root/'source.png';Image.new('RGB',(70,98),'purple').save(source) job=root/'job';native.prepare(source,job,None);native.add(job,'background',source,'real-generation-reference') before=native.load(job)['layers'];raw=(job/'raw/background.png').read_bytes() (job/'prompts.json').write_text('{"background":"stale instructions"}') state=native.load(job) self.assertEqual(json.loads((job/'prompts.json').read_text()),native.current_prompts()) self.assertEqual(state['layers'],before);self.assertEqual((job/'raw/background.png').read_bytes(),raw) native.add(job,'background',job/'raw/background.png','reviewed same file',replace=True) def test_legacy_native_job_cannot_silently_assemble(self): with tempfile.TemporaryDirectory() as folder: job=Path(folder);(job/'task.json').write_text(json.dumps({'version':1,'layers':{}})) with self.assertRaisesRegex(ValueError,'Obsolete native mask job'):native.assemble(job) def test_structure_uses_repaired_character_alpha(self): with tempfile.TemporaryDirectory() as folder: root=Path(folder);source=root/'source.png';Image.new('RGB',(70,98),'purple').save(source) character=root/'character.png';im=Image.new('RGBA',(70,98),'white');im.putpixel((10,10),(255,255,255,0));im.save(character) structure=root/'structure.png';Image.new('L',(70,98),255).save(structure) job=root/'job';native.prepare(source,job,None) for kind in native.KINDS:native.add(job,kind,structure if kind=='structure' else source if kind=='background' else character,'fixture') native.assemble(job);alpha=Image.open(job/'assets/structure.png').getchannel('A') self.assertEqual(alpha.getpixel((10,10)),0);self.assertEqual(alpha.getpixel((11,10)),255) if __name__=='__main__':unittest.main()README.mdupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/lersent001-holo-card-skills-holo-card.md
