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

# Blur anything in a video with d1

> Describe what to hide in plain English and blur it in a video, with the hosted d1 decision model locating it frame by frame through the Liquid API.

> [card] [View Source Code](https://github.com/Liquid4All/cookbook/tree/main/examples/video-blur)
>
> Browse the complete example on GitHub

This example uses Liquid's hosted [decision model](https://docs.liquid.ai/lfm/models/decision-models.md) d1 to blur whatever you describe in a video, here everyone in swimwear. Streaming platforms can suspend streamers when nudity, or even swimwear, shows up on screen, and a check like this can run on every frame for about \$1 per hour of video with `d1.2`. It works for anything you can describe, such as license plates, faces, or logos.

d1 answers a `boxes` question on each sampled frame and returns a box around every match in a single call. There is no detector to train, and a few hundred lines of Python turn the per-frame boxes into smooth blurs. The 32-second demo clip takes 162 calls and costs about one cent.

![Video blur demo](https://mintcdn.com/liquidai/vI7Js-taYgPUtPmk/images/examples/hosted/video-blur/demo.gif?s=def831536e7c7f8ddee2c753a6020c86)

*Left: the original clip. Right: blurred with `d1.3-ultra`. The tutorial uses the cheaper `d1.2` by default. See the `--model` option in [step 4](#4-blur-the-clip). Clip: [People on Beach](https://www.pexels.com/video/people-on-beach-13361171/) by Fábio Reis de Abreu, [Pexels License](https://www.pexels.com/license/).*

## Prerequisites

You need the following to run this example:

* Python 3.10+ and [uv](https://docs.astral.sh/uv/getting-started/installation/)
* [ffmpeg](https://ffmpeg.org/download.html) (on macOS: `brew install ffmpeg`)
* Liquid API key (create one at [console.liquid.ai](https://console.liquid.ai) under **Dashboard > API Keys**)
* Video clip to blur (the demo uses [People on Beach](https://www.pexels.com/video/people-on-beach-13361171/) by Fábio Reis de Abreu, free to use under the [Pexels License](https://www.pexels.com/license/))

## Quickstart

### 1. Clone the repository

The code for this example is available in the Liquid AI cookbook repository. Clone it with:

```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
git clone https://github.com/Liquid4All/cookbook.git
cd cookbook/examples/video-blur
```

The project is structured as follows:

```
video-blur/
├── blur.py              # The pipeline: sample, ask d1, track, render
├── media/
│   └── demo.gif         # Before and after of the beach demo
├── .env.example         # Template for your API key
└── pyproject.toml
```

### 2. Add your API key

Copy the template and set `LIQUID_API_KEY` in the new `.env` file:

```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
cp .env.example .env
```

### 3. Download the demo clip

Download the beach clip from Pexels as `beach.mp4` into the `video-blur` folder:

```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -L -o beach.mp4 https://videos.pexels.com/video-files/13361171/13361171-hd_1920_1080_60fps.mp4
```

Alternatively, use your own clip instead. Any format that ffmpeg can read works.

### 4. Blur the clip

Blur everyone in swimwear and keep people in street clothes sharp:

```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
uv run --env-file .env blur.py beach.mp4 out.mp4 \
  --blur "Every man and every woman wearing only a swimsuit, a bikini, swim trunks or underwear, or less." \
  --keep "Every person wearing a t-shirt, a shirt, a dress or other street clothes."
```

The run prints the number of API calls, the tokens used, and the cost:

```
162 API calls, 468,666 tokens, $0.0094
99 tracks, 40 blurred
out.mp4: 1280x720, 1939 frames at 59.94 fps, 1939 with a blur
```

The script takes these options:

| Option | Default | Description |
| - | - | - |
| `--blur "..."` | | What to blur. Required. Repeat it to ask in several ways. |
| `--keep "..."` | | What stays sharp, even when a `--blur` question boxes it. Repeatable. |
| `--model` | `d1.2` | Hosted d1 model. See [d1 models](https://docs.liquid.ai/lfm/models/d1#models) for the current list. |
| `--fps` | `5` | Frames sent to the API per second of video. Raise it for fast motion. The cost grows with it. |

## How to build a video blur tool with decision models

The whole demo is a single Python file, `blur.py`. Its pipeline has five steps. Only step 2 calls the model. The other steps are geometry and video plumbing.

```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
flowchart TD
    V[Input video] --> S["1. Sample frames<br/>ffmpeg, 5 per second"]
    S -->|one request per frame| D["2. Ask d1 for boxes<br/>Liquid API"]
    D --> C["3. Choose boxes<br/>drop duplicates and keep matches"]
    C --> T["4. Link into tracks<br/>drop flicker, smooth"]
    T --> R["5. Render<br/>blur every frame"]
    V -->|all frames and audio| R
    R --> O[Blurred video]
```

### Step 1: Sample frames

Sending every frame of a 60 fps video would be slow and expensive, and objects barely move between neighboring frames. The `decisions()` function starts by asking ffmpeg for `--fps` frames per second (5 by default), saved as JPEG files in a temporary folder.:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def decisions(clip, opts, tmp):
    run("ffmpeg", "-v", "error", "-y", "-i", clip, "-vf", f"fps={opts.fps}", "-q:v", "2", tmp / "%06d.jpg")
    paths = sorted(Path(tmp).glob("*.jpg"))
    ...
```

The `decide()` function then opens each frame and shrinks it to at most 1280 pixels wide (`WIDTH`) before sending it. Image tokens scale with the pixel count, so a 1280-pixel frame costs about half as much as a full 1080p frame:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
def decide(path, opts):
    image = Image.open(path).convert("RGB")
    size = image.size
    if image.width > WIDTH:
        image = image.resize((WIDTH, round(image.height * WIDTH / image.width)))
    ...
```

### Step 2: Ask d1 for boxes

Each sampled frame goes to the decision API in a single request. Besides classification question types such as Noul, Choice, and Score, d1 has two question types that locate objects in a picture:

| Question type | What it returns | Example |
| - | - | - |
| **Box** | A box around one object, with the probability it's there | "The person wearing round glasses." |
| **Boxes** | A box around every instance, with a count | "Every license plate." |

This example uses **boxes**, since a frame can hold any number of things to blur. To build the request, the `questions()` function turns every `--blur` and `--keep` description into a named `boxes` question. The `ask()` function then posts the frame, Base64-encoded, and the questions to the Liquid API, and waits and retries if the API answers 429 (too many requests at once). For a full API reference, see the [d1 documentation](https://docs.liquid.ai/lfm/models/d1).

For the beach demo, each request looks like this (the Base64 image is shortened):

```sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl https://api.liquid.ai/decisions/v1/systemone \
  -H "Authorization: Bearer $LIQUID_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "d1.2",
    "images": ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."],
    "questions": {
      "blur0": {
        "type": "boxes",
        "max": 32,
        "instructions": "Every man and every woman wearing only a swimsuit, a bikini, swim trunks or underwear, or less."
      },
      "keep0": {
        "type": "boxes",
        "max": 32,
        "instructions": "Every person wearing a t-shirt, a shirt, a dress or other street clothes."
      }
    }
  }'
```

The API returns one answer per question, each with a list of boxes (shortened, with illustrative values):

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "answers": {
    "blur0": {
      "type": "boxes",
      "boxes": [
        {"box": {"top": 0.47, "bottom": 0.74, "left": 0.33, "right": 0.47}, "found": 1, "confidence": 0.71},
        {"box": {"top": 0.45, "bottom": 0.68, "left": 0.86, "right": 0.91}, "found": 1, "confidence": 0.64}
      ],
      "count": 2,
      "at_least": false
    },
    "keep0": {"type": "boxes", "boxes": ["..."], "count": 2}
  },
  "usage": {"input_tokens": 2893, "cost": 0.000058}
}
```

Box edges are fractions of the frame's width (`left`, `right`) and height (`top`, `bottom`), measured from the top-left corner. As a result, the same box works on the downscaled frame sent to the API and on the full-resolution frame you blur.

The model answers all the questions in one call, and the image is billed only once per request. Adding a second `--blur` with another wording therefore costs only the extra question's tokens. It can catch objects that one wording misses, but test it: a broader wording such as "Every person close to the camera …" can also return one box around two people sitting side by side.

The frames are independent, so `decisions()` sends them in parallel, 16 at a time (`WORKERS`).

### Step 3: Choose the boxes to blur in each frame

The `chosen()` function merges the answers from step 2 into the final list of boxes to blur for that frame. It goes through the `blur` boxes from largest to smallest and drops a box when:

* **It's a speck.** The box is under 6 pixels wide or tall.
* **It's a duplicate.** The box overlaps a box that's already kept, usually because two `--blur` wordings found the same thing, or the model returned two boxes for one person.
* **A `--keep` question boxed it.** The box overlaps a box from a `--keep` question.

Two boxes count as the same object when their [intersection over union](https://en.wikipedia.org/wiki/Jaccard_index) (IoU) is high, or when most of the smaller box lies inside the larger one:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
if any(iou(b, o) >= 0.45 or overlap(b, o) / max(1e-9, area(b)) >= 0.8 for o in out):
    continue
```

Use `--keep` as a counterweight. A broad `--blur` description has good recall but also boxes some things you want to leave sharp. A `--keep` description of those things removes them without making the `--blur` wording narrower.

### Step 4: Link boxes into tracks

Per-frame boxes flicker: an object found in four frames is sometimes missed in the fifth, and a spurious box can appear for one frame. Blurring the raw boxes would flash on and off. The `linked()` function connects the boxes across frames into one track per object:

1. Each live track predicts where its object is in the current frame from its last box and its velocity.
2. Every pair of track and new box gets a score, its IoU with the prediction. A box that moved past its predicted position still matches if it's nearby and about as tall.
3. Pairs are matched greedily from the best score down. Unmatched boxes start new tracks, and a track unseen for more than `GAP` (0.5 seconds) ends.

The `smoothed()` function then keeps a track only if it's reliable:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
SEEN = 0.5  # share of the sampled frames a track spans in which it must be seen
SIGHTINGS = 3  # and the fewest times it must be seen
```

A track seen fewer than 3 times, or in fewer than half of the frames it spans, is a false positive and is dropped. The tracks that pass have their box centers and sizes averaged over neighboring sightings, which removes jitter.

### Step 5: Render the blurred video

The output keeps the original frame rate, so most output frames fall between two sampled frames. For each output frame, the `at()` function interpolates every track's box linearly between its two nearest sightings. It also starts the blur slightly before the first sighting (`PRE`) and holds it after the last one (`POST`), fading in and out over `FADE` seconds:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
PRE, POST, FADE = 0.12, 0.3, 0.12  # seconds: blur before the first sighting, after the last, fade at each end
```

The `paint()` function builds the blur by downscaling the frame 14×, blurring it, and scaling it back up. It then pastes this blurred frame through a mask of rounded rectangles, padded slightly around each box and feathered at the edges. Finally, `render()` streams raw frames from ffmpeg, paints them in a thread pool, and pipes them back into ffmpeg to encode H.264, copying the original audio track.

## Limits

* **It processes a finished clip.** Tracking looks ahead and behind in time, so the script reads the whole clip before it renders. For a live stream, you would need to process the video in short chunks and add a delay of about a second.
* **Cost grows with the clip.** It grows linearly with `--fps`, the number of questions, and the clip length, and the frame size sets the image tokens per call. See [Image Token Usage](https://docs.liquid.ai/lfm/models/d1#image-token-usage) for the formula.
* **The sampled frames are sent to the Liquid API.** To keep footage on your machine, run an open-weight decision model such as [d1-2B](https://docs.liquid.ai/lfm/models/d1-2b) locally. It also answers `boxes` questions, but you need to replace the API call in `ask()`.

## Need help?

> [card] [Join our Discord](https://discord.gg/DFU3WQeaYD)
>
> Connect with the community and ask questions about this example.


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