openclawv1.0.0

Ultimate AI Media Generator

ZeroLu@ZeroLu⭐ 107 stars· last commit 2mo ago· 0 open issues

Generate and monitor CyberBara Public API v1 image, video, audio, and music tasks end-to-end. Use when work involves CyberBara `/api/v1` endpoints for listing models, uploading reference media, quoting credits, creating generation tasks, polling task status, checking credits balance and usage, or saving final media outputs.

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.

7.7/10
Verified
Mar 9, 2026

// RATINGS

⭐GitHub Stars
⭐ 10 on GitHubGitHub ↗

Growing

🟢ProSkills ScoreAI Verified
7.7/10
📍

Not yet listed on ClawHub or SkillsMP

// README

Ultimate-AI-Media-Generator-Skill

GitHub Repo stars AtomGitStars GitHub Forks MIT License

Ultimate AI Media Generator Skill Cover

An open-source ai image generator skill, ai video generator skill, and ai audio generator skill for AI agents. Empower your agent to generate images, videos, sound effects, and music on their own. Top models like Nano Banana 2, Nano Banana 2 Lite, Sora 2, Seedance, Kling, HappyHorse, and Suno are supported.

Quick Start | Key Features | Supported Platforms | Platform Prompts | Use Cases | Chinese README


Key Features

  • 🚀 Cost-efficient generation: in many scenarios, CyberBara pricing is lower than official model APIs.
  • 💳 Credit visibility before submission: quote credits first, then decide whether to continue.
  • 🧠 Curated prompt library: production-ready prompts selected and refined by artists and prompt engineers.
  • 🛠️ Built-in workflow templates: starter workflows for ai ppt skill, ai seo article skill, and AI comic drama production.
  • 🔓 Fully open source: fork, customize, and iterate for your own team or product.
  • 🌍 Multi-agent compatibility: supports mainstream skill-enabled AI coding platforms.

Supported Platforms

This skill supports all platforms that support skills, including but not limited to:

  • OpenClaw
  • Claude Code
  • Codex
  • Claude Cowork
  • Cursor
  • Antigravity
  • Other compatible skill-enabled agent platforms

Quick Start

Vibe Install

Just send the following command to your AI(OpenClaw, Claude Code, Codex etc)

Help me install this skill, use command `npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all`

Manual Install

Step 1) Install (npx skills)

# List what can be installed from this repo
npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --list

# Install all skills from this repo
npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all

# Optional: install for specific agents (if your skills runtime supports agent targeting)
npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all -a codex -a claude-code

Step 2) Get and configure API key

Get your free API key here: https://cyberbara.com/settings/apikeys

Configure it once (recommended):

python3 scripts/cyberbara_api.py setup-api-key "<your_api_key>"

This stores your key at ~/.config/cyberbara/api_key, so you do not need to export it every session.

Step 3) Use the skill on Codex, Claude Code, OpenClaw, Claude Cowork, Cursor, and Antigravity

You can paste these prompts directly in your agent chat, or just tell your agent to generate images, videos, audio, or music.

A) Create an image (nano banana skill)

Use $ultimate-ai-media-generator-skill to generate one image:
- model: nano-banana-pro
- scene: text-to-image
- prompt: A cute kitten dancing, 3D cartoon style, dynamic full body, clean stage background
- options: aspect_ratio=16:9, resolution=1k
Return task id, final status, and output image URL.

B) Create a video (seedance 2.0 skill / sora 2 skill)

Use $ultimate-ai-media-generator-skill to generate one video:
- model: seedance-2-ark
- scene: text-to-video
- prompt: Cinematic wide shot of a futuristic city at sunrise, smooth drone motion
- options: duration=10, resolution=720p
If seedance-2-ark is unavailable, fallback to sora-2.
Return task id and final video URL.

C) Check credits before generation

Use $ultimate-ai-media-generator-skill to quote credits before submission for this request:
- model: nano-banana-pro
- media_type: image
- scene: text-to-image
- prompt: Minimalist product poster for a smart watch
- options: aspect_ratio=1:1, resolution=1k
Return estimated_credits and can_afford.

D) Create a sound effect

Use $ultimate-ai-media-generator-skill to generate one sound effect:
- model: suno-sound-v5-5
- scene: text-to-audio
- prompt: A short cinematic whoosh with soft digital sparkle
- options: loop=false
Return task id, final status, and output audio URL.

E) Create music

Use $ultimate-ai-media-generator-skill to generate one music track:
- model: suno-music-v5
- scene: text-to-music
- prompt: Warm lo-fi study music with mellow keys
- options: instrumental=true
Return task id, final status, and output audio URL.

F) Check balance and recent usage

Use $ultimate-ai-media-generator-skill to check current credit balance and the latest 20 usage records.

Typical Use Cases

  • ai image generator skill for social posts, ad creatives, product hero images.
  • ai video generator skill for short promo clips and storyboard previsualization.
  • ai audio generator skill for sound effects and production-ready music tracks.
  • ai ppt skill workflow to generate slide visuals and style-consistent image sets.
  • ai seo article skill workflow to generate article covers, inline visuals, and metadata image sets.
  • open claw image generator skill setup for teams using OpenClaw + CyberBara in the same workflow.

Workflow templates:

Curated prompts:


Model Coverage

CyberBara supported image, video, audio, and music models:

Media TypeModelSupported Scenes
Audiosuno-sound-v5text-to-audio
Audiosuno-sound-v5-5text-to-audio
Imagenano-banana-2text-to-image, image-to-image
Imagenano-banana-2-litetext-to-image, image-to-image
Imagenano-banana-protext-to-image, image-to-image
Imagegpt-image-2text-to-image, image-to-image
Imagemidjourney-v7text-to-image, image-to-image
Imageseedream-5-pro-layer-decompositionimage-to-image
Musicsuno-music-v3-5text-to-music
Musicsuno-music-v4text-to-music
Musicsuno-music-v4-5text-to-music
Musicsuno-music-v4-5-plustext-to-music
Musicsuno-music-v5text-to-music
Musicsuno-music-v5-5text-to-music

// HOW IT'S BUILT

TECHNOLOGY STACK

Python

This skill is built with Python..

// FILES

27 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md8.7 KB24ff1c33809dupstream ↗
    ---
    name: ultimate-ai-media-generator-skill
    description: Generate and monitor CyberBara Public API v1 image, video, audio, and music tasks end-to-end. Use when work involves CyberBara `/api/v1` endpoints for listing models, uploading reference media, quoting credits, creating generation tasks, polling task status, checking credits balance and usage, or saving final media outputs.
    ---
    
    # Ultimate-AI-Media-Generator-Skill
    
    ## Overview
    
    Use this skill to call CyberBara APIs reliably, create image, video, audio, and music generation tasks, and return final media URLs with credit-aware flow.
    
    For Chinese article or repo-promo title images, default to model `nano-banana-2-lite` unless the user requests a different image model. Prefer generating a text-free cover background first, then add the final Chinese headline locally so the published title is exact and readable.
    
    ## Implementation Architecture
    
    The runtime uses a layered Python architecture:
    
    - `scripts/cyberbara_api.py`: thin entrypoint only
    - `src/cyberbara_cli/cli.py`: command parsing and command routing
    - `src/cyberbara_cli/usecases/`: flow orchestration (generation + polling)
    - `src/cyberbara_cli/policies/`: safety and policy rules (credits quote + formal confirmation)
    - `src/cyberbara_cli/gateways/`: raw CyberBara API client
    - `src/cyberbara_cli/config.py`: API key discovery and local persistence
    - `src/cyberbara_cli/constants.py`: fixed base URL and shared constants
    
    When extending behavior, keep business rules in `usecases/` or `policies/`, not in `scripts/`.
    
    ## Set Up Runtime Inputs
    
    The script uses fixed base URL:
    
    ```text
    https://cyberbara.com
    ```
    
    API key lookup order:
    
    1. `--api-key`
    2. environment variable `CYBERBARA_API_KEY`
    3. local cache file `~/.config/cyberbara/api_key`
    4. interactive prompt (if running in terminal)
    
    Recommended one-time setup command:
    
    ```bash
    python3 scripts/cyberbara_api.py setup-api-key "<api-key>"
    ```
    
    Or save from environment variable:
    
    ```bash
    export CYBERBARA_API_KEY="<api-key>"
    python3 scripts/cyberbara_api.py setup-api-key --from-env
    ```
    
    If API key is missing, the script immediately asks for it and shows where to get one:
    
    ```text
    https://cyberbara.com/settings/apikeys
    ```
    
    When you provide API key via `--api-key` or interactive prompt, it is saved to:
    
    ```text
    ~/.config/cyberbara/api_key
    ```
    
    Future runs reuse this cached key, so users do not need to provide it every time.
    
    ## Run The Standard Generation Flow
    
    1. Discover available models.
    2. Upload reference images or videos when task scene needs local media inputs.
    3. Quote credits before creating a generation task.
    4. Create image or video generation task and wait for final output.
    5. Automatically save generated media locally and open it.
    6. Check usage records when needed.
    
    Reference commands:
    
    ```bash
    # 1) List video models
    python3 scripts/cyberbara_api.py models --media-type video
    
    # Also available: image, audio, and music models
    python3 scripts/cyberbara_api.py models --media-type audio
    python3 scripts/cyberbara_api.py models --media-type music
    
    # 2) Upload local reference images
    python3 scripts/cyberbara_api.py upload-images ./frame.png ./style.jpg
    
    # Upload local reference videos
    python3 scripts/cyberbara_api.py upload-videos ./clip.mp4
    
    # 3) Estimate credits
    python3 scripts/cyberbara_api.py quote --json '{
      "model":"sora-2",
      "media_type":"video",
      "scene":"text-to-video",
      "options":{"duration":"10"}
    }'
    
    # 4) Create a video task (default behavior: wait for success, save outputs to ./media_outputs, auto-open)
    python3 scripts/cyberbara_api.py generate-video --json '{
      "model":"sora-2",
      "prompt":"A calm drone shot over snowy mountains at sunrise",
      "scene":"text-to-video",
      "options":{"duration":"10","resolution":"standard"}
    }'
    
    # 5) Existing task: wait + save/open outputs
    python3 scripts/cyberbara_api.py wait --task-id <TASK_ID> --interval 5 --timeout 900
    ```
    
    Image and video generation are confirmation-gated by default:
    
    ```bash
    # Single image request: script auto-quotes, then asks you to type CONFIRM
    python3 scripts/cyberbara_api.py generate-image --json '{
      "model":"nano-banana-pro",
      "prompt":"A cinematic portrait under neon rain",
      "scene":"text-to-image",
      "options":{"resolution":"1k"}
    }'
    
    # Batch image requests (JSON array): script auto-quotes each request and prints total estimated credits
    python3 scripts/cyberbara_api.py generate-image --file ./image-requests.json
    ```
    
    `image-requests.json` format:
    
    ```json
    [
      {
        "model": "nano-banana-pro",
        "prompt": "A cinematic portrait under neon rain",
        "scene": "text-to-image",
        "options": { "resolution": "1k" }
      },
      {
        "model": "nano-banana-pro",
        "prompt": "A product still life with dramatic side light",
        "scene": "text-to-image",
        "options": { "resolution": "1k" }
      }
    ]
    ```
    
    Only use `--yes` after explicit user approval has been obtained:
    
    ```bash
    python3 scripts/cyberbara_api.py generate-image --file ./image-requests.json --yes
    python3 scripts/cyberbara_api.py generate-video --json '{
      "model":"sora-2",
      "prompt":"A calm drone shot over snowy mountains at sunrise",
      "scene":"text-to-video",
      "options":{"duration":"10","resolution":"standard"}
    }' --yes
    
    python3 scripts/cyberbara_api.py generate-audio --json '{
      "model":"suno-sound-v5-5",
      "prompt":"A short cinematic whoosh with soft digital sparkle",
      "scene":"text-to-audio",
      "options":{"loop":false}
    }' --yes
    
    python3 scripts/cyberbara_api.py generate-music --json '{
      "model":"suno-music-v5",
      "prompt":"Warm lo-fi study music with mellow keys",
      "scene":"text-to-music",
      "options":{"instrumental":true}
    }' --yes
    ```
    
    Control auto-save and open behavior:
    
    ```bash
    # keep waiting but do not auto-open media
    python3 scripts/cyberbara_api.py generate-image --file ./image-requests.json --yes --no-open
    
    # custom output directory
    python3 scripts/cyberbara_api.py generate-video --json '{...}' --yes --output-dir ./downloads
    
    # submit only (no wait/save/open)
    python3 scripts/cyberbara_api.py generate-video --json '{...}' --yes --async
    ```
    
    ## Use Script Capabilities
    
    `scripts/cyberbara_api.py` supports:
    
    - `setup-api-key` to persist API key into local cache
    - `models` to list public models (`--media-type image|video|audio|music` optional)
    - `upload-images` to upload local image files to `/api/v1/uploads/images`
    - `upload-videos` to upload local video files to `/api/v1/uploads/videos`
    - `quote` to estimate credit cost from JSON request body
    - `generate-image` to auto-quote credits, compute total for batch requests, require formal confirmation, create task(s), wait, then save/open outputs
    - `generate-video` to auto-quote credits, compute total for batch requests, require formal confirmation, create task(s), wait, then save/open outputs
    - `generate-audio` to auto-quote credits, compute total for batch requests, require formal confirmation, create task(s), wait, then save/open outputs
    - `generate-music` to auto-quote credits, compute total for batch requests, require formal confirmation, create task(s), wait, then save/open outputs
    - `task` to fetch task snapshot by task ID
    - `wait` to poll task until `success`, `failed`, or `canceled`, then save/open outputs
    - `balance` and `usage` to inspect credits
    - `raw` for direct custom endpoint calls
    
    Use `--file request.json` instead of `--json` for long payloads.
    
    ## Enforce API Payload Rules
    
    - Send auth via API key (`Authorization: Bearer <key>` or `x-api-key`).
    - Send public request fields under `options.*` only.
    - Prefer explicit `scene` to avoid inference ambiguity.
    - Include `options.image_input` for `image-to-image` and `image-to-video`.
    - Include `options.video_input` for `video-to-video`.
    - Poll `/api/v1/tasks/{taskId}` until final status; only `success` guarantees output URLs.
    - Before every image, video, audio, or music generation submission, obtain quote first and get explicit user confirmation.
    - For multiple image/video/audio/music requests, calculate and present total estimated credits before submission.
    - Save output files under `media_outputs/` by default and auto-open them unless disabled.
    
    ## Navigate Detailed Model Options
    
    Use the reference file for full model matrices and examples:
    
    - `references/cyberbara-api-reference.mdx`
    
    For fast lookup in large reference:
    
    ```bash
    rg '^## |^### ' references/cyberbara-api-reference.mdx
    rg 'kling-2.6|sora-2|veo-3.1|seedance' references/cyberbara-api-reference.mdx
    ```
    
    ## Handle Common Failures
    
    - `invalid_api_key` or `api_key_required`: verify key and headers.
    - `insufficient_credits`: quote first or recharge credits.
    - `invalid_scene` or `scene_not_supported`: choose scene supported by model.
    - `invalid_request`: verify `prompt` and `options` requirements by model.
    - `UPLOAD_INVALID`: inspect and report the complete `error.message` and `error.details`; these provider upload-validation errors occur before a task ID is created.
    - `task_not_found`: verify task ID and environment domain.
    
  • README.md12 KBf74bcef90b38upstream ↗
    # Ultimate-AI-Media-Generator-Skill
    
    [![GitHub Repo stars](https://img.shields.io/github/stars/ZeroLu/Ultimate-AI-Media-Generator-Skill?style=for-the-badge)](https://github.com/ZeroLu/Ultimate-AI-Media-Generator-Skill/stargazers)
    [![AtomGitStars](https://atomgit.com/ZeroLuAtom/Ultimate-AI-Media-Generator-Skill/star/badge.svg)](https://atomgit.com/ZeroLuAtom/Ultimate-AI-Media-Generator-Skill)
    [![GitHub Forks](https://img.shields.io/github/forks/ZeroLu/Ultimate-AI-Media-Generator-Skill?style=for-the-badge)](https://github.com/ZeroLu/Ultimate-AI-Media-Generator-Skill/network/members)
    [![MIT License](https://img.shields.io/github/license/ZeroLu/Ultimate-AI-Media-Generator-Skill?style=for-the-badge)](./LICENSE)
    
    ![Ultimate AI Media Generator Skill Cover](./assets/readme-cover-2k-16x9.jpg)
    
    An open-source **ai image generator skill**, **ai video generator skill**, and **ai audio generator skill** for AI agents. Empower your agent to generate images, videos, sound effects, and music on their own. Top models like Nano Banana 2, Nano Banana 2 Lite, Sora 2, Seedance, Kling, HappyHorse, and Suno are supported.
    
    [Quick Start](#quick-start) | [Key Features](#key-features) | [Supported Platforms](#supported-platforms) | [Platform Prompts](#step-3-use-the-skill-on-codex-claude-code-openclaw-claude-cowork-cursor-and-antigravity) | [Use Cases](#typical-use-cases) | [Chinese README](./README-zh.md)
    
    ---
    
    ## Key Features
    
    - 🚀 **Cost-efficient generation**: in many scenarios, CyberBara pricing is lower than official model APIs.
    - 💳 **Credit visibility before submission**: quote credits first, then decide whether to continue.
    - 🧠 **Curated prompt library**: production-ready prompts selected and refined by artists and prompt engineers.
    - 🛠️ **Built-in workflow templates**: starter workflows for **ai ppt skill**, **ai seo article skill**, and AI comic drama production.
    - 🔓 **Fully open source**: fork, customize, and iterate for your own team or product.
    - 🌍 **Multi-agent compatibility**: supports mainstream skill-enabled AI coding platforms.
    
    ---
    
    ## Supported Platforms
    
    This skill supports all platforms that support skills, including but not limited to:
    
    - OpenClaw
    - Claude Code
    - Codex
    - Claude Cowork
    - Cursor
    - Antigravity
    - Other compatible skill-enabled agent platforms
    
    ---
    
    ## Quick Start
    
    ### Vibe Install
    
    Just send the following command to your AI(OpenClaw, Claude Code, Codex etc)
    
    ```text
    Help me install this skill, use command `npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all`
    ```
    
    ### Manual Install
    
    ### Step 1) Install (npx skills)
    
    ```bash
    # List what can be installed from this repo
    npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --list
    
    # Install all skills from this repo
    npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all
    
    # Optional: install for specific agents (if your skills runtime supports agent targeting)
    npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all -a codex -a claude-code
    ```
    
    ### Step 2) Get and configure API key
    
    Get your free API key here: https://cyberbara.com/settings/apikeys
    
    Configure it once (recommended):
    
    ```bash
    python3 scripts/cyberbara_api.py setup-api-key "<your_api_key>"
    ```
    
    This stores your key at `~/.config/cyberbara/api_key`, so you do not need to export it every session.
    
    ### Step 3) Use the skill on Codex, Claude Code, OpenClaw, Claude Cowork, Cursor, and Antigravity
    
    You can paste these prompts directly in your agent chat, or just tell your agent to generate images, videos, audio, or music.
    
    #### A) Create an image (nano banana skill)
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one image:
    - model: nano-banana-pro
    - scene: text-to-image
    - prompt: A cute kitten dancing, 3D cartoon style, dynamic full body, clean stage background
    - options: aspect_ratio=16:9, resolution=1k
    Return task id, final status, and output image URL.
    ```
    
    #### B) Create a video (seedance 2.0 skill / sora 2 skill)
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one video:
    - model: seedance-2-ark
    - scene: text-to-video
    - prompt: Cinematic wide shot of a futuristic city at sunrise, smooth drone motion
    - options: duration=10, resolution=720p
    If seedance-2-ark is unavailable, fallback to sora-2.
    Return task id and final video URL.
    ```
    
    #### C) Check credits before generation
    
    ```text
    Use $ultimate-ai-media-generator-skill to quote credits before submission for this request:
    - model: nano-banana-pro
    - media_type: image
    - scene: text-to-image
    - prompt: Minimalist product poster for a smart watch
    - options: aspect_ratio=1:1, resolution=1k
    Return estimated_credits and can_afford.
    ```
    
    #### D) Create a sound effect
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one sound effect:
    - model: suno-sound-v5-5
    - scene: text-to-audio
    - prompt: A short cinematic whoosh with soft digital sparkle
    - options: loop=false
    Return task id, final status, and output audio URL.
    ```
    
    #### E) Create music
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one music track:
    - model: suno-music-v5
    - scene: text-to-music
    - prompt: Warm lo-fi study music with mellow keys
    - options: instrumental=true
    Return task id, final status, and output audio URL.
    ```
    
    #### F) Check balance and recent usage
    
    ```text
    Use $ultimate-ai-media-generator-skill to check current credit balance and the latest 20 usage records.
    ```
    
    ---
    
    ## Typical Use Cases
    
    - **ai image generator skill** for social posts, ad creatives, product hero images.
    - **ai video generator skill** for short promo clips and storyboard previsualization.
    - **ai audio generator skill** for sound effects and production-ready music tracks.
    - **ai ppt skill** workflow to generate slide visuals and style-consistent image sets.
    - **ai seo article skill** workflow to generate article covers, inline visuals, and metadata image sets.
    - **open claw image generator skill** setup for teams using OpenClaw + CyberBara in the same workflow.
    
    Workflow templates:
    
    - [AI PPT Workflow](./workflows/ai-ppt-skill.md)
    - [AI SEO Article Workflow](./workflows/ai-seo-article-skill.md)
    - [AI Comic Drama Workflow](./workflows/ai-comic-drama-skill.md)
    
    Curated prompts:
    
    - [Curated Prompt Library](./workflows/curated-prompts.md)
    
    ---
    
    ## Model Coverage
    
    CyberBara supported image, video, audio, and music models:
    
    | Media Type | Model                                | Supported Scenes                                    |
    | ---------- | ------------------------------------ | --------------------------------------------------- |
    | Audio      | `suno-sound-v5`                      | `text-to-audio`                                     |
    | Audio      | `suno-sound-v5-5`                    | `text-to-audio`                                     |
    | Image      | `nano-banana-2`                      | `text-to-image`, `image-to-image`                   |
    | Image      | `nano-banana-2-lite`                 | `text-to-image`, `image-to-image`                   |
    | Image      | `nano-banana-pro`                    | `text-to-image`, `image-to-image`                   |
    | Image      | `gpt-image-2`                        | `text-to-image`, `image-to-image`                   |
    | Image      | `midjourney-v7`                      | `text-to-image`, `image-to-image`                   |
    | Image      | `seedream-5-pro-layer-decomposition` | `image-to-image`                                    |
    | Music      | `suno-music-v3-5`                    | `text-to-music`                                     |
    | Music      | `suno-music-v4`                      | `text-to-music`                                     |
    | Music      | `suno-music-v4-5`                    | `text-to-music`                                     |
    | Music      | `suno-music-v4-5-plus`               | `text-to-music`                                     |
    | Music      | `suno-music-v5`                      | `text-to-music`                                     |
    | Music      | `suno-music-v5-5`                    | `text-to-music`                                     |
    | Video      | `happyhorse-1.0`                     | `text-to-video`                                     |
    | Video      | `happyhorse-1.0-first-frame`         | `image-to-video`                                    |
    | Video      | `happyhorse-1.0-reference`           | `image-to-video`                                    |
    | Video      | `happyhorse-1.0-video-edit`          | `video-to-video`                                    |
    | Video      | `sora-2`                             | `text-to-video`, `image-to-video`                   |
    | Video      | `sora-2-pro`                         | `text-to-video`, `image-to-video`                   |
    | Video      | `seedance-2.5`                       | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video      | `seedance-2.5-stable`                | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video      | `seedance-1-pro`                     | `text-to-video`, `image-to-video`                   |
    | Video      | `seedance-1-lite`                    | `text-to-video`, `image-to-video`                   |
    | Video      | `seedance-1-pro-fast`                | `image-to-video`                                    |
    | Video      | `kling-2.6`                          | `text-to-video`, `image-to-video`                   |
    | Video      | `kling-3.0`                          | `text-to-video`, `image-to-video`                   |
    | Video      | `kling-o3`                           | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video      | `kling-3.0-motion-control`           | `video-to-video`                                    |
    | Video      | `veo-3.1-fast`                       | `text-to-video`, `image-to-video`                   |
    | Video      | `veo-3.1-quality`                    | `text-to-video`, `image-to-video`                   |
    | Video      | `gemini-omni-video`                  | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video      | `minimax-h3`                         | `text-to-video`, `image-to-video`                   |
    | Video      | `kling-video-o1`                     | `video-to-video`                                    |
    
    For detailed and latest credit pricing by model, visit https://cyberbara.com/credit-costs.
    
    ---
    
    ## Core Commands (CLI)
    
    ```bash
    python3 scripts/cyberbara_api.py setup-api-key "<your_api_key>"
    python3 scripts/cyberbara_api.py models --media-type image
    python3 scripts/cyberbara_api.py models --media-type video
    python3 scripts/cyberbara_api.py models --media-type audio
    python3 scripts/cyberbara_api.py models --media-type music
    python3 scripts/cyberbara_api.py upload-images ./reference.png
    python3 scripts/cyberbara_api.py upload-videos ./reference.mp4
    python3 scripts/cyberbara_api.py quote --json '{...}'
    python3 scripts/cyberbara_api.py generate-image --json '{...}'
    python3 scripts/cyberbara_api.py generate-video --json '{...}'
    python3 scripts/cyberbara_api.py generate-audio --json '{...}'
    python3 scripts/cyberbara_api.py generate-music --json '{...}'
    python3 scripts/cyberbara_api.py wait --task-id <TASK_ID> --interval 5 --timeout 900
    python3 scripts/cyberbara_api.py balance
    python3 scripts/cyberbara_api.py usage --limit 20
    ```
    
    ---
    
    ## Contributing
    
    Contributions are welcome. Please open an issue for bugs/feature ideas, and submit pull requests to improve prompts, workflows, docs, or platform integrations.
    
    If this project helps you, please star the repository and help make it better together.
    
    ---
    
    ## License
    
    This project is licensed under the MIT License. See [LICENSE](./LICENSE).
    
    ---
    
    ## Star History
    
    [![Star History Chart](https://api.star-history.com/svg?repos=ZeroLu/Ultimate-AI-Media-Generator-Skill&type=Date)](https://star-history.com/#ZeroLu/Ultimate-AI-Media-Generator-Skill&Date)
    
  • scripts/cyberbara_api.py478 B74c82956f1a9upstream ↗
    #!/usr/bin/env python3
    """Thin entrypoint for CyberBara CLI."""
    
    from __future__ import annotations
    
    import sys
    from pathlib import Path
    
    
    def _bootstrap() -> None:
        skill_root = Path(__file__).resolve().parents[1]
        src_path = skill_root / "src"
        if str(src_path) not in sys.path:
            sys.path.insert(0, str(src_path))
    
    
    def main() -> None:
        _bootstrap()
        from cyberbara_cli.cli import main as run_main
    
        run_main()
    
    
    if __name__ == "__main__":
        main()
    
  • references/cyberbara-api-reference.mdx59 KB96b881dc4eacupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • assets/readme-cover-2k-16x9.jpg2.5 MBe6840ac499acupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .gitignore41 B23a5e4f0b1f9upstream ↗
    __pycache__/
    *.pyc
    *.pyo
    *.pyd
    .DS_Store
    
  • agents/openai.yaml309 Be91a15514233upstream ↗
    interface:
      display_name: "Ultimate-AI-Media-Generator-Skill"
      short_description: "Create and poll CyberBara image, video, audio, and music generation tasks with credit-aware flow"
      default_prompt: "Use $ultimate-ai-media-generator-skill to create a CyberBara generation task and return final media URLs."
    
  • LICENSE1.0 KB5027643c5b93upstream ↗
    MIT License
    
    Copyright (c) 2026 ZeroLu
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
    
  • README-zh.md11 KBeab95610c602upstream ↗
    # Ultimate-AI-Media-Generator-Skill
    
    [![GitHub Repo stars](https://img.shields.io/github/stars/ZeroLu/Ultimate-AI-Media-Generator-Skill?style=for-the-badge)](https://github.com/ZeroLu/Ultimate-AI-Media-Generator-Skill/stargazers)
    [![AtomGitStars](https://atomgit.com/ZeroLuAtom/Ultimate-AI-Media-Generator-Skill/star/badge.svg)](https://atomgit.com/ZeroLuAtom/Ultimate-AI-Media-Generator-Skill)
    [![GitHub Forks](https://img.shields.io/github/forks/ZeroLu/Ultimate-AI-Media-Generator-Skill?style=for-the-badge)](https://github.com/ZeroLu/Ultimate-AI-Media-Generator-Skill/network/members)
    [![MIT License](https://img.shields.io/github/license/ZeroLu/Ultimate-AI-Media-Generator-Skill?style=for-the-badge)](./LICENSE)
    
    ![Ultimate AI Media Generator Skill Cover](./assets/readme-cover-2k-16x9.jpg)
    
    一个开源的 **ai image generator skill**、**ai video generator skill** 与 **ai audio generator skill**,为 AI Agent 提供一站式图像、视频、音效与音乐生成能力。支持 Nano Banana 2、Nano Banana 2 Lite、Sora 2、Seedance、Kling、HappyHorse、Suno 等模型,适合内容生产、创意设计与自动化工作流。
    
    [快速开始](#快速开始) | [核心特性](#核心特性) | [支持平台](#支持平台) | [平台调用示例](#platform-prompts) | [典型场景](#典型场景) | [English README](./README.md)
    
    ---
    
    ## 核心特性
    
    - 🚀 **更高性价比生成**:在很多场景下,CyberBara 成本低于官方模型 API。
    - 💳 **先看积分再提交**:先 `quote` 预估积分,再决定是否发起任务。
    - 🧠 **精选提示词库**:由艺术家与提示词工程师整理,降低上手门槛。
    - 🛠️ **内置工作流模板**:覆盖 **ai ppt skill**、**ai seo article skill**、AI 漫剧创作等场景。
    - 🔓 **完全开源可定制**:支持 fork、改造、二次开发。
    - 🌍 **多 Agent 平台兼容**:面向主流 skill 生态平台可直接使用。
    
    ---
    
    ## 支持平台
    
    本 skill 支持所有支持 skill 的平台,包括但不限于:
    
    - OpenClaw
    - Claude Code
    - Codex
    - Claude Cowork
    - Cursor
    - Antigravity
    - 其他兼容 skill 的 Agent 平台
    
    ---
    
    ## 快速开始
    
    ### Vibe Install
    
    只需要把下面这句话发给 AI(OpenClaw、Claude Code、Codex 等),AI 会帮你安装:
    
    ```text
    Help me install this skill, use command `npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all`
    ```
    
    ### Manual Install
    
    ### Step 1) 安装(npx skills)
    
    ```bash
    # 查看可安装内容
    npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --list
    
    # 安装全部技能
    npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all
    
    # 可选:按指定 Agent 安装(如果你的 skills 运行时支持)
    npx skills add ZeroLu/Ultimate-AI-Media-Generator-Skill --all -a codex -a claude-code
    ```
    
    ### Step 2) 获取并配置 API Key
    
    免费 API Key 获取地址:https://cyberbara.com/settings/apikeys
    
    推荐一次性配置:
    
    ```bash
    python3 scripts/cyberbara_api.py setup-api-key "<your_api_key>"
    ```
    
    该命令会把 key 保存到 `~/.config/cyberbara/api_key`,后续无需每次重复配置。
    
    <a id="platform-prompts"></a>
    
    ### Step 3) 在 Codex、Claude Code、OpenClaw、Claude Cowork、Cursor、Antigravity 中使用 skill
    
    你可以直接把下面提示词粘贴到 Agent 对话框,或直接让 Agent 帮你生图、生视频、生成音效或音乐。
    
    #### A) 生图示例(nano banana skill)
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one image:
    - model: nano-banana-pro
    - scene: text-to-image
    - prompt: A cute kitten dancing, 3D cartoon style, dynamic full body, clean stage background
    - options: aspect_ratio=16:9, resolution=1k
    Return task id, final status, and output image URL.
    ```
    
    #### B) 生视频示例(seedance 2.0 skill / sora 2 skill)
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one video:
    - model: seedance-2-ark
    - scene: text-to-video
    - prompt: Cinematic wide shot of a futuristic city at sunrise, smooth drone motion
    - options: duration=10, resolution=720p
    If seedance-2-ark is unavailable, fallback to sora-2.
    Return task id and final video URL.
    ```
    
    #### C) 生成前先查积分
    
    ```text
    Use $ultimate-ai-media-generator-skill to quote credits before submission for this request:
    - model: nano-banana-pro
    - media_type: image
    - scene: text-to-image
    - prompt: Minimalist product poster for a smart watch
    - options: aspect_ratio=1:1, resolution=1k
    Return estimated_credits and can_afford.
    ```
    
    #### D) 生成音效
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one sound effect:
    - model: suno-sound-v5-5
    - scene: text-to-audio
    - prompt: A short cinematic whoosh with soft digital sparkle
    - options: loop=false
    Return task id, final status, and output audio URL.
    ```
    
    #### E) 生成音乐
    
    ```text
    Use $ultimate-ai-media-generator-skill to generate one music track:
    - model: suno-music-v5
    - scene: text-to-music
    - prompt: Warm lo-fi study music with mellow keys
    - options: instrumental=true
    Return task id, final status, and output audio URL.
    ```
    
    #### F) 查询余额与最近使用记录
    
    ```text
    Use $ultimate-ai-media-generator-skill to check current credit balance and the latest 20 usage records.
    ```
    
    ---
    
    ## 典型场景
    
    - **ai image generator skill**:社媒配图、广告素材、产品主视觉
    - **ai video generator skill**:短视频制作、分镜预演、创意样片
    - **ai audio generator skill**:生成音效与可用于制作的音乐素材
    - **ai ppt skill**:生成演示文稿配图与风格统一素材集
    - **ai seo article skill**:生成文章封面、插图与元数据图组
    - **open claw image generator skill**:OpenClaw + CyberBara 联动出图工作流
    
    工作流模板:
    
    - [AI PPT Workflow](./workflows/ai-ppt-skill.md)
    - [AI SEO Article Workflow](./workflows/ai-seo-article-skill.md)
    - [AI Comic Drama Workflow](./workflows/ai-comic-drama-skill.md)
    
    精选提示词:
    
    - [Curated Prompt Library](./workflows/curated-prompts.md)
    
    ---
    
    ## 模型覆盖(Model Coverage)
    
    CyberBara 当前支持的图像、视频、音频与音乐模型:
    
    | 媒体类型 | 模型                                 | 支持场景                                            |
    | -------- | ------------------------------------ | --------------------------------------------------- |
    | Audio    | `suno-sound-v5`                      | `text-to-audio`                                     |
    | Audio    | `suno-sound-v5-5`                    | `text-to-audio`                                     |
    | Image    | `nano-banana-2`                      | `text-to-image`, `image-to-image`                   |
    | Image    | `nano-banana-2-lite`                 | `text-to-image`, `image-to-image`                   |
    | Image    | `nano-banana-pro`                    | `text-to-image`, `image-to-image`                   |
    | Image    | `gpt-image-2`                        | `text-to-image`, `image-to-image`                   |
    | Image    | `midjourney-v7`                      | `text-to-image`, `image-to-image`                   |
    | Image    | `seedream-5-pro-layer-decomposition` | `image-to-image`                                    |
    | Music    | `suno-music-v3-5`                    | `text-to-music`                                     |
    | Music    | `suno-music-v4`                      | `text-to-music`                                     |
    | Music    | `suno-music-v4-5`                    | `text-to-music`                                     |
    | Music    | `suno-music-v4-5-plus`               | `text-to-music`                                     |
    | Music    | `suno-music-v5`                      | `text-to-music`                                     |
    | Music    | `suno-music-v5-5`                    | `text-to-music`                                     |
    | Video    | `happyhorse-1.0`                     | `text-to-video`                                     |
    | Video    | `happyhorse-1.0-first-frame`         | `image-to-video`                                    |
    | Video    | `happyhorse-1.0-reference`           | `image-to-video`                                    |
    | Video    | `happyhorse-1.0-video-edit`          | `video-to-video`                                    |
    | Video    | `sora-2`                             | `text-to-video`, `image-to-video`                   |
    | Video    | `sora-2-pro`                         | `text-to-video`, `image-to-video`                   |
    | Video    | `seedance-2.5`                       | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video    | `seedance-2.5-stable`                | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video    | `seedance-1-pro`                     | `text-to-video`, `image-to-video`                   |
    | Video    | `seedance-1-lite`                    | `text-to-video`, `image-to-video`                   |
    | Video    | `seedance-1-pro-fast`                | `image-to-video`                                    |
    | Video    | `kling-2.6`                          | `text-to-video`, `image-to-video`                   |
    | Video    | `kling-3.0`                          | `text-to-video`, `image-to-video`                   |
    | Video    | `kling-o3`                           | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video    | `kling-3.0-motion-control`           | `video-to-video`                                    |
    | Video    | `veo-3.1-fast`                       | `text-to-video`, `image-to-video`                   |
    | Video    | `veo-3.1-quality`                    | `text-to-video`, `image-to-video`                   |
    | Video    | `gemini-omni-video`                  | `text-to-video`, `image-to-video`, `video-to-video` |
    | Video    | `minimax-h3`                         | `text-to-video`, `image-to-video`                   |
    | Video    | `kling-video-o1`                     | `video-to-video`                                    |
    
    具体和最新积分费用请访问:https://cyberbara.com/credit-costs
    
    ---
    
    ## 核心命令(CLI)
    
    ```bash
    python3 scripts/cyberbara_api.py setup-api-key "<your_api_key>"
    python3 scripts/cyberbara_api.py models --media-type image
    python3 scripts/cyberbara_api.py models --media-type video
    python3 scripts/cyberbara_api.py models --media-type audio
    python3 scripts/cyberbara_api.py models --media-type music
    python3 scripts/cyberbara_api.py upload-images ./reference.png
    python3 scripts/cyberbara_api.py upload-videos ./reference.mp4
    python3 scripts/cyberbara_api.py quote --json '{...}'
    python3 scripts/cyberbara_api.py generate-image --json '{...}'
    python3 scripts/cyberbara_api.py generate-video --json '{...}'
    python3 scripts/cyberbara_api.py generate-audio --json '{...}'
    python3 scripts/cyberbara_api.py generate-music --json '{...}'
    python3 scripts/cyberbara_api.py wait --task-id <TASK_ID> --interval 5 --timeout 900
    python3 scripts/cyberbara_api.py balance
    python3 scripts/cyberbara_api.py usage --limit 20
    ```
    
    ---
    
    ## 欢迎贡献
    
    欢迎提交 Issue 和 Pull Request,一起完善提示词库、工作流模板、文档和平台适配能力。
    
    如果这个项目对你有帮助,欢迎点个 Star 支持。
    
    ---
    
    ## 许可证
    
    本项目采用 MIT 协议,详见 [LICENSE](./LICENSE)。
    
    ---
    
    ## Star History
    
    [![Star History Chart](https://api.star-history.com/svg?repos=ZeroLu/Ultimate-AI-Media-Generator-Skill&type=Date)](https://star-history.com/#ZeroLu/Ultimate-AI-Media-Generator-Skill&Date)
    
  • src/cyberbara_cli/__init__.py41 Baf0719eed661upstream ↗
    """CyberBara Public API CLI package."""
    
    
  • src/cyberbara_cli/cli.py20 KBab7c779238f5upstream ↗
    """Command-line interface for CyberBara skill."""
    
    from __future__ import annotations
    
    import argparse
    from typing import Any
    
    from cyberbara_cli.config import resolve_api_key, setup_api_key
    from cyberbara_cli.constants import DEFAULT_BASE_URL, DEFAULT_OUTPUT_DIR
    from cyberbara_cli.gateways import CyberbaraClient
    from cyberbara_cli.output import print_payload
    from cyberbara_cli.payloads import add_json_input_flags, load_json_payload
    from cyberbara_cli.usecases.generation import generate_media_with_credit_guard
    from cyberbara_cli.usecases.media_output import persist_and_open_task_output
    from cyberbara_cli.usecases.wait_task import wait_for_task, wait_for_task_payload
    
    
    def _extract_task_id(payload: Any) -> str | None:
        if not isinstance(payload, dict):
            return None
        data = payload.get("data")
        if not isinstance(data, dict):
            return None
        task_id = data.get("task_id")
        if isinstance(task_id, str) and task_id.strip():
            return task_id.strip()
        return None
    
    
    def _collect_submitted_tasks(submit_payload: Any) -> list[dict[str, Any]]:
        single_task_id = _extract_task_id(submit_payload)
        if single_task_id:
            return [{"index": 1, "task_id": single_task_id, "estimated_credits": None}]
    
        if not isinstance(submit_payload, dict):
            return []
        data = submit_payload.get("data")
        if not isinstance(data, dict):
            return []
        items = data.get("items")
        if not isinstance(items, list):
            return []
    
        tasks: list[dict[str, Any]] = []
        for index, item in enumerate(items, start=1):
            if not isinstance(item, dict):
                continue
            generation_response = item.get("generation_response")
            task_id = _extract_task_id(generation_response)
            if not task_id:
                continue
            tasks.append(
                {
                    "index": index,
                    "task_id": task_id,
                    "estimated_credits": item.get("estimated_credits"),
                }
            )
        return tasks
    
    
    def _finalize_submitted_tasks(
        *,
        client: CyberbaraClient,
        submit_payload: Any,
        interval: float,
        wait_timeout: int,
        timeout_per_request: int,
        save_outputs: bool,
        open_outputs: bool,
        output_dir: str,
    ) -> Any:
        tasks = _collect_submitted_tasks(submit_payload)
        if not tasks:
            return submit_payload
    
        final_items: list[dict[str, Any]] = []
        for task_meta in tasks:
            task_payload = wait_for_task_payload(
                client=client,
                task_id=task_meta["task_id"],
                interval=interval,
                timeout=wait_timeout,
                timeout_per_request=timeout_per_request,
            )
            saved_files: list[str] = []
            if save_outputs:
                saved_files = persist_and_open_task_output(
                    task_payload=task_payload,
                    output_dir=output_dir,
                    open_files=open_outputs,
                )
    
            final_items.append(
                {
                    "index": task_meta["index"],
                    "task_id": task_meta["task_id"],
                    "estimated_credits": task_meta.get("estimated_credits"),
                    "saved_files": saved_files,
                    "task_payload": task_payload,
                }
            )
    
        if len(final_items) == 1:
            return final_items[0]["task_payload"]
    
        return {
            "data": {
                "count": len(final_items),
                "items": final_items,
            }
        }
    
    
    def build_parser() -> argparse.ArgumentParser:
        parser = argparse.ArgumentParser(
            prog="cyberbara_api.py",
            description="Call CyberBara Public API v1 endpoints from CLI.",
        )
        parser.add_argument(
            "--api-key",
            default=None,
            help="CyberBara API key. If omitted, CLI uses env/cache and prompts when missing.",
        )
        parser.add_argument(
            "--timeout",
            type=int,
            default=120,
            help="HTTP request timeout in seconds (default: 120).",
        )
        parser.add_argument(
            "--compact",
            action="store_true",
            help="Print compact JSON output.",
        )
    
        subparsers = parser.add_subparsers(dest="command", required=True)
    
        setup_key_cmd = subparsers.add_parser(
            "setup-api-key",
            help="Persist API key to local cache so you do not need to export it every session.",
        )
        setup_key_cmd.add_argument(
            "input_api_key",
            nargs="?",
            help="API key value to store (optional if using --from-env or interactive input).",
        )
        setup_key_cmd.add_argument(
            "--from-env",
            action="store_true",
            help="Read API key from CYBERBARA_API_KEY and save it to local cache.",
        )
    
        models_cmd = subparsers.add_parser("models", help="List available models.")
        models_cmd.add_argument(
            "--media-type",
            choices=["image", "video", "audio", "music"],
            help="Optional media type filter.",
        )
    
        subparsers.add_parser("balance", help="Get current credit balance.")
    
        usage_cmd = subparsers.add_parser("usage", help="Get credits usage history.")
        usage_cmd.add_argument("--page", type=int, default=1, help="Page number.")
        usage_cmd.add_argument("--limit", type=int, default=20, help="Items per page.")
        usage_cmd.add_argument(
            "--from-date",
            help="Start date/time. Accepts ISO datetime or YYYY-MM-DD.",
        )
        usage_cmd.add_argument(
            "--to-date",
            help="End date/time. Accepts ISO datetime or YYYY-MM-DD.",
        )
    
        quote_cmd = subparsers.add_parser("quote", help="Estimate credit cost.")
        add_json_input_flags(quote_cmd, required=True)
    
        image_cmd = subparsers.add_parser(
            "generate-image",
            help="Quote credits, require confirmation, then create image generation task(s).",
        )
        add_json_input_flags(image_cmd, required=True)
        image_cmd.add_argument(
            "--yes",
            action="store_true",
            help="Skip interactive prompt after quote. Use only after explicit user approval.",
        )
        image_cmd.add_argument(
            "--async",
            dest="async_mode",
            action="store_true",
            help="Submit task(s) only and return immediately without waiting for outputs.",
        )
        image_cmd.add_argument(
            "--interval",
            type=float,
            default=5.0,
            help="Polling interval in seconds for waiting final output (default: 5).",
        )
        image_cmd.add_argument(
            "--wait-timeout",
            type=int,
            default=900,
            help="Max seconds to wait for task completion after submit (default: 900).",
        )
        image_cmd.add_argument(
            "--timeout-per-request",
            type=int,
            default=120,
            help="HTTP timeout per polling request in seconds (default: 120).",
        )
        image_cmd.add_argument(
            "--output-dir",
            default=DEFAULT_OUTPUT_DIR,
            help=f"Directory to save generated media files (default: {DEFAULT_OUTPUT_DIR}).",
        )
        image_cmd.add_argument(
            "--no-save",
            action="store_true",
            help="Do not save generated media files locally.",
        )
        image_cmd.add_argument(
            "--no-open",
            action="store_true",
            help="Save generated media files but do not auto-open them.",
        )
    
        video_cmd = subparsers.add_parser(
            "generate-video",
            help="Quote credits, require confirmation, then create video generation task(s).",
        )
        add_json_input_flags(video_cmd, required=True)
        video_cmd.add_argument(
            "--yes",
            action="store_true",
            help="Skip interactive prompt after quote. Use only after explicit user approval.",
        )
        video_cmd.add_argument(
            "--async",
            dest="async_mode",
            action="store_true",
            help="Submit task(s) only and return immediately without waiting for outputs.",
        )
        video_cmd.add_argument(
            "--interval",
            type=float,
            default=5.0,
            help="Polling interval in seconds for waiting final output (default: 5).",
        )
        video_cmd.add_argument(
            "--wait-timeout",
            type=int,
            default=900,
            help="Max seconds to wait for task completion after submit (default: 900).",
        )
        video_cmd.add_argument(
            "--timeout-per-request",
            type=int,
            default=120,
            help="HTTP timeout per polling request in seconds (default: 120).",
        )
        video_cmd.add_argument(
            "--output-dir",
            default=DEFAULT_OUTPUT_DIR,
            help=f"Directory to save generated media files (default: {DEFAULT_OUTPUT_DIR}).",
        )
        video_cmd.add_argument(
            "--no-save",
            action="store_true",
            help="Do not save generated media files locally.",
        )
        video_cmd.add_argument(
            "--no-open",
            action="store_true",
            help="Save generated media files but do not auto-open them.",
        )
    
        audio_cmd = subparsers.add_parser(
            "generate-audio",
            help="Quote credits, require confirmation, then create audio generation task(s).",
        )
        add_json_input_flags(audio_cmd, required=True)
        audio_cmd.add_argument(
            "--yes",
            action="store_true",
            help="Skip interactive prompt after quote. Use only after explicit user approval.",
        )
        audio_cmd.add_argument(
            "--async",
            dest="async_mode",
            action="store_true",
            help="Submit task(s) only and return immediately without waiting for outputs.",
        )
        audio_cmd.add_argument(
            "--interval",
            type=float,
            default=5.0,
            help="Polling interval in seconds for waiting final output (default: 5).",
        )
        audio_cmd.add_argument(
            "--wait-timeout",
            type=int,
            default=900,
            help="Max seconds to wait for task completion after submit (default: 900).",
        )
        audio_cmd.add_argument(
            "--timeout-per-request",
            type=int,
            default=120,
            help="HTTP timeout per polling request in seconds (default: 120).",
        )
        audio_cmd.add_argument(
            "--output-dir",
            default=DEFAULT_OUTPUT_DIR,
            help=f"Directory to save generated media files (default: {DEFAULT_OUTPUT_DIR}).",
        )
        audio_cmd.add_argument(
            "--no-save",
            action="store_true",
            help="Do not save generated media files locally.",
        )
        audio_cmd.add_argument(
            "--no-open",
            action="store_true",
            help="Save generated media files but do not auto-open them.",
        )
    
        music_cmd = subparsers.add_parser(
            "generate-music",
            help="Quote credits, require confirmation, then create music generation task(s).",
        )
        add_json_input_flags(music_cmd, required=True)
        music_cmd.add_argument(
            "--yes",
            action="store_true",
            help="Skip interactive prompt after quote. Use only after explicit user approval.",
        )
        music_cmd.add_argument(
            "--async",
            dest="async_mode",
            action="store_true",
            help="Submit task(s) only and return immediately without waiting for outputs.",
        )
        music_cmd.add_argument(
            "--interval",
            type=float,
            default=5.0,
            help="Polling interval in seconds for waiting final output (default: 5).",
        )
        music_cmd.add_argument(
            "--wait-timeout",
            type=int,
            default=900,
            help="Max seconds to wait for task completion after submit (default: 900).",
        )
        music_cmd.add_argument(
            "--timeout-per-request",
            type=int,
            default=120,
            help="HTTP timeout per polling request in seconds (default: 120).",
        )
        music_cmd.add_argument(
            "--output-dir",
            default=DEFAULT_OUTPUT_DIR,
            help=f"Directory to save generated media files (default: {DEFAULT_OUTPUT_DIR}).",
        )
        music_cmd.add_argument(
            "--no-save",
            action="store_true",
            help="Do not save generated media files locally.",
        )
        music_cmd.add_argument(
            "--no-open",
            action="store_true",
            help="Save generated media files but do not auto-open them.",
        )
    
        upload_cmd = subparsers.add_parser("upload-images", help="Upload reference image files.")
        upload_cmd.add_argument("files", nargs="+", help="Local image files to upload.")
    
        upload_videos_cmd = subparsers.add_parser(
            "upload-videos",
            help="Upload reference video files.",
        )
        upload_videos_cmd.add_argument("files", nargs="+", help="Local video files to upload.")
    
        task_cmd = subparsers.add_parser("task", help="Fetch task status by task ID.")
        task_cmd.add_argument("--task-id", required=True, help="Task ID.")
    
        wait_cmd = subparsers.add_parser(
            "wait",
            help="Poll task status until success/failed/canceled.",
        )
        wait_cmd.add_argument("--task-id", required=True, help="Task ID.")
        wait_cmd.add_argument(
            "--interval",
            type=float,
            default=5.0,
            help="Polling interval in seconds (default: 5).",
        )
        wait_cmd.add_argument(
            "--timeout",
            type=int,
            default=900,
            help="Total polling timeout in seconds (default: 900). Use 0 for no limit.",
        )
        wait_cmd.add_argument(
            "--timeout-per-request",
            type=int,
            default=120,
            help="HTTP timeout per polling request in seconds (default: 120).",
        )
        wait_cmd.add_argument(
            "--output-dir",
            default=DEFAULT_OUTPUT_DIR,
            help=f"Directory to save generated media files (default: {DEFAULT_OUTPUT_DIR}).",
        )
        wait_cmd.add_argument(
            "--no-save",
            action="store_true",
            help="Do not save generated media files locally.",
        )
        wait_cmd.add_argument(
            "--no-open",
            action="store_true",
            help="Save generated media files but do not auto-open them.",
        )
    
        raw_cmd = subparsers.add_parser("raw", help="Call any endpoint directly.")
        raw_cmd.add_argument("--method", required=True, help="HTTP method.")
        raw_cmd.add_argument("--path", required=True, help="API path (for example /api/v1/models).")
        add_json_input_flags(raw_cmd, required=False)
    
        return parser
    
    
    def main() -> None:
        parser = build_parser()
        args = parser.parse_args()
    
        if args.command == "setup-api-key":
            payload = {
                "data": setup_api_key(
                    input_api_key=args.input_api_key,
                    from_env=args.from_env,
                )
            }
            print_payload(payload, args.compact)
            return
    
        api_key = resolve_api_key(args.api_key)
    
        client = CyberbaraClient(api_key=api_key, base_url=DEFAULT_BASE_URL)
    
        if args.command == "models":
            payload = client.models(media_type=args.media_type, timeout=args.timeout)
            print_payload(payload, args.compact)
            return
    
        if args.command == "balance":
            payload = client.balance(timeout=args.timeout)
            print_payload(payload, args.compact)
            return
    
        if args.command == "usage":
            payload = client.usage(
                page=args.page,
                limit=args.limit,
                from_date=args.from_date,
                to_date=args.to_date,
                timeout=args.timeout,
            )
            print_payload(payload, args.compact)
            return
    
        if args.command == "quote":
            request_payload = load_json_payload(args.json, args.file)
            payload = client.quote(request_payload, timeout=args.timeout)
            print_payload(payload, args.compact)
            return
    
        if args.command == "generate-image":
            request_payload = load_json_payload(args.json, args.file)
            submit_payload = generate_media_with_credit_guard(
                client=client,
                media_label="image",
                payload_body=request_payload,
                yes=args.yes,
                timeout=args.timeout,
            )
            if args.async_mode:
                print_payload(submit_payload, args.compact)
                return
            payload = _finalize_submitted_tasks(
                client=client,
                submit_payload=submit_payload,
                interval=args.interval,
                wait_timeout=args.wait_timeout,
                timeout_per_request=args.timeout_per_request,
                save_outputs=not args.no_save,
                open_outputs=not args.no_open,
                output_dir=args.output_dir,
            )
            print_payload(payload, args.compact)
            return
    
        if args.command == "generate-video":
            request_payload = load_json_payload(args.json, args.file)
            submit_payload = generate_media_with_credit_guard(
                client=client,
                media_label="video",
                payload_body=request_payload,
                yes=args.yes,
                timeout=args.timeout,
            )
            if args.async_mode:
                print_payload(submit_payload, args.compact)
                return
            payload = _finalize_submitted_tasks(
                client=client,
                submit_payload=submit_payload,
                interval=args.interval,
                wait_timeout=args.wait_timeout,
                timeout_per_request=args.timeout_per_request,
                save_outputs=not args.no_save,
                open_outputs=not args.no_open,
                output_dir=args.output_dir,
            )
            print_payload(payload, args.compact)
            return
    
        if args.command == "generate-audio":
            request_payload = load_json_payload(args.json, args.file)
            submit_payload = generate_media_with_credit_guard(
                client=client,
                media_label="audio",
                payload_body=request_payload,
                yes=args.yes,
                timeout=args.timeout,
            )
            if args.async_mode:
                print_payload(submit_payload, args.compact)
                return
            payload = _finalize_submitted_tasks(
                client=client,
                submit_payload=submit_payload,
                interval=args.interval,
                wait_timeout=args.wait_timeout,
                timeout_per_request=args.timeout_per_request,
                save_outputs=not args.no_save,
                open_outputs=not args.no_open,
                output_dir=args.output_dir,
            )
            print_payload(payload, args.compact)
            return
    
        if args.command == "generate-music":
            request_payload = load_json_payload(args.json, args.file)
            submit_payload = generate_media_with_credit_guard(
                client=client,
                media_label="music",
                payload_body=request_payload,
                yes=args.yes,
                timeout=args.timeout,
            )
            if args.async_mode:
                print_payload(submit_payload, args.compact)
                return
            payload = _finalize_submitted_tasks(
                client=client,
                submit_payload=submit_payload,
                interval=args.interval,
                wait_timeout=args.wait_timeout,
                timeout_per_request=args.timeout_per_request,
                save_outputs=not args.no_save,
                open_outputs=not args.no_open,
                output_dir=args.output_dir,
            )
            print_payload(payload, args.compact)
            return
    
        if args.command == "upload-images":
            payload = client.upload_images(args.files, timeout=args.timeout)
            print_payload(payload, args.compact)
            return
    
        if args.command == "upload-videos":
            payload = client.upload_videos(args.files, timeout=args.timeout)
            print_payload(payload, args.compact)
            return
    
        if args.command == "task":
            payload = client.task(args.task_id, timeout=args.timeout)
            print_payload(payload, args.compact)
            return
    
        if args.command == "wait":
            wait_for_task(
                client=client,
                task_id=args.task_id,
                interval=args.interval,
                timeout=args.timeout,
                timeout_per_request=args.timeout_per_request,
                compact=args.compact,
                auto_save=not args.no_save,
                open_files=not args.no_open,
                output_dir=args.output_dir,
            )
            return
    
        if args.command == "raw":
            raw_payload = None
            if args.json or args.file:
                raw_payload = load_json_payload(args.json, args.file)
            payload = client.raw(
                method=args.method,
                path=args.path,
                payload=raw_payload,
                timeout=args.timeout,
            )
            print_payload(payload, args.compact)
            return
    
        parser.error(f"Unsupported command: {args.command}")
    
  • src/cyberbara_cli/config.py3.4 KB8fbb78ff677aupstream ↗
    """API key resolution and local persistence helpers."""
    
    from __future__ import annotations
    
    import os
    from pathlib import Path
    import sys
    from typing import Any
    
    from cyberbara_cli.constants import API_KEY_PAGE_URL
    
    API_KEY_ENV_VAR = "CYBERBARA_API_KEY"
    API_KEY_STORE_PATH = Path.home() / ".config" / "cyberbara" / "api_key"
    
    
    def _normalize_api_key(api_key: str | None) -> str:
        return (api_key or "").strip()
    
    
    def _mask_api_key(api_key: str) -> str:
        key = _normalize_api_key(api_key)
        if not key:
            return ""
        if len(key) <= 8:
            return "*" * len(key)
        return f"{key[:4]}...{key[-4:]}"
    
    
    def load_cached_api_key() -> str | None:
        if not API_KEY_STORE_PATH.is_file():
            return None
        key = _normalize_api_key(API_KEY_STORE_PATH.read_text(encoding="utf-8"))
        return key or None
    
    
    def save_cached_api_key(api_key: str) -> None:
        key = _normalize_api_key(api_key)
        if not key:
            raise SystemExit("API key is empty.")
    
        API_KEY_STORE_PATH.parent.mkdir(parents=True, exist_ok=True)
        try:
            API_KEY_STORE_PATH.parent.chmod(0o700)
        except OSError:
            pass
    
        API_KEY_STORE_PATH.write_text(f"{key}\n", encoding="utf-8")
        try:
            API_KEY_STORE_PATH.chmod(0o600)
        except OSError:
            pass
    
    
    def _prompt_and_cache_api_key() -> str:
        message = (
            "API key not found. Visit "
            f"{API_KEY_PAGE_URL} to create one."
        )
    
        if not sys.stdin.isatty():
            raise SystemExit(
                f"{message} Then provide --api-key or set {API_KEY_ENV_VAR}."
            )
    
        print(message, file=sys.stderr)
        entered = _normalize_api_key(input("Please paste your CyberBara API key: "))
        if not entered:
            raise SystemExit("No API key provided.")
    
        save_cached_api_key(entered)
        print(f"API key saved to {API_KEY_STORE_PATH}.", file=sys.stderr)
        return entered
    
    
    def resolve_api_key(cli_api_key: str | None) -> str:
        key_from_arg = _normalize_api_key(cli_api_key)
        if key_from_arg:
            save_cached_api_key(key_from_arg)
            return key_from_arg
    
        key_from_env = _normalize_api_key(os.getenv(API_KEY_ENV_VAR))
        if key_from_env:
            return key_from_env
    
        key_from_cache = load_cached_api_key()
        if key_from_cache:
            return key_from_cache
    
        return _prompt_and_cache_api_key()
    
    
    def setup_api_key(
        *,
        input_api_key: str | None = None,
        from_env: bool = False,
    ) -> dict[str, Any]:
        """Persist API key to local cache and return non-sensitive metadata."""
        source = ""
        key = _normalize_api_key(input_api_key)
    
        if key:
            source = "argument"
        elif from_env:
            key = _normalize_api_key(os.getenv(API_KEY_ENV_VAR))
            if not key:
                raise SystemExit(
                    f"{API_KEY_ENV_VAR} is empty. Export it first or pass key directly."
                )
            source = "environment"
        elif sys.stdin.isatty():
            print(
                f"Visit {API_KEY_PAGE_URL} to create one.",
                file=sys.stderr,
            )
            key = _normalize_api_key(input("Please paste your CyberBara API key: "))
            if not key:
                raise SystemExit("No API key provided.")
            source = "interactive_prompt"
        else:
            raise SystemExit(
                "No API key provided. Use `setup-api-key <key>` or `setup-api-key --from-env`."
            )
    
        save_cached_api_key(key)
        return {
            "saved": True,
            "source": source,
            "store_path": str(API_KEY_STORE_PATH),
            "api_key_masked": _mask_api_key(key),
        }
    
  • src/cyberbara_cli/constants.py402 B2d87f44e5dadupstream ↗
    """Shared constants for CyberBara CLI."""
    
    DEFAULT_BASE_URL = "https://cyberbara.com"
    API_KEY_PAGE_URL = f"{DEFAULT_BASE_URL}/settings/apikeys"
    FINAL_TASK_STATUSES = {"success", "failed", "canceled"}
    DEFAULT_OUTPUT_DIR = "media_outputs"
    DEFAULT_HTTP_USER_AGENT = (
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/123.0.0.0 Safari/537.36"
    )
    
  • src/cyberbara_cli/gateways/__init__.py148 B3b97ca079601upstream ↗
    """Gateway package for CyberBara API calls."""
    
    from cyberbara_cli.gateways.cyberbara_client import CyberbaraClient
    
    __all__ = ["CyberbaraClient"]
    
    
  • src/cyberbara_cli/gateways/cyberbara_client.py7.4 KB08e22c71db07upstream ↗
    """Low-level CyberBara API client."""
    
    from __future__ import annotations
    
    import json
    import mimetypes
    import uuid
    from pathlib import Path
    from typing import Any
    from urllib import error, parse, request
    
    from cyberbara_cli.constants import DEFAULT_BASE_URL, DEFAULT_HTTP_USER_AGENT
    from cyberbara_cli.output import print_error_and_exit
    
    
    class CyberbaraClient:
        """HTTP client for CyberBara `/api/v1` endpoints."""
    
        def __init__(self, *, api_key: str, base_url: str = DEFAULT_BASE_URL) -> None:
            self.api_key = api_key
            self.base_url = base_url.rstrip("/")
    
        @staticmethod
        def _parse_json_bytes(raw: bytes) -> Any:
            if not raw:
                return {}
            text = raw.decode("utf-8", errors="replace")
            try:
                return json.loads(text)
            except json.JSONDecodeError:
                return {"_raw": text}
    
        def _build_url(self, path: str, query: dict[str, Any] | None = None) -> str:
            normalized_path = path if path.startswith("/") else f"/{path}"
            url = f"{self.base_url}{normalized_path}"
            if query:
                clean = {k: v for k, v in query.items() if v is not None and v != ""}
                if clean:
                    url = f"{url}?{parse.urlencode(clean)}"
            return url
    
        def _api_request(
            self,
            *,
            method: str,
            path: str,
            query: dict[str, Any] | None = None,
            json_body: Any | None = None,
            body: bytes | None = None,
            content_type: str | None = None,
            timeout: int = 120,
        ) -> tuple[int, Any]:
            url = self._build_url(path=path, query=query)
            headers = {
                "Accept": "application/json",
                "Authorization": f"Bearer {self.api_key}",
                "x-api-key": self.api_key,
                "User-Agent": DEFAULT_HTTP_USER_AGENT,
            }
    
            if json_body is not None:
                body = json.dumps(json_body, ensure_ascii=False).encode("utf-8")
                headers["Content-Type"] = "application/json"
            elif content_type:
                headers["Content-Type"] = content_type
    
            req = request.Request(url=url, data=body, method=method.upper(), headers=headers)
    
            try:
                with request.urlopen(req, timeout=timeout) as resp:
                    return resp.status, self._parse_json_bytes(resp.read())
            except error.HTTPError as exc:
                return exc.code, self._parse_json_bytes(exc.read())
            except error.URLError as exc:
                raise SystemExit(f"Request failed for {method.upper()} {url}: {exc.reason}") from exc
    
        def request(
            self,
            *,
            method: str,
            path: str,
            query: dict[str, Any] | None = None,
            json_body: Any | None = None,
            body: bytes | None = None,
            content_type: str | None = None,
            timeout: int = 120,
        ) -> Any:
            status_code, payload = self._api_request(
                method=method,
                path=path,
                query=query,
                json_body=json_body,
                body=body,
                content_type=content_type,
                timeout=timeout,
            )
            if 200 <= status_code < 300:
                return payload
            print_error_and_exit(payload)
            return payload
    
        @staticmethod
        def _build_multipart_upload(file_paths: list[str]) -> tuple[bytes, str]:
            boundary = f"----CyberBaraBoundary{uuid.uuid4().hex}"
            chunks: list[bytes] = []
    
            for file_path in file_paths:
                path = Path(file_path)
                if not path.is_file():
                    raise SystemExit(f"File not found: {path}")
    
                mime = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
                filename = path.name.replace('"', "")
    
                chunks.append(f"--{boundary}\r\n".encode("utf-8"))
                chunks.append(
                    (
                        "Content-Disposition: form-data; "
                        f'name="files"; filename="{filename}"\r\n'
                    ).encode("utf-8")
                )
                chunks.append(f"Content-Type: {mime}\r\n\r\n".encode("utf-8"))
                chunks.append(path.read_bytes())
                chunks.append(b"\r\n")
    
            chunks.append(f"--{boundary}--\r\n".encode("utf-8"))
            return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
    
        def models(self, *, media_type: str | None, timeout: int) -> Any:
            query = {"media_type": media_type} if media_type else None
            return self.request(
                method="GET",
                path="/api/v1/models",
                query=query,
                timeout=timeout,
            )
    
        def balance(self, *, timeout: int) -> Any:
            return self.request(
                method="GET",
                path="/api/v1/credits/balance",
                timeout=timeout,
            )
    
        def usage(
            self,
            *,
            page: int,
            limit: int,
            from_date: str | None,
            to_date: str | None,
            timeout: int,
        ) -> Any:
            return self.request(
                method="GET",
                path="/api/v1/credits/usage",
                query={
                    "page": page,
                    "limit": limit,
                    "from": from_date,
                    "to": to_date,
                },
                timeout=timeout,
            )
    
        def quote(self, payload: Any, *, timeout: int) -> Any:
            return self.request(
                method="POST",
                path="/api/v1/credits/quote",
                json_body=payload,
                timeout=timeout,
            )
    
        def generate_image(self, payload: Any, *, timeout: int) -> Any:
            return self.request(
                method="POST",
                path="/api/v1/images/generations",
                json_body=payload,
                timeout=timeout,
            )
    
        def generate_video(self, payload: Any, *, timeout: int) -> Any:
            return self.request(
                method="POST",
                path="/api/v1/videos/generations",
                json_body=payload,
                timeout=timeout,
            )
    
        def generate_audio(self, payload: Any, *, timeout: int) -> Any:
            return self.request(
                method="POST",
                path="/api/v1/audio/generations",
                json_body=payload,
                timeout=timeout,
            )
    
        def generate_music(self, payload: Any, *, timeout: int) -> Any:
            return self.request(
                method="POST",
                path="/api/v1/music/generations",
                json_body=payload,
                timeout=timeout,
            )
    
        def upload_images(self, files: list[str], *, timeout: int) -> Any:
            body, content_type = self._build_multipart_upload(files)
            return self.request(
                method="POST",
                path="/api/v1/uploads/images",
                body=body,
                content_type=content_type,
                timeout=timeout,
            )
    
        def upload_videos(self, files: list[str], *, timeout: int) -> Any:
            body, content_type = self._build_multipart_upload(files)
            return self.request(
                method="POST",
                path="/api/v1/uploads/videos",
                body=body,
                content_type=content_type,
                timeout=timeout,
            )
    
        def task(self, task_id: str, *, timeout: int) -> Any:
            return self.request(
                method="GET",
                path=f"/api/v1/tasks/{task_id}",
                timeout=timeout,
            )
    
        def raw(self, *, method: str, path: str, payload: Any | None, timeout: int) -> Any:
            return self.request(
                method=method,
                path=path,
                json_body=payload,
                timeout=timeout,
            )
    
  • src/cyberbara_cli/output.py568 B04daf81c5572upstream ↗
    """Output helpers for JSON responses."""
    
    from __future__ import annotations
    
    import json
    import sys
    from typing import Any
    
    
    def to_json(payload: Any, compact: bool) -> str:
        if compact:
            return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
        return json.dumps(payload, ensure_ascii=False, indent=2)
    
    
    def print_payload(payload: Any, compact: bool) -> None:
        print(to_json(payload, compact=compact))
    
    
    def print_error_and_exit(payload: Any) -> None:
        print(to_json(payload, compact=False), file=sys.stderr)
        raise SystemExit(1)
    
    
  • src/cyberbara_cli/payloads.py1.1 KB4bef5fa65df8upstream ↗
    """Payload parsing helpers."""
    
    from __future__ import annotations
    
    import argparse
    import json
    from pathlib import Path
    from typing import Any
    
    
    def load_json_payload(inline_json: str | None, json_file: str | None) -> Any:
        if inline_json:
            try:
                return json.loads(inline_json)
            except json.JSONDecodeError as exc:
                raise SystemExit(f"Invalid --json payload: {exc}") from exc
    
        if json_file:
            path = Path(json_file)
            if not path.is_file():
                raise SystemExit(f"JSON file not found: {path}")
            try:
                return json.loads(path.read_text(encoding="utf-8"))
            except json.JSONDecodeError as exc:
                raise SystemExit(f"Invalid JSON file {path}: {exc}") from exc
    
        raise SystemExit("JSON payload is required. Use --json or --file.")
    
    
    def add_json_input_flags(cmd: argparse.ArgumentParser, required: bool = True) -> None:
        group = cmd.add_mutually_exclusive_group(required=required)
        group.add_argument("--json", help="Inline JSON payload string.")
        group.add_argument("--file", help="Path to JSON payload file.")
    
    
  • src/cyberbara_cli/policies/__init__.py53 B5219ee7a0ec4upstream ↗
    """Policies package for runtime behavior guards."""
    
    
  • src/cyberbara_cli/policies/credit_guard.py4.7 KBd4da7b91560bupstream ↗
    """Credit guard policy used before generation requests."""
    
    from __future__ import annotations
    
    from dataclasses import dataclass
    import sys
    from typing import Any
    
    
    @dataclass
    class QuoteResult:
        index: int
        estimated_credits: float
        quote_data: dict[str, Any]
    
    
    def normalize_generation_requests(payload_body: Any, media_label: str) -> list[dict[str, Any]]:
        if isinstance(payload_body, dict):
            return [payload_body]
    
        if isinstance(payload_body, list):
            if not payload_body:
                raise SystemExit(f"{media_label.capitalize()} generation request list is empty.")
            requests: list[dict[str, Any]] = []
            for index, item in enumerate(payload_body, start=1):
                if not isinstance(item, dict):
                    raise SystemExit(
                        f"{media_label.capitalize()} generation request #{index} must be a JSON object."
                    )
                requests.append(item)
            return requests
    
        raise SystemExit(
            f"{media_label.capitalize()} generation payload must be an object or an array of objects."
        )
    
    
    def build_quote_payload(request_body: dict[str, Any], media_type: str) -> dict[str, Any]:
        payload = dict(request_body)
        existing_media_type = payload.get("media_type")
        if existing_media_type in (None, ""):
            payload["media_type"] = media_type
        return payload
    
    
    def extract_estimated_credits(quote_payload: Any) -> float:
        if not isinstance(quote_payload, dict):
            raise SystemExit("Quote response is not valid JSON.")
    
        data = quote_payload.get("data")
        if not isinstance(data, dict):
            raise SystemExit("Quote response missing data object.")
    
        estimated = data.get("estimated_credits")
        if isinstance(estimated, bool):
            raise SystemExit("Quote response estimated_credits has invalid type.")
    
        if isinstance(estimated, (int, float)):
            return float(estimated)
    
        if isinstance(estimated, str):
            text = estimated.strip()
            if text:
                try:
                    return float(text)
                except ValueError as exc:
                    raise SystemExit("Quote response estimated_credits is not numeric.") from exc
    
        raise SystemExit("Quote response missing estimated_credits.")
    
    
    def normalize_credit_number(value: float) -> int | float:
        return int(value) if float(value).is_integer() else value
    
    
    def format_credit_number(value: float) -> str:
        normalized = normalize_credit_number(value)
        if isinstance(normalized, int):
            return str(normalized)
        return str(normalized)
    
    
    def collect_quote_results(
        *,
        client: Any,
        requests: list[dict[str, Any]],
        media_label: str,
        timeout: int,
    ) -> list[QuoteResult]:
        results: list[QuoteResult] = []
        for index, request_body in enumerate(requests, start=1):
            quote_body = build_quote_payload(request_body, media_label)
            quote_payload = client.quote(quote_body, timeout=timeout)
            estimated = extract_estimated_credits(quote_payload)
            quote_data = (
                quote_payload.get("data", {})
                if isinstance(quote_payload, dict) and isinstance(quote_payload.get("data"), dict)
                else {}
            )
            results.append(
                QuoteResult(
                    index=index,
                    estimated_credits=estimated,
                    quote_data=quote_data,
                )
            )
        return results
    
    
    def confirm_generation_or_exit(
        *,
        quote_results: list[QuoteResult],
        request_count: int,
        media_label: str,
        yes: bool,
    ) -> float:
        total_estimated = sum(item.estimated_credits for item in quote_results)
    
        print(
            f"[quote] {media_label}_requests={request_count} "
            f"total_estimated_credits={format_credit_number(total_estimated)}",
            file=sys.stderr,
        )
        for item in quote_results:
            model = item.quote_data.get("model", "unknown")
            scene = item.quote_data.get("scene", "unknown")
            estimated = format_credit_number(item.estimated_credits)
            print(
                f"[quote] request#{item.index} model={model} scene={scene} "
                f"estimated_credits={estimated}",
                file=sys.stderr,
            )
    
        if yes:
            print("[confirm] --yes provided, continue to submit requests.", file=sys.stderr)
            return total_estimated
    
        if not sys.stdin.isatty():
            raise SystemExit(
                f"Formal confirmation required before {media_label} generation. "
                "Run interactively and type CONFIRM, or re-run with --yes only after explicit user approval."
            )
    
        answer = input(f"Type CONFIRM to submit {media_label} generation request(s): ").strip()
        if answer != "CONFIRM":
            raise SystemExit("Canceled: confirmation not received.")
    
        return total_estimated
    
    
  • src/cyberbara_cli/usecases/__init__.py26 B60ec6e9db169upstream ↗
    """Use cases package."""
    
    
  • src/cyberbara_cli/usecases/generation.py2.1 KB0d3597d5f73dupstream ↗
    """Generation use cases with credit guard flow."""
    
    from __future__ import annotations
    
    from typing import Any
    
    from cyberbara_cli.policies.credit_guard import (
        collect_quote_results,
        confirm_generation_or_exit,
        normalize_credit_number,
        normalize_generation_requests,
    )
    
    
    def generate_media_with_credit_guard(
        *,
        client: Any,
        media_label: str,
        payload_body: Any,
        yes: bool,
        timeout: int,
    ) -> Any:
        requests = normalize_generation_requests(payload_body, media_label)
        quote_results = collect_quote_results(
            client=client,
            requests=requests,
            media_label=media_label,
            timeout=timeout,
        )
        total_estimated = confirm_generation_or_exit(
            quote_results=quote_results,
            request_count=len(requests),
            media_label=media_label,
            yes=yes,
        )
    
        generation_payloads: list[Any] = []
        for request_body in requests:
            if media_label == "image":
                payload = client.generate_image(request_body, timeout=timeout)
            elif media_label == "video":
                payload = client.generate_video(request_body, timeout=timeout)
            elif media_label == "audio":
                payload = client.generate_audio(request_body, timeout=timeout)
            elif media_label == "music":
                payload = client.generate_music(request_body, timeout=timeout)
            else:
                raise SystemExit(f"Unsupported media label: {media_label}")
            generation_payloads.append(payload)
    
        if len(generation_payloads) == 1:
            return generation_payloads[0]
    
        items: list[dict[str, Any]] = []
        for quote_result, generation_payload in zip(quote_results, generation_payloads):
            items.append(
                {
                    "index": quote_result.index,
                    "estimated_credits": normalize_credit_number(quote_result.estimated_credits),
                    "generation_response": generation_payload,
                }
            )
    
        return {
            "data": {
                "count": len(items),
                "total_estimated_credits": normalize_credit_number(total_estimated),
                "items": items,
            }
        }
    
  • src/cyberbara_cli/usecases/media_output.py4.2 KB4c0cea12f798upstream ↗
    """Download and open generated media outputs."""
    
    from __future__ import annotations
    
    from datetime import datetime, timezone
    import mimetypes
    from pathlib import Path
    import shutil
    import subprocess
    import sys
    from typing import Any
    from urllib import parse, request
    import uuid
    
    from cyberbara_cli.constants import DEFAULT_HTTP_USER_AGENT, DEFAULT_OUTPUT_DIR
    
    
    def _collect_urls_from_unknown(value: Any, *, depth: int = 0) -> list[str]:
        if depth > 5 or value is None:
            return []
    
        if isinstance(value, str):
            text = value.strip()
            if text.startswith(("http://", "https://")):
                return [text]
            return []
    
        urls: list[str] = []
        if isinstance(value, list):
            for item in value:
                urls.extend(_collect_urls_from_unknown(item, depth=depth + 1))
            return urls
    
        if isinstance(value, dict):
            preferred_keys = [
                "images",
                "videos",
                "audios",
                "audio",
                "music",
                "songs",
                "url",
                "uri",
                "src",
                "imageUrl",
                "videoUrl",
                "audioUrl",
                "streamAudioUrl",
                "sourceAudioUrl",
            ]
            for key in preferred_keys:
                if key in value:
                    urls.extend(_collect_urls_from_unknown(value[key], depth=depth + 1))
            return urls
    
        return []
    
    
    def _extract_output_urls(task_payload: Any) -> list[str]:
        if not isinstance(task_payload, dict):
            return []
        data = task_payload.get("data")
        if not isinstance(data, dict):
            return []
        task = data.get("task")
        if not isinstance(task, dict):
            return []
        output = task.get("output")
        if not isinstance(output, dict):
            return []
    
        return list(dict.fromkeys(_collect_urls_from_unknown(output)))
    
    
    def _guess_extension(url: str, content_type: str | None) -> str:
        path_suffix = Path(parse.urlparse(url).path).suffix.lower()
        if path_suffix:
            return path_suffix
    
        if content_type:
            ext = mimetypes.guess_extension(content_type)
            if ext:
                if ext == ".jpe":
                    return ".jpg"
                return ext
    
        return ".bin"
    
    
    def _download_media_url(url: str, output_dir: Path) -> Path:
        req = request.Request(
            url=url,
            headers={"User-Agent": DEFAULT_HTTP_USER_AGENT},
            method="GET",
        )
    
        with request.urlopen(req, timeout=180) as resp:
            content = resp.read()
            content_type = resp.headers.get_content_type() if resp.headers else None
    
        ext = _guess_extension(url, content_type)
        timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
        filename = f"cyberbara_{timestamp}_{uuid.uuid4().hex[:8]}{ext}"
        file_path = output_dir / filename
        file_path.write_bytes(content)
        return file_path
    
    
    def _open_file(file_path: Path) -> None:
        try:
            if sys.platform.startswith("darwin"):
                subprocess.Popen(["open", str(file_path)])
                return
    
            if os_name_is_windows():
                subprocess.Popen(["cmd", "/c", "start", "", str(file_path)])
                return
    
            xdg_open = shutil.which("xdg-open")
            if xdg_open:
                subprocess.Popen([xdg_open, str(file_path)])
                return
    
            print(
                f"[open] Unable to auto-open {file_path}. No supported opener found.",
                file=sys.stderr,
            )
        except Exception as exc:  # pragma: no cover - best-effort open
            print(f"[open] Failed to open {file_path}: {exc}", file=sys.stderr)
    
    
    def os_name_is_windows() -> bool:
        return sys.platform.startswith("win")
    
    
    def persist_and_open_task_output(
        *,
        task_payload: Any,
        output_dir: str | None = None,
        open_files: bool = True,
    ) -> list[str]:
        urls = _extract_output_urls(task_payload)
        if not urls:
            return []
    
        target_dir = Path(output_dir or DEFAULT_OUTPUT_DIR).expanduser().resolve()
        target_dir.mkdir(parents=True, exist_ok=True)
    
        saved_files: list[str] = []
        for url in urls:
            path = _download_media_url(url, target_dir)
            saved_files.append(str(path))
            print(f"[save] {path}", file=sys.stderr)
            if open_files:
                _open_file(path)
    
        return saved_files
    
  • src/cyberbara_cli/usecases/wait_task.py2.2 KB4b9ff387d502upstream ↗
    """Task polling use case."""
    
    from __future__ import annotations
    
    import sys
    import time
    from typing import Any
    
    from cyberbara_cli.constants import FINAL_TASK_STATUSES
    from cyberbara_cli.output import print_payload
    from cyberbara_cli.usecases.media_output import persist_and_open_task_output
    
    
    def extract_task_status(payload: Any) -> str | None:
        if not isinstance(payload, dict):
            return None
        data = payload.get("data")
        if not isinstance(data, dict):
            return None
        task = data.get("task")
        if not isinstance(task, dict):
            return None
        status = task.get("status")
        if isinstance(status, str):
            return status
        return None
    
    
    def wait_for_task(
        *,
        client: Any,
        task_id: str,
        interval: float,
        timeout: int,
        timeout_per_request: int,
        compact: bool,
        auto_save: bool = True,
        open_files: bool = True,
        output_dir: str | None = None,
    ) -> None:
        payload = wait_for_task_payload(
            client=client,
            task_id=task_id,
            interval=interval,
            timeout=timeout,
            timeout_per_request=timeout_per_request,
        )
        print_payload(payload, compact)
        if auto_save:
            persist_and_open_task_output(
                task_payload=payload,
                output_dir=output_dir,
                open_files=open_files,
            )
    
    
    def wait_for_task_payload(
        *,
        client: Any,
        task_id: str,
        interval: float,
        timeout: int,
        timeout_per_request: int,
    ) -> Any:
        deadline = time.time() + timeout if timeout > 0 else None
        last_payload: Any = {}
    
        while True:
            payload = client.task(task_id, timeout=timeout_per_request)
            last_payload = payload
            task_status = extract_task_status(payload)
            if not task_status:
                raise SystemExit("Task status is missing in response.")
    
            print(f"[wait] task={task_id} status={task_status}", file=sys.stderr)
    
            if task_status in FINAL_TASK_STATUSES:
                if task_status != "success":
                    print_payload(payload, compact=False)
                    raise SystemExit(2)
                return payload
    
            if deadline is not None and time.time() >= deadline:
                print_payload(last_payload, compact=False)
                raise SystemExit(3)
    
            time.sleep(interval)
    
  • workflows/ai-comic-drama-skill.md635 Bc0ec793b9282upstream ↗
    # AI Comic Drama Workflow
    
    Goal: turn a short story idea into a scene-by-scene image/video production plan.
    
    ## Inputs
    
    - genre
    - main character
    - story arc
    - tone
    
    ## Prompt Template
    
    ```text
    Transform this story idea into a comic-drama production brief.
    Genre: {genre}
    Main character: {main_character}
    Story arc: {story_arc}
    Tone: {tone}
    Output:
    1) 8 scene prompts (visual storyboard),
    2) 2 transition video prompts,
    3) character consistency checklist,
    4) style lock instructions.
    ```
    
    ## Media Generation Tips
    
    - Reuse character descriptors exactly to improve consistency.
    - Use image keyframes first, then animate selected scenes.
    
  • workflows/ai-ppt-skill.md612 B2ea6d928ceceupstream ↗
    # AI PPT Skill Workflow
    
    Goal: generate a complete visual package for a slide deck without design expertise.
    
    ## Inputs
    
    - topic
    - audience
    - slide count
    - visual style
    
    ## Prompt Template
    
    ```text
    Create a visual plan for a {slide_count}-slide presentation about {topic}.
    Audience: {audience}.
    Style: {visual_style}.
    Output:
    1) one hero cover image prompt,
    2) one visual prompt per slide,
    3) icon style guide,
    4) color palette,
    5) short image alt text for accessibility.
    ```
    
    ## Media Generation Tips
    
    - Use `nano-banana-pro` for fast image ideation.
    - Keep consistent `aspect_ratio` and palette across slides.
    
  • workflows/ai-seo-article-skill.md721 B29d11f6d594cupstream ↗
    # AI SEO Article Skill Workflow
    
    Goal: produce SEO-friendly article assets (cover + inline visuals + metadata image variants).
    
    ## Inputs
    
    - primary keyword
    - secondary keywords
    - article angle
    - target audience
    
    ## Prompt Template
    
    ```text
    Create a complete visual asset plan for an SEO article.
    Primary keyword: {primary_keyword}
    Secondary keywords: {secondary_keywords}
    Angle: {article_angle}
    Audience: {audience}
    Output:
    1) cover image prompt,
    2) 3 inline image prompts,
    3) social preview image prompt,
    4) image naming suggestions using SEO-friendly slugs.
    ```
    
    ## Media Generation Tips
    
    - Generate 1:1 for social previews and 16:9 for article banners.
    - Keep visual entities aligned with the article keyword intent.
    
  • workflows/curated-prompts.md1.4 KBcfef4a011b07upstream ↗
    # Curated Prompt Library
    
    A starter pack of high-signal prompts inspired by artist and prompt-engineer workflows.
    
    ## 1) Product Hero (Minimal)
    
    ```text
    A premium smartwatch floating above a matte pedestal, studio rim light, clean gradient background, ultra-clean composition, product advertising style, high detail
    ```
    
    ## 2) Cinematic Character Portrait
    
    ```text
    A confident female pilot in futuristic suit, medium close-up, cinematic teal-orange grade, volumetric light, shallow depth of field, high detail facial texture
    ```
    
    ## 3) 3D Cartoon Mascot
    
    ```text
    A cute orange cat mascot dancing on a spotlight stage, 3D cartoon style, full-body framing, joyful expression, soft global illumination, clean background
    ```
    
    ## 4) Architecture Concept
    
    ```text
    A sustainable floating city with layered sky gardens, wide aerial shot, morning haze, realistic materials, cinematic composition, ultra-detailed
    ```
    
    ## 5) Storyboard Frame
    
    ```text
    A detective enters a neon-lit alley at night, rain reflections on pavement, wide shot, high contrast, dramatic mood, film storyboard style
    ```
    
    ## 6) Social Thumbnail
    
    ```text
    Bold centered composition of a robotic chef cooking ramen, vibrant colors, high contrast, eye-catching thumbnail style, clean typography-safe space
    ```
    
    ## 7) Video Prompt (Seedance/Sora style)
    
    ```text
    Cinematic drone fly-through over a futuristic harbor at golden hour, smooth camera motion, realistic water reflections, dramatic sky, 10-second sequence
    ```
    

Plain-text copy, no login: /skill-bundles/ultimate-ai-media-generator.md

// REPO STATS

107 stars
0 open issues
Last commit: 2mo ago