feat: Title - AI translation for booking pages (#17794)

* feat: AI description - DB model + frontend + backend (fetch only)

* fix types and add validation to backend

* improve log

* improve

* import type

* add EventTypeTranslationRepository

* fix replexica error

* fix replexica error

* fix

* fix test

* wip

* wip

* add createManyDescriptionTranslations method

* improve logic

* refactor

* update replexica type

* improve typing

* Renamed descriptionTranslations to fieldTranslations

* log errors in replexica service

* handle translations in background

* don't create, upsert instead

* make sure that description is updated

* simplify

* fix

* Update packages/trpc/server/routers/viewer/eventTypes/update.handler.ts

* improve filter logic in frontend

* implement background job using Tasker

* update schema

* update schema again

* rename

* rename id to uid

* add migration

* fix type

* update

* update schema and migration sql

* fix migration

* fix type check

* fix type check 2

* improve find logic in EventMeta

* add more validation

* add logger

* rename

* upgrade replexica/sdk to 0.7.0

* upgrade replexica to 0.7.0

* use batchLocalizeText

* add comments

* override browser locale if user is a signed in calcom user

* fix type in replexica

* fix migration sql

* fix type

* use dynamic import

* do not use batchLocalizeText

* chore: drop sourceLang, targetLang and id columns

* fix

* wip

* add more validations

* fix type error

* address comment

* refactor

* update booking page to use translated title

* fix type error

* fix

* revert yarn.lock changes

* remove unused import

* remove duplication migrate.sql file

* fix test

* remove test tags

* fix function name

* refactor

* fix type check

* use Promise.all

* remove unneeded code

---------

Co-authored-by: Keith Williams <[email protected]>
This commit is contained in:
Benny JooandKeith Williams authored and GitHub committed 2024-12-11 14:18:32 +01:00
1 parent dd3505ad8b
commit 6739ed3a87
14 files changed
+190 -111

No files matched your search

+2 -2
View File
@@ -14,8 +14,8 @@ type TaskPayloads = {
triggerFormSubmittedNoEventWebhook: z.infer<
typeof import("./tasks/triggerFormSubmittedNoEvent/triggerFormSubmittedNoEventWebhook").ZTriggerFormSubmittedNoEventWebhookPayloadSchema
>;
translateEventTypeDescription: z.infer<
typeof import("./tasks/translateEventTypeDescription").ZTranslateEventTypeDescriptionPayloadSchema
translateEventTypeData: z.infer<
typeof import("./tasks/translateEventTypeData").ZTranslateEventDataPayloadSchema
>;
};
export type TaskTypes = keyof TaskPayloads;
+2 -2
View File
@@ -17,8 +17,8 @@ const tasks: Record<TaskTypes, () => Promise<TaskHandler>> = {
(module) => module.triggerFormSubmittedNoEventWebhook
),
sendSms: () => Promise.resolve(() => Promise.reject(new Error("Not implemented"))),
translateEventTypeDescription: () =>
import("./translateEventTypeDescription").then((module) => module.translateEventTypeDescription),
translateEventTypeData: () =>
import("./translateEventTypeData").then((module) => module.translateEventTypeData),
};
export default tasks;
@@ -0,0 +1,108 @@
import { z } from "zod";
import { locales as i18nLocales } from "@calcom/lib/i18n";
import logger from "@calcom/lib/logger";
import { EventTypeTranslationRepository } from "@calcom/lib/server/repository/eventTypeTranslation";
import { EventTypeAutoTranslatedField } from "@calcom/prisma/enums";
export const ZTranslateEventDataPayloadSchema = z.object({
eventTypeId: z.number(),
userId: z.number(),
description: z.string().nullable().optional(),
title: z.string().optional(),
userLocale: z.string(),
});
const SUPPORTED_LOCALES = [
"en", // English
"es", // Spanish
"de", // German
"pt", // Portuguese
"pt-BR", // Portuguese Brazilian
"fr", // French
"it", // Italian
"ar", // Arabic
"ru", // Russian
"zh-CN", // Simplified Chinese
"nl", // Dutch
"zh-TW", // Traditional Chinese
"ko", // Korean
"ja", // Japanese
"sv", // Swedish
"da", // Danish
] as const;
async function processTranslations({
text,
userLocale,
eventTypeId,
userId,
field,
}: {
text: string;
field: EventTypeAutoTranslatedField;
} & z.infer<typeof ZTranslateEventDataPayloadSchema>) {
const { ReplexicaService } = await import("@calcom/lib/server/service/replexica");
try {
const targetLocales = SUPPORTED_LOCALES.filter(
(locale) => locale !== userLocale && i18nLocales.includes(locale)
);
const translations = await Promise.all(
targetLocales.map((targetLocale) => ReplexicaService.localizeText(text, userLocale, targetLocale))
);
// Filter out null translations and their corresponding locales
const validTranslations = translations
.filter((trans): trans is string => trans !== null)
.map((trans, index) => ({
translatedText: trans,
targetLocale: targetLocales[index],
}));
if (validTranslations.length > 0) {
const translationData = validTranslations.map(({ translatedText, targetLocale }) => ({
eventTypeId,
sourceLocale: userLocale,
targetLocale,
translatedText,
userId,
}));
const upsertMany =
field === EventTypeAutoTranslatedField.DESCRIPTION
? EventTypeTranslationRepository.upsertManyDescriptionTranslations
: EventTypeTranslationRepository.upsertManyTitleTranslations;
await upsertMany(translationData);
}
} catch (error) {
logger.error(`Failed to process ${field} translations:`, error);
}
}
export async function translateEventTypeData(payload: string): Promise<void> {
const { eventTypeId, description, title, userLocale, userId } = ZTranslateEventDataPayloadSchema.parse(
JSON.parse(payload)
);
await Promise.all([
description &&
processTranslations({
text: description,
userLocale,
eventTypeId,
userId,
field: EventTypeAutoTranslatedField.DESCRIPTION,
}),
title &&
processTranslations({
text: title,
userLocale,
eventTypeId,
userId,
field: EventTypeAutoTranslatedField.TITLE,
}),
]);
}
@@ -1,74 +0,0 @@
import { z } from "zod";
import { locales as i18nLocales } from "@calcom/lib/i18n";
import logger from "@calcom/lib/logger";
import { EventTypeTranslationRepository } from "@calcom/lib/server/repository/eventTypeTranslation";
export const ZTranslateEventTypeDescriptionPayloadSchema = z.object({
eventTypeId: z.number(),
userId: z.number(),
description: z.string(),
userLocale: z.string(),
});
const SUPPORTED_LOCALES = [
"en", // English
"es", // Spanish
"de", // German
"pt", // Portuguese
"pt-BR", // Portuguese Brazilian
"fr", // French
"it", // Italian
"ar", // Arabic
"ru", // Russian
"zh-CN", // Simplified Chinese
"nl", // Dutch
"zh-TW", // Traditional Chinese
"ko", // Korean
"ja", // Japanese
"sv", // Swedish
"da", // Danish
] as const;
export async function translateEventTypeDescription(payload: string): Promise<void> {
const { eventTypeId, description, userLocale, userId } = ZTranslateEventTypeDescriptionPayloadSchema.parse(
JSON.parse(payload)
);
const targetLocales = SUPPORTED_LOCALES.filter(
(locale) => locale !== userLocale && i18nLocales.includes(locale)
);
const { ReplexicaService } = await import("@calcom/lib/server/service/replexica");
try {
const translatedDescriptions = await Promise.all(
targetLocales.map((targetLocale) =>
ReplexicaService.localizeText(description, userLocale, targetLocale)
)
);
const validTranslations = translatedDescriptions
.map((translatedText, index) => ({
translatedText,
targetLocale: targetLocales[index],
}))
.filter(
(item): item is { translatedText: string; targetLocale: (typeof SUPPORTED_LOCALES)[number] } =>
item.translatedText !== null
);
if (validTranslations.length > 0) {
await EventTypeTranslationRepository.upsertManyDescriptionTranslations(
validTranslations.map(({ translatedText, targetLocale }) => ({
eventTypeId,
sourceLocale: userLocale,
targetLocale,
translatedText,
userId,
}))
);
}
} catch (error) {
logger.error("Failed to process event type description translations:", error);
}
}