# VideoSummarizer: Reduced RAG for Video (Shots → Scenes → EvidenceM SK4

<!-- category -- AI,Video,ONNX,Patterns,Architecture,LLM,NER,CLIP -->
<datetime class="hidden">2026-01-15T19:00</datetime>

> **Lo stato**: In fase di sviluppo come parte del [lucidRAG](https://www.lucidrag.com).
> **Source**: [github.comM SK1scottgal/lucidrag](https://github.com/scottgal/lucidrag)

**Dove questo va bene?**: VideoSummarizer è il **orchestratore** Non si tratta di una questione di breve termine. [lucidRAG](https://www.lucidrag.com) famiglia, che combina tre pipelines in un motore di analisi video unificato:

- **[DocSummarizer](/blog/building-a-document-summarizer-with-rag)** - Documenti
- **[ImageSummarizer](/blog/constrained-fuzzy-image-intelligence)** - Immagini
- **[AudioSummarizer](/blog/audiosummarizer-forensic-audio-characterization)** - Audio
- **VideoSummarizer** (Questo articoloM SK1 - Video | (orchestra tutte le tre |, aggiungono l'immagine |
- **[DataSummarizer](/blog/datasummarizer-how-it-works)** - Donni (Inferenza schematicaM SK2Profiliamento)

Tutti segueno la stessa cosa. **[Esempio RAG ridotto](/blog/reduced-rag)**: estrarre i segnali una volta , immagazzinare le prove, sintetizzare con un input LLM limitatoM SK3

---


Il processo di un fotogramma da due ore con inserzioni CLIP richiederebbe ore e centinaia di dollari di calcolo.

**VideoSummarizer lo risolve con tre ottimizzazioni chiave:**

1. **Deduplicazione percepibile del hash** - Skip visually similar frames before expensive ML
2. **Inserzione di una catena CLIP** - Processo 8 immagini per passaggio GPU invece di una sola.
3. **Composizione dei tubi** - Chain ImageSummarizer per i frammenti chiave, AudioSum marizer per la parolaM SK2 NER per le entità

Il risultato: un M SK1processi di video per ore in ~10-15 minuti, non oreMSC4 Gli stessi principi dell'architettura come [ImageSummarizer](/blog/constrained-fuzzy-image-intelligence) e [AudioSummarizer](/blog/audiosummarizer-forensic-audio-characterization), ma formato in un tubo di analisi video unificatoM SK1

> **Percezione fondamentale:** Video sono riprese + audio + testoM SK2 Progettare ogni dominio con strumenti specializzati, fondere i risultati in scene coerenti
> 
> - **Structure del processo prima** (cutsM SK1 I-frames , segmenti audioMSC4
> - **Estratto una volta i segnali multimodali cross-.** (inserzioni,transcrizioni ,entitàM SK3

**Terminologia:**

- **Shot** - la telecamera scatta tra i tagli strutturale, dalla detezione della scena FFmpegM SK3
- **La scena.** - gruppo contiguo di colpi formando un'unità coerente semanticiM SK2 da un gruppo di colpi
- **Le prove** - `(start_time, end_time)` I segnali + i puntatori + la provenienza

**Key ML models used:**

- **[CLIP](https://openai.com/research/clip)** - OpenAIM SK1La lingua contrastiva-Pre-imaging di immagini -formiamentoMSC4 genera 512-inserzioni dimensionali che codificano la semantica visiva
- **[Pensiamo.](https://openai.com/research/whisper)** - OpenAIM SK1 il modello di riconoscimento vocale; trasscrive l'audio al testo con tasti temporali
- **[BERT-NER](https://huggingface.co/dslim/bert-base-NER)** - Ricognizione delle entità chiamateM SK1 estratto le persone, organizzazioniMSC3 posizioni dal testo
- **[Il tempo di esecuzione di ONNX](https://onnxruntime.ai/)** - Cross-inferenza ML per la piattaforma ; conduce modelli su CPUM SK3GPU senza blocco strutturaleMSC4in

Questo articolo riguarda:

- Come il VideoSummarizer orchestra tre pipelines (ImageSommarizerM SK1 AudioSum marizer , NER)
- L'architettura delle onde: M SK1 le onde dalla normalizzazione alla generazione di prove
- **Il sistema delle capacità**: Lazy model downloads, Detezione GPUM SK2 routing reactive
- Optimizzazione del CLIP in serie per i frammenti di chiave (3-5x più veloce)
- Deduplicazione percepibile del hash (40% riduzione del frammentoM SK1
- Multi-clusteramento di scena del segnale M SK1inserzione + transcrizione \+ tipo di taglio |+ temporale
- Integrazione NER per l'estrazione delle entità dalle trascrizioni
- **Atomi ephemeri** per la limitazione del tasso, stima del tempoM SK1 e pressione posteriore
- Output: scenesM SK1 shots , transcrizioni, text tracks as RAG evidence

**Article connessi**:

- **[RAG ridotto](https://www.mostlylucid.net/blog/reduced-rag)** - Il modello di base
- **[Patterno di Fuzzine Constretto](/blog/constrained-fuzziness-pattern)** - Il modello fondamentale
- **Implementazioni RAG riducite:**
  - [DocSummarizer](/blog/building-a-document-summarizer-with-rag) - Document RAG con estrazione di entità
  - [ImageSummarizer](/blog/constrained-fuzzy-image-intelligence) - Image RAG con l'intelligenza visiva delle onde 22-
  - [AudioSummarizer](/blog/audiosummarizer-forensic-audio-characterization) - Caratificazione forense audio
  - **VideoSummarizer (Questo articolo)** - Organizzatore dell'intelligenza video

[TOC]

---


## Il problema: il video è costoso

> **I punti di riferimento**: Numeri sotto misurati sull'AMD 9950X (16-coreM SK3 SSK4 NVIDIA A4000 \(16GBMSC7 | | / ♫96GB RAM |

Un tipico film contiene:

- **Frami ~170,000** (2 ore a 24fps)
- **~2 ore di audio** (
- **Molte strati di testo** (subtitlesM SK1 credits , on-screen textMSC4

L'approccio strawman ( Nessuno lo faM SK1 ma stabilisce la scala):

- CLIP embedding per ogni fotogramma: ~200ms × **9.4 ore**
- Vision LLM per fotogramma: ~2s × ≥170,000 | **94 ore** (cloud Vision API ballpark

Anche con l'estrazione di frammenti chiave ( direM SK1 500-1000 frammenti), cheMSC4 è ancora CSK5 secondi di deduzione seriale CLIPMST6

**Appoggio tradizionale**: "Escludere frammenti chiave, mandare a Vision LLMM SK3 sperare nel meglioMSC4

**Il problema.**: Questo brucia la computazione su frammenti ridondanti ( molti frammenti di chiavi sono visibilmente simili ), li processa in serie

**Soluzione**: MultiM SK1Filtura in fase,Processo di lottiMNK3 e composizione dei tubiMRK4

---


## L'architettura del VideoSummarizer

VideoSummarizer implements **[RAG ridotto](/blog/reduced-rag)** per video con una riduzione di tre gradi

```mermaid
flowchart TB
    subgraph Input["Video File (.mp4, .mkv, etc.)"]
        V[Video Stream]
        A[Audio Stream]
    end

    subgraph Stage1["Stage 1: Structural Analysis"]
        N[NormalizeWave<br/>FFprobe metadata]
        SD[ShotDetectionWave<br/>Scene cuts via FFmpeg]
        KE[KeyframeExtractionWave<br/>I-frame + dedup]
    end

    subgraph Stage2["Stage 2: Content Extraction"]
        IS[ImageSummarizer<br/>CLIP, OCR, Vision]
        AS[AudioSummarizer<br/>Whisper, Diarization]
        NER[NER Service<br/>Entity extraction]
    end

    subgraph Stage3["Stage 3: Scene Assembly"]
        SC[SceneClusteringWave<br/>CLIP similarity]
        EV[EvidenceGenerationWave<br/>RAG chunks]
    end

    V --> N --> SD --> KE
    KE --> IS
    A --> AS
    AS --> NER
    IS --> SC
    NER --> SC
    SC --> EV

    style Stage1 stroke:#22c55e,stroke-width:2px
    style Stage2 stroke:#3b82f6,stroke-width:2px
    style Stage3 stroke:#8b5cf6,stroke-width:2px
```

### Artefatti di prova prodotti

Prima di cominciare la implementazione, qui' è quello che si ottieneM SK2il schema di output :

| Artefatto | campi chiave | Source S|
|----------|------------|--------|
| **La scena.** | `id`, `start_time`, `end_time`, `key_terms[]`, `speaker_ids[]`, `embedding[512]` | SceneClusteringWave  |
| **Shot** | `id`, `start_time`, `end_time`, `cut_type`, `keyframe_path` | ShotDetectionWave  |
| **L'espressione** | `id`, `text`, `start_time`, `end_time`, `speaker_id`, `confidence` | TranscriptionWave  |
| **TextTrack** | `id`, `text`, `start_time`, `text_type` (titleM SK1credito/subtitle /ocrMSC4 | SubtitleExtractionWave SSK6
| **Keyframe** | `id`, `timestamp`, `frame_path`, `dhash`, `clip_embedding[512]` | KeyframeExtractionWave

Ogni manufatto include **provenienza**: onda sorgente, tasso di tempo di traitementM SK2 punteggio di fiduciaMSC3 Questo è il " ledger di proveMST5 su cui operano le queries RAG in avalito.

### Il Pipeline Signal-Aware Wave

VideoSummarizer usa un **L'architettura delle onde basata sul segnale-** dove ogni onda dichiara esplicitamente i suoi contratti di segnale:

```csharp
public interface ISignalAwareVideoWave
{
    /// <summary>Signals this wave requires before it can run.</summary>

    IReadOnlyList<string> RequiredSignals { get; }

    /// <summary>Signals this wave can optionally use if available.</summary>

    IReadOnlyList<string> OptionalSignals { get; }

    /// <summary>Signals this wave emits on successful completion.</summary>

    IReadOnlyList<string> EmittedSignals { get; }

    /// <summary>Cache keys this wave produces for downstream waves.</summary>

    IReadOnlyList<string> CacheEmits { get; }

    /// <summary>Cache keys this wave consumes from upstream waves.</summary>

    IReadOnlyList<string> CacheUses { get; }
}
```

Questo permette **Coordinazione delle onde dinamiche**:

- Le onde saltano automaticamente se mancano i segnali necessari.
- Le dipendenze si risolvono al runtime ( nessun ordine codificato)
- Le riprese parziali sono riproducibili (cache con la chiave di segnale)
- Granularità del progresso dell'UI: ogni onda emette il progresso indipendentemente

### Il Pipeline 16-Wave

L'estrazione dei frammenti chiave è implementata come 7 onde granulare per un migliore parallelismo e efficienza del cache:

| Wave | Priorità | Richiede M| Emiti m| Tempo D|
|------|----------|----------|-------|------|
| **Normalizzare l'onda** | 1000 | - | `video.duration`, `video.fps`, `video.normalized` |  ~2s |
| **FFmpegShotDetectionWave** | 900 | `video.normalized` | `shots.detected`, `shots.count` |  ~5-10s |
| **La Wave di Detezione di IFrame** | 850 | `video.normalized` | `keyframes.iframes_detected`, `keyframes.iframes_count` |  ~3s |
| **La curva di selezione del Keyframe** | 840 | `shots.detected`, `keyframes.iframes_detected` | `keyframes.selected`, `keyframes.selected_count` |  ~1s |
| **La Wave di Extrazione delle Immagini** | 830 | `keyframes.selected` | `keyframes.thumbnails_extracted` |  ~5s |
| **KeyframeDeduplicationWave** | 820 | `keyframes.thumbnails_extracted` | `keyframes.deduplicated`, `keyframes.duplicates_skipped` |  ~1s |
| **KeyframeFullResExtractionWave** | 810 | `keyframes.deduplicated` | `keyframes.extracted`, `keyframes.count` |  ~10s |
| **ClipEmbeddingWave** | 800 | `keyframes.extracted` | `clip.embeddings_ready`, `clip.embeddings_count` |  ~30s |
| **Wave di analisi dell'immagine** | 790 | `keyframes.deduplicated` | `keyframes.analyzed`, `ocr.extracted` |  ~60s |
| **TitleCreditsDetectionWave** | 750 | `shots.detected` | `title.detected`, `credits.detected` |  ~5s |
| **AudioExtractionWave** | 650 | `video.normalized` | `audio.extracted`, `audio.path` |  ~30s |
| **TranscriptionWave** | 600 | `audio.extracted` | `transcription.complete`, `transcription.utterance_count` |  ~120s |
| **SubtitleExtractionWave** | 550 | `video.normalized` | `subtitles.extracted` |  ~2s |
| **ChapterExtractionWave** | 500 | `video.normalized` | `chapters.extracted` |  ~1s |
| **SceneClusteringWave** | 400 | `shots.detected` | `scenes.detected`, `scene.count` |  ~5s |
| **EvidenceGenerationWave** | 100 | `scenes.detected` | `evidence.generated` |  ~2s |

**Notes:**

- Usazioni di ImageAnalysisWave `keyframes.deduplicated` (non interoM SK1res): L'OCR funziona su immagini miniature ; il sottoscritto della visione usa interiMSC4res quando è disponibile tramite il routing delle capacitàMST5
- Le onde 3-7 sono le onde granularie per l'estrazione di frammenti chiave " sotto PSK3pipeline CSK4 per la migliore efficienza del cachingo

**Totale per 2-ora di filmato**: ~10-15 minuti (vsM SK3 ore senza ottimizzazione)

### Beh-Le chiavi di segnale che conosciamo

I segnali sono definiti come konstante per la coerenza:

```csharp
public static class VideoSignals
{
    // NormalizeWave signals
    public const string VideoDuration = "video.duration";
    public const string VideoFps = "video.fps";
    public const string VideoNormalized = "video.normalized";

    // Shot detection signals
    public const string ShotsDetected = "shots.detected";
    public const string ShotsCount = "shots.count";

    // Keyframe signals
    public const string IframesDetected = "keyframes.iframes_detected";
    public const string KeyframesSelected = "keyframes.selected";
    public const string KeyframesDeduplicated = "keyframes.deduplicated";
    public const string KeyframesExtracted = "keyframes.extracted";

    // CLIP embedding signals
    public const string ClipEmbeddingsReady = "clip.embeddings_ready";

    // Scene clustering signals
    public const string ScenesDetected = "scenes.detected";
    public const string SceneCount = "scene.count";

    // Transcription signals
    public const string TranscriptionComplete = "transcription.complete";
}
```

---


## Sistema di Capacità: Modelli Lazy & Routing

VideoSummarizer usa un **capacità-architettura basata**: individuare GPU una volta al startup, scaricare i modelli lentamenteM SK2 lavorare con la strada per i componenti disponibili .

### Manifesto del modello (YAML + TipoM SK2Constanze sicure)

I modelli sono definiti in `models.yaml`-no stringi magici in codice:

```yaml
# models.yaml (excerpt)
models:
  clip-vit-b32:
    name: "CLIP ViT-B/32"
    download_url: "https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/onnx/visual_model.onnx"
    preferred_providers: [CUDAExecutionProvider, DmlExecutionProvider, CPUExecutionProvider]

components:
  ClipEmbeddingWave:
    models: [clip-vit-b32]
    fallback_chain: [ImageAnalysisWave]
```

```csharp
// Type-safe constants (no raw strings)
await coordinator.EnsureModelAsync(ModelIds.ClipVitB32);
await coordinator.ActivateWaveAsync(ComponentIds.TranscriptionWave);

// Route with fallback
var route = await coordinator.RouteWorkAsync(new[]
{
    ComponentIds.ClipEmbeddingWave,    // Primary (GPU)
    ComponentIds.ImageAnalysisWave     // Fallback (CPU)
});
```

### Atomi di Efficienza del Pipeline

Limitazione del tasso, stima del tempo, e pressione posteriore adattativa mantengono l'interfaccia reattiva while maximizing throughput

```csharp
// Time estimation from actual data
var estimator = CapabilityAtoms.CreateTimeEstimator();
using (estimator.Time("clip_embedding")) { await ProcessAsync(); }
var eta = estimator.GetEstimate("clip_embedding", remaining: 50);
// eta.Estimated, eta.Optimistic, eta.Pessimistic, eta.Confidence
```

> **Documenti del sistema completo di capacità.**: Vedete `Mostlylucid.Summarizer.Core/Capabilities/` per la rilevazione del GPU, pub di segnaliM SK1sub, controlli di pressione posteriore , e progettazione della topologia mesh

---


## Optimizzazione Key 1: Deduplicazione percettuale dell'hash

Prima di fare expensive CLIP embeddings, VideoSummarizer filtra frammenti visibilmente simili usando **La differenza hah (dHash)**.

### Come funziona dHash

```csharp
public class KeyframeDeduplicationService
{
    // dHash parameters: 9x8 grayscale = 64 bits
    private const int HashWidth = 9;
    private const int HashHeight = 8;
    private const int DefaultHammingThreshold = 10;

    public async Task<ulong> ComputeDHashAsync(string imagePath, CancellationToken ct)
    {
        using var image = Image.Load<Rgba32>(imagePath);

        // Resize to 9x8 (one extra column for gradient comparison)
        image.Mutate(x => x
            .Resize(HashWidth, HashHeight)
            .Grayscale());

        ulong hash = 0;
        int bit = 0;

        // Compare adjacent pixels horizontally
        for (int y = 0; y < HashHeight; y++)
        {
            for (int x = 0; x < HashWidth - 1; x++)
            {
                var left = image[x, y].R;
                var right = image[x + 1, y].R;

                // Set bit if left pixel is brighter than right
                if (left > right)
                {
                    hash |= (1UL << bit);
                }
                bit++;
            }
        }

        return hash;
    }

    public static int HammingDistance(ulong a, ulong b) =>
        BitOperations.PopCount(a ^ b);
}
```

**Esempio output:**

```
Input: 50 keyframe candidates (from codec I-frames)

Deduplication (Hamming threshold 10):
  Frame 0: hash=0x8f3a2c1d → KEEP (first frame)
  Frame 1: hash=0x8f3a2c1e → SKIP (distance=1 from frame 0)
  Frame 2: hash=0x8f3a2c1f → SKIP (distance=2 from frame 0)
  Frame 3: hash=0xc7e1b4a2 → KEEP (distance=28 from frame 0)
  ...

Result: 50 → 30 frames (40% reduction)
Processing saved: ~8 seconds of CLIP inference
```

**Perché questo conta:**

- **~40% riduzione di struttura** sul contenuto tipico.
- **<1ms per fotogramma** per il calcolo a hash (vs. 200ms per CLIPM SK3
- Filtra frammenti ridondanti. **prima.** Operazioni GPU costose

---


## Optimizzazione chiave 2: Inserzione di catena CLIP

Invece di elaborare un'immagine alla volta, VideoSummarizer batchi M SK1 immagini per passaggio GPU.

### L'architettura di processo in serie

```csharp
public class BatchClipEmbeddingService
{
    private const int ClipImageSize = 224;
    private const int DefaultBatchSize = 8; // 8 images per GPU pass

    public async Task<Dictionary<int, float[]>> GenerateBatchEmbeddingsAsync(
        Dictionary<int, string> framePaths,
        int batchSize = DefaultBatchSize,
        CancellationToken ct = default)
    {
        var session = await GetOrLoadClipModelAsync(ct);
        var results = new Dictionary<int, float[]>();

        // Pre-index batch for O(1) lookup (not batch.IndexOf!)
        var batches = framePaths
            .Select((kvp, idx) => (idx, kvp.Key, kvp.Value))
            .Chunk(batchSize);

        foreach (var batch in batches)
        {
            // Create batch tensor [batchSize, 3, 224, 224]
            var tensor = new DenseTensor<float>(new[] { batch.Length, 3, ClipImageSize, ClipImageSize });

            // Preprocess images in parallel (simplified; production uses vectorised span copy)
            Parallel.ForEach(batch, item =>
            {
                var (batchIdx, frameIndex, path) = item;
                var localIdx = batchIdx % batchSize;
                PreprocessImageToTensor(path, tensor, localIdx); // ImageSharp pixel buffers
            });

            // Single GPU pass for entire batch
            var inputs = new List<NamedOnnxValue>
            {
                NamedOnnxValue.CreateFromTensor("input", tensor)
            };

            using var outputResults = session.Run(inputs);
            // Extract embeddings from batch output...
        }

        return results;
    }
}
```

**Paragonazione di performance:**

```
Input: 30 keyframes (after deduplication)

Serial processing (1 frame at a time):
  30 × 200ms = 6,000ms (6.0 seconds)

Batch processing (8 frames per pass):
  4 batches × 350ms = 1,400ms (1.4 seconds)

Speedup: 4.3x
```

**Perché funziona il processo di lotto:**

- Il parallelismo GPU è sottoutilizzato con una sola deduzione di immagini-.
- Tensor di catena `[8, 3, 224, 224]` usa la stessa memoria GPU dell'immagine unica (almost)
- ONNX Runtime ottimizza le operazioni di lotti internamente

---


## Optimizzazione chiave 3: Composizione del tubo

VideoSummarizer non reinventa ImageSum marizer o AudioSommarizer. **Le catene.** them.

### Keyframe Sub-Pipeline: Integrazione di ImageSummarizer

L'estrazione del frammento chiave è divisa in 7 onde granulare ( vedete il grafico delle onde sopraM SK2 Qui' c'è un modello di coordinazione che mostra come si collegano insieme

```csharp
// IFrameDetectionWave → KeyframeSelectionWave → ThumbnailExtractionWave
// → KeyframeDeduplicationWave → KeyframeFullResExtractionWave → ClipEmbeddingWave

// ClipEmbeddingWave coordinates with ImageSummarizer
public class ClipEmbeddingWave : IVideoWave, ISignalAwareVideoWave
{
    public IReadOnlyList<string> RequiredSignals => [VideoSignals.KeyframesExtracted];
    public IReadOnlyList<string> EmittedSignals => [VideoSignals.ClipEmbeddingsReady];

    public async Task ProcessAsync(VideoContext context, CancellationToken ct)
    {
        var keyframes = context.GetCached<Dictionary<int, string>>("keyframes.paths");

        // Batch CLIP embedding (3-5x faster than serial)
        var embeddings = await _batchClipService.GenerateBatchEmbeddingsAsync(
            keyframes, batchSize: 8, ct);

        foreach (var (frameIndex, embedding) in embeddings)
            context.KeyframeEmbeddings[frameIndex] = embedding;
    }
}

// ImageAnalysisWave runs ImageSummarizer on deduplicated frames
public class ImageAnalysisWave : IVideoWave, ISignalAwareVideoWave
{
    public IReadOnlyList<string> RequiredSignals => [VideoSignals.KeyframesDeduplicated];

    public async Task ProcessAsync(VideoContext context, CancellationToken ct)
    {
        var keyframePaths = context.GetCached<List<string>>("keyframes.deduplicated_paths");

        foreach (var path in keyframePaths)
        {
            // Run ImageSummarizer for OCR, vision, captions
            var result = await _imageOrchestrator.AnalyzeAsync(path, ct);
            context.SetCached($"image_analysis.{Path.GetFileName(path)}", result);
        }
    }
}
```

### TranscriptionWave: Integrazione di AudioSummarizer

L'estrazione audio e la trascrizione sono ora segnali separati-onde di consapevolezza:

```csharp
// AudioExtractionWave runs first (extracts audio track from video)
public class AudioExtractionWave : IVideoWave, ISignalAwareVideoWave
{
    public IReadOnlyList<string> RequiredSignals => [VideoSignals.VideoNormalized];
    public IReadOnlyList<string> EmittedSignals => ["audio.extracted", "audio.path"];

    public async Task ProcessAsync(VideoContext context, CancellationToken ct)
    {
        var audioPath = await _ffmpegService.ExtractAudioAsync(
            context.VideoPath, context.WorkingDirectory, ct);
        context.SetCached("audio.path", audioPath);
    }
}

// TranscriptionWave depends on audio.extracted signal
public class TranscriptionWave : IVideoWave, ISignalAwareVideoWave
{
    public IReadOnlyList<string> RequiredSignals => ["audio.extracted"];
    public IReadOnlyList<string> EmittedSignals => [
        VideoSignals.TranscriptionComplete,
        "transcription.utterance_count"
    ];

    public async Task ProcessAsync(VideoContext context, CancellationToken ct)
    {
        var audioPath = context.GetCached<string>("audio.path");

        // Run AudioSummarizer pipeline (Whisper + diarization)
        var audioProfile = await _audioOrchestrator.AnalyzeAsync(audioPath, ct);

        // Extract utterances with speaker info
        var turns = audioProfile.GetValue<List<SpeakerTurn>>("speaker.turns");
        foreach (var turn in turns ?? [])
        {
            context.Utterances.Add(new Utterance
            {
                Id = Guid.NewGuid(),
                Text = turn.Text,
                StartTime = turn.StartSeconds,
                EndTime = turn.EndSeconds,
                SpeakerId = turn.SpeakerId,
                Confidence = turn.Confidence
            });
        }

        // Run NER on full transcript for entity extraction
        var transcript = audioProfile.GetValue<string>("transcription.full_text");
        if (!string.IsNullOrEmpty(transcript))
        {
            var entities = await _nerService.ExtractEntitiesAsync(transcript, ct);
            context.SetCached("transcript_entities", entities);

            // Emit entity signals by type (PER, ORG, LOC, MISC)
            foreach (var group in entities.GroupBy(e => e.Type))
            {
                context.AddSignal($"transcript.entities.{group.Key.ToLowerInvariant()}",
                    group.Select(e => e.Text).Distinct().ToList());
            }
        }
    }
}
```

---


## NER Integration: Ricognizione delle entità chiamate

VideoSummarizer extrae entità chiamate dalle trascrizioni usando BERT-based NER M SK1ONNX).

### OnnxNerService

```csharp
public class OnnxNerService
{
    // Model: dslim/bert-base-NER (ONNX exported)
    // Entities: PER (Person), ORG (Organization), LOC (Location), MISC (Miscellaneous)

    public async Task<List<EntitySpan>> ExtractEntitiesAsync(string text, CancellationToken ct)
    {
        var entities = new List<EntitySpan>();

        // Chunk long text (BERT max 512 tokens)
        foreach (var chunk in ChunkText(text, maxTokens: 400, overlap: 50))
        {
            // Tokenize with WordPiece
            var tokens = _tokenizer.Tokenize(chunk);

            // Run ONNX inference
            var inputs = PrepareInputs(tokens);
            using var results = _session.Run(inputs);

            // Decode BIO tags
            var predictions = DecodePredictions(results);
            var chunkEntities = ExtractEntitySpans(tokens, predictions);

            entities.AddRange(chunkEntities);
        }

        // Deduplicate entities
        return entities
            .GroupBy(e => (e.Text.ToLowerInvariant(), e.Type))
            .Select(g => g.First())
            .ToList();
    }
}
```

**Esempio output:**

```
Transcript: "Today we're speaking with John Smith from Microsoft about
their new AI lab in Seattle. The project, codenamed Phoenix, builds
on research from Stanford University."

Entities extracted:
  PER: John Smith
  ORG: Microsoft, Stanford University
  LOC: Seattle
  MISC: Phoenix

Signals emitted:
  transcript.entities.per = ["John Smith"]
  transcript.entities.org = ["Microsoft", "Stanford University"]
  transcript.entities.loc = ["Seattle"]
  transcript.entities.misc = ["Phoenix"]
```

**Perché il NER è importante per i video:**

- Enable queries like "Trovare video che menzionano Microsoft"
- Linki al grafico dell'entità DocSummarizer
- Fornisce metadati strutturati senza una deduzione LLM.

---


## Multi-Clustering di scena segnale

L'uso di inserzioni CLIP da sola per la rilevazione delle scene non funziona bene'keyframe sono sparsi dal design M SK2un cambio per ripresa), ma le riprese sono denseMSC4 Con 39 inserzioni per 1881 riprese (~2% coperturaMST8 l'insieme puro dell'inserzione produce solo una scena per un film d'oraMSSK9

VideoSummarizer usa un **approccio multi-signale** che combina segnali pesanti 4 per la rilevazione robusta dei confini della scena:

### SceneClusteringWave: Multi-Architectura del segnale

```csharp
public class SceneClusteringWave : IVideoWave, ISignalAwareVideoWave
{
    // Signal weights for boundary scoring
    private const double EmbeddingWeight = 0.4;   // CLIP embedding dissimilarity
    private const double TranscriptWeight = 0.3;  // Semantic shift in transcript
    private const double CutTypeWeight = 0.2;     // Fade/dissolve detection
    private const double TemporalWeight = 0.1;    // Time since last scene

    // Temporal constraints
    private const double MinSceneDuration = 15.0;   // Don't split scenes < 15s
    private const double MaxSceneDuration = 300.0;  // Force split at 5 minutes
    private const double TargetSceneDuration = 90.0; // Prefer ~90s scenes

    public IReadOnlyList<string> RequiredSignals => [VideoSignals.ShotsDetected];
    public IReadOnlyList<string> OptionalSignals => [
        VideoSignals.ClipEmbeddingsReady,
        VideoSignals.TranscriptionComplete,
        VideoSignals.KeyframesDeduplicated
    ];
    public IReadOnlyList<string> EmittedSignals => [
        VideoSignals.ScenesDetected,
        "scene.count",
        "scene.avg_duration",
        "scene.clustering_method"
    ];

    private List<(int shotIndex, double score)> ComputeBoundaryScores(VideoContext context)
    {
        var shots = context.Shots.OrderBy(s => s.StartTime).ToList();
        var scores = new List<(int, double)>();

        // Build embedding map with nearest-neighbor interpolation
        var shotEmbeddings = PropagateEmbeddingsToNearbyShots(context, shots);

        // Build transcript windows for semantic shift detection
        var transcriptWindows = BuildTranscriptWindows(context, shots, windowSeconds: 10);

        for (int i = 0; i < shots.Count - 1; i++)
        {
            double score = 0;
            var currentShot = shots[i];
            var nextShot = shots[i + 1];

            // 1. Embedding dissimilarity (40%)
            if (shotEmbeddings.TryGetValue(i, out var currentEmbed) &&
                shotEmbeddings.TryGetValue(i + 1, out var nextEmbed))
            {
                var similarity = CosineSimilarity(currentEmbed, nextEmbed);
                score += (1.0 - similarity) * EmbeddingWeight;
            }

            // 2. Transcript semantic shift (30%)
            if (transcriptWindows.TryGetValue(i, out var currentWords) &&
                transcriptWindows.TryGetValue(i + 1, out var nextWords))
            {
                var overlap = currentWords.Intersect(nextWords).Count();
                var union = currentWords.Union(nextWords).Count();
                var jaccard = union > 0 ? (double)overlap / union : 0;
                score += (1.0 - jaccard) * TranscriptWeight;
            }

            // 3. Cut type signal (20%) - fades/dissolves suggest scene boundaries
            if (currentShot.CutType is "fade" or "dissolve")
            {
                score += CutTypeWeight;
            }

            // 4. Temporal pressure (10%) - encourage splits near target duration
            var timeSinceLastScene = currentShot.EndTime - GetLastSceneBoundary();
            if (timeSinceLastScene > TargetSceneDuration)
            {
                var pressure = Math.Min(1.0, (timeSinceLastScene - TargetSceneDuration) / 60);
                score += pressure * TemporalWeight;
            }

            scores.Add((i, score));
        }

        return scores;
    }
}
```

### Principali innovazioni

1. **Avvicinamento-Propagazione dell'imbarcazione vicino**: Solo ~2% di scatto hanno inserzioni CLIP directeM SK2 La nuova approccio propaga le inserzioni ai scattos vicini in pochi secondi usando il weighting temporale della vicinanza.

2. **Windows Semantici di Transcrizione**: Costruisce 10-secondi di finestre su parole intorno a ogni scatto e rileva i cambiamenti semantici attraverso la distanza di Jaccard-un proxy di spostamento semantice economico (la sovrapposizione bassa S= cambiamento di temaM SK5 BMMSC6 si può usare la sovrapposta o l'inserzione di un spostamento se disponibile

3. **La consapevolezza del tipo di taglio**: FadeM SK1to-Le transizioni di nero e di dissolvimento indicano fortemente i confini della scena , stimolando il punteggio dei confiniMSC4

4. **Limiti adattivi**: Invece di una soglia fissaM SK1 seleziona i limiti dalla parte superiore 25% dei punteggi ( adatta al contenuto).

5. **Contrattivi Temporali**: Fa rispettare il minimo 15 le scene e imposce i limiti a

**Esempio:**

```
Input: 1881 shots from a 2-hour movie
       39 keyframes with CLIP embeddings
       2302 utterances from transcript

Boundary scoring per shot:
  Shot 45-46: embedding=0.15, transcript=0.32, cut=0.0, temporal=0.0 → score=0.156
  Shot 46-47: embedding=0.08, transcript=0.12, cut=0.0, temporal=0.0 → score=0.068
  Shot 47-48: embedding=0.35, transcript=0.41, cut=0.2, temporal=0.05 → score=0.388 ← BOUNDARY
  ...

Adaptive threshold (top 25%): 0.25
Natural boundaries found: 45

Output: 47 scenes (avg 2.6 minutes per scene)
  - Min scene: 15.2s
  - Max scene: 298.4s
  - Total coverage: 100%

Signals:
  scenes.detected = true
  scene.count = 47
  scene.avg_duration = 156.3
  scene.clustering_method = "multi_signal_weighted"
```

---


## Il Video Signal Contract

VideoSummarizer estende il contratto di segnale da ImageSommarizer e AudioSum marizer:

```csharp
public record VideoSignal
{
    public required string Key { get; init; }      // "scene.count", "transcript.entities.per"
    public object? Value { get; init; }
    public double Confidence { get; init; } = 1.0;
    public required string Source { get; init; }   // "SceneClusteringWave"

    // Video-specific: time range
    public double? StartTime { get; init; }
    public double? EndTime { get; init; }

    public DateTime Timestamp { get; init; }
    public Dictionary<string, object>? Metadata { get; init; }
    public List<string>? Tags { get; init; }       // ["visual", "scene"]
}

public static class VideoSignalTags
{
    public const string Visual = "visual";
    public const string Audio = "audio";
    public const string Speech = "speech";
    public const string Ocr = "ocr";
    public const string Motion = "motion";
    public const string Scene = "scene";
    public const string Shot = "shot";
    public const string Metadata = "metadata";
}
```

**I segnali chiave emetti:**

| Signale | Source | Description S|
|--------|--------|-------------|
| `video.duration` | NormalizzareWave | Duration totale in secondi |
| `video.resolution` | NormalizzareWave | larghezzaM SK2altezza |
| `video.fps` | NormalizzareWave | Tasso di riferimento |
| `shots.count` | ShotDetectionWave
| `keyframes.count` | KeyframeExtractionWave | Frami chiave unici dopo la dedupzione |
| `keyframes.duplicates_skipped` | KeyframeExtractionWave
| `scene.count` | SceneClusteringWave
| `transcript.entities.per` | TranscriptionWave | I nomi delle persone del NER |
| `transcript.entities.org` | TranscriptionWave | I nomi dell'organizzazione |
| `transcript.word_count` | TranscriptionWave | Totale parole in trascrizione |

---


## VideoPipeline: Output RAG

L'informazione figura nella parte dispositiva. `VideoPipeline` converte i segnali video in `ContentChunk` per l'indexazione RAG:

```csharp
public class VideoPipeline : PipelineBase
{
    public override string PipelineId => "video";
    public override IReadOnlySet<string> SupportedExtensions => new HashSet<string>
    {
        ".mp4", ".mkv", ".avi", ".mov", ".wmv", ".webm", ".flv", ".m4v", ".mpeg", ".mpg"
    };

    private List<ContentChunk> BuildContentChunks(VideoContext context, string filePath)
    {
        var chunks = new List<ContentChunk>();

        // 1. Scene-based chunks (best for video retrieval)
        foreach (var scene in context.Scenes)
        {
            var sceneText = BuildSceneText(context, scene);
            var embedding = context.GetCached<float[]>($"scene_centroid.{scene.Id}");

            chunks.Add(new ContentChunk
            {
                Text = sceneText,
                ContentType = ContentType.Summary,
                Embedding = embedding,  // Proper vector column, not metadata
                Metadata = new Dictionary<string, object?>
                {
                    ["source"] = "video_scene",
                    ["scene_id"] = scene.Id,
                    ["key_terms"] = scene.KeyTerms,
                    ["speakers"] = scene.SpeakerIds,
                    ["start_time"] = scene.StartTime,
                    ["end_time"] = scene.EndTime
                }
            });
        }

        // 2. Transcript chunks (1-minute windows)
        var transcriptChunks = BuildTranscriptChunks(context, filePath);
        chunks.AddRange(transcriptChunks);

        // 3. Text track chunks (on-screen text/subtitles)
        foreach (var textTrack in context.TextTracks)
        {
            chunks.Add(new ContentChunk
            {
                Text = $"On-screen text: {textTrack.Text}",
                ContentType = ContentType.ImageOcr,
                Metadata = new Dictionary<string, object?>
                {
                    ["source"] = "video_ocr",
                    ["text_type"] = textTrack.TextType.ToString(),
                    ["start_time"] = textTrack.StartTime
                }
            });
        }

        return chunks;
    }

    private string BuildSceneText(VideoContext context, SceneSegment scene)
    {
        var parts = new List<string>();

        if (!string.IsNullOrEmpty(scene.Label))
            parts.Add($"Scene: {scene.Label}");

        parts.Add($"[{FormatTime(scene.StartTime)} - {FormatTime(scene.EndTime)}]");

        if (scene.KeyTerms.Count > 0)
            parts.Add($"Topics: {string.Join(", ", scene.KeyTerms)}");

        // Add utterances in this scene
        var sceneUtterances = context.Utterances
            .Where(u => u.StartTime >= scene.StartTime && u.EndTime <= scene.EndTime)
            .OrderBy(u => u.StartTime);

        if (sceneUtterances.Any())
            parts.Add($"Speech: {string.Join(" ", sceneUtterances.Select(u => u.Text))}");

        return string.Join("\n", parts);
    }
}
```

**Esempio di output per un film:**

```json
{
  "chunks": [
    {
      "text": "Scene: Opening montage\n[0:00 - 2:34]\nTopics: city, night, traffic\nSpeech: The year is 2049. The world has changed.",
      "contentType": "Summary",
      "metadata": {
        "source": "video_scene",
        "scene_id": "abc123",
        "key_terms": ["city", "night", "traffic"],
        "start_time": 0.0,
        "end_time": 154.0
      }
    },
    {
      "text": "The detective arrived at the crime scene. Forensics had already processed the area.",
      "contentType": "Transcript",
      "metadata": {
        "source": "video_transcript",
        "time_window": "2:34 - 3:34",
        "utterance_count": 4
      }
    },
    {
      "text": "On-screen text: LOS ANGELES 2049",
      "contentType": "ImageOcr",
      "metadata": {
        "source": "video_ocr",
        "text_type": "Title"
      }
    }
  ]
}
```

---


## Carattéristiche di performance

### Tempo di processo (2-ora di filmato, 1080pM SK3

| Stazione | Tempo | Note S|
|-------|------|-------|
| FFprobe metadata
| Detezione di sparatorie | ~10s S| Filtro di scena FFmpeg M|
| Extrazione di frammenti chiave | ~30s | \500 IM SK5frame SSK6
| deduplicazione di dHash | ~0.5s | \500 | | 5 | 6 | frami | 7
| Inserzione di CLIP in un batchetto | CSK2s | \300 fotogrammi, batchamento S8 ||
| ImageSummarizer OCR
| Extrazione d'audio |
| Transcrizione murmurata | ~180s S| \2 ore di discorso SSK5
| Diarizzazione dell'altoparlante | ~60s M| ECAPA-TDNN P|
| Extrazione del NER | ~10s M| BERTM SK4NER sulla trascrizione |
| Clustrazione di scena | ~5s M| ≥|
| Generazione di prove | ~2s M| ≥|
| **Totale** | **~8-10 minuti** | |

### Senza ottimizzazioni

| ottimizzazione | risparmio |
|--------------|---------|
| deduplicazione di dHash | ~40% fotogrammi filtrati M= \~24s CLIP salvato |
| CLIP di catena | 3-5x più veloce SSK3 \~180s risparmiato S|
| Composizione del tubo | Riutilizza l'immaurizzatore di immaginiM SK2Le onde dell'audio|
| **Totali risparmi** | **~3-4 minuti** |

### Usazione della memoria

| Componente
|-----------|--------|
| CLIP ViT
| Base di fischio | ~500MB S|
| ECAPA-TDNN
| BERTM SK1NER
| **Piccolo** | **~1.5GB** |

---


## Integrazione con lucidRAG

VideoSummarizer registra come un `IPipeline` per il routing automatico:

```csharp
// In Program.cs
builder.Services.AddDocSummarizer(builder.Configuration.GetSection("DocSummarizer"));
builder.Services.AddDocSummarizerImages(builder.Configuration.GetSection("Images"));
builder.Services.AddVideoSummarizer();  // NEW
builder.Services.AddPipelineRegistry(); // Must be last

// Auto-routing by extension
var registry = services.GetRequiredService<IPipelineRegistry>();
var pipeline = registry.FindForFile("movie.mp4");  // Returns VideoPipeline
var result = await pipeline.ProcessAsync("movie.mp4");
```

**Estensioni supportate:**

- `.mp4`, `.mkv`, `.avi`, `.mov`, `.wmv`, `.webm`, `.flv`, `.m4v`, `.mpeg`, `.mpg`

---


## Quello che otteniamo

- **Scene-segni RAG di livello**: Segmenti coerenti con le trascrizioni, termini chiaveM SK2 ID degli oratori
- **Evidenze multi-modale**: Visuale (Keyframe embeddings),Audio Speecher diarizationM SK4Texto \(\OCR\MSC6\Subtitles\)\
- **Entità chiamate**: PersoneM SK1 organizzazioni, posizioni dalla trascrizione NER
- **La provenienza verificabile**: Ogni segnale ha una onda di sorgente, fiduciaM SK2 tappi temporali
- **Un processo efficiente**: 10-15 minuti per un film d'ora.

## Quanto costa?

- **Memory GPU ~1.5GB** per tutti i modelli ONNX
- **~8-10 processo di minuti** per 2-ora di filmato
- **Spazio di disco** per i file intermedi ( pulito automaticamente)
- **La complessità**: L'orchestrazione di tre pipelines richiede la comprensione delle dipendenze dalle onde.

---


## Conclusione

VideoSummarizer dimostra che **La composizione delle pipeline.** Scale:

1. **Riutilizzare i tubi specializzati**: DonM SK1 non ricostruire ImageSummarizer o AudioSum marizer-le stringere.
2. **Filtrare prima delle operazioni costose**: Costi di deduplicazione dHash <1msM SK2 risparmia 40% della deduzione CLIP
3. **Operazioni di GPU in serie**:
4. **Estratto la struttura prima del contenuto**: Shots → Scenes → Evidence (no frammenti crudi S→ LLM)
5. **Gestione dei modelli pigri**: scaricare i modelli solo quando è necessario, rilevare GPU automaticamente
6. **Routing reattivo**: Funziona con i componenti disponibili, fallback gracefully

Il risultato: un film di 2-ora diventa un ledger di segnali strutturato con scene, transcrizioni, entità, ,, e inserzioni,-, pronti per ricerche RAG come l':.

- "Trovare scene in cui John Smith parla di Microsoft"
- " Mostra video con il testo sullo schermo - sul progetto Phoenix"
- "Trovare video simili a questa scenaM SK1 (CLIP embedding search)

**Il modello RAG ridotto per video:**

```
Ingestion:  Video → 16 waves → Signals + Evidence (scenes, transcripts, entities)
Storage:    Signals (indexed) + Embeddings (CLIP, voice) + Evidence (chunks)
Query:      Filter (SQL) → Search (BM25 + vector) → Synthesize (LLM, ~5 results)
```

**Il sistema di capacità:**

```
Startup:    Detect GPU → Load ModelManifest (YAML) → Initialize SignalSink
Activation: Component requests model → Lazy download → Signal "ModelAvailable"
Routing:    Route to best provider → Fallback chain → Backpressure control
Atoms:      Rate limiting + Time estimation + Pipeline balancing
```

Questo è **Fuzzinesse limitata** a scala:

- **Componenti probabilistice propongono segnali.**: inserzioni (CLIPM SK2 ipotesi OCR, stime di diarizzazione
- **Il punteggio deterministico monta la struttura.**: punteggi di confine ponderati, selezione del sogliassoM SK2 restrizioni temporali
- **LLM (opzionale) si sintetizza dalle prove.**: contesto confinato, provenienza verificabile

Il LLM opera su pre--evidenza computata-non video crudo.

---


## Ressource

### Documentazione lucidRAG

- **[VideoSummarizer Library](https://github.com/scottgal/lucidrag/tree/main/src/VideoSummarizer.Core)** - codice sorgente
- **[Documentazione NER](https://github.com/scottgal/lucidrag/blob/main/docs/NER_EXTRACTION_DEDUPLICATION.md)** - L'architettura di estrazione delle entità

### Biblioteche connesse

- **[ImageSummarizer](https://github.com/scottgal/lucidrag/tree/main/src/ImageSummarizer.Core)** - Pipeline di intelligenza visiva
- **[AudioSummarizer](https://github.com/scottgal/lucidrag/tree/main/src/AudioSummarizer.Core)** - Audio forense pipeline
- **[DocSummarizer](https://github.com/scottgal/lucidrag/tree/main/src/Mostlylucid.DocSummarizer.Core)** - Pipeline per i documenti

### I modelli di ONNX

- **[CLIP ViT-B/32](https://huggingface.co/openai/clip-vit-base-patch32)** - Inserzioni visive
- **[ECAPA-TDNN](https://huggingface.co/Wespeaker/wespeaker-ecapa-tdnn512-LM)** - Speaker embeddings
- **[BERT-NER](https://huggingface.co/dslim/bert-base-NER)** - Ricognizione di entità chiamata
- **[Pensiamo.](https://github.com/openai/whisper)** - Transcrizione vocale

### Article connessi

**Patterns Core:**

- **[RAG ridotto](https://www.mostlylucid.net/blog/reduced-rag)** - Il modello di base
- **[Patterno di Fuzzine Constretto](/blog/constrained-fuzziness-pattern)** - Patto fondamentale

**Implementazioni RAG riducite:**

- **[DocSummarizer](/blog/building-a-document-summarizer-with-rag)** - Document RAG con estrazione di entità
- **[ImageSummarizer](/blog/constrained-fuzzy-image-intelligence)** - Image RAG con l'intelligenza visiva delle onde 22-
  - **[Tre-Tier OCR Pipeline](/blog/constrained-fuzzy-image-ocr-pipeline)** - Eskalazione dell'OCR
- **[AudioSummarizer](/blog/audiosummarizer-forensic-audio-characterization)** - Caratificazione forense audio
- **VideoSummarizer (Questo articolo)** - Organizzatore dell'intelligenza video
- **[DataSummarizer](/blog/datasummarizer-how-it-works)** - Profilazione dei dati e deduzione del schema

---


## La serie

| Parte | Pattern | Focus S|
|------|---------|-------|
| 1 | [Fuzzinesse limitata](/blog/constrained-fuzziness-pattern) | Componente unica |
| 2 | [MoM Fuzzy Constretto](/blog/constrained-mom-mixture-of-models) | Numerosi componenti |
| 3 | [Dragging Contexto](/blog/constrained-fuzzy-context-dragging) | Tempo / memoria |
| 4 | [Intelligenza dell'immagine](/blog/constrained-fuzzy-image-intelligence) | Architectura delle ondeM SK1 22 onde |
| 4.1 | [Tre-Tier OCR Pipeline](/blog/constrained-fuzzy-image-ocr-pipeline) | OCRM SK1 Modelli ONNX, filmtrips |
| 4.2 | [AudioSummarizer](/blog/audiosummarizer-forensic-audio-characterization) | Audio forense, diarizzazione dell'altoparlante |
| **4.3** | **VideoSummarizer (Questo articolo)** | **Orchestrazione video, batch CLIP, NER** |

**Più avanti**: MultiM SK1Graphmodal RAG con lucidRAG-componendo tutti i quattro somministratori in un grafico di conoscenza unificato con un crossMSC3ente multi collegato a .

Tutte le parti segueno la stessa invariante: **Componenti probabilistice propose; sistemi deterministici persistono**.