Skip to content

🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.

v2.3: Gemini media parity, 50x faster slideshow rendering, evergreen template topics

darkzOGxb5c0943d793d
diff --git a/.env.example b/.env.example
index baf8c75..69103e4 100644
--- a/.env.example
+++ b/.env.example
@@ -16,6 +16,14 @@ OPENAI_API_KEY=your-openai-api-key-here
# Replicate (optional, for AI video generation)
# REPLICATE_API_KEY=your-replicate-api-key-here
+# Gemini media generation (used when GEMINI_API_KEY is your provider)
+# GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
+# GEMINI_TTS_MODEL=gemini-3.1-flash-tts-preview
+# GEMINI_TTS_VOICE=Kore
+
+# FFmpeg (optional override; resolution order: FFMPEG_PATH > bundled ffmpeg-static > system PATH)
+# FFMPEG_PATH=
+
# Azure Speech TTS (optional alternative)
# AZURE_SPEECH_KEY=your-azure-speech-key-here
# AZURE_SPEECH_REGION=eastus
diff --git a/README.md b/README.md
index e69220a..077a687 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,12 @@
# YouTube Automation Agent
+## What's New in v2.3
+
+- **Full free-tier pipeline with Gemini** β€” image generation (`gemini-3.1-flash-image`) and native voice narration (`gemini-3.1-flash-tts-preview`) now run on your Gemini key. A Gemini-only setup produces complete narrated videos end to end; OpenAI/ElevenLabs are used first when configured. Models and voice are configurable via `GEMINI_IMAGE_MODEL`, `GEMINI_TTS_MODEL`, `GEMINI_TTS_VOICE`. (Thanks to PR #6 for demonstrating the demand and fallback-chain direction.)
+- **~50Γ— faster slideshow rendering** β€” instead of screenshotting a headless browser at 30fps (~10 minutes for a 30-second video), the renderer captures one still per slide and lets FFmpeg build the video with crossfades (seconds).
+- **No more junk template topics** β€” template mode (no AI key) previously scraped single keywords from trending titles and produced videos like "crown: The Complete Guide". It now uses a curated evergreen topic list and only accepts trending topics that read like real subjects.
+- **Model catalog corrections** β€” replaced the nonexistent `gemini-3.5-pro` picker entry with `gemini-3.1-pro-preview` / `gemini-2.5-pro` (verified against Google's current model list).
+
## What's New in v2.2
This release resolves every open GitHub issue (#1, #2, #3, #4, #8, #9, #13):
@@ -121,7 +128,7 @@ Dashboard runs at `http://localhost:3456`.
- FFmpeg β€” bundled automatically via `ffmpeg-static` on `npm install`; a system install on your PATH or an `FFMPEG_PATH` env var takes precedence
- Google account (YouTube Data API β€” free)
- At least one AI provider key (OpenAI, Gemini, OpenRouter, Kimi, MiMo, or GLM) β€” without one, agents fall back to template-based generation
-- Optional: an OpenAI key for image generation and a TTS provider (OpenAI / ElevenLabs / Azure) for narration β€” without them you get gradient slides and silent video
+- Images and narration come from your AI key: OpenAI **or Gemini** both cover image generation and TTS (ElevenLabs / Azure Speech optional for premium voices) β€” with no media provider at all you get gradient slides and silent video
## Configuration
diff --git a/agents/content-strategy-agent.js b/agents/content-strategy-agent.js
index fdf9e40..6b4f3da 100644
--- a/agents/content-strategy-agent.js
+++ b/agents/content-strategy-agent.js
@@ -344,15 +344,46 @@ Avoid fabricated claims and unsupported numbers.`;
selectOptimalTopic() {
// Use scoring algorithm to select best topic
const recentTopics = this.getRecentTopics();
-
+
const scoredTopics = this.trendingTopics
.filter(topic => !recentTopics.includes(topic.topic))
.map(topic => ({
...topic,
finalScore: topic.score * this.getSeasonalMultiplier(topic.topic) * this.getAudienceMultiplier(topic.topic)
- }));
+ }))
+ .sort((a, b) => b.finalScore - a.finalScore);
+
+ // Single keywords scraped from trending titles ("crown", "official") make
+ // meaningless video topics β€” only use a trend that reads like a real subject.
+ const readable = scoredTopics.find(t => t.topic.trim().includes(' ') && t.topic.trim().length >= 8);
+ if (readable) {
+ return readable;
+ }
- return scoredTopics[0] || { topic: 'Technology Trends', score: 1 };
+ const fallbackTopics = this.getEvergreenFallbackTopics();
+ const pick = fallbackTopics[Math.floor(Math.random() * fallbackTopics.length)];
+ this.logger.info(`Template mode: no readable trending topic available β€” using evergreen topic "${pick}"`);
+ return { topic: pick, score: 1 };
+ }
+
+ getEvergreenFallbackTopics() {
+ return [
+ 'Time Management Strategies That Actually Work',
+ 'Beginner Mistakes to Avoid When Learning a New Skill',
+ 'How to Start a Side Project With Zero Budget',
+ 'Simple Habits That Improve Focus and Productivity',
+ 'How to Learn Anything Faster Using Proven Study Techniques',
+ 'Practical Ways to Save Money Every Month',
+ 'How Artificial Intelligence Is Changing Everyday Life',
+ 'The Science of Building Habits That Stick',
+ 'How to Give a Presentation People Actually Remember',
+ 'Getting Started With Investing: A Beginner Roadmap',
+ 'Digital Minimalism: Reclaiming Your Attention',
+ 'How to Negotiate Anything: Tactics That Work',
+ 'The Psychology of Procrastination and How to Beat It',
+ 'Remote Work Productivity: Setting Up for Success',
+ 'How to Read More Books Without Finding Extra Time'
+ ];
}
async generateAngle(topic) {
diff --git a/index.js b/index.js
index 951b776..b407171 100644
--- a/index.js
+++ b/index.js
@@ -92,19 +92,21 @@ class YouTubeAutomationAgent {
const creds = this.credentials.credentials || {};
const hasText = this.credentials.hasAITextProvider();
- const hasImages = Boolean(creds.openai?.apiKey || process.env.OPENAI_API_KEY);
+ const hasGemini = Boolean(creds.gemini?.apiKey || process.env.GEMINI_API_KEY);
+ const hasImages = Boolean(creds.openai?.apiKey || process.env.OPENAI_API_KEY || hasGemini);
const hasTTS = Boolean(
creds.openai?.apiKey || process.env.OPENAI_API_KEY ||
creds.elevenLabs?.apiKey || process.env.ELEVENLABS_API_KEY ||
- creds.azureSpeech?.subscriptionKey || process.env.AZURE_SPEECH_KEY
+ creds.azureSpeech?.subscriptionKey || process.env.AZURE_SPEECH_KEY ||
+ hasGemini
);
const hasFFmpeg = await checkFFmpeg();
const hasUpload = Boolean(creds.youtube && this.credentials.tokens?.youtube);
const capabilities = [
{ name: 'Script & strategy generation', ok: hasText, hint: 'configure an AI provider (npm run credentials:setup)' },
- { name: 'Image generation (visuals/thumbnails)', ok: hasImages, hint: 'requires an OpenAI API key β€” otherwise gradient slides are used' },
- { name: 'Voice narration (TTS)', ok: hasTTS, hint: 'configure OpenAI, ElevenLabs, or Azure Speech β€” otherwise videos are silent' },
+ { name: 'Image generation (visuals/thumbnails)', ok: hasImages, hint: 'requires an OpenAI or Gemini API key β€” otherwise gradient slides are used' },
+ { name: 'Voice narration (TTS)', ok: hasTTS, hint: 'configure OpenAI, Gemini, ElevenLabs, or Azure Speech β€” otherwise videos are silent' },
{ name: 'Video assembly (FFmpeg)', ok: hasFFmpeg, hint: ffmpegInstallHint() },
{ name: 'YouTube upload', ok: hasUpload, hint: 'run: npm run credentials:setup' }
];
diff --git a/package.json b/package.json
index 48a9d70..d8d4e7b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "youtube-automation-agent",
- "version": "2.2.1",
+ "version": "2.3.0",
"description": "Fully automated YouTube channel management system with specialized AI agents",
"main": "index.js",
"scripts": {
diff --git a/test.js b/test.js
index 2c73f46..69d09b6 100644
--- a/test.js
+++ b/test.js
@@ -23,6 +23,9 @@ class SystemTest {
{ name: 'Multi-Provider Credential Validation', test: () => this.testCredentialValidation() },
{ name: 'Placeholder Scheduling Guard', test: () => this.testPlaceholderSchedulingGuard() },
{ name: 'FFmpeg Resolution', test: () => this.testFFmpegResolution() },
+ { name: 'Gemini Media Provider Selection', test: () => this.testGeminiMediaProvider() },
+ { name: 'Slideshow Renderer', test: () => this.testSlideshowRenderer() },
+ { name: 'Evergreen Template Topics', test: () => this.testEvergreenTopics() },
{ name: 'Logger System', test: () => this.testLogger() },
{ name: 'Directory Structure', test: () => this.testDirectories() },
{ name: 'Agent Loading', test: () => this.testAgentLoading() },
@@ -358,6 +361,111 @@ class SystemTest {
this.logger.info(`FFmpeg resolution test completed (binary: ${ffmpegPath}, available: ${available})`);
}
+ async testGeminiMediaProvider() {
+ const { AIVideoGenerator } = require('./utils/ai-video-generator');
+
+ const envKeys = ['OPENAI_API_KEY', 'GEMINI_API_KEY', 'REPLICATE_API_KEY', 'ELEVENLABS_API_KEY'];
+ const savedEnv = {};
+ for (const key of envKeys) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+
+ try {
+ const geminiOnly = new AIVideoGenerator({ gemini: { apiKey: 'test-key' } });
+ if (!geminiOnly.gemini) {
+ throw new Error('Gemini media service was not initialized from gemini credentials');
+ }
+ if (geminiOnly.openai) {
+ throw new Error('OpenAI client initialized without a key');
+ }
+
+ const none = new AIVideoGenerator({});
+ if (none.gemini || none.openai) {
+ throw new Error('Media services initialized without any credentials');
+ }
+ } finally {
+ for (const key of envKeys) {
+ if (savedEnv[key] === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = savedEnv[key];
+ }
+ }
+ }
+
+ this.logger.info('Gemini media provider selection test completed successfully');
+ }
+
+ async testSlideshowRenderer() {
+ const { AIVideoGenerator } = require('./utils/ai-video-generator');
+ const { checkFFmpeg } = require('./utils/ffmpeg');
+ const fs = require('fs').promises;
+ const os = require('os');
+
+ if (!(await checkFFmpeg())) {
+ this.logger.warn('FFmpeg unavailable β€” skipping slideshow renderer test');
+ return;
+ }
+
+ const sharp = require('sharp');
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'yaa-slides-'));
+
+ try {
+ const stills = [];
+ for (let i = 0; i < 3; i++) {
+ const stillPath = path.join(dir, `slide_${i}.png`);
+ await sharp({
+ create: { width: 320, height: 180, channels: 3, background: { r: 60 * i, g: 80, b: 160 } }
+ }).png().toFile(stillPath);
+ stills.push(stillPath);
+ }
+
+ const generator = new AIVideoGenerator({});
+ const videoPath = path.join(dir, 'out.mp4');
+ await generator.renderSlidesToVideo(stills, 6, videoPath);
+
+ const stats = await fs.stat(videoPath);
+ if (!stats.size) {
+ throw new Error('Rendered slideshow video is empty');
+ }
+
+ // Silent fallback: an unusable audio path must still yield a playable output
+ const finalPath = path.join(dir, 'final.mp4');
+ await generator.addAudioToVideo(videoPath, path.join(dir, 'missing.mp3'), finalPath);
+ const finalStats = await fs.stat(finalPath);
+ if (!finalStats.size) {
+ throw new Error('Silent-audio fallback did not produce a video');
+ }
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
+ }
+
+ this.logger.info('Slideshow renderer test completed successfully');
+ }
+
+ async testEvergreenTopics() {
+ const { ContentStrategyAgent } = require('./agents/content-strategy-agent');
+ const agent = new ContentStrategyAgent(null, {});
+ agent.historicalPerformance = [];
+
+ // Single scraped keywords must never become video topics
+ agent.trendingTopics = [{ topic: 'crown', score: 5 }, { topic: 'official', score: 3 }];
+ const fallback = agent.selectOptimalTopic();
+ if (!fallback.topic.includes(' ') || fallback.topic.length < 8) {
+ throw new Error(`Template mode produced a junk topic: "${fallback.topic}"`);
+ }
+
+ // A readable multi-word trend should be used when available
+ agent.trendingTopics = [{ topic: 'artificial intelligence explained', score: 5 }];
+ const readable = agent.selectOptimalTopic();
+ if (readable.topic !== 'artificial intelligence explained') {
+ throw new Error(`Readable trending topic was not selected: "${readable.topic}"`);
+ }
+
+ this.logger.info('Evergreen template topics test completed successfully');
+ }
+
async testLogger() {
const testLogger = new Logger('TestLogger');
diff --git a/utils/ai-video-generator.js b/utils/ai-video-generator.js
index b1c3495..802c811 100644
--- a/utils/ai-video-generator.js
+++ b/utils/ai-video-generator.js
@@ -28,6 +28,18 @@ class AIVideoGenerator {
} else {
this.logger.warn('Replicate API key not found - advanced video generation unavailable');
}
+
+ // Gemini media generation (images + native TTS) β€” free-tier alternative to OpenAI
+ const geminiKey = credentials.gemini?.apiKey || process.env.GEMINI_API_KEY;
+ if (geminiKey) {
+ try {
+ const { GoogleGenAI } = require('@google/genai');
+ this.gemini = new GoogleGenAI({ apiKey: geminiKey });
+ this.logger.info('Gemini media service initialized (images + TTS)');
+ } catch (error) {
+ this.logger.warn('Failed to initialize Gemini media service:', error.message);
+ }
+ }
// ElevenLabs configuration
this.elevenLabsApiKey = credentials.elevenLabs?.apiKey || process.env.ELEVENLABS_API_KEY;
@@ -51,7 +63,12 @@ class AIVideoGenerator {
if (this.openai) {
return await this.generateOpenAITTS(text, outputPath);
}
-
+
+ // Fallback to Gemini native TTS (free tier)
+ if (this.gemini) {
+ return await this.generateGeminiTTS(text, outputPath);
+ }
+
// Final fallback to simulation
return await this.simulateTTSGeneration(text, outputPath);
} catch (error) {
@@ -108,16 +125,48 @@ class AIVideoGenerator {
const buffer = Buffer.from(await response.arrayBuffer());
await fs.writeFile(outputPath, buffer);
-
+
this.logger.info('OpenAI TTS generation complete');
return outputPath;
}
+ async generateGeminiTTS(text, outputPath) {
+ const model = process.env.GEMINI_TTS_MODEL || 'gemini-3.1-flash-tts-preview';
+ const voiceName = process.env.GEMINI_TTS_VOICE || 'Kore';
+
+ const response = await this.gemini.models.generateContent({
+ model,
+ contents: [{ parts: [{ text }] }],
+ config: {
+ responseModalities: ['AUDIO'],
+ speechConfig: {
+ voiceConfig: {
+ prebuiltVoiceConfig: { voiceName }
+ }
+ }
+ }
+ });
+
+ const audioData = response.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
+ if (!audioData) {
+ throw new Error('Gemini TTS returned no audio data');
+ }
+
+ // Gemini returns raw PCM (24kHz, mono, 16-bit); encode to the requested container via FFmpeg
+ const pcmPath = outputPath + '.pcm';
+ await fs.writeFile(pcmPath, Buffer.from(audioData, 'base64'));
+ await runFFmpeg(['-y', '-f', 's16le', '-ar', '24000', '-ac', '1', '-i', pcmPath, outputPath]);
+ await fs.unlink(pcmPath).catch(() => {});
+
+ this.logger.info('Gemini TTS generation complete');
+ return outputPath;
+ }
+
async generateVisualAssets(prompt, style = "ethereal", count = 1) {
this.logger.info(`Generating ${count} visual assets with style: ${style}`);
-
+
try {
- if (!this.openai) {
+ if (!this.openai && !this.gemini) {
return await this.simulateVisualAssets(prompt, style, count);
}
@@ -125,21 +174,8 @@ class AIVideoGenerator {
const localPaths = [];
for (let i = 0; i < count; i++) {
- const response = await this.openai.images.generate({
- model: "gpt-image-2",
- prompt: enhancedPrompt,
- n: 1,
- size: "1536x1024",
- quality: "high",
- });
-
const imagePath = path.join(__dirname, '..', 'data', 'assets', `visual_${Date.now()}_${i}.png`);
- if (response.data[0].b64_json) {
- const buffer = Buffer.from(response.data[0].b64_json, 'base64');
- await fs.writeFile(imagePath, buffer);
- } else {
- await this.downloadImage(response.data[0].url, imagePath);
- }
+ await this.generateImage(enhancedPrompt, imagePath);
localPaths.push(imagePath);
}
@@ -151,6 +187,57 @@ class AIVideoGenerator {
}
}
+ async generateImage(prompt, imagePath) {
+ await fs.mkdir(path.dirname(imagePath), { recursive: true });
+
+ if (this.openai) {
+ return await this.generateOpenAIImage(prompt, imagePath);
+ }
+
+ if (this.gemini) {
+ return await this.generateGeminiImage(prompt, imagePath);
+ }
+
+ throw new Error('No image generation provider configured');
+ }
+
+ async generateOpenAIImage(prompt, imagePath) {
+ const response = await this.openai.images.generate({
+ model: "gpt-image-2",
+ prompt: prompt,
+ n: 1,
+ size: "1536x1024",
+ quality: "high",
+ });
+
+ if (response.data[0].b64_json) {
+ const buffer = Buffer.from(response.data[0].b64_json, 'base64');
+ await fs.writeFile(imagePath, buffer);
+ } else {
+ await this.downloadImage(response.data[0].url, imagePath);
+ }
+
+ return imagePath;
+ }
+
+ async generateGeminiImage(prompt, imagePath) {
+ const model = process.env.GEMINI_IMAGE_MODEL || 'gemini-3.1-flash-image';
+
+ const response = await this.gemini.models.generateContent({
+ model,
+ contents: prompt
+ });
+
+ const parts = response.candidates?.[0]?.content?.parts || [];
+ const imagePart = parts.find(part => part.inlineData?.data);
+ if (!imagePart) {
+ throw new Error('Gemini image generation returned no image data');
+ }
+
+ await fs.writeFile(imagePath, Buffer.from(imagePart.inlineData.data, 'base64'));
+ return imagePath;
+ }
+
enhanceVisualPrompt(prompt, style) {
const styleEnhancements = {
ethereal: "ethereal, dreamy, mystical, soft lighting, floating particles, cosmic background",
@@ -230,65 +317,92 @@ class AIVideoGenerator {
const { chromium } = require('playwright');
const browser = await chromium.launch();
- const page = await browser.newPage();
+ const slidesDir = path.join(path.dirname(outputPath), 'slides');
- // Create HTML for slideshow (only real image files can be embedded)
- const imageAssets = await this.filterImageAssets(visualAssets);
- const slideshowHtml = this.createSlideshowHTML(script, imageAssets);
-
- // Set page content
- await page.setContent(slideshowHtml);
- await page.setViewportSize({ width: 1920, height: 1080 });
+ try {
+ const page = await browser.newPage();
+ await page.setViewportSize({ width: 1920, height: 1080 });
+
+ // Create HTML for slideshow (only real image files can be embedded)
+ const imageAssets = await this.filterImageAssets(visualAssets);
+ await page.setContent(this.createSlideshowHTML(script, imageAssets));
+
+ // Freeze CSS transitions/animations so each still is captured fully rendered
+ await page.addStyleTag({ content: '* { transition: none !important; animation: none !important; }' });
+ await page.waitForTimeout(1000); // Wait for assets to load
+
+ // Capture ONE still per slide instead of screenshotting at 30fps β€”
+ // FFmpeg turns the stills into a crossfaded video in seconds.
+ const slideCount = await page.evaluate(() => document.querySelectorAll('.slide').length);
+ await fs.mkdir(slidesDir, { recursive: true });
+
+ const stills = [];
+ for (let i = 0; i < slideCount; i++) {
+ await page.evaluate((index) => {
+ document.querySelectorAll('.slide').forEach((slide, s) => {
+ slide.classList.toggle('active', s === index);
+ });
+ }, i);
- // Record video of the slideshow
- const videoPath = outputPath.replace('.mp4', '_visual.mp4');
-
- // Use Playwright to record
- await page.waitForTimeout(1000); // Wait for assets to load
-
- // Create video frames by taking screenshots at intervals
- const duration = this.calculateScriptDuration(script);
- const frameCount = Math.ceil(duration * 30); // 30 FPS
- const frameInterval = duration / frameCount * 1000;
-
- const framesDir = path.join(path.dirname(outputPath), 'frames');
- await fs.mkdir(framesDir, { recursive: true });
-
- for (let i = 0; i < frameCount; i++) {
- await page.screenshot({
- path: path.join(framesDir, `frame_${String(i).padStart(6, '0')}.png`),
- fullPage: true
- });
-
- // Advance animation
- await page.evaluate(() => {
- if (window.advanceAnimation) {
- window.advanceAnimation();
- }
- });
-
- await page.waitForTimeout(frameInterval);
+ const stillPath = path.join(slidesDir, `slide_${String(i).padStart(3, '0')}.png`);
+ await page.screenshot({ path: stillPath });
+ stills.push(stillPath);
+ }
+
+ const videoPath = outputPath.replace('.mp4', '_visual.mp4');
+ const duration = this.calculateScriptDuration(script);
+ await this.renderSlidesToVideo(stills, duration, videoPath);
+
+ // Add audio
+ await this.addAudioToVideo(videoPath, audioPath, outputPath);
+
+ return outputPath;
+ } finally {
+ await browser.close().catch(() => {});
+ await this.cleanupDirectory(slidesDir);
}
+ }
- await browser.close();
+ async renderSlidesToVideo(stills, totalDuration, videoPath) {
+ if (stills.length === 0) {
+ throw new Error('No slides to render');
+ }
- // Convert frames to video using FFmpeg
- await runFFmpeg([
- '-y',
- '-framerate', '30',
- '-i', path.join(framesDir, 'frame_%06d.png'),
- '-c:v', 'libx264',
- '-pix_fmt', 'yuv420p',
- videoPath
- ]);
+ const fade = 0.5;
+ const perSlide = Math.max(2, totalDuration / stills.length);
+
+ const args = ['-y'];
+ for (const still of stills) {
+ args.push('-loop', '1', '-t', perSlide.toFixed(2), '-framerate', '30', '-i', still);
+ }
- // Add audio
- await this.addAudioToVideo(videoPath, audioPath, outputPath);
+ if (stills.length === 1) {
+ args.push('-vf', 'format=yuv420p', '-c:v', 'libx264', videoPath);
+ await runFFmpeg(args);
+ return videoPath;
+ }
- // Cleanup frames
- await this.cleanupDirectory(framesDir);
+ // Chain crossfades: transition k starts fade seconds before slide k ends
+ const filters = [];
+ let prev = '[0:v]';
+ for (let i = 1; i < stills.length; i++) {
+ const out = `[v${i}]`;
+ const offset = (i * (perSlide - fade)).toFixed(2);
+ filters.push(`${prev}[${i}:v]xfade=transition=fade:duration=${fade}:offset=${offset}${out}`);
+ prev = out;
+ }
+ filters.push(`${prev}format=yuv420p[vfinal]`);
- return outputPath;
+ args.push(
+ '-filter_complex', filters.join(';'),
+ '-map', '[vfinal]',
+ '-c:v', 'libx264',
+ '-r', '30',
+ videoPath
+ );
+
+ await runFFmpeg(args);
+ return videoPath;
}
async filterImageAssets(visualAssets = []) {
@@ -600,31 +714,16 @@ class AIVideoGenerator {
async generateThumbnail(script, style = "ethereal") {
this.logger.info('Generating custom thumbnail...');
-
+
try {
- if (!this.openai) {
+ if (!this.openai && !this.gemini) {
return await this.simulateThumbnailGeneration(script, style);
}
const prompt = `YouTube thumbnail for "${script.title}", ${style} style, eye-catching, high contrast text, professional design, clickable, engaging`;
-
- const response = await this.openai.images.generate({
- model: "gpt-image-2",
- prompt: prompt,
- n: 1,
- size: "1536x1024",
- quality: "high"
- });
-
const thumbnailPath = path.join(__dirname, '..', 'uploads', 'thumbnails', `thumbnail_${Date.now()}.png`);
- await fs.mkdir(path.dirname(thumbnailPath), { recursive: true });
- if (response.data[0].b64_json) {
- const buffer = Buffer.from(response.data[0].b64_json, 'base64');
- await fs.writeFile(thumbnailPath, buffer);
- } else {
- await this.downloadImage(response.data[0].url, thumbnailPath);
- }
+ await this.generateImage(prompt, thumbnailPath);
return {
path: thumbnailPath,
diff --git a/utils/credential-manager.js b/utils/credential-manager.js
index 9351961..dc70d24 100644
--- a/utils/credential-manager.js
+++ b/utils/credential-manager.js
@@ -206,7 +206,8 @@ class CredentialManager {
message: 'Select your preferred Gemini model:',
choices: [
'gemini-3.5-flash',
- 'gemini-3.5-pro'
+ 'gemini-3.1-pro-preview',
+ 'gemini-2.5-pro'
],
default: 'gemini-3.5-flash'
}