> ## 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.

# Chess Match Montage Generator

> Automatically create highlight reels from long chess matches with AI-powered move detection

<a href="https://colab.research.google.com/github/video-db/videodb-cookbook/blob/main/editor/creative/chess_montage.ipynb" target="_blank">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" noZoom />
</a>

## The Challenge

A chess match can last 4+ hours. As a content creator, you want to turn that into a punchy highlight reel, but manually scrubbing through and identifying key moments is tedious.

What if AI could watch the entire match, detect every move, and automatically compile a highlight montage?

## What You'll Build

Turn a long chess match into a **punchy highlight reel** — automatically! You'll:

1. Upload chess video + background music
2. Index scenes with simple move detection
3. Extract timestamps automatically using AI
4. Build a montage with transitions and effects
5. Output a professional highlight reel

All powered by **VideoDB's Editor SDK** — no manual frame-by-frame editing needed.

## Setup

### Install Dependencies

```bash theme={null}
pip install videodb
```

### Connect to VideoDB

```python theme={null}
import videodb

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

## Implementation

### Step 1: Upload Chess Video and Music

```python theme={null}
from videodb import MediaType

# Upload the chess match video
chess_video = coll.upload(url="https://www.youtube.com/watch?v=dhDe-RcoyAU")

# Upload background music for the montage
bg_music = coll.upload(
    url="https://www.youtube.com/watch?v=S19UcWdOA-I",
    media_type=MediaType.audio
)
```

### Step 2: Analyze Scenes with Structured Move Detection

Analyze the video in eight-second segments with a **strict binary prompt**. Each scene returns `move_status` as exactly `Player Moved` when a chess move is evidenced across the sampled frames, or `No Move` otherwise.

```python theme={null}
print("Analyzing scenes for move detection...")

moves_understanding = chess_video.understand(
    segmentation={"type": "time", "seconds": 8},
    analyzers=[
        {
            "type": "vlm",
            "name": "move_detection",
            "sampling": {
                "strategy": "uniform",
                "frame_count": 5,
            },
            "config": {
                "prompt": """Look at this chess scene and focus on the chess board. Your task is to detect when pieces are moved.

Set move_status to exactly "Player Moved" only when a chess move is evidenced across the sampled frames. Otherwise, set move_status to exactly "No Move" (same position, paused, talking, etc.).

Be strict. Only set move_status to "Player Moved" if you clearly see a chess piece moved.""",
                "schema": {
                    "move_status": "string",
                },
            },
        },
    ],
)
moves_understanding.wait_until_complete()

moves_analyzer = moves_understanding.get_analyzer("move_detection")
```

### View the Structured Move Detections

```python theme={null}
import json

moves_output = moves_analyzer.get_output()
moves_scenes = moves_output.get("scenes", [])
print(json.dumps(moves_scenes, indent=2))
```

### Step 3: Extract Move Timestamps

```python theme={null}
timestamps = [
    scene["start"]
    for scene in moves_scenes
    if "move_status" in scene["data"] and scene["data"]["move_status"] == "Player Moved"
]

print("✓ Move timestamps extracted!")
```

### Review the Timestamps

```python theme={null}
print(f"✓ Found {len(timestamps)} moves")
print(f"Timestamps: {timestamps}")
```

Initialize timeline and sample moves:

```python theme={null}
from videodb.editor import (
    Timeline, Track, Clip, VideoAsset, AudioAsset,
    Filter, Transition, TextAsset, Font
)

CLIP_DURATION = 5  # seconds per clip
TARGET_CLIPS = 10  # how many clips we want

# Sample timestamps evenly
total_detected = len(timestamps)
step = max(1, total_detected // TARGET_CLIPS)
sampled_timestamps = timestamps[::step][:TARGET_CLIPS]

# Initialize timeline
timeline = Timeline(conn)
timeline.background = "#000000"

# Create intro text
intro_text = TextAsset(
    text="Let the Match Begin",
    font=Font(family="Clear Sans", size=56, color="#FFFFFF"),
)

intro_clip = Clip(
    asset=intro_text,
    duration=3,
    transition=Transition(in_="fade", out="fade", duration=0.5)
)

intro_track = Track()
intro_track.add_clip(0, intro_clip)
timeline.add_track(intro_track)
```

### Step 5: Add Video Clips with Transitions

```python theme={null}
# Add video clips
video_track = Track()
timeline_position = 3

for i, start_time in enumerate(sampled_timestamps):
    clip = Clip(
        asset=VideoAsset(
            id=chess_video.id,
            start=start_time-1,
            volume=0  # Muting the original audio
        ),
        duration=CLIP_DURATION,
        filter=Filter.contrast,
        transition=Transition(in_="fade", out="fade", duration=1)
    )

    video_track.add_clip(timeline_position, clip)
    timeline_position += CLIP_DURATION

timeline.add_track(video_track)

total_duration = len(sampled_timestamps) * CLIP_DURATION + 3
```

### Step 6: Add Background Music

```python theme={null}
# Add music track
music_clip = Clip(
    asset=AudioAsset(
        id=bg_music.id,
        start=0,
        volume=0.7
    ),
    duration=total_duration
)

audio_track = Track()
audio_track.add_clip(0, music_clip)
timeline.add_track(audio_track)
```

### Step 7: Render Montage

```python theme={null}
# Generate final montage stream
stream_url = timeline.generate_stream()
```

## What You Get

A professional highlight reel with:

* AI-detected key moves
* Evenly sampled clips for pacing
* Smooth fade transitions
* Enhanced contrast for visual impact
* Background music
* Professional polish in seconds

Here's the final chess montage:

<iframe className="w-full aspect-video rounded-xl" src="https://play.videodb.io/v1/e66a4b69-251b-4a83-aba9-dd4c254b2060.m3u8" title="Chess Match Highlight Montage" allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />

## Perfect For

* **Tournament Highlights** - Post-tournament recap videos
* **Streamer Clips** - Highlight reels for streaming communities
* **Educational Analysis** - Study videos from master games
* **Social Media** - Short-form clips from longer matches
* **Archive Content** - Transform library of matches into reels

## The Result

What took hours of manual editing now takes minutes. Your audience gets punchy, professional highlight reels. You get back your time.

No more endless scrubbing. Just AI-powered chess analysis and automatic montages.

<Card icon="notebook" title="Explore the Full Notebook" href="https://colab.research.google.com/github/video-db/videodb-cookbook/blob/main/editor/creative/chess_montage.ipynb">
  Open the complete implementation with advanced filtering, custom transitions, and batch processing.
</Card>

## Related Tutorials

<CardGroup cols={2}>
  <Card title="Intro & Outro" icon="play" href="/examples-and-tutorials/programmatic-editing/intro-outro">
    Auto-add opening and closing sequences
  </Card>

  <Card title="Word Counter" icon="hash" href="/examples-and-tutorials/programmatic-editing/word-counter">
    Add analytical text overlays
  </Card>
</CardGroup>
