feat: AI Transcribe (#14140)

* chore: transcribe

* chore: provider

* chore: use daily provider

* chore: rebase

* chore: remove types file

* chore: remove recoil

* chore: progress

* chore: add recoil

* chore: save progress

* chore: save progress

* fix: type err

* fix: err

* fix: save progress

* feat: finish emails

* chore: add new env variable

* chore: fix type err

* chore: turbo

* chore: improvements

---------

Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
Co-authored-by: Carina Wollendorfer <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-04-17 11:09:11 -04:00
1 parent ebca5c6409
commit b9ac22d4ed
20 files changed
+859 -55

No files matched your search

@@ -0,0 +1,87 @@
import { useTranscription } from "@daily-co/daily-react";
import { useDaily, useDailyEvent } from "@daily-co/daily-react";
import React, { Fragment, useCallback, useRef, useState, useLayoutEffect, useEffect } from "react";
import { Toaster } from "react-hot-toast";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { showToast } from "@calcom/ui";
export const CalAiTransctibe = () => {
const daily = useDaily();
const { t } = useLocale();
const [transcript, setTranscript] = useState("");
const [transcriptHeight, setTranscriptHeight] = useState(0);
const transcriptRef = useRef<HTMLDivElement | null>(null);
const transcription = useTranscription();
useDailyEvent(
"app-message",
useCallback((ev) => {
const data = ev?.data;
if (data.user_name && data.text) setTranscript(`${data.user_name}: ${data.text}`);
}, [])
);
useDailyEvent("transcription-started", (ev) => {
showToast(t("transcription_enabled"), "success");
});
useDailyEvent("transcription-stopped", (ev) => {
showToast(t("transcription_stopped"), "success");
});
useDailyEvent("custom-button-click", (ev) => {
if (ev?.button_id !== "transcription") {
return;
}
if (transcription?.isTranscribing) {
daily?.stopTranscription();
} else {
daily?.startTranscription();
}
});
useLayoutEffect(() => {
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
setTranscriptHeight(entry.target.scrollHeight);
}
});
if (transcriptRef.current) {
observer.observe(transcriptRef.current);
}
return () => observer.disconnect();
}, []);
useEffect(() => {
transcriptRef.current?.scrollTo({
top: transcriptRef.current?.scrollHeight,
behavior: "smooth",
});
}, [transcriptHeight]);
return (
<>
<Toaster position="bottom-right" />
<div
id="cal-ai-thing"
ref={transcriptRef}
className="max-h-full overflow-x-hidden overflow-y-scroll p-2 text-center text-white">
{transcript
? transcript.split("\n").map((line, i) => (
<Fragment key={`transcript-${i}`}>
{i > 0 && <br />}
{line}
</Fragment>
))
: ""}
</div>
</>
);
};
@@ -1,22 +1,27 @@
"use client";
import type { DailyCall } from "@daily-co/daily-js";
import DailyIframe from "@daily-co/daily-js";
import { DailyProvider } from "@daily-co/daily-react";
import Head from "next/head";
import { useState, useEffect, useRef } from "react";
import dayjs from "@calcom/dayjs";
import classNames from "@calcom/lib/classNames";
import { APP_NAME, SEO_IMG_OGIMG_VIDEO, WEBSITE_URL } from "@calcom/lib/constants";
import { APP_NAME, SEO_IMG_OGIMG_VIDEO, WEBSITE_URL, WEBAPP_URL } from "@calcom/lib/constants";
import { formatToLocalizedDate, formatToLocalizedTime } from "@calcom/lib/date-fns";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import { Icon } from "@calcom/ui";
import { CalAiTransctibe } from "~/videos/ai/ai-transcribe";
import { type PageProps } from "./videos-single-view.getServerSideProps";
export default function JoinCall(props: PageProps) {
const { t } = useLocale();
const { meetingUrl, meetingPassword, booking } = props;
const [daily, setDaily] = useState<DailyCall | null>(null);
useEffect(() => {
const callFrame = DailyIframe.createFrame({
@@ -42,8 +47,20 @@ export default function JoinCall(props: PageProps) {
},
url: meetingUrl,
...(typeof meetingPassword === "string" && { token: meetingPassword }),
customTrayButtons: {
transcription: {
label: "Enable Transcription",
tooltip: "Toggle Transcription",
iconPath: `${WEBAPP_URL}/sparkles.svg`,
iconPathDarkMode: `${WEBAPP_URL}/sparkles.svg`,
},
},
});
setDaily(callFrame);
callFrame.join();
return () => {
callFrame.destroy();
};
@@ -67,30 +84,35 @@ export default function JoinCall(props: PageProps) {
<meta property="twitter:title" content={`${APP_NAME} Video`} />
<meta property="twitter:description" content={t("quick_video_meeting")} />
</Head>
<div style={{ zIndex: 2, position: "relative" }}>
{booking?.user?.organization?.calVideoLogo ? (
<img
className="min-w-16 min-h-16 fixed z-10 hidden aspect-square h-16 w-16 rounded-full sm:inline-block"
src={booking.user.organization.calVideoLogo}
alt="My Org Logo"
style={{
top: 32,
left: 32,
}}
/>
) : (
<img
className="fixed z-10 hidden sm:inline-block"
src={`${WEBSITE_URL}/cal-logo-word-dark.svg`}
alt="Logo"
style={{
top: 32,
left: 32,
}}
/>
)}
</div>
<VideoMeetingInfo booking={booking} />
<DailyProvider callObject={daily}>
<div className="mx-auto" style={{ zIndex: 2, position: "absolute", bottom: 60, width: "100%" }}>
<CalAiTransctibe />
</div>
<div style={{ zIndex: 2, position: "relative" }}>
{booking?.user?.organization?.calVideoLogo ? (
<img
className="min-w-16 min-h-16 fixed z-10 hidden aspect-square h-16 w-16 rounded-full sm:inline-block"
src={booking.user.organization.calVideoLogo}
alt="My Org Logo"
style={{
top: 32,
left: 32,
}}
/>
) : (
<img
className="fixed z-10 hidden sm:inline-block"
src={`${WEBSITE_URL}/cal-logo-word-dark.svg`}
alt="Logo"
style={{
top: 32,
left: 32,
}}
/>
)}
</div>
<VideoMeetingInfo booking={booking} />
</DailyProvider>
</>
);
}
+3 -1
View File
@@ -38,7 +38,8 @@
"@calcom/trpc": "*",
"@calcom/tsconfig": "*",
"@calcom/ui": "*",
"@daily-co/daily-js": "^0.37.0",
"@daily-co/daily-js": "^0.59.0",
"@daily-co/daily-react": "^0.17.2",
"@formkit/auto-animate": "1.0.0-beta.5",
"@glidejs/glide": "^3.5.2",
"@hookform/error-message": "^2.0.0",
@@ -121,6 +122,7 @@
"react-timezone-select": "^1.4.0",
"react-turnstile": "^1.1.3",
"react-use-intercom": "1.5.1",
"recoil": "^0.7.7",
"remove-markdown": "^0.5.0",
"rrule": "^2.7.1",
"sanitize-html": "^2.10.0",
+1
View File
@@ -12,6 +12,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
res.setHeader("Content-Type", "text/html");
res.setHeader("Cache-Control", "no-cache, no-store, private, must-revalidate");
res.write(
await renderEmail("MonthlyDigestEmail", {
language: t,
+2 -2
View File
@@ -15,7 +15,7 @@ import { getTranslation } from "@calcom/lib/server/i18n";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import type { CalendarEvent } from "@calcom/types/Calendar";
const log = logger.getSubLogger({ prefix: ["recorded-daily-video"] });
const log = logger.getSubLogger({ prefix: ["daily-video-webhook-handler"] });
const schema = z
.object({
@@ -116,7 +116,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const response = schema.safeParse(req.body);
log.debug(
"Recording Request Body:",
"Daily video recording webhook Request Body:",
safeStringify({
response,
})
@@ -0,0 +1,182 @@
import { createHmac } from "crypto";
import type { NextApiRequest, NextApiResponse } from "next";
import { z } from "zod";
import { getAllTranscriptsAccessLinkFromRoomName } from "@calcom/core/videoClient";
import { sendDailyVideoTranscriptEmails } from "@calcom/emails";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { defaultHandler } from "@calcom/lib/server";
import { getTranslation } from "@calcom/lib/server/i18n";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import type { CalendarEvent } from "@calcom/types/Calendar";
const testRequestSchema = z.object({
test: z.enum(["test"]),
});
const log = logger.getSubLogger({ prefix: ["send-daily-video-transcript-handler"] });
const schema = z
.object({
version: z.string(),
type: z.string(),
id: z.string(),
payload: z
.object({
meeting_id: z.string(),
end_ts: z.number().optional(),
room: z.string(),
start_ts: z.number().optional(),
})
.passthrough(),
event_ts: z.number().optional(),
})
.passthrough();
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (testRequestSchema.safeParse(req.body).success) {
return res.status(200).json({ message: "Test request successful" });
}
const hmacSecret = process.env.DAILY_MEETING_ENDED_WEBHOOK_SECRET;
if (!hmacSecret) {
return res.status(405).json({ message: "No Daily Webhook Secret" });
}
const signature = `${req.headers["x-webhook-timestamp"]}.${JSON.stringify(req.body)}`;
const base64DecodedSecret = Buffer.from(hmacSecret, "base64");
const hmac = createHmac("sha256", base64DecodedSecret);
const computed_signature = hmac.update(signature).digest("base64");
if (req.headers["x-webhook-signature"] !== computed_signature) {
return res.status(403).json({ message: "Signature does not match" });
}
const response = schema.safeParse(req.body);
log.debug(
"Daily video transcript webhook Request Body:",
safeStringify({
response,
})
);
if (!response.success || response.data.type !== "meeting.ended") {
return res.status(400).send({
message: "Invalid Payload",
});
}
const { room, meeting_id } = response.data.payload;
try {
const bookingReference = await prisma.bookingReference.findFirst({
where: { type: "daily_video", uid: room, meetingId: room },
select: { bookingId: true },
});
if (!bookingReference || !bookingReference.bookingId) {
log.error(
"bookingReference Not found:",
safeStringify({
bookingReference,
requestBody: req.body,
})
);
return res.status(404).send({ message: "Booking reference not found" });
}
const booking = await prisma.booking.findUniqueOrThrow({
where: {
id: bookingReference.bookingId,
},
select: {
...bookingMinimalSelect,
uid: true,
location: true,
isRecorded: true,
eventTypeId: true,
eventType: {
select: {
teamId: true,
parentId: true,
},
},
user: {
select: {
id: true,
timeZone: true,
email: true,
name: true,
locale: true,
destinationCalendar: true,
},
},
},
});
if (!booking) {
log.error(
"Booking Not Found:",
safeStringify({
booking,
requestBody: req.body,
})
);
return res.status(404).send({
message: `Booking of room_name ${room} does not exist or does not contain daily video as location`,
});
}
const transcripts = await getAllTranscriptsAccessLinkFromRoomName(room);
if (!transcripts || !transcripts.length)
return res.status(200).json({ message: `No Transcripts found for room name ${room}` });
const t = await getTranslation(booking?.user?.locale ?? "en", "common");
const attendeesListPromises = booking.attendees.map(async (attendee) => {
return {
id: attendee.id,
name: attendee.name,
email: attendee.email,
timeZone: attendee.timeZone,
language: {
translate: await getTranslation(attendee.locale ?? "en", "common"),
locale: attendee.locale ?? "en",
},
};
});
const attendeesList = await Promise.all(attendeesListPromises);
// Send emails
const evt: CalendarEvent = {
type: booking.title,
title: booking.title,
description: booking.description || undefined,
startTime: booking.startTime.toISOString(),
endTime: booking.endTime.toISOString(),
organizer: {
email: booking?.userPrimaryEmail || booking.user?.email || "Email-less",
name: booking.user?.name || "Nameless",
timeZone: booking.user?.timeZone || "Europe/London",
language: { translate: t, locale: booking?.user?.locale ?? "en" },
},
attendees: attendeesList,
uid: booking.uid,
};
await sendDailyVideoTranscriptEmails(evt, transcripts);
return res.status(200).json({ message: "Success" });
} catch (err) {
console.error("Error in /send-daily-video-transcript", err);
return res.status(500).json({ message: "something went wrong" });
}
}
export default defaultHandler({
POST: Promise.resolve({ default: handler }),
});
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#f4f4f4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sparkles"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>

After

Width:  |  Height:  |  Size: 467 B

@@ -19,6 +19,7 @@
"verify_email_banner_body": "Verify your email address to guarantee the best email and calendar deliverability",
"verify_email_email_header": "Verify your email address",
"verify_email_email_button": "Verify email",
"cal_ai_assistant":"Cal AI Assistant",
"verify_email_change_description": "You have recently requested to change the email address you use to log into your {{appName}} account. Please click the button below to confirm your new email address.",
"verify_email_change_success_toast": "Updated your email to {{email}}",
"verify_email_change_failure_toast": "Failed to update email.",
@@ -110,7 +111,9 @@
"event_still_awaiting_approval": "An event is still waiting for your approval",
"booking_submitted_subject": "Booking Submitted: {{title}} at {{date}}",
"download_recording_subject": "Download Recording: {{title}} at {{date}}",
"download_transcript_email_subject":"Download Transcript: {{title}} at {{date}}",
"download_your_recording": "Download your recording",
"download_your_transcripts":"Download your Transcripts",
"your_meeting_has_been_booked": "Your meeting has been booked",
"event_type_has_been_rescheduled_on_time_date": "Your {{title}} has been rescheduled to {{date}}.",
"event_has_been_rescheduled": "Updated - Your event has been rescheduled",
@@ -1429,7 +1432,11 @@
"download_responses_description": "Download all responses to your form in CSV format.",
"download": "Download",
"download_recording": "Download Recording",
"transcription_enabled": "Transcriptions are enabled now",
"transcription_stopped": "Transcriptions are stopped now",
"download_transcript": "Download Transcript",
"recording_from_your_recent_call": "A recording from your recent call on {{appName}} is ready for download",
"transcript_from_previous_call": "Transcript from your recent call on {{appName}} is ready to download. Links are valid only for 1 Hour",
"link_valid_for_12_hrs":"Note: The download link is valid only for 12 hours. You can generate new download link by following instructions <1>here</1>.",
"create_your_first_form": "Create your first form",
"create_your_first_form_description": "With Routing Forms you can ask qualifying questions and route to the correct person or event type.",