| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- /**
- * Generate Visuals — Appel API Google Nano Banana (Gemini 2.5 Flash Image)
- *
- * Charge les variables depuis .env à la racine du projet.
- *
- * Usage:
- * node scripts/generate-visuals.js outputs/2026-02/week-08
- *
- * Prérequis:
- * - Variable d'environnement GOOGLE_AI_API_KEY (ou GEMINI_API_KEY)
- * - Fichier visual-prompts.json dans le dossier de la semaine
- *
- * Le script lit visual-prompts.json, appelle l'API pour chaque prompt,
- * et enregistre les images dans outputs/YYYY-MM/week-XX/visuals/
- */
- require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
- const fs = require('fs');
- const path = require('path');
- const ASPECT_RATIO_MAP = {
- '1:1': '1:1',
- '4:5': '4:5',
- '5:4': '5:4',
- '9:16': '9:16',
- '16:9': '16:9',
- '3:2': '3:2',
- '2:3': '2:3',
- };
- async function generateVisuals(weekDir) {
- const absPath = path.resolve(weekDir);
- const promptsPath = path.join(absPath, 'visual-prompts.json');
- const visualsDir = path.join(absPath, 'visuals');
- if (!fs.existsSync(promptsPath)) {
- console.error(`❌ Fichier introuvable : ${promptsPath}`);
- console.error(' Créez visual-prompts.json via le workflow generate-visuals.');
- process.exit(1);
- }
- const apiKey = process.env.GOOGLE_AI_API_KEY || process.env.GEMINI_API_KEY;
- if (!apiKey) {
- console.error('❌ Variable GOOGLE_AI_API_KEY ou GEMINI_API_KEY manquante.');
- console.error(' Obtenez une clé sur https://aistudio.google.com/apikey');
- process.exit(1);
- }
- let GoogleGenerativeAI;
- try {
- const pkg = require('@google/generative-ai');
- GoogleGenerativeAI = pkg.GoogleGenerativeAI;
- } catch (e) {
- console.error('❌ Package @google/generative-ai manquant. Installez avec :');
- console.error(' npm install @google/generative-ai');
- process.exit(1);
- }
- const genAI = new GoogleGenerativeAI(apiKey);
- const promptsData = JSON.parse(fs.readFileSync(promptsPath, 'utf8'));
- if (!fs.existsSync(visualsDir)) {
- fs.mkdirSync(visualsDir, { recursive: true });
- }
- console.log(`📁 Dossier : ${absPath}`);
- console.log(`🖼️ ${promptsData.prompts.length} visuel(s) à générer\n`);
- for (const item of promptsData.prompts) {
- const outPath = path.join(visualsDir, item.output_filename);
- const aspectRatio = ASPECT_RATIO_MAP[item.aspect_ratio] || '1:1';
- console.log(`⏳ ${item.id} — ${item.output_filename} (${aspectRatio})`);
- try {
- const modelId = process.env.GEMINI_IMAGE_MODEL || 'gemini-2.5-flash-image';
- const model = genAI.getGenerativeModel({
- model: modelId,
- generationConfig: { responseModalities: ['IMAGE', 'TEXT'] },
- });
- const result = await model.generateContent(item.prompt);
- const response = result.response;
- if (!response || !response.candidates || response.candidates.length === 0) {
- console.error(` ⚠️ Pas de réponse pour ${item.id}`);
- continue;
- }
- const candidate = response.candidates[0];
- if (!candidate.content || !candidate.content.parts) {
- console.error(` ⚠️ Contenu vide pour ${item.id}`);
- continue;
- }
- let saved = false;
- for (const part of candidate.content.parts) {
- if (part.inlineData && part.inlineData.data) {
- const ext = part.inlineData.mimeType?.includes('png') ? 'png' : 'jpg';
- const finalPath = outPath.replace(/\.(png|jpg)$/, `.${ext}`);
- fs.writeFileSync(finalPath, Buffer.from(part.inlineData.data, 'base64'));
- console.log(` ✅ ${finalPath}`);
- saved = true;
- break;
- }
- }
- if (!saved) {
- console.error(` ⚠️ Aucune image dans la réponse pour ${item.id}`);
- }
- } catch (err) {
- console.error(` ❌ Erreur : ${err.message}`);
- }
- }
- console.log('\n✅ Terminé.');
- }
- const weekDir = process.argv[2];
- if (!weekDir) {
- console.error('Usage: node scripts/generate-visuals.js outputs/YYYY-MM/week-XX');
- process.exit(1);
- }
- generateVisuals(weekDir).catch((err) => {
- console.error('Erreur:', err);
- process.exit(1);
- });
|