> ## Documentation Index
> Fetch the complete documentation index at: https://docs.videodb.io/llms.txt
> Use this file to discover all available pages before exploring further.

# AI-Generated Ads

> Generate professional product advertisements from raw footage

> **Automatically Creating a professional quality advertisement from product videography B-Roll**

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/video-db/videodb-cookbook/blob/main/examples/Voiceover_Ad_Films.ipynb)

## Overview

Creating professional product advertisements typically requires a team: copywriters for the script, voice actors for the narration, and editors to stitch it all together.

**VideoDB** streamlines this into a single, automated workflow.

In this tutorial, we will:

1. **Upload** raw product footage (a jewelry shoot).
2. **Analyze** the visual content automatically.
3. **Generate** a professional ad script based on the visuals.
4. **Synthesize** a high-quality voiceover.
5. **Publish** the final commercial.

## Setup

### Installing VideoDB

```python Python theme={null}
!pip install videodb
```

```javascript Node.js theme={null}
npm install videodb
```

### API Key

> [!NOTE]
>
> You only need your VideoDB API Key. Get your API key from [VideoDB Console](https://console.videodb.io/auth?utm_source=docs_videodb_io\&utm_medium=docs_link\&utm_campaign=console_auth\&utm_content=docs_link\&id=docs). Free for first 50 uploads, no credit card required.

## Implementation

### Step 1: Connect to VideoDB

Establish a connection to your VideoDB project.

```python Python theme={null}
import videodb

# Set your API key
api_key = "your_api_key"

# Connect to VideoDB
conn = videodb.connect(api_key=api_key)
coll = conn.get_collection()
```

```javascript Node.js theme={null}
import { connect } from 'videodb';

// Connect to VideoDB
const conn = await connect({ apiKey: process.env.VIDEO_DB_API_KEY });
const coll = await conn.getCollection();
```

### Step 2: Upload Product Footage

We'll upload a raw video clip of a jewelry product shoot from YouTube.

```python Python theme={null}
# Upload a video by URL
video = coll.upload(url='https://www.youtube.com/watch?v=2DcAMbmmYNM')
```

```javascript Node.js theme={null}
// Upload a video by URL
const video = await coll.uploadURL({ url: 'https://www.youtube.com/watch?v=2DcAMbmmYNM' });
```

### Step 3: Analyze Visuals

To write a relevant script, we first need to understand what's in the video. The analyzer creates detailed timestamped descriptions of the visual content.

```python Python theme={null}
print("Analyzing visual scenes... this might take a moment.")

scene_understanding = video.understand(
    analyzers=[
        {
            "type": "vlm",
            "name": "scene",
            "config": {
                "prompt": "Describe the scene in detail, focusing on the product, craftsmanship, lighting, camera movement, and mood.",
                "schema": {
                    "scene_description": "string",
                },
            },
        },
    ],
)
scene_understanding.wait_until_complete()

scene_analyzer = scene_understanding.get_analyzer("scene")
```

```javascript Node.js theme={null}
const sceneUnderstanding = await video.understand([
    {
        type: "vlm",
        name: "scene",
        config: {
            prompt: "Describe the scene in detail, focusing on the product, craftsmanship, lighting, camera movement, and mood.",
            schema: {
                scene_description: "string",
            },
        },
    },
]);
await sceneUnderstanding.waitUntilComplete();

const sceneAnalyzer = await sceneUnderstanding.getAnalyzer("scene");
```

Let's view the descriptions of the first three scenes from the video.

```python Python theme={null}
import json

scene_output = scene_analyzer.get_output()

scenes = [
    {
        "start": scene["start"],
        "end": scene["end"],
        "description": scene["data"]["scene_description"],
    }
    for scene in scene_output["scenes"]
]

print(json.dumps(scenes[:3], indent=2))
```

```javascript Node.js theme={null}
const sceneOutput = await sceneAnalyzer.getOutput();
const scenes = sceneOutput.scenes.map((scene) => ({
    start: scene.start,
    end: scene.end,
    description: scene.data.scene_description,
}));

console.log(JSON.stringify(scenes.slice(0, 3), null, 2));
```

### Step 4: Generate Ad Script

Now we use VideoDB's text generation to write the commercial. We feed the visual descriptions into the prompt to ensure the script perfectly matches the mood of the footage.

```python Python theme={null}
# Construct a prompt with the scene context
scene_context = "\n".join([f"- {scene['description']}" for scene in scenes])

prompt = f"""
Here is a visual description of a jewelry product video:
{scene_context}

Write a short, elegant, and luxurious voiceover script for this video advertisement.
- Tone: Sophisticated, calming, premium.
- Length: Short (approx 20 seconds of speech).
- Content: Focus on beauty, craftsmanship, and elegance.
- Format: Return ONLY the raw narration text.
"""

# Generate script
text_response = coll.generate_text(
    prompt=prompt,
    model_name="pro")

ad_script = text_response["output"]

print("--- Generated Ad Script ---")
print(ad_script)
```

```javascript Node.js theme={null}
// Construct a prompt with the scene context
const sceneContext = scenes.map(scene => `- ${scene.description}`).join('\n');

const prompt = `
Here is a visual description of a jewelry product video:
${sceneContext}

Write a short, elegant, and luxurious voiceover script for this video advertisement.
- Tone: Sophisticated, calming, premium.
- Length: Short (approx 20 seconds of speech).
- Content: Focus on beauty, craftsmanship, and elegance.
- Format: Return ONLY the raw narration text.
`;

// Generate script
const adScriptResult = await coll.generateText(prompt, "pro", "text");
const adScript = typeof adScriptResult === "string"
    ? adScriptResult
    : adScriptResult.output;

if (typeof adScript !== "string") {
    throw new Error("Expected a text response for the ad script.");
}

console.log("--- Generated Ad Script ---");
console.log(adScript);
```

### Step 5: Generate Voiceover

We'll turn the script into audio.

```python Python theme={null}
# Generate speech directly as a VideoDB Audio Asset
audio = coll.generate_voice(
    text=ad_script,
    voice_name="Default")
```

```javascript Node.js theme={null}
// Generate speech directly as a VideoDB Audio Asset
import { Audio, GenerationJob } from 'videodb';

const audioCandidate = await coll.generateVoice(
    adScript,
    "Default"
);
const audio = audioCandidate instanceof GenerationJob
    ? await audioCandidate.wait()
    : audioCandidate;

if (!(audio instanceof Audio)) {
    throw new Error("Expected generated voice audio.");
}
```

### Step 6: Compose the Advertisement

We'll overlay the generated voiceover onto the original video using the Timeline editor.

```python Python theme={null}
from videodb.editor import Timeline, Track, Clip, VideoAsset, AudioAsset

# Create a timeline
timeline = Timeline(conn)

# 1. Video Track (Background)
video_track = Track()
video_asset = VideoAsset(id=video.id)
video_clip = Clip(asset=video_asset, duration=float(video.length))
video_track.add_clip(0, video_clip)
timeline.add_track(video_track)

# 2. Audio Track (Voiceover Overlay)
audio_track = Track()
audio_asset = AudioAsset(id=audio.id)
audio_clip = Clip(asset=audio_asset, duration=float(audio.length))
audio_track.add_clip(0, audio_clip)
timeline.add_track(audio_track)
```

```javascript Node.js theme={null}
import { EditorTimeline, Track, Clip, EditorVideoAsset, EditorAudioAsset } from 'videodb';

// Create a timeline
const timeline = new EditorTimeline(conn);

// 1. Video Track (Background)
const videoTrack = new Track();
const videoAsset = new EditorVideoAsset({ id: video.id });
const videoClip = new Clip({ asset: videoAsset, duration: parseFloat(video.length) });
videoTrack.addClip(0, videoClip);
timeline.addTrack(videoTrack);

// 2. Audio Track (Voiceover Overlay)
const audioTrack = new Track();
const audioAsset = new EditorAudioAsset({ id: audio.id });
const audioClip = new Clip({ asset: audioAsset, duration: parseFloat(audio.length) });
audioTrack.addClip(0, audioClip);
timeline.addTrack(audioTrack);
```

### Step 7: Review and Share

Generate the stream URL to watch your AI-created commercial.

```python Python theme={null}
from videodb import play_stream

stream_url = timeline.generate_stream()
play_stream(stream_url)
```

```javascript Node.js theme={null}
const streamUrl = await timeline.generateStream();
console.log(streamUrl);
```

**Output:**

[AI-Generated Product Advertisement](https://www.youtube.com/embed/NPvxczplmW0)

### Conclusion

You have successfully automated the production of a product advertisement.

By replacing multiple external tools with VideoDB's unified SDK, you can now build scalable video generation engines that turn raw footage into polished content automatically.

> [card] [Explore Full Notebook](https://colab.research.google.com/github/video-db/videodb-cookbook/blob/main/examples/Voiceover_Ad_Films.ipynb)
>
> Open the complete implementation in Google Colab with all code examples.

## Related Tutorials

> [card] [Faceless Video Creator](https://docs.videodb.io/examples-and-tutorials/content-factory/faceless-video-creator.md)
>
> Generate complete videos from scripts without camera

> [card] [AI Voiceovers](https://docs.videodb.io/examples-and-tutorials/content-factory/voiceovers.md)
>
> Add professional narration to silent footage


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.