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

# Video Analysis

> AI-powered video and advertisement analysis

## Overview

The Video Analysis API provides comprehensive analysis of videos and advertisements, measuring emotional, cognitive, behavioral, and technical metrics. Perfect for optimizing ad creatives, understanding viewer engagement, and improving video content.

## Before You Start

Video analysis requires a **video file** that has been uploaded to Mavera. You cannot analyze a file that lives only on your local machine or a third-party URL. The flow is:

<Steps>
  <Step title="Upload the video">
    Use the [Files API](/features/files) to upload your video. Follow the presigned URL flow: `POST /files/upload-url` → `PUT` to the upload URL → `POST /files` to create the record. You receive a **file ID** (this becomes `asset_id`).
  </Step>

  <Step title="Create the analysis">
    Call `POST /video-analyses` with `asset_id`, plus goal, brand, product, and analysis settings.
  </Step>

  <Step title="Poll for completion">
    Analysis runs asynchronously. Poll `GET /video-analyses/{id}` every 15–30 seconds until `status` is `COMPLETED`. Typical runtime: 2–10 minutes depending on video length.
  </Step>

  <Step title="Read results and optionally chat">
    Use `results.full_video_metrics` and `results.chunks` for metrics. Use `POST /video-analyses/{id}/chat` to ask natural-language questions about the analysis.
  </Step>
</Steps>

<Info>
  For a full walkthrough including upload code, see [Tutorial: Video Ad Analysis](/tutorials/video-ad-analysis).
</Info>

## Key Metrics

<CardGroup cols={2}>
  <Card title="Emotional" icon="heart">
    Sentiment, emotional triggers, mood progression
  </Card>

  <Card title="Cognitive" icon="brain">
    Attention, comprehension, memory encoding
  </Card>

  <Card title="Behavioral" icon="bullseye">
    Call-to-action effectiveness, engagement drivers
  </Card>

  <Card title="Technical" icon="video">
    Pacing, visual quality, audio analysis
  </Card>
</CardGroup>

## Creating an Analysis

```python theme={"dark"}
import requests

response = requests.post(
    "https://app.mavera.io/api/v1/video-analyses",
    headers={"Authorization": "Bearer mvra_live_your_key_here"},
    json={
        "title": "Q1 Product Ad Analysis",
        "asset_id": "asset_video_123",  # Your uploaded video
        "goal": "Analyze viewer engagement and emotional response",
        "brand": "Your Brand",
        "product": "Product Name",
        "primary_intent": "Drive product awareness",
        "chunk_duration": 5,  # Analyze in 5-second chunks
        "frames_per_chunk": 3,
        "workspace_id": "your_workspace_id"
    }
)

analysis = response.json()
print(f"Analysis ID: {analysis['id']}")
print(f"Status: {analysis['status']}")
```

## Retrieving Results

Analysis runs asynchronously. Poll `GET /video-analyses/{id}` until `status` is `COMPLETED`.

### Polling Pattern

<CodeGroup>
  ```python Python theme={"dark"}
  import time

  def wait_for_completion(analysis_id, max_wait_minutes=15):
      for _ in range(max_wait_minutes * 4):
          resp = requests.get(
              f"https://app.mavera.io/api/v1/video-analyses/{analysis_id}",
              headers={"Authorization": "Bearer mvra_live_your_key_here"}
          )
          data = resp.json()
          if "error" in data:
              raise Exception(data["error"]["message"])
          if data.get("status") == "COMPLETED":
              return data
          time.sleep(15)
      raise TimeoutError("Analysis did not complete in time")
  ```

  ```javascript JavaScript theme={"dark"}
  async function waitForCompletion(analysisId, maxWaitMinutes = 15) {
    for (let i = 0; i < maxWaitMinutes * 4; i++) {
      const resp = await fetch(
        `https://app.mavera.io/api/v1/video-analyses/${analysisId}`,
        { headers: { Authorization: "Bearer mvra_live_your_key_here" } }
      );
      const data = await resp.json();
      if (data.error) throw new Error(data.error.message);
      if (data.status === "COMPLETED") return data;
      await new Promise((r) => setTimeout(r, 15000));
    }
    throw new Error("Analysis did not complete");
  }
  ```
</CodeGroup>

### Reading Metrics

```python theme={"dark"}
result = wait_for_completion(analysis_id)
metrics = result["results"]["full_video_metrics"]
print(f"Overall Score: {metrics['overall_score']}/100")
print(f"Emotional Impact: {metrics['emotional_impact']}/10")
print(f"Attention Score: {metrics['attention_score']}/10")

for chunk in result["results"]["chunks"]:
    print(f"Timestamp {chunk['start_time']}-{chunk['end_time']}:")
    print(f"  Engagement: {chunk['engagement_score']}")
    print(f"  Key Moments: {chunk['key_moments']}")
```

## Chat About Results

Ask natural-language questions about your completed analysis. The chat endpoint has full context of the metrics and chunks.

<CodeGroup>
  ```python Python theme={"dark"}
  response = requests.post(
      f"https://app.mavera.io/api/v1/video-analyses/{analysis_id}/chat",
      headers={"Authorization": "Bearer mvra_live_your_key_here"},
      json={
          "message": "What are the weakest moments in this video and how can I improve them?"
      }
  )

  data = response.json()
  if "error" not in data:
      print(data.get("content", ""))
  ```

  ```javascript JavaScript theme={"dark"}
  const resp = await fetch(
    `https://app.mavera.io/api/v1/video-analyses/${analysisId}/chat`,
    {
      method: "POST",
      headers: {
        Authorization: "Bearer mvra_live_your_key_here",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        message: "What are the weakest moments and how can I improve them?",
      }),
    }
  );
  const data = await resp.json();
  if (!data.error) console.log(data.content);
  ```
</CodeGroup>

Example questions:

* "What are the weakest moments in this video and how can I improve them?"
* "Which segment has the best emotional impact?"
* "Summarize the top 3 recommendations for the next version."

## Response Format

```json theme={"dark"}
{
  "id": "va_abc123",
  "title": "Q1 Product Ad Analysis",
  "status": "COMPLETED",
  "results": {
    "full_video_metrics": {
      "overall_score": 78,
      "emotional_impact": 8.2,
      "attention_score": 7.5,
      "brand_recall_likelihood": 0.72,
      "cta_effectiveness": 6.8
    },
    "chunks": [
      {
        "start_time": 0,
        "end_time": 5,
        "engagement_score": 8.5,
        "emotional_valence": "positive",
        "key_moments": ["Strong opening hook"],
        "recommendations": []
      }
    ],
    "recommendations": [
      "Consider shortening the middle section",
      "Add stronger CTA at 0:45"
    ]
  },
  "usage": {
    "credits_used": 250
  }
}
```

## Credit Costs

| Video Length  | Approximate Cost |
| ------------- | ---------------- |
| \< 30 seconds | 100-150 credits  |
| 30s - 1 min   | 150-250 credits  |
| 1-3 minutes   | 250-400 credits  |
| 3+ minutes    | 400+ credits     |

## Best Practices

<AccordionGroup>
  <Accordion title="Use short clips for iteration">
    Start with 15–60 second clips to iterate quickly. Longer videos use more credits and take longer to process.
  </Accordion>

  <Accordion title="Provide context (goal, brand, product)">
    The `goal`, `brand`, and `primary_intent` parameters improve relevance of metrics and recommendations.
  </Accordion>

  <Accordion title="Adjust chunk_duration">
    Shorter chunks (e.g. 3–5 seconds) give finer granularity; longer chunks (e.g. 10 seconds) reduce processing time.
  </Accordion>

  <Accordion title="Compare creatives">
    Run multiple analyses and compare `overall_score`, `emotional_impact`, and `cta_effectiveness` across variants.
  </Accordion>
</AccordionGroup>

<CardGroup cols={2}>
  <Card title="Tutorial" icon="book" href="/tutorials/video-ad-analysis">
    Full end-to-end script: upload → analyze → chat
  </Card>

  <Card title="Quickstart" icon="rocket" href="/quickstart-video">
    Get your first analysis in 20 minutes
  </Card>

  <Card title="Files API" icon="cloud-arrow-up" href="/features/files">
    Upload flow for videos
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/video-analysis/create-a-video-analysis">
    Full API specification
  </Card>
</CardGroup>
