File size: 8,175 Bytes
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
 * 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,
};