Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat: add AI highlight extractor and fix speed playback zoom bug

Augustus Otu68144de5e64d
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 1916bb10..d9959aab 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -50,6 +50,7 @@ import {
} from "./inspector";
import { OPENREEL_TTS_URL } from "../../config/api-endpoints";
import { AutoEditPanel } from "./panels/AutoEditPanel";
+import { HighlightExtractorPanel } from "./panels/HighlightExtractorPanel";
import {
getAudioBridgeEffects,
initializeAudioBridgeEffects,
@@ -762,6 +763,13 @@ export const InspectorPanel: React.FC = () => {
</Section>
)}
+ {/* AI Highlight Extractor */}
+ {showAudioEffects && (
+ <Section title="AI Highlights" sectionId="ai-highlights" defaultOpen={false}>
+ <HighlightExtractorPanel clipId={clipId} />
+ </Section>
+ )}
+
{/* Transform */}
{showTransformControls && (
<Section title="Transform" sectionId="transform">
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index fd7c035c..77e2073e 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -70,14 +70,6 @@ import { ProcessingOverlay } from "./ProcessingOverlay";
import { getPersonSegmentationEngine, getBackgroundRemovalEngine } from "@openreel/core";
import type { MotionPathConfig, GSAPMotionPathPoint } from "@openreel/core";
-const getAdaptivePoolSize = (width: number, height: number): number => {
- const pixels = width * height;
- if (pixels >= 3840 * 2160) return 6;
- if (pixels >= 2560 * 1440) return 5;
- if (pixels >= 1920 * 1080) return 4;
- return 3;
-};
-
interface GPULayer {
bitmap: ImageBitmap;
transform: ClipTransform;
@@ -2559,24 +2551,8 @@ export const Preview: React.FC = () => {
canvas.height = settings.height;
}
- // Validate final canvas dimensions
- const sinkWidth = canvas.width || settings.width;
- const sinkHeight = canvas.height || settings.height;
-
- if (sinkWidth === 0 || sinkHeight === 0) {
- console.error(
- "[Preview] Cannot create CanvasSink with zero dimensions",
- );
- input[Symbol.dispose]?.();
- pause();
- return;
- }
-
const sink = new CanvasSink(videoTrack, {
- width: sinkWidth,
- height: sinkHeight,
- fit: "contain",
- poolSize: getAdaptivePoolSize(sinkWidth, sinkHeight),
+ poolSize: 3,
});
const speedEngine = getSpeedEngine();
@@ -2900,13 +2876,8 @@ export const Preview: React.FC = () => {
return null;
}
- const sinkWidth = settings.width || 1920;
- const sinkHeight = settings.height || 1080;
const sink = new CanvasSink(videoTrack, {
- width: sinkWidth,
- height: sinkHeight,
- fit: "contain",
- poolSize: getAdaptivePoolSize(sinkWidth, sinkHeight),
+ poolSize: 3,
});
return {
diff --git a/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx b/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx
new file mode 100644
index 00000000..8baaadc5
--- /dev/null
+++ b/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx
@@ -0,0 +1,316 @@
+import React, { useState, useCallback } from "react";
+import { Sparkles, Play, Check, Loader2 } from "lucide-react";
+import { useProjectStore } from "../../../stores/project-store";
+import { useTimelineStore } from "../../../stores/timeline-store";
+import {
+ getTranscriptionService,
+ initializeTranscriptionService,
+ type TranscriptWord,
+} from "@openreel/core";
+import { OPENREEL_TRANSCRIBE_URL } from "../../../config/api-endpoints";
+import {
+ extractHighlights,
+ type HighlightResult,
+ type HighlightPreferences,
+} from "../../../services/highlight-service";
+
+interface HighlightExtractorPanelProps {
+ clipId: string;
+}
+
+export const HighlightExtractorPanel: React.FC<HighlightExtractorPanelProps> = ({
+ clipId,
+}) => {
+ const [highlights, setHighlights] = useState<HighlightResult[]>([]);
+ const [selected, setSelected] = useState<Set<number>>(new Set());
+ const [phase, setPhase] = useState("");
+ const [progress, setProgress] = useState(0);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const project = useProjectStore((s) => s.project);
+ const getMediaItem = useProjectStore((s) => s.getMediaItem);
+ const setPlayheadPosition = useTimelineStore((s) => s.setPlayheadPosition);
+
+ const [preferences, setPreferences] = useState<HighlightPreferences>({
+ targetClipCount: 5,
+ minClipDuration: 5,
+ maxClipDuration: 60,
+ contentType: "video",
+ });
+
+ const handleAnalyze = useCallback(async () => {
+ if (!project) return;
+
+ const clip = project.timeline.tracks
+ .flatMap((t) => t.clips)
+ .find((c) => c.id === clipId);
+ if (!clip) return;
+
+ const mediaItem = getMediaItem(clip.mediaId);
+ if (!mediaItem?.blob) {
+ setError("Media not found or not loaded");
+ return;
+ }
+
+ setIsProcessing(true);
+ setError(null);
+ setHighlights([]);
+
+ try {
+ setPhase("Transcribing audio...");
+ setProgress(5);
+
+ const transcriptionService = getTranscriptionService() || initializeTranscriptionService({
+ apiEndpoint: `${OPENREEL_TRANSCRIBE_URL}/transcribe`,
+ });
+ const subtitles = await transcriptionService.transcribeClip(
+ clip,
+ mediaItem,
+ (p) => setProgress(Math.round(p.progress * 20)),
+ );
+
+ const transcript: TranscriptWord[] = subtitles.flatMap((sub) =>
+ sub.words
+ ? sub.words.map((w) => ({ text: w.text, start: w.startTime, end: w.endTime }))
+ : [{ text: sub.text, start: sub.startTime, end: sub.endTime }],
+ );
+
+ if (transcript.length === 0) {
+ throw new Error("No transcript words found");
+ }
+
+ setPhase("Decoding audio...");
+ setProgress(25);
+
+ const arrayBuffer = await mediaItem.blob.arrayBuffer();
+ const audioContext = new OfflineAudioContext(1, 44100, 44100);
+ const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
+
+ const results = await extractHighlights(
+ audioBuffer,
+ transcript,
+ preferences,
+ (phaseName, prog) => {
+ setPhase(phaseName);
+ setProgress(25 + Math.round(prog * 0.75));
+ },
+ );
+
+ setHighlights(results);
+ setSelected(new Set(results.map((_, i) => i)));
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Analysis failed");
+ } finally {
+ setIsProcessing(false);
+ setPhase("");
+ setProgress(0);
+ }
+ }, [clipId, project, getMediaItem, preferences]);
+
+ const handlePreview = useCallback(
+ (highlight: HighlightResult) => {
+ setPlayheadPosition(highlight.start);
+ },
+ [setPlayheadPosition],
+ );
+
+ const toggleSelect = useCallback((index: number) => {
+ setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(index)) {
+ next.delete(index);
+ } else {
+ next.add(index);
+ }
+ return next;
+ });
+ }, []);
+
+ const formatTime = (seconds: number): string => {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
+ };
+
+ return (
+ <div className="space-y-3">
+ <div className="space-y-2">
+ <div className="flex items-center gap-2">
+ <label className="text-[10px] text-text-secondary">Clips</label>
+ <input
+ type="number"
+ min={1}
+ max={20}
+ value={preferences.targetClipCount}
+ onChange={(e) =>
+ setPreferences((p) => ({ ...p, targetClipCount: parseInt(e.target.value) || 5 }))
+ }
+ className="w-12 px-1 py-0.5 text-[10px] bg-background-secondary border border-border rounded text-text-primary"
+ />
+ <label className="text-[10px] text-text-secondary">Max</label>
+ <input
+ type="number"
+ min={1}
+ max={300}
+ value={preferences.maxClipDuration}
+ onChange={(e) =>
+ setPreferences((p) => ({ ...p, maxClipDuration: parseInt(e.target.value) || 60 }))
+ }
+ className="w-12 px-1 py-0.5 text-[10px] bg-background-secondary border border-border rounded text-text-primary"
+ />
+ <span className="text-[10px] text-text-muted">s</span>
+ </div>
+
+ <button
+ onClick={handleAnalyze}
+ disabled={isProcessing}
+ className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-primary hover:bg-primary/90 text-white rounded text-[11px] font-medium transition-colors disabled:opacity-50"
+ >
+ {isProcessing ? (
+ <>
+ <Loader2 size={14} className="animate-spin" />
+ {phase} ({progress}%)
+ </>
+ ) : (
+ <>
+ <Sparkles size={14} />
+ Find Highlights
+ </>
+ )}
+ </button>
+
+ {error && (
+ <p className="text-[10px] text-red-400">{error}</p>
+ )}
+ </div>
+
+ {highlights.length > 0 && (
+ <div className="space-y-1.5">
+ {highlights.map((highlight, index) => (
+ <div
+ key={index}
+ className={`p-2 rounded border transition-colors cursor-pointer ${
+ selected.has(index)
+ ? "bg-primary/10 border-primary/30"
+ : "bg-background-tertiary border-transparent hover:border-border"
+ }`}
+ onClick={() => toggleSelect(index)}
+ >
+ <div className="flex items-center justify-between mb-1">
+ <div className="flex items-center gap-1.5">
+ <div
+ className={`w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold text-white ${
+ highlight.score >= 8
+ ? "bg-green-500"
+ : highlight.score >= 5
+ ? "bg-yellow-500"
+ : "bg-gray-500"
+ }`}
+ >
+ {highlight.score}
+ </div>
+ <span className="text-[10px] text-text-primary font-medium truncate max-w-[140px]">
+ {highlight.title}
+ </span>
+ </div>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePreview(highlight);
+ }}
+ className="p-1 hover:bg-background-secondary rounded"
+ >
+ <Play size={10} className="text-text-muted" />
+ </button>
+ {selected.has(index) && (
+ <Check size={12} className="text-primary" />
+ )}
+ </div>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-[9px] text-text-muted">
+ {formatTime(highlight.start)} - {formatTime(highlight.end)}
+ </span>
+ <span className="text-[9px] text-text-muted italic truncate max-w-[120px]">
+ {highlight.reason}
+ </span>
+ </div>
+ </div>
+ ))}
+
+ <button
+ onClick={async () => {
+ const selectedHighlights = highlights
+ .filter((_, i) => selected.has(i))
+ .sort((a, b) => a.start - b.start);
+ if (selectedHighlights.length === 0) return;
+
+ const store = useProjectStore.getState();
+ const proj = store.project;
+ const originalTrack = proj.timeline.tracks.find((t) =>
+ t.clips.some((c) => c.id === clipId),
+ );
+ if (!originalTrack) return;
+
+ const clip = originalTrack.clips.find((c) => c.id === clipId);
+ if (!clip) return;
+
+ const clipStart = clip.startTime;
+ const clipInPoint = clip.inPoint;
+
+ const splitTimes: number[] = [];
+ for (const h of selectedHighlights) {
+ const hStartOnTimeline = clipStart + (h.start - clipInPoint);
+ const hEndOnTimeline = clipStart + (h.end - clipInPoint);
+ splitTimes.push(hStartOnTimeline);
+ splitTimes.push(hEndOnTimeline);
+ }
+
+ const uniqueSplitTimes = [...new Set(splitTimes)]
+ .sort((a, b) => a - b)
+ .filter((t) => t > clipStart && t < clipStart + clip.duration);
+
+ for (const splitTime of uniqueSplitTimes) {
+ const currentProj = useProjectStore.getState().project;
+ const track = currentProj.timeline.tracks.find((t) => t.id === originalTrack.id);
+ if (!track) break;
+
+ const clipAtTime = track.clips.find(
+ (c) => c.startTime < splitTime && c.startTime + c.duration > splitTime,
+ );
+ if (clipAtTime) {
+ await store.splitClip(clipAtTime.id, splitTime);
+ }
+ }
+
+ const finalProj = useProjectStore.getState().project;
+ const finalTrack = finalProj.timeline.tracks.find((t) => t.id === originalTrack.id);
+ if (!finalTrack) return;
+
+ const clipsToRemove = finalTrack.clips.filter((c) => {
+ const cSourceStart = c.inPoint;
+ const cSourceEnd = c.inPoint + c.duration;
+ return !selectedHighlights.some(
+ (h) => h.start < cSourceEnd && h.end > cSourceStart,
+ );
+ });
+
+ for (const c of clipsToRemove.sort((a, b) => b.startTime - a.startTime)) {
+ await useProjectStore.getState().rippleDeleteClip(c.id);
+ }
+ }}
+ disabled={selected.size === 0}
+ className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-green-600 hover:bg-green-700 text-white rounded text-[11px] font-medium transition-colors disabled:opacity-50"
+ >
+ <Check size={14} />
+ Apply {selected.size} Highlight{selected.size !== 1 ? "s" : ""}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default HighlightExtractorPanel;
diff --git a/apps/web/src/components/editor/preview/canvas-renderers.ts b/apps/web/src/components/editor/preview/canvas-renderers.ts
index 9b75471e..0019a323 100644
--- a/apps/web/src/components/editor/preview/canvas-renderers.ts
+++ b/apps/web/src/components/editor/preview/canvas-renderers.ts
@@ -1829,8 +1829,7 @@ export const drawFrameWithTransform = (
sourceHeight = "height" in frame ? frame.height : canvasHeight;
}
- // Calculate draw size to fit frame within canvas while preserving aspect ratio
- // Uses 'cover' fit mode: fills canvas while maintaining aspect ratio
+ // Calculate draw size to fit frame within canvas while preserving aspect ratio (contain)
const sourceAspect = sourceWidth / sourceHeight;
const canvasAspect = canvasWidth / canvasHeight;
diff --git a/apps/web/src/config/api-endpoints.ts b/apps/web/src/config/api-endpoints.ts
index b6ade178..fcb0f679 100644
--- a/apps/web/src/config/api-endpoints.ts
+++ b/apps/web/src/config/api-endpoints.ts
@@ -15,6 +15,9 @@ export const OPENREEL_CLOUD_URL = isDev
/** OpenReel transcription / TTS service */
export const OPENREEL_TTS_URL = "https://transcribe.openreel.video";
+/** OpenReel transcription service (GPU) */
+export const OPENREEL_TRANSCRIBE_URL = "https://cloud.openreel.video";
+
/**
* Third-party API base URLs.
* These are used by the api-proxy service in dev mode (direct calls)
diff --git a/apps/web/src/services/highlight-service.ts b/apps/web/src/services/highlight-service.ts
new file mode 100644
index 00000000..b1681ee1
--- /dev/null
+++ b/apps/web/src/services/highlight-service.ts
@@ -0,0 +1,81 @@
+import {
+ analyzeAudioForHighlights,
+ type TranscriptWord,
+ type AudioSegmentMetrics,
+} from "@openreel/core";
+
+export interface HighlightResult {
+ start: number;
+ end: number;
+ score: number;
+ title: string;
+ reason: string;
+}
+
+export interface HighlightPreferences {
+ targetClipCount: number;
+ minClipDuration: number;
+ maxClipDuration: number;
+ contentType: string;
+}
+
+const DEFAULT_PREFERENCES: HighlightPreferences = {
+ targetClipCount: 5,
+ minClipDuration: 5,
+ maxClipDuration: 60,
+ contentType: "video",
+};
+
+type ProgressCallback = (phase: string, progress: number, message: string) => void;
+
+const API_BASE = import.meta.env.VITE_CLOUD_API_URL || "https://openreel-cloud.niiyeboah1996.workers.dev";
+
+export async function extractHighlights(
+ audioBuffer: AudioBuffer,
+ transcript: TranscriptWord[],
+ preferences: Partial<HighlightPreferences> = {},
+ onProgress?: ProgressCallback,
+): Promise<HighlightResult[]> {
+ const prefs = { ...DEFAULT_PREFERENCES, ...preferences };
+
+ onProgress?.("analyze", 10, "Analyzing audio energy...");
+ const analysis = analyzeAudioForHighlights(audioBuffer, transcript);
+
+ onProgress?.("analyze", 30, "Preparing data for AI...");
+ const energyData = analysis.segments
+ .filter((seg) => !seg.isSilence)
+ .map((seg: AudioSegmentMetrics) => ({
+ start: seg.start,
+ end: seg.end,
+ rmsDb: seg.rmsDb,
+ peakDb: seg.peakDb,
+ }));
+
+ onProgress?.("ai", 40, "Sending to AI for highlight detection...");
+
+ const response = await fetch(`${API_BASE}/highlights`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ transcript: transcript.map((w) => ({
+ text: w.text,
+ start: w.start,
+ end: w.end,
+ })),
+ energy: energyData,
+ duration: analysis.duration,
+ preferences: prefs,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error((errorData as { error?: string }).error || `API error: ${response.status}`);
+ }
+
+ onProgress?.("ai", 80, "Processing AI response...");
+ const data = (await response.json()) as { highlights: HighlightResult[] };
+
+ onProgress?.("done", 100, "Highlights ready");
+ return data.highlights;
+}
diff --git a/infra/transcribe-gpu/Dockerfile b/infra/transcribe-gpu/Dockerfile
new file mode 100644
index 00000000..40bea480
--- /dev/null
+++ b/infra/transcribe-gpu/Dockerfile
@@ -0,0 +1,25 @@
+FROM nvidia/cuda:12.1.1-runtime-ubuntu22.04
+
+ENV DEBIAN_FRONTEND=noninteractive
+ENV PYTHONUNBUFFERED=1
+
+RUN apt-get update && apt-get install -y \
+ python3.11 python3.11-venv python3-pip \
+ ffmpeg \
+ && rm -rf /var/lib/apt/lists/*
+
+RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1
+
+WORKDIR /app
+
+COPY requirements.txt .
+RUN pip3 install --no-cache-dir -r requirements.txt
+RUN pip3 install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cu121
+
+RUN python3 -c "from faster_whisper import WhisperModel; WhisperModel('large-v3-turbo', device='cpu', compute_type='int8')"
+
+COPY main.py .
+
+EXPOSE 8000
+
+CMD ["python3", "main.py"]
diff --git a/infra/transcribe-gpu/Dockerfile.cpu b/infra/transcribe-gpu/Dockerfile.cpu
new file mode 100644
index 00000000..a3c6c7fe
--- /dev/null
+++ b/infra/transcribe-gpu/Dockerfile.cpu
@@ -0,0 +1,16 @@
+FROM python:3.11-slim
+
+ENV PYTHONUNBUFFERED=1
+
+RUN apt-get update && apt-get install -y ffmpeg && apt-get clean && find /var/lib/apt/lists -type f -delete
+
+WORKDIR /app
+
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+COPY main.py .
+
+EXPOSE 8000
+
+CMD ["python", "main.py"]
diff --git a/infra/transcribe-gpu/docker-compose.cpu.yml b/infra/transcribe-gpu/docker-compose.cpu.yml
new file mode 100644
index 00000000..6057d791
--- /dev/null
+++ b/infra/transcribe-gpu/docker-compose.cpu.yml
@@ -0,0 +1,12 @@
+services:
+ transcribe:
+ build:
+ context: .
+ dockerfile: Dockerfile.cpu
+ ports:
+ - "8000:8000"
+ restart: always
+ environment:
+ - WHISPER_MODEL=large-v3-turbo
+ - WHISPER_DEVICE=cpu
+ - WHISPER_COMPUTE_TYPE=int8
diff --git a/infra/transcribe-gpu/docker-compose.yml b/infra/transcribe-gpu/docker-compose.yml
new file mode 100644
index 00000000..fc0efe74
--- /dev/null
+++ b/infra/transcribe-gpu/docker-compose.yml
@@ -0,0 +1,17 @@
+services:
+ transcribe:
+ build: .
+ ports:
+ - "8000:8000"
+ restart: always
+ deploy:
+ resources:
+ reservations:
+ devices:
+ - driver: nvidia
+ count: 1
+ capabilities: [gpu]
+ environment:
+ - WHISPER_MODEL=large-v3-turbo
+ - WHISPER_DEVICE=cuda
+ - WHISPER_COMPUTE_TYPE=float16
diff --git a/infra/transcribe-gpu/main.py b/infra/transcribe-gpu/main.py
new file mode 100644
index 00000000..095ba61e
--- /dev/null
+++ b/infra/transcribe-gpu/main.py
@@ -0,0 +1,175 @@
+import os
+import tempfile
+from typing import Optional
+
+from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
+from fastapi.middleware.cors import CORSMiddleware
+from faster_whisper import WhisperModel
+import uvicorn
+from deep_translator import GoogleTranslator
+
+app = FastAPI(title="OpenReel Transcription API (GPU)")
+
+ALLOWED_ORIGINS = [
+ "https://openreel.video",
+ "https://www.openreel.video",
+ "https://app.openreel.video",
+ "https://editor.openreel.video",
+ "http://localhost:5173",
+ "http://localhost:3000",
+ "http://localhost:5174",
+ "http://localhost:5175",
+]
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=ALLOWED_ORIGINS,
+ allow_credentials=True,
+ allow_methods=["GET", "POST", "OPTIONS"],
+ allow_headers=["*"],
+)
+
+whisper_model: Optional[WhisperModel] = None
+
+MODEL_SIZE = os.environ.get("WHISPER_MODEL", "large-v3-turbo")
+DEVICE = os.environ.get("WHISPER_DEVICE", "cuda")
+COMPUTE_TYPE = os.environ.get("WHISPER_COMPUTE_TYPE", "float16")
+
+
+def get_model() -> WhisperModel:
+ global whisper_model
+ if whisper_model is None:
+ print(f"Loading Whisper model ({MODEL_SIZE}) on {DEVICE} ({COMPUTE_TYPE})...")
+ whisper_model = WhisperModel(
+ MODEL_SIZE, device=DEVICE, compute_type=COMPUTE_TYPE
+ )
+ print("Model loaded!")
+ return whisper_model
+
+
[email protected]_event("startup")
+async def startup():
+ get_model()
+
+
[email protected]("/transcribe")
+async def transcribe(
+ request: Request,
+ audio: UploadFile = File(...),
+ language: Optional[str] = Form(None),
+ target_language: Optional[str] = Form(None),
+):
+ if not audio.filename:
+ raise HTTPException(status_code=400, detail="No audio file provided")
+
+ suffix = os.path.splitext(audio.filename)[1] or ".wav"
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
+ file_content = await audio.read()
+ tmp.write(file_content)
+ tmp_path = tmp.name
+
+ try:
+ model = get_model()
+
+ transcribe_kwargs = {
+ "word_timestamps": True,
+ "vad_filter": True,
+ }
+ if language and isinstance(language, str) and len(language) <= 5:
+ transcribe_kwargs["language"] = language
+
+ use_whisper_translate = (
+ target_language
+ and target_language == "en"
+ and (not language or language != "en")
+ )
+ if use_whisper_translate:
+ transcribe_kwargs["task"] = "translate"
+
+ segments, info = model.transcribe(tmp_path, **transcribe_kwargs)
+
+ words = []
+ full_text = []
+
+ for segment in segments:
+ full_text.append(segment.text.strip())
+ if segment.words:
+ for word in segment.words:
+ words.append(
+ {
+ "word": word.word.strip(),
+ "start": round(word.start, 2),
+ "end": round(word.end, 2),
+ }
+ )
+
+ text = " ".join(full_text)
+ detected_language = info.language
+
+ need_translation = (
+ target_language
+ and target_language != "en"
+ and target_language != detected_language
+ and not use_whisper_translate
+ )
+
+ if need_translation:
+ try:
+ translator = GoogleTranslator(
+ source=detected_language if detected_language else "auto",
+ target=target_language,
+ )
+ text = translator.translate(text)
+ for w in words:
+ if len(w["word"]) > 1:
+ w["word"] = translator.translate(w["word"])
+ except Exception as e:
+ print(f"Translation failed: {e}")
+
+ return {
+ "text": text,
+ "word_count": len(words),
+ "words": words,
+ "language": detected_language,
+ "target_language": target_language,
+ "duration": info.duration,
+ }
+ finally:
+ os.unlink(tmp_path)
+
+
+async def transcribe_root(
+ request: Request,
+ audio: UploadFile = File(...),
+ language: Optional[str] = Form(None),
+ target_language: Optional[str] = Form(None),
+):
+ return await transcribe(request, audio, language, target_language)
+
+
+async def health():
+ gpu_available = False
+ gpu_name = None
+ try:
+ import torch
+
+ gpu_available = torch.cuda.is_available()
+ gpu_name = torch.cuda.get_device_name(0) if gpu_available else None
+ except ImportError:
+ pass
+
+ return {
+ "status": "ok",
+ "model": MODEL_SIZE,
+ "device": DEVICE,
+ "compute_type": COMPUTE_TYPE,
+ "gpu": gpu_name,
+ "gpu_available": gpu_available,
+ "ready": whisper_model is not None,
+ }
+
+
+if __name__ == "__main__":
+ uvicorn.run(app, host="0.0.0.0", port=8000)
diff --git a/infra/transcribe-gpu/requirements.txt b/infra/transcribe-gpu/requirements.txt
new file mode 100644
index 00000000..2a4dc20d
--- /dev/null
+++ b/infra/transcribe-gpu/requirements.txt
@@ -0,0 +1,5 @@
+faster-whisper==1.1.0
+fastapi==0.115.6
+uvicorn[standard]==0.34.0
+python-multipart==0.0.18
+deep-translator==1.11.4
diff --git a/infra/transcribe-gpu/setup.sh b/infra/transcribe-gpu/setup.sh
new file mode 100644
index 00000000..7d1d2431
--- /dev/null
+++ b/infra/transcribe-gpu/setup.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+set -e
+
+echo "=== OpenReel GPU Transcription Setup ==="
+
+if ! command -v nvidia-smi &> /dev/null; then
+ echo "ERROR: NVIDIA drivers not found. Use a Deep Learning AMI."
+ exit 1
+fi
+
+echo "GPU detected:"
+nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
+
+if ! command -v docker &> /dev/null; then
+ echo "Installing Docker..."
+ curl -fsSL https://get.docker.com | sh
+ sudo usermod -aG docker $USER
+ echo "Docker installed. You may need to log out and back in for group changes."
+fi
+
+if ! dpkg -l | grep -q nvidia-container-toolkit; then
+ echo "Installing NVIDIA Container Toolkit..."
+ curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | \
+ sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
+ curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
+ sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
+ sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
+ sudo apt-get update
+ sudo apt-get install -y nvidia-container-toolkit
+ sudo nvidia-ctk runtime configure --runtime=docker
+ sudo systemctl restart docker
+fi
+
+echo "Building and starting transcription service..."
+docker compose up -d --build
+
+echo ""
+echo "Waiting for service to start (model download may take a few minutes)..."
+for i in $(seq 1 60); do
+ if curl -s http://localhost:8000/health | grep -q '"ready":true'; then
+ echo ""
+ echo "=== Service is ready! ==="
+ curl -s http://localhost:8000/health | python3 -m json.tool
+ exit 0
+ fi
+ printf "."
+ sleep 10
+done
+
+echo ""
+echo "Service not ready yet. Check logs with: docker compose logs -f"
diff --git a/packages/core/src/audio/highlight-analyzer.ts b/packages/core/src/audio/highlight-analyzer.ts
new file mode 100644
index 00000000..257a0d3b
--- /dev/null
+++ b/packages/core/src/audio/highlight-analyzer.ts
@@ -0,0 +1,74 @@
+export interface TranscriptWord {
+ text: string;
+ start: number;
+ end: number;
+}
+
+export interface AudioSegmentMetrics {
+ start: number;
+ end: number;
+ rmsDb: number;
+ peakDb: number;
+ speechRate: number;
+ isSilence: boolean;
+}
+
+export interface HighlightAnalysisResult {
+ segments: AudioSegmentMetrics[];
+ duration: number;
+}
+
+export function analyzeAudioForHighlights(
+ buffer: AudioBuffer,
+ transcript: TranscriptWord[],
+ segmentDuration: number = 5,
+): HighlightAnalysisResult {
+ const channelData = buffer.getChannelData(0);
+ const sampleRate = buffer.sampleRate;
+ const duration = buffer.duration;
+ const segmentCount = Math.ceil(duration / segmentDuration);
+ const segments: AudioSegmentMetrics[] = [];
+ const silenceThreshold = Math.pow(10, -60 / 20);
+
+ for (let i = 0; i < segmentCount; i++) {
+ const segStart = i * segmentDuration;
+ const segEnd = Math.min((i + 1) * segmentDuration, duration);
+
+ const startSample = Math.floor(segStart * sampleRate);
+ const endSample = Math.min(Math.floor(segEnd * sampleRate), channelData.length);
+
+ let sumSquares = 0;
+ let peak = 0;
+ let maxAmp = 0;
+ const sampleCount = endSample - startSample;
+
+ for (let j = startSample; j < endSample; j++) {
+ const sample = Math.abs(channelData[j]);
+ sumSquares += sample * sample;
+ peak = Math.max(peak, sample);
+ maxAmp = Math.max(maxAmp, sample);
+ }
+
+ const rms = sampleCount > 0 ? Math.sqrt(sumSquares / sampleCount) : 0;
+ const rmsDb = 20 * Math.log10(rms || 0.0001);
+ const peakDb = 20 * Math.log10(peak || 0.0001);
+ const isSilence = maxAmp < silenceThreshold;
+
+ const wordsInSegment = transcript.filter(
+ (w) => w.start >= segStart && w.start < segEnd,
+ );
+ const segDuration = segEnd - segStart;
+ const speechRate = segDuration > 0 ? wordsInSegment.length / segDuration : 0;
+
+ segments.push({
+ start: segStart,
+ end: segEnd,
+ rmsDb,
+ peakDb,
+ speechRate,
+ isSilence,
+ });
+ }
+
+ return { segments, duration };
+}
diff --git a/packages/core/src/audio/index.ts b/packages/core/src/audio/index.ts
index bf9ce569..680915b8 100644
--- a/packages/core/src/audio/index.ts
+++ b/packages/core/src/audio/index.ts
@@ -10,3 +10,4 @@ export * from "./effects-worklet-processor";
export * from "./sound-library-engine";
export * from "./sound-generator";
export * from "./beat-detection-engine";
+export * from "./highlight-analyzer";