ai-captions
Live closed captions for video rooms — floating caption overlay with speaker labels, configurable font size, position, and opacity. Powered by Deepgram transcription via LiveKit data channels. Use this skill when the user says "add captions", "setup closed captions", "add subtitles", "live captions", or "setup ai-captions".
What this skill does
# AI Captions
Live closed captions for video rooms, powered by Deepgram transcription delivered via LiveKit data channels. Displays a floating caption bar at the bottom (or top) of the video with the current speaker's name and spoken text. Includes a settings panel for font size, position, background opacity, and language. Captions fade out after a configurable silence duration.
## Prerequisites
- Next.js app with `src/` directory and App Router
- `transcription` skill installed (Deepgram transcription + data channel types)
- `video-room` skill installed (LiveKit room infrastructure)
- `video-ui` skill installed (video layout components)
- shadcn/ui initialized
## Installation
No new packages required. Uses packages already installed by dependencies:
- `@deepgram/sdk` (from transcription)
- `livekit-client` (from video-room)
## What Gets Created
```
src/
├── lib/
│ └── video/
│ ├── captions.ts # Caption formatting utilities
│ └── use-captions.ts # "use client" hook for caption display state
└── components/
└── video/
├── caption-overlay.tsx # Floating caption bar for video
└── caption-settings.tsx # Settings panel (font size, position, opacity)
```
## Setup Steps
### Step 1: Create `src/lib/video/captions.ts`
```typescript
/**
* Caption formatting and display utilities.
* Pure functions with no side effects — safe for server or client use.
*/
/** Maximum characters to display in a single caption line */
const MAX_CAPTION_LENGTH = 120;
/** Minimum display duration in milliseconds */
const MIN_DISPLAY_MS = 2000;
/** Milliseconds per word for calculating display duration */
const MS_PER_WORD = 300;
/** Maximum display duration in milliseconds */
const MAX_DISPLAY_MS = 10000;
/**
* Truncate caption text to a maximum length, preserving whole words.
* If the text exceeds the limit, it truncates at the last space before the limit
* and appends an ellipsis.
*/
export function truncateToMaxLength(text: string, maxLength = MAX_CAPTION_LENGTH): string {
if (text.length <= maxLength) return text;
const truncated = text.slice(0, maxLength);
const lastSpace = truncated.lastIndexOf(" ");
if (lastSpace > maxLength * 0.5) {
return `${truncated.slice(0, lastSpace)}...`;
}
return `${truncated}...`;
}
/**
* Format a speaker label for display in captions.
* Shortens long names and adds a colon separator.
*
* @param speakerName - The speaker's display name
* @param maxLength - Maximum length for the speaker label (default 20)
*/
export function formatSpeakerLabel(speakerName: string, maxLength = 20): string {
if (!speakerName || speakerName.trim().length === 0) {
return "";
}
const trimmed = speakerName.trim();
if (trimmed.length <= maxLength) {
return `${trimmed}:`;
}
// Try to use first name only
const firstName = trimmed.split(" ")[0];
if (firstName.length <= maxLength) {
return `${firstName}:`;
}
return `${firstName.slice(0, maxLength)}...:`;
}
/**
* Calculate how long a caption should be displayed based on word count.
* Longer captions stay on screen longer to give users time to read.
*
* @param text - The caption text
* @returns Display duration in milliseconds
*/
export function calculateDisplayDuration(text: string): number {
const wordCount = text.split(/\s+/).filter(Boolean).length;
const calculated = wordCount * MS_PER_WORD;
return Math.min(Math.max(calculated, MIN_DISPLAY_MS), MAX_DISPLAY_MS);
}
export type CaptionFontSize = "small" | "medium" | "large";
export type CaptionPosition = "top" | "bottom";
export type CaptionSettings = {
fontSize: CaptionFontSize;
position: CaptionPosition;
backgroundOpacity: number;
enabled: boolean;
};
export const DEFAULT_CAPTION_SETTINGS: CaptionSettings = {
fontSize: "medium",
position: "bottom",
backgroundOpacity: 0.75,
enabled: true,
};
/**
* Map font size setting to Tailwind CSS class.
*/
export function getFontSizeClass(size: CaptionFontSize): string {
switch (size) {
case "small":
return "text-sm";
case "medium":
return "text-base";
case "large":
return "text-lg";
}
}
/**
* Map position setting to Tailwind CSS positioning classes.
*/
export function getPositionClasses(position: CaptionPosition): string {
switch (position) {
case "top":
return "top-4 left-1/2 -translate-x-1/2";
case "bottom":
return "bottom-4 left-1/2 -translate-x-1/2";
}
}
```
### Step 2: Create `src/lib/video/use-captions.ts`
```typescript
"use client";
import { useState, useCallback, useEffect, useRef } from "react";
import type { TranscriptSegment } from "./types-transcription";
import {
truncateToMaxLength,
formatSpeakerLabel,
calculateDisplayDuration,
DEFAULT_CAPTION_SETTINGS,
type CaptionSettings,
type CaptionFontSize,
type CaptionPosition,
} from "./captions";
type CaptionEntry = {
speaker: string;
text: string;
timestamp: number;
displayUntil: number;
};
type UseCaptionsOptions = {
/** Map of speaker IDs to display names */
speakerNames?: Record<number, string>;
/** Initial settings override */
initialSettings?: Partial<CaptionSettings>;
};
type TranscriptMessage = {
type: "transcript";
segment: TranscriptSegment;
isFinal: boolean;
};
/**
* Hook that subscribes to transcription data channel messages,
* buffers recent segments, and manages caption display timing.
*
* Returns the current caption to display, active state, and settings controls.
*/
export function useCaptions(
onDataReceived?: (handler: (payload: Uint8Array) => void) => () => void,
options: UseCaptionsOptions = {}
) {
const { speakerNames = {}, initialSettings } = options;
const [settings, setSettings] = useState<CaptionSettings>({
...DEFAULT_CAPTION_SETTINGS,
...initialSettings,
});
const [currentCaption, setCurrentCaption] = useState<CaptionEntry | null>(null);
const [isActive, setIsActive] = useState(false);
const fadeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const decoderRef = useRef(new TextDecoder());
// Clear fade timer on unmount
useEffect(() => {
return () => {
if (fadeTimerRef.current) {
clearTimeout(fadeTimerRef.current);
}
};
}, []);
const showCaption = useCallback(
(segment: TranscriptSegment) => {
if (!settings.enabled) return;
// Clear existing fade timer
if (fadeTimerRef.current) {
clearTimeout(fadeTimerRef.current);
}
const speakerName = speakerNames[segment.speaker] ?? `Speaker ${segment.speaker + 1}`;
const displayText = truncateToMaxLength(segment.text);
const displayDuration = calculateDisplayDuration(segment.text);
const entry: CaptionEntry = {
speaker: formatSpeakerLabel(speakerName),
text: displayText,
timestamp: Date.now(),
displayUntil: Date.now() + displayDuration,
};
setCurrentCaption(entry);
setIsActive(true);
// Set timer to fade out
fadeTimerRef.current = setTimeout(() => {
setCurrentCaption(null);
setIsActive(false);
fadeTimerRef.current = null;
}, displayDuration);
},
[settings.enabled, speakerNames]
);
const handleMessage = useCallback(
(payload: Uint8Array) => {
try {
const text = decoderRef.current.decode(payload);
const message = JSON.parse(text) as TranscriptMessage;
if (message.type !== "transcript") return;
// Show both interim and final results for responsive captions
showCaption(message.segment);
} catch {
// Ignore malformed messages
}
},
[showCaption]
);
// Subscribe to data channel
useEffect(() => {
if (!onDataReceived) return;
const unsubscribe = onDataReceived(handleMessage);
return unsubscribe;
}, [onDataReceived, handleMessage]);
const updateSettings = useCallback((updatRelated in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.