Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add transcription API support

Richie McIlroycaadc83a54f6
diff --git a/apps/web/app/api/transcribe/route.ts b/apps/web/app/api/transcribe/route.ts
new file mode 100644
index 000000000..a7163a7be
--- /dev/null
+++ b/apps/web/app/api/transcribe/route.ts
@@ -0,0 +1,241 @@
+import { NextRequest } from "next/server";
+import {
+ S3Client,
+ ListObjectsV2Command,
+ GetObjectCommand,
+ HeadObjectCommand,
+ PutObjectCommand,
+} from "@aws-sdk/client-s3";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+import { createClient } from "@deepgram/sdk";
+import { getHeaders } from "@/utils/helpers";
+import { db } from "@cap/database";
+import { videos } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+
+export async function OPTIONS(request: NextRequest) {
+ const origin = request.headers.get("origin") as string;
+
+ return new Response(null, {
+ status: 200,
+ headers: getHeaders(origin),
+ });
+}
+
+export async function GET(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const userId = searchParams.get("userId") || "";
+ const videoId = searchParams.get("videoId") || "";
+ const origin = request.headers.get("origin") as string;
+
+ if (
+ !process.env.CAP_AWS_BUCKET ||
+ !process.env.CAP_AWS_REGION ||
+ !process.env.CAP_AWS_ACCESS_KEY ||
+ !process.env.CAP_AWS_SECRET_KEY ||
+ !process.env.DEEPGRAM_API_KEY
+ ) {
+ return new Response(
+ JSON.stringify({
+ error: true,
+ message: "Missing necessary environment variables",
+ }),
+ {
+ status: 500,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+
+ if (!userId || !videoId) {
+ return new Response(
+ JSON.stringify({
+ error: true,
+ message: "userId or videoId not supplied",
+ }),
+ {
+ status: 401,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+
+ const query = await db.select().from(videos).where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Video does not exist" }),
+ {
+ status: 401,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+
+ const video = query[0];
+
+ if (
+ video.transcriptionStatus === "COMPLETE" ||
+ video.transcriptionStatus === "PROCESSING"
+ ) {
+ return new Response(
+ JSON.stringify({
+ message: "Transcription already completed or in progress",
+ }),
+ {
+ status: 200,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+
+ await db
+ .update(videos)
+ .set({ transcriptionStatus: "PROCESSING" })
+ .where(eq(videos.id, videoId));
+
+ const bucket = process.env.CAP_AWS_BUCKET || "";
+ const audioPrefix = `${userId}/${videoId}/audio/`;
+
+ const s3Client = new S3Client({
+ region: process.env.CAP_AWS_REGION || "",
+ credentials: {
+ accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
+ secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
+ },
+ });
+
+ try {
+ const audioSegmentCommand = new ListObjectsV2Command({
+ Bucket: bucket,
+ Prefix: audioPrefix,
+ });
+
+ const objects = await s3Client.send(audioSegmentCommand);
+
+ const chunksUrls = await Promise.all(
+ (objects.Contents || []).map(async (object) => {
+ const url = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket: bucket,
+ Key: object.Key,
+ }),
+ { expiresIn: 3600 }
+ );
+ const metadata = await s3Client.send(
+ new HeadObjectCommand({
+ Bucket: bucket,
+ Key: object.Key,
+ })
+ );
+
+ return {
+ url: url,
+ duration: metadata?.Metadata?.duration ?? "",
+ key: object.Key,
+ };
+ })
+ );
+
+ let elapsedTime = 0;
+ const transcriptions = [];
+ for (const chunk of chunksUrls) {
+ const transcription = await transcribeAudioSegment(chunk, elapsedTime);
+ elapsedTime += Number(chunk.duration);
+ transcriptions.push(transcription);
+ }
+
+ const vttContent =
+ "WEBVTT\n\n" +
+ transcriptions
+ .map((transcription, index) => {
+ const end = transcription.end;
+ return `${index + 1}\n${formatTimestamp(
+ Number(transcription.start)
+ )} --> ${formatTimestamp(Number(end))}\n${transcription.text}\n\n`;
+ })
+ .join("");
+
+ const vttKey = `${userId}/${videoId}/subtitles.vtt`;
+ await s3Client.send(
+ new PutObjectCommand({
+ Bucket: bucket,
+ Key: vttKey,
+ Body: vttContent,
+ ContentType: "text/vtt",
+ })
+ );
+
+ await db
+ .update(videos)
+ .set({ transcriptionStatus: "COMPLETE" })
+ .where(eq(videos.id, videoId));
+
+ return new Response(
+ JSON.stringify({
+ message: "VTT file generated and uploaded successfully",
+ }),
+ {
+ status: 200,
+ headers: getHeaders(origin),
+ }
+ );
+ } catch (error) {
+ await db
+ .update(videos)
+ .set({ transcriptionStatus: "ERROR" })
+ .where(eq(videos.id, videoId));
+
+ return new Response(
+ JSON.stringify({ error: true, message: "Error processing audio files" }),
+ {
+ status: 500,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+}
+
+function formatTimestamp(seconds: number): string {
+ const date = new Date(seconds * 1000);
+ const hours = date.getUTCHours().toString().padStart(2, "0");
+ const minutes = date.getUTCMinutes().toString().padStart(2, "0");
+ const secs = date.getUTCSeconds().toString().padStart(2, "0");
+ const millis = (date.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5);
+
+ return `${hours}:${minutes}:${secs}.${millis}`;
+}
+
+async function transcribeAudioSegment(
+ chunk: any,
+ startTime: number
+): Promise<any> {
+ const transcription = await transcribeAudio(chunk.url);
+ const duration = Number(chunk.duration);
+
+ return {
+ start: startTime,
+ text: transcription,
+ end: startTime + duration,
+ };
+}
+
+async function transcribeAudio(audioUrl: string): Promise<string> {
+ const deepgram = createClient(process.env.DEEPGRAM_API_KEY as string);
+
+ const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
+ {
+ url: audioUrl,
+ },
+ {
+ model: "nova-2",
+ smart_format: true,
+ language: "en-GB",
+ }
+ );
+
+ if (error) return "";
+
+ return result.results.channels[0].alternatives[0].transcript;
+}
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index ece537555..2fd90598f 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -12,6 +12,7 @@ import {
import { LogoSpinner } from "@cap/ui";
import { userSelectProps } from "@cap/database/auth/session";
import { Tooltip } from "react-tooltip";
+import { fromVtt, Subtitle } from "subtitles-parser-vtt";
declare global {
interface Window {
@@ -44,6 +45,7 @@ export const ShareVideo = ({
const [seeking, setSeeking] = useState(false);
const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
const [overlayVisible, setOverlayVisible] = useState(true);
+ const [subtitles, setSubtitles] = useState<Subtitle[]>([]);
const overlayTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
@@ -239,6 +241,32 @@ export const ShareVideo = ({
}
}, [isPlaying, isLoading]);
+ const parseSubTime = (timeString: number) => {
+ const [hours, minutes, seconds] = timeString
+ .toString()
+ .split(":")
+ .map(Number);
+ return hours * 3600 + minutes * 60 + seconds;
+ };
+
+ useEffect(() => {
+ if (data.transcriptionStatus !== "complete") return;
+
+ fetch(`https://v.cap.so/${data.ownerId}/${data.id}/subtitles.vtt`)
+ .then((response) => response.text())
+ .then((text) => {
+ const parsedSubtitles = fromVtt(text);
+ console.log("Parsed subtitles:", parsedSubtitles);
+ setSubtitles(parsedSubtitles);
+ });
+ }, [data]);
+
+ const currentSubtitle = subtitles.find(
+ (subtitle) =>
+ parseSubTime(subtitle.startTime) <= currentTime &&
+ parseSubTime(subtitle.endTime) >= currentTime
+ );
+
if (data.jobStatus === "ERROR") {
return (
<div className="flex items-center justify-center w-full h-full rounded-lg overflow-hidden">
@@ -290,6 +318,13 @@ export const ShareVideo = ({
className="relative block w-full h-full rounded-lg bg-black"
style={{ paddingBottom: "min(806px, 56.25%)" }}
>
+ {currentSubtitle && currentSubtitle.text && (
+ <div className="absolute bottom-0 w-full text-center transform transition p-1.5 lg:p-2.5 xl:p-3.5 -translate-y-16 z-10">
+ <div className="inline px-2 py-1 text-sm text-white bg-black bg-opacity-75 rounded-xl leading-7 md:text-lg md:leading-9 lg:text-2xl lg:leading-11 2xl:text-3xl 2xl:leading-13 xs:text-base box-decoration-break-clone xs:leading-8 xl:text-2.5xl">
+ {currentSubtitle.text}
+ </div>
+ </div>
+ )}
<VideoPlayer
ref={videoRef}
videoSrc={
diff --git a/apps/web/package.json b/apps/web/package.json
index 14e6cdb0a..90a10220b 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -17,6 +17,7 @@
"@cap/database": "workspace:*",
"@cap/ui": "workspace:*",
"@cap/utils": "workspace:*",
+ "@deepgram/sdk": "^3.3.4",
"@ffmpeg/ffmpeg": "^0.12.10",
"@ffmpeg/util": "^0.12.1",
"@headlessui/react": "^1.7.17",
@@ -55,6 +56,7 @@
"react-tooltip": "^5.26.3",
"resend": "1.1.0",
"server-only": "^0.0.1",
+ "subtitles-parser-vtt": "^0.1.0",
"tailwind-merge": "^2.1.0",
"zod": "^3.22.4"
},
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 9024c117d..6a5018ed2 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -151,6 +151,7 @@ export const videos = mysqlTable(
jobId: varchar("jobId", { length: 255 }),
jobStatus: varchar("jobStatus", { length: 255 }),
skipProcessing: boolean("skipProcessing").notNull().default(false),
+ transcriptionStatus: varchar("transcriptionStatus", { length: 255 }),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
},