clip-score
4-axis video segment scoring using AI extended thinking — returns emotional peak, info density, surprise, and standalone scores per segment. Use this skill when the user says "add clip scoring", "score video segments", "find best clips", or "clip analysis".
What this skill does
# Clip Score Skill
Sends transcript segments to Claude with extended thinking (budgetTokens: 8000) and receives per-segment scores on four axes: emotional peak, info density, surprise, and standalone. Returns a ranked list plus the full scored set. Auth-protected POST endpoint.
## Prerequisites
- Next.js app with App Router (no `src/` directory)
- `ai-reasoning` skill applied (provides `@anthropic-ai/sdk` and extended thinking pattern)
- `env-config` skill applied (provides env var validation)
- `better-auth` configured at `@/lib/auth`
## Installation
```bash
bun add @anthropic-ai/sdk
```
## What Gets Created
```
app/
└── api/
└── clip-score/
└── route.ts # POST endpoint — auth-gated, calls Anthropic with extended thinking
lib/
└── clip-score/
└── index.ts # Types + scoring prompt builder
```
## Environment Variables
Add to `.env.local`:
```
ANTHROPIC_API_KEY=sk-ant-...
```
## Setup Steps
### Step 1: Create `lib/clip-score/index.ts`
```typescript
export type TranscriptSegment = {
id: number;
start: number; // seconds
end: number; // seconds
text: string;
};
export type ClipScoreInput = {
segments: TranscriptSegment[];
videoContext?: string; // optional: title, description of the video
preferences?: {
preferFunny?: boolean;
preferInformational?: boolean;
preferControversial?: boolean;
};
};
export type ScoredSegment = TranscriptSegment & {
score: number; // composite 0-1
axes: {
emotionalPeak: number; // 0-1
infoDensity: number; // 0-1
surprise: number; // 0-1
standAlone: number; // 0-1
};
rationale: string;
};
export type ClipScoreResult = {
segments: ScoredSegment[];
topSegments: ScoredSegment[]; // top 5 by score
processingMs: number;
};
const TOP_SEGMENT_COUNT = 5;
export function buildScoringPrompt(input: ClipScoreInput): string {
const { segments, videoContext, preferences } = input;
const contextBlock = videoContext
? `\nVideo context:\n${videoContext}\n`
: "";
const preferenceLines: string[] = [];
if (preferences?.preferFunny) {
preferenceLines.push("- Prefer segments that are funny or entertaining");
}
if (preferences?.preferInformational) {
preferenceLines.push("- Prefer segments with high informational value");
}
if (preferences?.preferControversial) {
preferenceLines.push("- Prefer segments with provocative or controversial content");
}
const preferencesBlock =
preferenceLines.length > 0
? `\nUser preferences (adjust weights accordingly):\n${preferenceLines.join("\n")}\n`
: "";
const segmentLines = segments
.map(
(seg) =>
`[ID:${seg.id}] ${formatTime(seg.start)}–${formatTime(seg.end)}: ${seg.text.trim()}`
)
.join("\n");
return `You are an expert video editor and content analyst. Your task is to score each transcript segment on four axes to identify the best short-form clips.
${contextBlock}${preferencesBlock}
## Scoring Axes
Score each axis from 0.0 to 1.0:
- **emotionalPeak**: How much laughter, surprise, strong emotion, or high energy is present. 1.0 = maximum emotional intensity.
- **infoDensity**: Facts, insights, actionable takeaways, or memorable information per minute. 1.0 = packed with value.
- **surprise**: Unexpected revelations, counterintuitive ideas, or dramatic turns. 1.0 = completely unexpected.
- **standAlone**: Can this clip be understood without watching the rest of the video? 1.0 = fully self-contained.
The composite **score** is the weighted average: (emotionalPeak * 0.3) + (infoDensity * 0.25) + (surprise * 0.25) + (standAlone * 0.2).
## Transcript Segments
${segmentLines}
## Output Format
Return ONLY a valid JSON array with no markdown fences or extra text. Each element must match this shape:
{
"id": <number matching the segment ID>,
"score": <number 0.0–1.0, two decimal places>,
"axes": {
"emotionalPeak": <number 0.0–1.0>,
"infoDensity": <number 0.0–1.0>,
"surprise": <number 0.0–1.0>,
"standAlone": <number 0.0–1.0>
},
"rationale": "<one sentence explaining the scores>"
}
Return one object per segment in the same order as the input. Do not omit any segments.`;
}
function formatTime(seconds: number): string {
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
return `${m}:${s.toString().padStart(2, "0")}`;
}
type RawScoredItem = {
id: number;
score: number;
axes: {
emotionalPeak: number;
infoDensity: number;
surprise: number;
standAlone: number;
};
rationale: string;
};
export function mergeScores(
segments: TranscriptSegment[],
rawScores: RawScoredItem[]
): ScoredSegment[] {
return segments.map((seg) => {
const scored = rawScores.find((r) => r.id === seg.id);
if (!scored) {
return {
...seg,
score: 0,
axes: { emotionalPeak: 0, infoDensity: 0, surprise: 0, standAlone: 0 },
rationale: "No score returned for this segment.",
};
}
return { ...seg, ...scored };
});
}
export function getTopSegments(segments: ScoredSegment[]): ScoredSegment[] {
return segments
.slice()
.sort((a, b) => b.score - a.score)
.slice(0, TOP_SEGMENT_COUNT);
}
```
### Step 2: Create `app/api/clip-score/route.ts`
```typescript
import { NextRequest, NextResponse } from "next/server";
import Anthropic from "@anthropic-ai/sdk";
import { auth } from "@/lib/auth";
import {
buildScoringPrompt,
mergeScores,
getTopSegments,
type ClipScoreInput,
type ClipScoreResult,
type TranscriptSegment,
type ScoredSegment,
} from "@/lib/clip-score";
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
type RawScoreItem = {
id: number;
score: number;
axes: {
emotionalPeak: number;
infoDensity: number;
surprise: number;
standAlone: number;
};
rationale: string;
};
function isValidRawScoreItem(item: unknown): item is RawScoreItem {
if (typeof item !== "object" || item === null) return false;
const obj = item as Record<string, unknown>;
if (typeof obj.id !== "number") return false;
if (typeof obj.score !== "number") return false;
if (typeof obj.rationale !== "string") return false;
if (typeof obj.axes !== "object" || obj.axes === null) return false;
const axes = obj.axes as Record<string, unknown>;
return (
typeof axes.emotionalPeak === "number" &&
typeof axes.infoDensity === "number" &&
typeof axes.surprise === "number" &&
typeof axes.standAlone === "number"
);
}
function extractJsonFromText(text: string): unknown {
// Strip markdown code fences if present
const stripped = text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
return JSON.parse(stripped);
}
export async function POST(request: NextRequest): Promise<NextResponse> {
// Auth check
const session = await auth.api.getSession({ headers: request.headers });
if (!session?.user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const input = body as Partial<ClipScoreInput>;
if (!Array.isArray(input.segments) || input.segments.length === 0) {
return NextResponse.json(
{ error: "segments must be a non-empty array" },
{ status: 400 }
);
}
const segments = input.segments as TranscriptSegment[];
const prompt = buildScoringPrompt({
segments,
videoContext: input.videoContext,
preferences: input.preferences,
});
const startMs = Date.now();
let rawScores: RawScoreItem[];
try {
const response = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 16000,
thinking: {
type: "enabled",
budget_tokens: 8000,
},
messages: [
{
role: "user",
content: prompt,
},
],
});
// ExtraRelated 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.