Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions apps/web/actions/videos/get-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ const MAX_AI_PROCESSING_TIME = 10 * 60 * 1000;

export interface VideoStatusResult {
transcriptionStatus: "PROCESSING" | "COMPLETE" | "ERROR" | null;
aiProcessing: boolean;
aiTitle: string | null;
aiProcessing: boolean;
summary: string | null;
chapters: { title: string; start: number }[] | null;
// generationError: string | null;
error?: string;
}

Expand Down
55 changes: 55 additions & 0 deletions apps/web/app/api/videos/[videoId]/retry-transcription/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";

export async function POST(
_request: Request,
{ params }: { params: { videoId: string } },
) {
try {
const user = await getCurrentUser();
if (!user) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}

const { videoId } = params;
if (!videoId) {
return Response.json({ error: "Video ID is required" }, { status: 400 });
}

// Verify user owns the video
const videoQuery = await db()
.select()
.from(videos)
.where(eq(videos.id, videoId))
.limit(1);

if (videoQuery.length === 0) {
return Response.json({ error: "Video not found" }, { status: 404 });
}

const video = videoQuery[0];
if (!video || video.ownerId !== user.id) {
return Response.json({ error: "Unauthorized" }, { status: 403 });
}

// Reset status to null - this will trigger automatic retry via get-status.ts
await db()
.update(videos)
.set({ transcriptionStatus: null })
.where(eq(videos.id, videoId));

// Revalidate the video page to ensure UI updates with fresh data
revalidatePath(`/s/${videoId}`);

return Response.json({
success: true,
message: "Transcription retry triggered",
});
} catch (error) {
console.error("Error resetting transcription status:", error);
return Response.json({ error: "Internal server error" }, { status: 500 });
}
}
65 changes: 57 additions & 8 deletions apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import type { videos } from "@cap/database/schema";
import { Button } from "@cap/ui";
import { useMutation } from "@tanstack/react-query";
import { useInvalidateTranscript, useTranscript } from "hooks/use-transcript";
import { Check, Copy, Download, Edit3, MessageSquare, X } from "lucide-react";
import { useEffect, useState } from "react";
Expand Down Expand Up @@ -142,6 +143,33 @@ export const Transcript: React.FC<TranscriptProps> = ({

const invalidateTranscript = useInvalidateTranscript();

const retryTranscriptionMutation = useMutation({
mutationFn: async () => {
const response = await fetch(
`/api/videos/${data.id}/retry-transcription`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
},
);

if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to retry transcription: ${errorText}`);
}

return response.json();
},
onSuccess: () => {
// Reset status - Share.tsx polling will automatically detect the change and trigger transcription
setIsTranscriptionProcessing(true);
invalidateTranscript(data.id);
},
onError: (error) => {
console.error("Failed to retry transcription:", error);
},
});

useEffect(() => {
if (transcriptContent) {
const parsed = parseVTT(transcriptContent);
Expand Down Expand Up @@ -212,11 +240,6 @@ export const Transcript: React.FC<TranscriptProps> = ({
}
}, [data.id, data.transcriptionStatus, data.createdAt]);

const handleReset = () => {
setIsLoading(true);
invalidateTranscript(data.id);
};

const handleTranscriptClick = (entry: TranscriptEntry) => {
if (editingEntry === entry.id) {
return;
Expand Down Expand Up @@ -421,14 +444,39 @@ export const Transcript: React.FC<TranscriptProps> = ({
);
}

if (hasTimedOut || (!transcriptData.length && !isTranscriptionProcessing)) {
const showRetryButton =
data.transcriptionStatus === "ERROR" ||
data.transcriptionStatus === null ||
(!transcriptData.length && !isTranscriptionProcessing);

if (showRetryButton) {
return (
<div className="flex justify-center items-center h-full text-gray-1">
<div className="text-center">
<MessageSquare className="mx-auto mb-2 w-8 h-8 text-gray-300" />
<p className="text-sm font-medium text-gray-12">
No transcript available
<p className="mb-4 text-sm font-medium text-gray-12">
{data.transcriptionStatus === "ERROR"
? "Transcript not available"
: "No transcript available"}
</p>
{canEdit &&
(data.transcriptionStatus === "ERROR" ||
data.transcriptionStatus === null ||
hasTimedOut) && (
<Button
onClick={() => {
retryTranscriptionMutation.mutate();
}}
disabled={retryTranscriptionMutation.isPending}
variant="primary"
size="sm"
spinner={retryTranscriptionMutation.isPending}
>
{retryTranscriptionMutation.isPending
? "Retrying..."
: "Retry Transcription"}
</Button>
)}
</div>
</div>
);
Expand Down Expand Up @@ -518,6 +566,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
e.stopPropagation();
startEditing(entry);
}}
type="button"
className="opacity-0 group-hover:opacity-100 p-1.5 hover:bg-gray-3 rounded-md transition-all duration-200"
title="Edit transcript"
>
Expand Down
4 changes: 0 additions & 4 deletions apps/web/hooks/use-transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ export const useTranscript = (
if (result.success && result.content) {
return result.content;
} else {
console.error(
"[useTranscript] Failed to fetch transcript:",
result.message,
);
if (result.message === "Transcript is not ready yet") {
throw new Error("TRANSCRIPT_NOT_READY");
}
Expand Down
60 changes: 58 additions & 2 deletions apps/web/lib/transcribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export async function transcribeVideo(
videoId: Video.VideoId,
userId: string,
aiGenerationEnabled = false,
isRetry = false,
): Promise<TranscribeResult> {
if (!serverEnv().DEEPGRAM_API_KEY) {
return {
Expand Down Expand Up @@ -77,8 +78,39 @@ export async function transcribeVideo(

const videoUrl = await bucket.getSignedObjectUrl(videoKey);

// Check if video file actually exists before transcribing
try {
const headResponse = await fetch(videoUrl, { method: "HEAD" });
if (!headResponse.ok) {
// Video not ready yet - reset to null for retry
await db()
.update(videos)
.set({ transcriptionStatus: null })
.where(eq(videos.id, videoId));

return {
success: false,
message: "Video file not ready yet - will retry automatically",
};
}
} catch {
console.log(
`[transcribeVideo] Video file not accessible yet for ${videoId}, will retry later`,
);
await db()
.update(videos)
.set({ transcriptionStatus: null })
.where(eq(videos.id, videoId));

return {
success: false,
message: "Video file not ready yet - will retry automatically",
};
}

const transcription = await transcribeAudio(videoUrl);

// Note: Empty transcription is valid for silent videos (just contains "WEBVTT\n\n")
if (transcription === "") {
throw new Error("Failed to transcribe audio");
}
Expand Down Expand Up @@ -127,19 +159,43 @@ export async function transcribeVideo(
};
} catch (error) {
console.error("Error transcribing video:", error);

// Determine if this is a temporary or permanent error
const errorMessage = error instanceof Error ? error.message : String(error);
const isTemporaryError =
errorMessage.includes("not found") ||
errorMessage.includes("access denied") ||
errorMessage.includes("network") ||
!isRetry; // First attempt failures are often temporary

const newStatus = isTemporaryError ? null : "ERROR";

await db()
.update(videos)
.set({ transcriptionStatus: "ERROR" })
.set({ transcriptionStatus: newStatus })
.where(eq(videos.id, videoId));

return { success: false, message: "Error processing video file" };
return {
success: false,
message: isTemporaryError
? "Video not ready - will retry"
: "Transcription failed permanently",
};
}
}

function formatToWebVTT(result: any): string {
let output = "WEBVTT\n\n";
let captionIndex = 1;

// Handle case where there are no utterances (silent video)
if (!result.results.utterances || result.results.utterances.length === 0) {
console.log(
"[formatToWebVTT] No utterances found - video appears to be silent",
);
return output; // Return valid but empty VTT file
}

result.results.utterances.forEach((utterance: any) => {
const words = utterance.words;
let group = [];
Expand Down
Loading