Test-Generate-123/Template-01/src/services/gemini.ts
2026-05-13 22:38:24 +00:00

57 lines
1.8 KiB
TypeScript

import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: (process.env.GEMINI_API_KEY as string) });
export async function translateText(text: string, targetLang: string) {
if (!text) return text;
try {
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: `Translate the following text to ${targetLang}. Keep the markdown formatting and don't add any extra commentary. Just the translation: \n\n${text}`,
});
return response.text || text;
} catch (error) {
console.error("Translation error:", error);
return text;
}
}
export async function translateArticle(article: any, targetLang: string) {
try {
const prompt = `Translate the following article object to ${targetLang}.
Return a JSON object with the same structure.
Only translate the 'title', 'excerpt', 'content', 'metaTitle', and 'metaDescription' fields.
Keep the 'id', 'slug', 'category', 'publishedAt', 'image', 'readTime', 'author', 'tags', and 'lang' (set lang to ${targetLang}) fields exactly as they are.
Article to translate:
${JSON.stringify({
title: article.title,
excerpt: article.excerpt,
content: article.content,
metaTitle: article.metaTitle,
metaDescription: article.metaDescription
})}
`;
const response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: prompt,
config: {
responseMimeType: "application/json",
}
});
const translatedParts = JSON.parse(response.text || "{}");
return {
...article,
...translatedParts,
lang: targetLang
};
} catch (error) {
console.error("Article translation error:", error);
return article;
}
}