# Text to video

Make a clip from words alone, and save it.

1. [Write the prompt](#1-write-the-prompt): what is seen, what moves, where, how it is filmed.
2. [Run the job](#2-run-the-job): send it, ask until it ends, save the clip.
3. [Read how it ended](#3-read-how-it-ended).
4. [Read what it cost](#4-read-what-it-cost).

## 1. Write the prompt

A video model reads the prompt as a shot list. Name each of these, and the clip comes back closer to what you had in mind.

| Part | Says | Example |
|---|---|---|
| Subject | who or what is in the frame | a baker in Tlemcen |
| Action | what moves | lifts a tray of makrout from a wood oven |
| Setting | the place, the hour, the light | warm morning light |
| Camera | the shot and its movement | close-up, slow push-in |
| Style | the look | documentary, natural colour |

<div class="dont">
<p>Send <code>a bakery</code>. The model fills every gap on its own, and each run fills them differently.</p>
</div>
<div class="do">
<p>Send <code>A baker in Tlemcen lifts a tray of makrout from a wood oven, close-up, warm morning light, slow push-in</code>.</p>
</div>

## 2. Run the job

A clip takes minutes to make, so [`POST /v1/videos`](/docs/reference/videos) answers at once with a job, not the clip. The code below sends the job, asks every ten seconds until it ends, then saves the clip as `makrout.mp4` or prints why there is none.

The model is `alibaba/wan-3.0`, asked for 6 seconds at `720p` in `9:16` with sound: a phone story. Another model takes other values: [Choose a video model](/docs/cookbook/choose-a-video-model).

```python
import json
import os
import time
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/videos"
MODEL = "alibaba/wan-3.0"
PROMPT = (
    "A baker in Tlemcen lifts a tray of makrout from a wood oven, "
    "close-up, warm morning light, slow push-in"
)


def call(url, body=None):
    request = urllib.request.Request(
        url,
        data=json.dumps(body).encode() if body else None,
        headers={
            "Authorization": "Bearer " + API_KEY,
            "Content-Type": "application/json",
        },
    )
    return urllib.request.urlopen(request)


with call(
    ADDRESS,
    {
        "model": MODEL,
        "prompt": PROMPT,
        "duration": 6,
        "resolution": "720p",
        "aspect_ratio": "9:16",
        "generate_audio": True,
    },
) as response:
    job = json.load(response)

while job["status"] in ("pending", "in_progress"):
    time.sleep(10)
    with call(ADDRESS + "/" + job["id"]) as response:
        job = json.load(response)

if job["status"] == "completed":
    print("charged", job["usage"]["cost"], "DA")
    clip_address = ADDRESS + "/" + job["id"] + "/content?index=0"
    with call(clip_address) as response:
        with open("makrout.mp4", "wb") as clip:
            clip.write(response.read())
else:
    print(job["status"], job.get("error"))
```

```javascript
import { writeFile } from "node:fs/promises";

const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/videos";
const MODEL = "alibaba/wan-3.0";
const PROMPT =
  "A baker in Tlemcen lifts a tray of makrout from a wood oven, " +
  "close-up, warm morning light, slow push-in";

const headers = {
  Authorization: `Bearer ${API_KEY}`,
  "Content-Type": "application/json",
};

let response = await fetch(ADDRESS, {
  method: "POST",
  headers,
  body: JSON.stringify({
    model: MODEL,
    prompt: PROMPT,
    duration: 6,
    resolution: "720p",
    aspect_ratio: "9:16",
    generate_audio: true,
  }),
});
let job = await response.json();

while (["pending", "in_progress"].includes(job.status)) {
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  response = await fetch(`${ADDRESS}/${job.id}`, { headers });
  job = await response.json();
}

if (job.status === "completed") {
  console.log("charged", job.usage.cost, "DA");
  const clip = `${ADDRESS}/${job.id}/content?index=0`;
  response = await fetch(clip, { headers });
  await writeFile("makrout.mp4", Buffer.from(await response.arrayBuffer()));
} else {
  console.log(job.status, job.error);
}
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

const (
	address = "https://opendunes.com/v1/videos"
	model   = "alibaba/wan-3.0"
	prompt  = "A baker in Tlemcen lifts a tray of makrout from a wood " +
		"oven, close-up, warm morning light, slow push-in"
)

var apiKey = os.Getenv("OPENDUNES_API_KEY")

type job struct {
	ID     string `json:"id"`
	Status string `json:"status"`
	Error  any    `json:"error"`
	Usage  *struct {
		Cost float64 `json:"cost"`
	} `json:"usage"`
}

func call(method, url string, body io.Reader) *http.Response {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	return res
}

func decode(res *http.Response) job {
	defer res.Body.Close()
	var j job
	if err := json.NewDecoder(res.Body).Decode(&j); err != nil {
		panic(err)
	}
	return j
}

func main() {
	body, err := json.Marshal(map[string]any{
		"model":          model,
		"prompt":         prompt,
		"duration":       6,
		"resolution":     "720p",
		"aspect_ratio":   "9:16",
		"generate_audio": true,
	})
	if err != nil {
		panic(err)
	}

	j := decode(call("POST", address, bytes.NewReader(body)))
	for j.Status == "pending" || j.Status == "in_progress" {
		time.Sleep(10 * time.Second)
		j = decode(call("GET", address+"/"+j.ID, nil))
	}

	if j.Status != "completed" {
		fmt.Println(j.Status, j.Error)
		return
	}
	if j.Usage != nil {
		fmt.Println("charged", j.Usage.Cost, "DA")
	}

	res := call("GET", address+"/"+j.ID+"/content?index=0", nil)
	defer res.Body.Close()
	clip, err := os.Create("makrout.mp4")
	if err != nil {
		panic(err)
	}
	defer clip.Close()
	if _, err := io.Copy(clip, res.Body); err != nil {
		panic(err)
	}
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/videos"
MODEL="alibaba/wan-3.0"
PROMPT="A baker in Tlemcen lifts a tray of makrout from a wood oven,"
PROMPT="$PROMPT close-up, warm morning light, slow push-in"

job=$(curl -s "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "prompt": "'"$PROMPT"'",
    "duration": 6,
    "resolution": "720p",
    "aspect_ratio": "9:16",
    "generate_audio": true
  }' | grep -o '"id":"[^"]*"' | cut -d '"' -f 4)

status=pending
while [ "$status" = pending ] || [ "$status" = in_progress ]; do
  sleep 10
  status=$(curl -s "$ADDRESS/$job" \
    -H "Authorization: Bearer $OPENDUNES_API_KEY" \
    | grep -o '"status":"[^"]*"' | cut -d '"' -f 4)
done
echo "$status"

if [ "$status" = completed ]; then
  curl -s "$ADDRESS/$job/content?index=0" \
    -H "Authorization: Bearer $OPENDUNES_API_KEY" \
    -o makrout.mp4
fi
```

| You send | Holds |
|---|---|
| `model` | a video model's ID |
| `prompt` | the words from step 1 |
| `duration` | the seconds of video, a whole number the model lists |
| `resolution` | the size, as the model offers |
| `aspect_ratio` | the frame's shape, as the model offers |
| `generate_audio` | `true` for a clip with sound, on a model that makes it |

The clip's address is not a public link: call it with your API key, as the code does. Asking and fetching are free, however often. Each route in full: [Clip status](/docs/reference/videos-id) · [Clip download](/docs/reference/videos-content).

<div class="good-to-know">
<p>Asking every ten seconds is one way to wait. A <code>callback_url</code> gets the job's end posted to your server instead: <a href="/docs/cookbook/video-webhooks">Video webhooks</a>.</p>
</div>

## 3. Read how it ended

`pending` and `in_progress` mean the job is still running. The other four are the end, and the job never moves again.

| Status | You get |
|---|---|
| `completed` | the clip, at `/v1/videos/{id}/content?index=0`, and the charge in `usage.cost` |
| `failed` | no clip; `error` holds the provider's reason |
| `cancelled` | no clip: the job was cancelled |
| `expired` | no clip: the job lapsed before a clip was made |

On `failed`, read `error`, change what it names, and send the job again: the failed one charged nothing.

## 4. Read what it cost

The clip is charged in DA from your balance once, when the job reports `completed`: its seconds, at the rate of the variant the request picked, its `resolution` and, on some models, `generate_audio`. The completed answer's `usage.cost` carries the charge, the number the code prints.

Sending the job holds its most from that moment, and the charge is taken when the clip is delivered. A job that ends `failed`, `cancelled` or `expired` charges nothing and gives the hold back. The model's rate per second is on its page in *Models*. How a charge leaves your balance: [Balance and charges](/docs/balance-and-charges).
