/** * Gemini Service — Unified wrapper for Google AI APIs * Uses @google/genai SDK for: Text (Gemini Flash), Video (Veo 3.1), Image (Nano Banana) * All FREE with the same GEMINI_API_KEY */ const fs = require('fs').promises; const path = require('path'); let _aiClient = null; /** * Get or create the GoogleGenAI client (lazy singleton) * Uses dynamic import because @google/genai is ESM-only */ async function getClient() { if (_aiClient) return _aiClient; const apiKey = process.env.GEMINI_API_KEY; if (!apiKey) { throw new Error('GEMINI_API_KEY not set in environment variables'); } const { GoogleGenAI } = await import('@google/genai'); _aiClient = new GoogleGenAI({ apiKey }); return _aiClient; } /** * Generate a YouTube Shorts script using Gemini AI * @param {string} topic - Video topic * @param {string} niche - Channel niche (e.g., "tech facts", "scary stories") * @param {number} durationSec - Target duration in seconds (default 45) * @returns {Object} Structured script object */ async function generateShortsScript(topic, niche = 'interesting facts', durationSec = 45) { const ai = await getClient(); const prompt = `You are an expert YouTube Shorts scriptwriter for a faceless channel in the "${niche}" niche. Write a viral YouTube Short script about: "${topic}" RULES: - Target duration: ${durationSec} seconds (about ${Math.round(durationSec * 2.5)} words) - Start with a powerful HOOK in the first 2 seconds (question, shocking fact, or bold statement) - Use short, punchy sentences - Include 3-5 key points or story beats - End with a call-to-action ("Follow for more" or a thought-provoking question) - Write ONLY the narration text (no stage directions, no visual descriptions) - Make it engaging, surprising, and shareable RESPOND IN THIS EXACT JSON FORMAT: { "title": "Catchy Shorts Title (under 100 chars)", "hook": "The opening 2-second hook line", "script": "The full narration script text", "scenes": [ { "sceneNumber": 1, "narration": "Text for this scene", "visualPrompt": "Cinematic description for AI video generation (what to show visually)", "durationSec": 8 } ], "hashtags": ["#shorts", "#tag1", "#tag2"], "description": "YouTube description text" } Make sure each scene's visualPrompt is a detailed, cinematic prompt suitable for AI video generation. Each scene should be about 6-8 seconds.`; const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: prompt, config: { responseMimeType: 'application/json', }, }); const text = response.text || response.candidates?.[0]?.content?.parts?.[0]?.text; try { return JSON.parse(text); } catch (e) { // Try to extract JSON from response const jsonMatch = text.match(/\{[\s\S]*\}/); if (jsonMatch) { return JSON.parse(jsonMatch[0]); } throw new Error('Failed to parse script response: ' + text.substring(0, 200)); } } /** * Generate a REAL AI video clip using Veo 3.1 * @param {string} prompt - Visual description for the video * @param {string} aspectRatio - "9:16" for Shorts (portrait) or "16:9" for landscape * @returns {string} Path to downloaded MP4 file */ async function generateVideoClip(prompt, aspectRatio = '9:16') { const ai = await getClient(); console.log(` 🎬 Generating Veo video clip...`); console.log(` Prompt: "${prompt.substring(0, 80)}..."`); let operation = await ai.models.generateVideos({ model: 'veo-3.1-generate-preview', prompt: prompt, config: { aspectRatio: aspectRatio, }, }); // Poll until done (video generation takes ~1-3 minutes) let pollCount = 0; const maxPolls = 60; // 10 minutes max while (!operation.done) { pollCount++; if (pollCount > maxPolls) { throw new Error('Video generation timed out after 10 minutes'); } console.log(` ⏳ Generating... (${pollCount * 10}s elapsed)`); await new Promise(r => setTimeout(r, 10000)); operation = await ai.operations.getVideosOperation({ operation }); } // Download the video const outputDir = path.join(__dirname, '..', 'data', 'videos', 'clips'); await fsPromises.mkdir(outputDir, { recursive: true }); const outputPath = path.join(outputDir, `veo_clip_${Date.now()}.mp4`); await ai.files.download({ file: operation.response.generatedVideos[0].video, downloadPath: outputPath, }); console.log(` ✅ Video clip saved: ${path.basename(outputPath)}`); return outputPath; } /** * Generate an AI image using Gemini Nano Banana (for thumbnails/visuals) * @param {string} prompt - Image description * @param {string} outputPath - Where to save the image * @returns {string} Path to saved image */ async function generateImage(prompt, outputPath = null) { const ai = await getClient(); console.log(` 🖼️ Generating AI image...`); const response = await ai.models.generateContent({ model: 'gemini-3.1-flash-image-preview', contents: prompt, config: { responseModalities: ['TEXT', 'IMAGE'], }, }); // Find the image part in the response try { const candidates = response.candidates || []; if (candidates.length === 0) throw new Error('No candidates in response'); const parts = candidates[0].content.parts || []; for (const part of parts) { if (part.inlineData) { const imageData = part.inlineData.data; const buffer = Buffer.from(imageData, 'base64'); if (!outputPath) { const outputDir = path.join(__dirname, '..', 'data', 'assets'); await fsPromises.mkdir(outputDir, { recursive: true }); outputPath = path.join(outputDir, `ai_image_${Date.now()}.png`); } await fsPromises.writeFile(outputPath, buffer); console.log(` ✅ Image saved: ${path.basename(outputPath)}`); return outputPath; } } } catch (err) { console.error(' ❌ Error parsing image response:', err.message); throw err; } throw new Error('No image generated in response: ' + JSON.stringify(response).substring(0, 200)); } /** * Generate a YouTube Shorts thumbnail * @param {string} title - Video title * @param {string} style - Visual style * @returns {string} Path to thumbnail image */ async function generateThumbnail(title, style = 'vibrant') { const outputDir = path.join(__dirname, '..', 'data', 'thumbnails'); await fsPromises.mkdir(outputDir, { recursive: true }); const outputPath = path.join(outputDir, `thumb_${Date.now()}.png`); const prompt = `Create a stunning, eye-catching YouTube Shorts thumbnail image for a video titled: "${title}". Style: ${style}, bold, high contrast, vibrant colors, clean composition. Portrait orientation (9:16). NO text on the image. Make it visually striking and click-worthy. Professional quality, cinematic lighting.`; return await generateImage(prompt, outputPath); } /** * Generate content ideas for a niche * @param {string} niche - Channel niche * @param {number} count - Number of ideas * @returns {Array} List of content ideas */ async function generateContentIdeas(niche, count = 10) { const ai = await getClient(); const prompt = `Generate ${count} viral YouTube Shorts video ideas for a faceless channel in the "${niche}" niche. Each idea should be likely to go viral and work well as a 30-60 second Short. RESPOND IN JSON FORMAT: { "ideas": [ { "title": "Video Title", "topic": "Brief topic description", "hook": "Opening hook line", "viralScore": 85 } ] } Focus on topics that are: surprising, emotional, educational, or entertaining.`; const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: prompt, config: { responseMimeType: 'application/json', }, }); const text = response.text || response.candidates?.[0]?.content?.parts?.[0]?.text; const data = JSON.parse(text); return data.ideas || data; } module.exports = { getClient, generateShortsScript, generateVideoClip, generateImage, generateThumbnail, generateContentIdeas, };