Skill: jackycser/seedance-video-generation (version 1.0.3)

--- name: seedance-video description: "Generate AI videos using ByteDance Seedance. Use when the user wants to: (1) generate videos from text prompts, (2) generate videos from images (first frame, first+last frame, reference images), or (3) query/manage video generation tasks. Supports Seedance 1.5 Pro (with audio), 1.0 Pro, 1.0 Pro Fast, and 1.0 Lite models." version: 1.0.0 category: file-generation argument-hint: "[text prompt or task ID]" --- # Seedance Video Generation Generate AI videos using ByteDance Seedance models via the Volcengine Ark API. ## Prerequisites The user must set the `ARK_API_KEY` environment variable. You can set it by running: ```bash export ARK_API_KEY="your-api-key-here" ``` **Base URL**: `https://ark.cn-beijing.volces.com/api/v3` ## Supported Models | Model | Model ID | Capabilities | |-------|----------|-------------| | Seedance 1.5 Pro | `doubao-seedance-1-5-pro-251215` | Text-to-video, Image-to-video (first frame, first+last frame), Audio support, Draft mode | | Seedance 1.0 Pro | `doubao-seedance-1-0-pro-250428` | Text-to-video, Image-to-video (first frame, first+last frame) | | Seedance 1.0 Pro Fast | [REDACTED_SECRET] | Text-to-video, Image-to-video (first frame only) | | Seedance 1.0 Lite T2V | [REDACTED_SECRET] | Text-to-video only | | Seedance 1.0 Lite I2V | [REDACTED_SECRET] | Image-to-video (first frame, first+last frame, reference images 1-4) | **Default model**: `doubao-seedance-1-5-pro-251215` (latest, supports audio) ## Execution (Recommended: Python CLI Tool) A Python CLI tool is provided at `~/.claude/skills/seedance-video/seedance.py` for robust execution with proper error handling, automatic retries, and local image base64 conversion. **Prefer using this tool over raw curl commands.** ### Quick Examples with Python CLI ```bash # Text-to-video (create + wait + download) python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "小猫对着镜头打哈欠" --wait --download ~/Desktop # Image-to-video from local file python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "人物缓缓转头微笑" --image /path/to/photo.jpg --wait --download ~/Desktop # Image-to-video from URL python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "风景画面缓缓推进" --image "https://example.com/image.jpg" --wait --download ~/Desktop # First + last frame python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "花朵从含苞到盛开" --image first.jpg --last-frame last.jpg --wait --download ~/Desktop # Reference images (Lite I2V) python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "[图1]的人物在跳舞" --ref-images ref1.jpg ref2.jpg --model doubao-seedance-1-0-lite-i2v-250219 --wait --download ~/Desktop # Custom parameters python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "城市夜景延时摄影" --ratio 21:9 --duration 8 --resolution 1080p --generate-audio false --wait --download ~/Desktop # Draft mode (cheaper preview) python3 ~/.claude/skills/seedance-video/seedance.py create --prompt "海浪拍打沙滩" --draft true --wait --download ~/Desktop # Generate final video from draft python3 ~/.claude/skills/seedance-video/seedance.py create --draft-task-id <DRAFT_TASK_ID> --resolution 720p --wait --download ~/Desktop # Query task status python3 ~/.claude/skills/seedance-video/seedance.py status <TASK_ID> # Wait for an existing task python3 ~/.claude/skills/seedance-video/seedance.py wait <TASK_ID> --download ~/Desktop # List tasks python3 ~/.claude/skills/seedance-video/seedance.py list --status succeeded # Delete/cancel task python3 ~/.claude/skills/seedance-video/seedance.py delete <TASK_ID> ``` ## Alternative: Raw curl Commands ### Step 1: Create Video Generation Task Determine the generation mode based on user input, then call the API. #### Mode A: Text-to-Video ```bash TASK_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": "doubao-seedance-1-5-pro-251215", "content": [ { "type": "text", "text": "YOUR_PROMPT_HERE" } ], "ratio": "16:9", "duration": 5, "resolution": "720p", "generate_audio": true }') TASK_ID=$(echo "$TASK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") echo "Task created: $TASK_ID" ``` #### Mode B: Image-to-Video (First Frame) The user provides one image as the first frame. The image can be a URL or local file path (convert to base64). **With image URL:** ```bash TASK_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": "doubao-seedance-1-5-pro-251215", "content": [ { "type": "text", "text": "YOUR_PROMPT_HERE" }, { "type": "image_url", "image_url": { "url": "IMAGE_URL_HERE" }, "role": "first_frame" } ], "ratio": "adaptive", "duration": 5, "resolution": "720p", "generate_audio": true }') TASK_ID=$(echo "$TASK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") echo "Task created: $TASK_ID" ``` **With local image file (convert to base64):** ```bash IMG_PATH="/path/to/image.png" IMG_EXT="${IMG_PATH##*.}" IMG_EXT_LOWER=$(echo "$IMG_EXT" | tr '[:upper:]' '[:lower:]') IMG_BASE64=$(base64 < "$IMG_PATH" | tr -d '\n') IMG_DATA_URL="data:image/${IMG_EXT_LOWER};base64,${IMG_BASE64}" TASK_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": "doubao-seedance-1-5-pro-251215", "content": [ { "type": "text", "text": "YOUR_PROMPT_HERE" }, { "type": "image_url", "image_url": { "url": "'"$IMG_DATA_URL"'" }, "role": "first_frame" } ], "ratio": "adaptive", "duration": 5, "resolution": "720p", "generate_audio": true }') TASK_ID=$(echo "$TASK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") echo "Task created: $TASK_ID" ``` #### Mode C: Image-to-Video (First + Last Frame) Requires two images. Supported by: Seedance 1.5 Pro, 1.0 Pro, 1.0 Lite I2V. ```bash TASK_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": "doubao-seedance-1-5-pro-251215", "content": [ { "type": "text", "text": "YOUR_PROMPT_HERE" }, { "type": "image_url", "image_url": { "url": "FIRST_FRAME_IMAGE_URL" }, "role": "first_frame" }, { "type": "image_url", "image_url": { "url": "LAST_FRAME_IMAGE_URL" }, "role": "last_frame" } ], "ratio": "adaptive", "duration": 5, "resolution": "720p", "generate_audio": true }') TASK_ID=$(echo "$TASK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") echo "Task created: $TASK_ID" ``` #### Mode D: Reference Image-to-Video (Seedance 1.0 Lite I2V only) Provide 1-4 reference images. Use `[图1]`, `[图2]` in prompt to reference specific images. ```bash TASK_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": [REDACTED_SECRET], "content": [ { "type": "text", "text": "[图1]的人物在跳舞" }, { "type": "image_url", "image_url": { "url": "REF_IMAGE_URL_1" }, "role": "reference_image" } ], "ratio": "16:9", "duration": 5, "resolution": "720p" }') TASK_ID=$(echo "$TASK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") echo "Task created: $TASK_ID" ``` ### Step 2: Poll for Task Completion Video generation is asynchronous. Poll the task status until it completes. ```bash echo "Waiting for video generation to complete..." while true; do STATUS_RESULT=$(curl -s -X GET "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks/${TASK_ID}" \ -H "Authorization: Bearer $ARK_API_KEY") STATUS=$(echo "$STATUS_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])") if [ "$STATUS" = "succeeded" ]; then echo "Video generation succeeded!" VIDEO_URL=$(echo "$STATUS_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['content']['video_url'])") echo "Video URL: $VIDEO_URL" break elif [ "$STATUS" = "failed" ]; then ERROR_MSG=$(echo "$STATUS_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('error',{}).get('message','Unknown error'))" 2>/dev/null || echo "Unknown error") echo "Video generation failed: $ERROR_MSG" break elif [ "$STATUS" = "expired" ]; then echo "Video generation task expired." break else echo "Status: $STATUS - still processing..." sleep 15 fi done ``` ### Step 3: Download and Open Video ```bash OUTPUT_PATH="$HOME/Desktop/seedance_video_$(date +%Y%m%d_%H%M%S).mp4" curl -s -o "$OUTPUT_PATH" "$VIDEO_URL" echo "Video saved to: $OUTPUT_PATH" open "$OUTPUT_PATH" ``` ## Optional Parameters Reference | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `model` | string | `doubao-seedance-1-5-pro-251215` | Model ID to use | | `ratio` | string | `16:9` (text2vid) / `adaptive` (img2vid) | Aspect ratio: `16:9`, `4:3`, `1:1`, `3:4`, `9:16`, `21:9`, `adaptive` | | `duration` | integer | `5` | Video duration in seconds (4-12 for 1.5 Pro, 2-12 for others). Set `-1` for auto (1.5 Pro only) | | `resolution` | string | `720p` | Resolution: `480p`, `720p`, `1080p` | | `seed` | integer | `-1` | Random seed for reproducibility. -1 = random | | `camera_fixed` | boolean | `false` | Fix camera position | | `watermark` | boolean | `false` | Add watermark to video | | `generate_audio` | boolean | `true` | Generate synchronized audio (Seedance 1.5 Pro only) | | `draft` | boolean | `false` | Generate draft/preview video at lower cost (Seedance 1.5 Pro only, forces 480p) | | `return_last_frame` | boolean | `false` | Return last frame image URL (for chaining consecutive videos) | | `service_tier` | string | `default` | `default` (online) or `flex` (offline, 50% cheaper, slower) | | `execution_expires_after` | integer | `172800` | Task timeout in seconds (3600-259200) | ## Additional Operations ### Query Task Status ```bash curl -s -X GET "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks/${TASK_ID}" \ -H "Authorization: Bearer $ARK_API_KEY" | python3 -m json.tool ``` ### List Tasks ```bash # List all tasks (paginated) curl -s -X GET "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks?page_num=1&page_size=10" \ -H "Authorization: Bearer $ARK_API_KEY" | python3 -m json.tool # Filter by status curl -s -X GET "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks?page_num=1&page_size=10&filter.status=succeeded" \ -H "Authorization: Bearer $ARK_API_KEY" | python3 -m json.tool ``` ### Cancel or Delete Task ```bash curl -s -X DELETE "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks/${TASK_ID}" \ -H "Authorization: Bearer $ARK_API_KEY" ``` Note: `queued` tasks will be cancelled; `succeeded`/`failed`/`expired` tasks will be deleted from history. ### Generate Consecutive Videos (Using Last Frame) Set `return_last_frame: true` on the first task, then use the returned `last_frame_url` as the first frame of the next task. ```bash # Get last frame URL from completed task LAST_FRAME_URL=$(curl -s -X GET "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks/${TASK_ID}" \ -H "Authorization: Bearer $ARK_API_KEY" | python3 -c "import sys,json; print(json.load(sys.stdin)['content']['last_frame_url'])") # Use it as first frame for the next video # ... (use Mode B with LAST_FRAME_URL as the image URL) ``` ### Draft Mode (Seedance 1.5 Pro) Generate a cheap preview first, then produce the final video if satisfied: ```bash # Step 1: Create draft DRAFT_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": "doubao-seedance-1-5-pro-251215", "content": [ { "type": "text", "text": "YOUR_PROMPT_HERE" } ], "draft": true, "resolution": "480p" }') DRAFT_TASK_ID=$(echo "$DRAFT_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") # Step 2: After draft succeeds, generate final video from draft FINAL_RESULT=$(curl -s -X POST "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $ARK_API_KEY" \ -d '{ "model": "doubao-seedance-1-5-pro-251215", "content": [ { "type": "draft_task", "draft_task": { "id": "'"$DRAFT_TASK_ID"'" } } ], "resolution": "720p" }') ``` ## Image Requirements - Formats: jpeg, png, webp, bmp, tiff, gif (1.5 Pro also supports heic, heif) - Aspect ratio (width/height): between 0.4 and 2.5 - Dimensions: 300-6000 px per side - Max file size: 30 MB ## 通过飞书发送视频文件（OpenClaw） 详见 [how_to_send_video_via_feishu_app.md](how_to_send_video_via_feishu_app.md) ## Rules 1. **Always check** that `ARK_API_KEY` is set before making API calls: `[ -z "$ARK_API_KEY" ] && echo "Error: ARK_API_KEY not set" && exit 1` 2. **Default to Seedance 1.5 Pro** (`doubao-seedance-1-5-pro-251215`) unless user requests a specific model. 3. **Default to 720p, 16:9, 5 seconds, with audio** for text-to-video. 4. **Default to adaptive ratio** for image-to-video (auto-adapts to the input image). 5. **Poll interval**: 15 seconds between status checks. 6. **Video URLs expire in 24 hours** - always download immediately after generation. 7. **Task history is kept for 7 days only**. 8. For local image files, convert to base64 data URL format before sending. 9. Always show the user the task ID so they can check status later. 10. When generation fails, display the error message clearly and suggest possible fixes.

path: how_to_send_video_via_feishu_app.md
content: ## 通过飞书发送视频文件（OpenClaw）

在 OpenClaw 中，你可以使用此 skill 生成视频后，通过飞书 App 将视频发送到聊天中。

### 完整步骤概览

生成视频 → 保存到本地 → 使用 message 工具发送 → 飞书 API 处理 → 视频上传到飞书 CDN → 发送到聊天

### 第一步：生成视频文件

使用 `seedance-video` skill 生成视频：

```bash
python3 /root/.openclaw/workspace/skills/seedance-video-generation/seedance.py \
  create \
  --prompt "新年祝福场景..." \
  --ratio 9:16 \
  --duration 5 \
  --resolution 1080p \
  --generate-audio true \
  --wait \
  --download /root/.openclaw/workspace
```

输出：本地视频文件路径，例如：
`/root/.openclaw/workspace/seedance_cgt-20260212104701-nqcr7_1770864513.mp4`

### 第二步：使用 message 工具发送视频

调用 OpenClaw 的 `message` 工具：

```python
message(
  action="send",           # 动作：发送消息
  channel="feishu",        # 目标频道：飞书
  filePath="/root/.openclaw/workspace/seedance_cgt-20260212104701-nqcr7_1770864513.mp4",  # 本地视频路径
  message="视频说明文字"    # 可选的附加说明
)
```

### 第三步：message 工具内部处理流程

`message` 工具接收到请求后，执行以下操作：

#### 3.1 读取本地文件

```python
with open(filePath, 'rb') as f:
    file_content = f.read()
```

#### 3.2 调用飞书 Open API

工具会调用飞书开放平台的 API，主要步骤：

**a) 获取上传凭证**

```
POST https://open.feishu.cn/open-apis/drive/v1/medias/upload_all
```

请求参数：
- `file_type`: video/mp4
- `file_name`: seedance_cgt-xxx.mp4
- `file_size`: [文件大小]

响应：
```json
{
  "code": 0,
  "data": {
    "upload_token": "xxxxx",
    "upload_url": "https://xxx.com/upload..."
  }
}
```

**b) 上传文件到飞书 CDN**

```
PUT {upload_url}
Content-Type: video/mp4
Authorization: Bearer {upload_token}

[视频二进制数据]
```

**c) 发送消息到飞书聊天**

```
POST https://open.feishu.cn/open-apis/im/v1/messages/send
```

请求参数：
```json
{
  "receive_id_type": "open_id",
  "receive_id": "ou_f323dd2c97951b029f7c43505c4b7566",
  "msg_type": "file",
  "content": "{\"file_key\":\"xxx\",\"file_name\":\"视频.mp4\"}"
}
```

### 权限认证

在整个流程中，需要以下权限：

| 环节 | 所需权限 | 配置位置 |
|------|---------|---------|
| 生成视频 | 火山引擎 ARK_API_KEY | 环境变量 |
| 读取本地文件 | 文件系统读取权限 | `/root/.openclaw/workspace/` |
| 飞书 API 调用 | 飞书 app_access_token | OpenClaw 飞书配置 |

飞书 app_access_token 获取：

```
POST https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal
```

使用配置在 OpenClaw 中的 `feishu.app_id` 和 `feishu.app_secret`。

### 飞书处理与分发

飞书接收到消息后：
1. **存储视频**：视频文件上传到飞书 CDN 存储
2. **生成资源 key**：为视频分配唯一的 `file_key`
3. **分发到客户端**：飞书接收端收到消息，从 CDN 下载视频预览，在聊天窗口显示视频播放器

### 完整流程图

```
┌─────────────────┐
│   用户请求       │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ seedance生成视频 │ → API调用火山引擎
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  保存到本地文件  │ → /root/.openclaw/workspace/
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ message工具调用  │ → 读取本地文件
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ 飞书API上传     │ → 1.获取upload_token
│                 │ → 2.上传到飞书CDN
│                 │ → 3.发送消息
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ 飞书分发到客户端 │
└─────────────────┘
```

### 关键技术细节

1. **文件大小限制**：飞书支持最大 100MB 的视频文件，超过限制需要使用分块上传
2. **支持的视频格式**：MP4（推荐）、MOV、AVI、WebM
3. **上传超时**：大文件上传可能超时，建议控制视频在 10MB 以内
4. **API 速率限制**：飞书 API 有 QPS 限制，频繁发送需要注意限流

### 总结

整个流程的核心是：1. 本地生成 → 2. 本地保存 → 3. 工具封装 → 4. API 上传 → 5. 飞书分发

OpenClaw 的 `message` 工具已经封装了步骤 3-5，你只需要提供本地文件路径即可！


path: CHANGELOG.md
content: # 更新日志

## v1.1.0 (2026-02-12)

### 新增功能

- **飞书视频发送指南**：新增 `how_to_send_video_via_feishu_app.md` 文档，详细说明如何在 OpenClaw 中将生成的视频通过飞书 App 发送到聊天中。
  - 完整的操作步骤：生成视频 → 本地保存 → message 工具发送 → 飞书 API 上传 → 飞书分发
  - 包含 message 工具调用示例
  - 飞书 Open API 调用细节（上传凭证、CDN 上传、消息发送）
  - 权限认证说明（ARK_API_KEY、飞书 app_access_token）
  - 关键技术细节（文件大小限制、支持格式、超时处理、速率限制）

## v1.0.0

- 初始版本
- 支持 Seedance 1.5 Pro、1.0 Pro、1.0 Pro Fast、1.0 Lite 模型
- 文本生成视频、图片生成视频（首帧、首尾帧、参考图）
- Python CLI 工具 (`seedance.py`)
- 完整的 curl 命令示例


path: seedance.py
content: #!/usr/bin/env python3
"""
Seedance Video Generation CLI Tool
Usage:
  python3 seedance.py create --prompt "描述" [options]
  python3 seedance.py create --prompt "描述" --image /path/to/image.png [options]
  python3 seedance.py create --prompt "描述" --image url1 --last-frame url2 [options]
  python3 seedance.py create --prompt "描述" --ref-images url1 url2 [options]
  python3 seedance.py create --draft-task-id <task_id> [options]
  python3 seedance.py status <task_id>
  python3 seedance.py wait <task_id> [--interval 15] [--download ~/Desktop]
  python3 seedance.py list [--status succeeded] [--page 1] [--page-size 10]
  python3 seedance.py delete <task_id>
"""

import argparse
import base64
import json
import os
import sys
import time
import urllib.request
import urllib.error
from pathlib import Path


BASE_URL = "https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks"
DEFAULT_MODEL = "doubao-seedance-1-5-pro-251215"


def get_api_key():
    key = os.environ.get("ARK_API_KEY")
    if not key:
        print("Error: ARK_API_KEY environment variable is not set.", file=sys.stderr)
        print("Set it with: export ARK_API_KEY='your-api-key-here'", file=sys.stderr)
        sys.exit(1)
    return key


def api_request(method, url, data=None):
    """Make an API request and return parsed JSON response."""
    [REDACTED_SECRET])
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }

    body = json.dumps(data).encode("utf-8") if data else None
    req = urllib.request.Request(url, data=body, headers=headers, method=method)

    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            resp_body = resp.read().decode("utf-8")
            if resp_body:
                return json.loads(resp_body)
            return {}
    except urllib.error.HTTPError as e:
        error_body = e.read().decode("utf-8", errors="replace")
        try:
            error_json = json.loads(error_body)
            error_msg = error_json.get("error", {}).get("message", error_body)
        except json.JSONDecodeError:
            error_msg = error_body
        print(f"API Error (HTTP {e.code}): {error_msg}", file=sys.stderr)
        sys.exit(1)
    except urllib.error.URLError as e:
        print(f"Network Error: {e.reason}", file=sys.stderr)
        sys.exit(1)


def image_to_data_url(image_path):
    """Convert a local image file to a base64 data URL."""
    p = Path(image_path)
    if not p.exists():
        print(f"Error: Image file not found: {image_path}", file=sys.stderr)
        sys.exit(1)

    ext = p.suffix.lower().lstrip(".")
    mime_map = {
        "jpg": "jpeg", "jpeg": "jpeg", "png": "png",
        "webp": "webp", "bmp": "bmp", "tiff": "tiff",
        "tif": "tiff", "gif": "gif", "heic": "heic", "heif": "heif",
    }
    mime_ext = mime_map.get(ext, ext)

    file_size = p.stat().st_size
    if file_size > 30 * 1024 * 1024:
        print(f"Error: Image file too large ({file_size / 1024 / 1024:.1f} MB). Max 30 MB.", file=sys.stderr)
        sys.exit(1)

    with open(p, "rb") as f:
        b64 = base64.b64encode(f.read()).decode("ascii")

    return f"data:image/{mime_ext};base64,{b64}"


def resolve_image(image_input):
    """Resolve image input to a URL or data URL. Accepts URL or local file path."""
    if image_input.startswith(("http://", "https://", "data:")):
        return image_input
    return image_to_data_url(image_input)


def cmd_create(args):
    """Create a video generation task."""
    content = []

    # Draft task mode
    if args.draft_task_id:
        content.append({
            "type": "draft_task",
            "draft_task": {"id": args.draft_task_id}
        })
    else:
        # Text prompt
        if args.prompt:
            content.append({"type": "text", "text": args.prompt})

        # Image inputs
        if args.ref_images:
            # Reference image mode (Lite I2V only)
            for img in args.ref_images:
                content.append({
                    "type": "image_url",
                    "image_url": {"url": resolve_image(img)},
                    "role": "reference_image"
                })
        elif args.image:
            # First frame
            content.append({
                "type": "image_url",
                "image_url": {"url": resolve_image(args.image)},
                "role": "first_frame"
            })
            # Last frame (optional)
            if args.last_frame:
                content.append({
                    "type": "image_url",
                    "image_url": {"url": resolve_image(args.last_frame)},
                    "role": "last_frame"
                })

    if not content:
        print("Error: Must provide --prompt, --image, or --draft-task-id.", file=sys.stderr)
        sys.exit(1)

    body = {
        "model": args.model,
        "content": content,
    }

    # Optional parameters
    if args.ratio:
        body["ratio"] = args.ratio
    if args.duration is not None:
        body["duration"] = args.duration
    if args.resolution:
        body["resolution"] = args.resolution
    if args.seed is not None:
        body["seed"] = args.seed
    if args.camera_fixed is not None:
        body["camera_fixed"] = args.camera_fixed
    if args.watermark is not None:
        body["watermark"] = args.watermark
    if args.generate_audio is not None:
        body["generate_audio"] = args.generate_audio
    if args.draft is not None:
        body["draft"] = args.draft
    if args.return_last_frame is not None:
        body["return_last_frame"] = args.return_last_frame
    if args.service_tier:
        body["service_tier"] = args.service_tier

    result = api_request("POST", BASE_URL, body)
    task_id = result.get("id", "")

    print(json.dumps({"task_id": task_id, "status": "created", "response": result}, indent=2))

    # Auto-wait if requested
    if args.wait:
        return cmd_wait_logic(task_id, args.interval or 15, args.download)

    return task_id


def cmd_status(args):
    """Query task status."""
    url = f"{BASE_URL}/{args.task_id}"
    result = api_request("GET", url)
    print(json.dumps(result, indent=2, ensure_ascii=False))
    return result


def cmd_wait_logic(task_id, interval=15, download_dir=None):
    """Wait for task completion, optionally download result."""
    url = f"{BASE_URL}/{task_id}"
    print(f"Waiting for task {task_id} to complete (polling every {interval}s)...")

    while True:
        result = api_request("GET", url)
        status = result.get("status", "unknown")

        if status == "succeeded":
            video_url = result.get("content", {}).get("video_url", "")
            last_frame_url = result.get("content", {}).get("last_frame_url")
            duration = result.get("duration", "?")
            resolution = result.get("resolution", "?")
            ratio = result.get("ratio", "?")

            print(f"\nVideo generation succeeded!")
            print(f"  Duration: {duration}s | Resolution: {resolution} | Ratio: {ratio}")
            print(f"  Video URL: {video_url}")
            if last_frame_url:
                print(f"  Last Frame URL: {last_frame_url}")

            # Download
            if download_dir and video_url:
                download_path = Path(download_dir).expanduser()
                download_path.mkdir(parents=True, exist_ok=True)
                filename = f"seedance_{task_id}_{int(time.time())}.mp4"
                filepath = download_path / filename

                print(f"\nDownloading video to {filepath}...")
                try:
                    urllib.request.urlretrieve(video_url, str(filepath))
                    print(f"Saved to: {filepath}")

                    # Open on macOS
                    if sys.platform == "darwin":
                        os.system(f'open "{filepath}"')
                except Exception as e:
                    print(f"Download failed: {e}", file=sys.stderr)

            print(json.dumps(result, indent=2, ensure_ascii=False))
            return result

        elif status == "failed":
            error = result.get("error", {})
            print(f"\nVideo generation failed!")
            print(f"  Error: {error.get('code', 'unknown')} - {error.get('message', 'Unknown error')}")
            print(json.dumps(result, indent=2, ensure_ascii=False))
            sys.exit(1)

        elif status == "expired":
            print(f"\nVideo generation task expired.")
            print(json.dumps(result, indent=2, ensure_ascii=False))
            sys.exit(1)

        else:
            print(f"  Status: {status}...", flush=True)
            time.sleep(interval)


def cmd_wait(args):
    """Wait for task completion."""
    return cmd_wait_logic(args.task_id, args.interval, args.download)


def cmd_list(args):
    """List video generation tasks."""
    params = []
    if args.page:
        params.append(f"page_num={args.page}")
    if args.page_size:
        params.append(f"page_size={args.page_size}")
    if args.status:
        params.append(f"filter.status={args.status}")

    url = BASE_URL
    if params:
        url += "?" + "&".join(params)

    result = api_request("GET", url)
    print(json.dumps(result, indent=2, ensure_ascii=False))
    return result


def cmd_delete(args):
    """Cancel or delete a task."""
    url = f"{BASE_URL}/{args.task_id}"
    api_request("DELETE", url)
    print(f"Task {args.task_id} cancelled/deleted successfully.")


def parse_bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ("true", "1", "yes"):
        return True
    if v.lower() in ("false", "0", "no"):
        return False
    raise argparse.ArgumentTypeError(f"Boolean expected, got '{v}'")


def main():
    parser = argparse.ArgumentParser(description="Seedance Video Generation CLI")
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # create
    p_create = subparsers.add_parser("create", help="Create a video generation task")
    p_create.add_argument("--prompt", "-p", help="Text prompt describing the video")
    p_create.add_argument("--image", "-i", help="First frame image (URL or local file path)")
    p_create.add_argument("--last-frame", help="Last frame image (URL or local file path)")
    p_create.add_argument("--ref-images", nargs="+", help="Reference images for Lite I2V (1-4 URLs or paths)")
    p_create.add_argument("--draft-task-id", help="Draft task ID to generate final video from")
    p_create.add_argument("--model", "-m", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})")
    p_create.add_argument("--ratio", choices=["16:9", "4:3", "1:1", "3:4", "9:16", "21:9", "adaptive"], help="Aspect ratio")
    p_create.add_argument("--duration", "-d", type=int, help="Duration in seconds (4-12 for 1.5 Pro)")
    p_create.add_argument("--resolution", "-r", choices=["480p", "720p", "1080p"], help="Resolution")
    p_create.add_argument("--seed", type=int, help="Random seed (-1 for random)")
    p_create.add_argument("--camera-fixed", type=parse_bool, help="Fix camera position (true/false)")
    p_create.add_argument("--watermark", type=parse_bool, help="Add watermark (true/false)")
    p_create.add_argument("--generate-audio", type=parse_bool, help="Generate audio (true/false, 1.5 Pro only)")
    p_create.add_argument("--draft", type=parse_bool, help="Draft/preview mode (true/false, 1.5 Pro only)")
    p_create.add_argument("--return-last-frame", type=parse_bool, help="Return last frame URL (true/false)")
    p_create.add_argument("--service-tier", choices=["default", "flex"], help="Service tier")
    p_create.add_argument("--wait", "-w", action="store_true", help="Wait for completion after creating")
    p_create.add_argument("--interval", type=int, default=15, help="Poll interval in seconds (default: 15)")
    p_create.add_argument("--download", help="Download directory (e.g. ~/Desktop)")

    # status
    p_status = subparsers.add_parser("status", help="Query task status")
    p_status.add_argument("task_id", help="Task ID to query")

    # wait
    p_wait = subparsers.add_parser("wait", help="Wait for task completion")
    p_wait.add_argument("task_id", help="Task ID to wait for")
    p_wait.add_argument("--interval", type=int, default=15, help="Poll interval in seconds (default: 15)")
    p_wait.add_argument("--download", help="Download directory (e.g. ~/Desktop)")

    # list
    p_list = subparsers.add_parser("list", help="List video generation tasks")
    p_list.add_argument("--status", choices=["queued", "running", "cancelled", "succeeded", "failed", "expired"])
    p_list.add_argument("--page", type=int, default=1)
    p_list.add_argument("--page-size", type=int, default=10)

    # delete
    p_delete = subparsers.add_parser("delete", help="Cancel or delete a task")
    p_delete.add_argument("task_id", help="Task ID to cancel/delete")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(1)

    commands = {
        "create": cmd_create,
        "status": cmd_status,
        "wait": cmd_wait,
        "list": cmd_list,
        "delete": cmd_delete,
    }
    commands[args.command](args)


if __name__ == "__main__":
    main()


path: LICENSE.txt
content: 
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)