Initial commit

This commit is contained in:
Sebastian
2025-11-26 19:00:04 +00:00
commit 0ba05b6483
27 changed files with 2517 additions and 0 deletions

26
.gitignore vendored Normal file
View File

@@ -0,0 +1,26 @@
# Entorno virtual
.venv/
venv/
env/
# Archivos de Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
# Credenciales y configuración sensible
*.json
!pyproject.toml
# IDE
.vscode/
.idea/
*.swp
*.swo
# Distribución
dist/
build/
*.egg-info/

12
docker-compose.yml Normal file
View File

@@ -0,0 +1,12 @@
version: '3.8'
services:
frontend:
build:
context: ./frontend
ports:
- "3000:3000"
env_file:
- ./frontend/.env
environment:
- NODE_ENV=production

View File

@@ -0,0 +1,6 @@
# Google Generative AI API Key (OPCIONAL)
# El proyecto usa automáticamente las credenciales del archivo bnt-ia-innovacion-new.json
# Solo necesitas configurar esto si quieres usar una API key diferente
# Obtén tu API key en: https://makersuite.google.com/app/apikey
# GOOGLE_API_KEY=tu_api_key_aqui

37
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,37 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
.env
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

15
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,15 @@
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]

138
frontend/README.md Normal file
View File

@@ -0,0 +1,138 @@
# 🎨 Image Playground - Google Generative AI
Playground interactivo para generar imágenes usando los modelos de Google Generative AI (Gemini).
## ✨ Características
- 🤖 **Múltiples modelos de Gemini** - Elige entre diferentes versiones de Gemini
- 🎭 **Configuración completa** - Aspect ratios, negative prompts, safety levels
- 🖼️ **Visualización en tiempo real** - Ve tus imágenes generadas al instante
- 💾 **Descarga directa** - Guarda las imágenes con un clic
- 📱 **Responsive** - Funciona en desktop y mobile
-**Vercel AI SDK** - Integración completa con el SDK oficial
## 🚀 Instalación
1. **Instalar dependencias:**
```bash
cd frontend
npm install
```
2. **Configuración automática:**
El proyecto usa automáticamente las credenciales del archivo `bnt-ia-innovacion-new.json` ubicado en la raíz del proyecto. **No necesitas configurar nada más.**
Si quieres usar una API key diferente (opcional), crea un archivo `.env.local`:
```bash
cp .env.local.example .env.local
# Edita y descomenta GOOGLE_API_KEY
```
3. **Ejecutar el proyecto:**
```bash
npm run dev
```
Abre [http://localhost:3000](http://localhost:3000) en tu navegador.
## 📦 Estructura del Proyecto
```
frontend/
├── app/
│ ├── api/
│ │ └── generate-image/
│ │ └── route.ts # API endpoint para generación
│ ├── layout.tsx # Layout principal
│ ├── page.tsx # Página del playground
│ └── globals.css # Estilos globales
├── components/
│ ├── model-selector.tsx # Selector de modelos
│ ├── image-config.tsx # Configuración de imágenes
│ └── image-card.tsx # Tarjeta de imagen generada
├── lib/
│ ├── google-ai.ts # Cliente de Google AI
│ └── utils.ts # Utilidades
└── package.json
```
## 🎯 Uso
1. **Selecciona un modelo** en el panel lateral
2. **Configura los parámetros:**
- Aspect Ratio (1:1, 16:9, etc.)
- Número de imágenes
- Negative prompt (opcional)
- Nivel de seguridad
3. **Escribe tu prompt** describiendo la imagen que quieres
4. **Haz clic en "Generar Imagen"** o presiona Enter
5. **Descarga las imágenes** haciendo hover y clic en el botón de descarga
## 🛠️ Tecnologías
- **Next.js 14** - Framework React con App Router
- **TypeScript** - Type safety
- **Vercel AI SDK** - Integración con IA
- **Google Generative AI SDK** - API de Google Gemini
- **Tailwind CSS** - Estilos
- **Lucide Icons** - Iconos
## 🔧 Configuración Avanzada
### Modelos Disponibles
El playground incluye estos modelos de Gemini:
- `gemini-2.0-flash-exp` - Experimental, rápido
- `gemini-exp-1206` - Experimental con mejoras
- `gemini-1.5-pro` - Más capaz para tareas complejas
- `gemini-1.5-flash` - Rápido y eficiente
### Aspect Ratios Soportados
- `1:1` - Cuadrado (1024x1024)
- `3:4` - Vertical (768x1024)
- `4:3` - Horizontal (1024x768)
- `9:16` - Móvil vertical (576x1024)
- `16:9` - Widescreen (1024x576)
## 🤝 Integración con el Backend Python
El proyecto también incluye un backend en Python en `/backend` que puedes usar alternativamente:
```bash
cd ../backend
python list_models.py
```
## 📝 Notas
- Las imágenes se generan usando la API de Google Generative AI
- Asegúrate de tener cuota suficiente en tu cuenta de Google Cloud
- Algunos prompts pueden ser bloqueados por políticas de seguridad
- Las imágenes se guardan temporalmente en el navegador
## 🐛 Troubleshooting
**Error: "API key inválida"**
- Verifica que tu API key esté correctamente configurada en `.env.local`
- Asegúrate de que la API key tenga permisos para Generative AI
**Error: "No se generaron imágenes"**
- Prueba con un prompt más descriptivo
- Cambia el modelo seleccionado
- Verifica los logs del servidor en la consola
**Las imágenes no se muestran**
- Verifica la consola del navegador para errores
- Asegúrate de que el modelo soporte generación de imágenes
## 📄 Licencia
MIT
## 🙋 Soporte
Si encuentras algún problema o tienes preguntas, crea un issue en el repositorio.

88
frontend/START.md Normal file
View File

@@ -0,0 +1,88 @@
# 🚀 Inicio Rápido
## Pasos para ejecutar el proyecto:
### 1. Instalar dependencias
```bash
npm install
```
### 2. Configuración (Automática)
**El proyecto usa automáticamente las credenciales del archivo `bnt-ia-innovacion-new.json`**
No necesitas configurar nada adicional. El archivo JSON ya contiene todas las credenciales necesarias.
Si quieres usar una API key diferente (opcional):
```bash
cp .env.local.example .env.local
# Edita y descomenta GOOGLE_API_KEY
```
### 3. Ejecutar el proyecto
```bash
npm run dev
```
### 4. Abrir en el navegador
Abre http://localhost:3000
---
## 📝 Notas Importantes
### Sobre la Autenticación
El proyecto usa **Google Generative AI SDK** (`@google/generative-ai`) con las credenciales del archivo `bnt-ia-innovacion-new.json`.
La autenticación es automática mediante `google-auth-library` que lee el Service Account del JSON.
### Verificar que todo funciona
1. Abre http://localhost:3000
2. Selecciona un modelo (por defecto: gemini-2.0-flash-exp)
3. Escribe un prompt simple: "un gato naranja"
4. Haz clic en "Generar Imagen"
Si ves errores:
- Verifica que la API key sea válida
- Revisa los logs en la terminal
- Revisa la consola del navegador (F12)
---
## 🔧 Comandos útiles
```bash
# Desarrollo
npm run dev
# Build para producción
npm run build
# Ejecutar producción
npm start
# Linting
npm run lint
```
---
## 🐛 Problemas Comunes
### Error: "API key not valid"
- Verifica que copiaste correctamente la API key
- Asegúrate de que el archivo `.env.local` existe
- Reinicia el servidor de desarrollo (Ctrl+C y `npm run dev` de nuevo)
### Error: "Module not found"
- Ejecuta `npm install` de nuevo
- Borra `node_modules` y `.next`, luego `npm install`
### Las imágenes no se generan
- Algunos modelos de Gemini aún no soportan generación de imágenes
- Prueba con diferentes prompts
- Revisa los logs del servidor para más detalles

View File

@@ -0,0 +1,154 @@
import { NextRequest, NextResponse } from 'next/server';
import { type ImageGenerationConfig, getSafetySettings } from '@/lib/google-ai';
import { vertexAI } from '@/lib/google-ai-server';
export const runtime = 'nodejs';
export const maxDuration = 60;
export async function POST(req: NextRequest) {
try {
const body: ImageGenerationConfig = await req.json();
const {
model,
prompt,
aspectRatio = '1:1',
numberOfImages = 1,
negativePrompt,
temperature = 1,
safetyFilterLevel = 'block_some',
referenceImages,
} = body;
if (!prompt || !model) {
return NextResponse.json(
{ error: 'Prompt y modelo son requeridos' },
{ status: 400 }
);
}
// Obtener el modelo generativo de Vertex AI
const generativeModel = vertexAI.getGenerativeModel({
model: model,
safetySettings: getSafetySettings(safetyFilterLevel) as any,
generationConfig: {
temperature: temperature,
maxOutputTokens: 8192,
},
});
// Construir el prompt completo
let fullPrompt = prompt;
if (negativePrompt) {
fullPrompt += `\n\nNo incluir: ${negativePrompt}`;
}
// Agregar instrucciones de aspect ratio si no es 1:1
if (aspectRatio !== '1:1') {
fullPrompt += `\n\nGenera la imagen en formato ${aspectRatio}.`;
}
// Construir parts con imágenes de referencia si existen
const parts: any[] = [];
// Agregar imágenes de referencia primero
if (referenceImages && referenceImages.length > 0) {
for (const refImg of referenceImages) {
parts.push({
inlineData: {
data: refImg.data,
mimeType: refImg.mimeType,
},
});
}
}
// Agregar el prompt de texto
parts.push({ text: fullPrompt });
// Generar contenido
const result = await generativeModel.generateContent({
contents: [
{
role: 'user',
parts: parts,
},
],
});
const response = result.response;
// Extraer imágenes de la respuesta
const images: string[] = [];
if (response.candidates && response.candidates.length > 0) {
for (const candidate of response.candidates) {
if (candidate.content?.parts) {
for (const part of candidate.content.parts) {
// Verificar si la parte contiene datos inline (imagen)
if ('inlineData' in part && part.inlineData) {
const imageData = part.inlineData.data;
if (imageData) {
images.push(imageData);
}
}
}
}
}
}
// Si no hay imágenes, intentar generar más información de debug
if (images.length === 0) {
console.error('No se encontraron imágenes en la respuesta');
return NextResponse.json(
{
error: 'El modelo no generó imágenes',
details: 'El modelo respondió pero no incluyó datos de imagen',
response: response,
suggestion: 'Prueba con un prompt más descriptivo o cambia el modelo',
},
{ status: 500 }
);
}
return NextResponse.json({
images: images,
model: model,
prompt: prompt,
aspectRatio: aspectRatio,
count: images.length,
});
} catch (error: any) {
console.error('Error generando imagen:', error);
// Manejar errores específicos de la API
let errorMessage = 'Error generando imagen';
let errorDetails = error.message;
if (error.message?.includes('credentials') || error.message?.includes('authentication')) {
errorMessage = 'Error de autenticación';
errorDetails = 'Verifica las credenciales del Service Account';
} else if (error.message?.includes('quota')) {
errorMessage = 'Límite de cuota excedido';
errorDetails = 'Has alcanzado el límite de uso de la API';
} else if (error.message?.includes('safety')) {
errorMessage = 'Contenido bloqueado por seguridad';
errorDetails = 'El prompt fue bloqueado por políticas de seguridad';
} else if (error.message?.includes('permission')) {
errorMessage = 'Error de permisos';
errorDetails = 'El Service Account no tiene permisos para Vertex AI';
}
return NextResponse.json(
{
error: errorMessage,
details: errorDetails,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,163 @@
import { NextRequest, NextResponse } from 'next/server';
import { type VideoGenerationConfig } from '@/lib/google-ai';
import { projectId, location, credentials } from '@/lib/google-ai-server';
import { GoogleAuth } from 'google-auth-library';
export const runtime = 'nodejs';
export const maxDuration = 300; // Los videos pueden tardar más
export async function POST(req: NextRequest) {
try {
const body: VideoGenerationConfig = await req.json();
const {
model,
prompt,
aspectRatio = '16:9',
duration = 5,
negativePrompt,
} = body;
if (!prompt || !model) {
return NextResponse.json(
{ error: 'Prompt y modelo son requeridos' },
{ status: 400 }
);
}
// Configurar autenticación
const auth = new GoogleAuth({
credentials: credentials,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const client = await auth.getClient();
const accessToken = await client.getAccessToken();
if (!accessToken.token) {
throw new Error('No se pudo obtener el token de acceso');
}
// Construir el endpoint de la API
const endpoint = `https://${location}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/publishers/google/models/${model}:predict`;
// Construir el prompt completo
let fullPrompt = prompt;
if (negativePrompt) {
fullPrompt += `\n\nNegative prompt: ${negativePrompt}`;
}
// Construir el payload
const payload = {
instances: [
{
prompt: fullPrompt,
},
],
parameters: {
aspectRatio: aspectRatio,
videoDuration: `${duration}s`,
},
};
console.log(`Endpoint: ${endpoint}`);
// Hacer la solicitud a la API de Vertex AI
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken.token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
const data = await response.json();
if (!response.ok) {
console.error('Error de la API:', data);
throw new Error(
data.error?.message ||
`Error ${response.status}: ${response.statusText}`
);
}
// Extraer video de la respuesta
let videoData: string | null = null;
if (data.predictions && data.predictions.length > 0) {
const prediction = data.predictions[0];
// Buscar el video en diferentes formatos posibles
if (prediction.bytesBase64Encoded) {
videoData = prediction.bytesBase64Encoded;
} else if (prediction.videoBase64) {
videoData = prediction.videoBase64;
} else if (prediction.video) {
videoData = prediction.video;
}
}
// Si no hay video, retornar error con más información
if (!videoData) {
console.error('No se encontró video en la respuesta');
return NextResponse.json(
{
error: 'El modelo no generó un video',
details: 'El modelo respondió pero no incluyó datos de video en el formato esperado',
response: data,
suggestion: 'Los modelos Veo pueden necesitar acceso especial o estar en preview. Verifica que tu proyecto tenga acceso a estos modelos.',
},
{ status: 500 }
);
}
return NextResponse.json({
videoData: videoData,
model: model,
prompt: prompt,
aspectRatio: aspectRatio,
duration: duration,
});
} catch (error: any) {
console.error('Error generando video:', error);
// Manejar errores específicos de la API
let errorMessage = 'Error generando video';
let errorDetails = error.message;
if (error.message?.includes('credentials') || error.message?.includes('authentication')) {
errorMessage = 'Error de autenticación';
errorDetails = 'Verifica las credenciales del Service Account';
} else if (error.message?.includes('Quota exceeded') || error.message?.includes('quota')) {
errorMessage = 'Cuota de uso excedida';
errorDetails = 'Necesitas solicitar un aumento de cuota para los modelos Veo en Google Cloud Console. Ve a: https://console.cloud.google.com/iam-admin/quotas y busca "Online prediction requests per base model"';
} else if (error.message?.includes('safety')) {
errorMessage = 'Contenido bloqueado por seguridad';
errorDetails = 'El prompt fue bloqueado por políticas de seguridad';
} else if (error.message?.includes('permission') || error.message?.includes('403')) {
errorMessage = 'Error de permisos';
errorDetails = 'El Service Account no tiene permisos para Vertex AI o los modelos Veo no están habilitados en tu proyecto';
} else if (error.message?.includes('not found') || error.message?.includes('404')) {
errorMessage = 'Modelo no encontrado';
errorDetails = 'El modelo Veo puede no estar disponible en tu región (us-central1). Prueba solicitar acceso a los modelos Veo en Google Cloud Console.';
} else if (error.message?.includes('Internal')) {
errorMessage = 'Error interno del servidor';
errorDetails = 'Los modelos Veo están en preview y pueden tener disponibilidad limitada. Intenta con otro modelo o más tarde.';
}
return NextResponse.json(
{
error: errorMessage,
details: errorDetails,
fullError: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
},
{ status: 500 }
);
}
}

55
frontend/app/globals.css Normal file
View File

@@ -0,0 +1,55 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

22
frontend/app/layout.tsx Normal file
View File

@@ -0,0 +1,22 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'Image Playground - Google Generative AI',
description: 'Genera imágenes con modelos de Google Generative AI',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="es">
<body className={inter.className}>{children}</body>
</html>
)
}

426
frontend/app/page.tsx Normal file
View File

@@ -0,0 +1,426 @@
'use client';
import { useState } from 'react';
import { Sparkles, Loader2, ImageIcon, Video } from 'lucide-react';
import { ModelSelector } from '@/components/model-selector';
import { ImageConfig } from '@/components/image-config';
import { VideoConfig } from '@/components/video-config';
import { ImageCard } from '@/components/image-card';
import { VideoCard } from '@/components/video-card';
import { ReferenceImages } from '@/components/reference-images';
type ContentType = 'image' | 'video';
interface GeneratedImage {
id: string;
imageData: string;
prompt: string;
model: string;
aspectRatio: string;
timestamp: number;
}
interface GeneratedVideo {
id: string;
videoData: string;
prompt: string;
model: string;
aspectRatio: string;
duration: number;
timestamp: number;
}
interface ReferenceImage {
id: string;
data: string;
mimeType: string;
preview: string;
name: string;
}
export default function Home() {
// Estado del tipo de contenido
const [contentType, setContentType] = useState<ContentType>('image');
// Estado del modelo y configuración
const [selectedModel, setSelectedModel] = useState('gemini-2.5-flash-image');
const [aspectRatio, setAspectRatio] = useState('1:1');
const [numberOfImages, setNumberOfImages] = useState(1);
const [videoDuration, setVideoDuration] = useState(5);
const [negativePrompt, setNegativePrompt] = useState('');
const [safetyLevel, setSafetyLevel] = useState<'block_none' | 'block_some' | 'block_most'>('block_some');
const [referenceImages, setReferenceImages] = useState<ReferenceImage[]>([]);
// Estado del chat
const [prompt, setPrompt] = useState('');
const [isGenerating, setIsGenerating] = useState(false);
const [generatedImages, setGeneratedImages] = useState<GeneratedImage[]>([]);
const [generatedVideos, setGeneratedVideos] = useState<GeneratedVideo[]>([]);
const [error, setError] = useState<string | null>(null);
// Cambiar tipo de contenido y actualizar modelo por defecto
const handleContentTypeChange = (type: ContentType) => {
setContentType(type);
if (type === 'image') {
setSelectedModel('gemini-2.5-flash-image');
setAspectRatio('1:1');
} else {
setSelectedModel('veo-3.0-generate-001');
setAspectRatio('16:9');
}
};
const handleGenerateImage = async () => {
if (!prompt.trim()) return;
setIsGenerating(true);
setError(null);
try {
const response = await fetch('/api/generate-image', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: selectedModel,
prompt: prompt.trim(),
aspectRatio,
numberOfImages,
negativePrompt: negativePrompt.trim() || undefined,
safetyFilterLevel: safetyLevel,
temperature: 1,
referenceImages: referenceImages.length > 0
? referenceImages.map(img => ({
data: img.data,
mimeType: img.mimeType,
}))
: undefined,
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.details || data.error || 'Error generando imagen');
}
// Agregar imágenes generadas al historial
const newImages: GeneratedImage[] = data.images.map((imageData: string, index: number) => ({
id: `${Date.now()}-${index}`,
imageData,
prompt: prompt.trim(),
model: selectedModel,
aspectRatio,
timestamp: Date.now(),
}));
setGeneratedImages([...newImages, ...generatedImages]);
setPrompt(''); // Limpiar prompt después de generar
} catch (err: any) {
setError(err.message);
} finally {
setIsGenerating(false);
}
};
const handleGenerateVideo = async () => {
if (!prompt.trim()) return;
setIsGenerating(true);
setError(null);
try {
const response = await fetch('/api/generate-video', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: selectedModel,
prompt: prompt.trim(),
aspectRatio,
duration: videoDuration,
negativePrompt: negativePrompt.trim() || undefined,
safetyFilterLevel: safetyLevel,
temperature: 1,
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.details || data.error || 'Error generando video');
}
// Agregar video generado al historial
const newVideo: GeneratedVideo = {
id: `${Date.now()}`,
videoData: data.videoData,
prompt: prompt.trim(),
model: selectedModel,
aspectRatio,
duration: videoDuration,
timestamp: Date.now(),
};
setGeneratedVideos([newVideo, ...generatedVideos]);
setPrompt(''); // Limpiar prompt después de generar
} catch (err: any) {
setError(err.message);
} finally {
setIsGenerating(false);
}
};
const handleGenerate = () => {
if (contentType === 'image') {
handleGenerateImage();
} else {
handleGenerateVideo();
}
};
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleGenerate();
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-background via-background to-secondary">
<div className="container mx-auto px-4 py-8">
{/* Header */}
<div className="mb-8 text-center">
<div className="flex items-center justify-center gap-3 mb-3">
<Sparkles className="w-8 h-8 text-primary" />
<h1 className="text-4xl font-bold bg-gradient-to-r from-primary to-purple-600 bg-clip-text text-transparent">
AI Playground
</h1>
</div>
<p className="text-muted-foreground">
Genera imágenes y videos con Google Generative AI
</p>
</div>
{/* Selector de tipo de contenido */}
<div className="mb-6 flex justify-center">
<div className="inline-flex bg-card border border-border rounded-lg p-1">
<button
onClick={() => handleContentTypeChange('image')}
className={`
flex items-center gap-2 px-6 py-2 rounded-md font-medium transition-all
${contentType === 'image'
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
}
`}
>
<ImageIcon className="w-4 h-4" />
Imágenes
</button>
<button
onClick={() => handleContentTypeChange('video')}
className={`
flex items-center gap-2 px-6 py-2 rounded-md font-medium transition-all
${contentType === 'video'
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
}
`}
>
<Video className="w-4 h-4" />
Videos
</button>
</div>
</div>
<div className="grid lg:grid-cols-[350px,1fr] gap-6">
{/* Panel de configuración */}
<div className="space-y-6">
<div className="bg-card border border-border rounded-xl p-6 shadow-lg space-y-6">
<ModelSelector
selectedModel={selectedModel}
onModelChange={setSelectedModel}
contentType={contentType}
/>
<div className="border-t border-border pt-6">
{contentType === 'image' ? (
<ImageConfig
model={selectedModel}
aspectRatio={aspectRatio}
onAspectRatioChange={setAspectRatio}
numberOfImages={numberOfImages}
onNumberOfImagesChange={setNumberOfImages}
negativePrompt={negativePrompt}
onNegativePromptChange={setNegativePrompt}
safetyLevel={safetyLevel}
onSafetyLevelChange={setSafetyLevel}
/>
) : (
<VideoConfig
model={selectedModel}
aspectRatio={aspectRatio}
onAspectRatioChange={setAspectRatio}
duration={videoDuration}
onDurationChange={setVideoDuration}
negativePrompt={negativePrompt}
onNegativePromptChange={setNegativePrompt}
safetyLevel={safetyLevel}
onSafetyLevelChange={setSafetyLevel}
/>
)}
</div>
{contentType === 'image' && (
<div className="border-t border-border pt-6">
<ReferenceImages
images={referenceImages}
onImagesChange={setReferenceImages}
maxImages={3}
/>
</div>
)}
</div>
{/* Stats */}
<div className="bg-card border border-border rounded-xl p-4">
<div className="flex items-center gap-2 text-sm text-muted-foreground mb-2">
{contentType === 'image' ? (
<ImageIcon className="w-4 h-4" />
) : (
<Video className="w-4 h-4" />
)}
<span className="font-medium">Estadísticas</span>
</div>
<div className="space-y-1 text-sm">
{contentType === 'image' ? (
<p>Imágenes generadas: <strong>{generatedImages.length}</strong></p>
) : (
<p>Videos generados: <strong>{generatedVideos.length}</strong></p>
)}
<p>Modelo actual: <strong>{selectedModel}</strong></p>
</div>
</div>
</div>
{/* Área principal */}
<div className="space-y-6">
{/* Input de prompt */}
<div className="bg-card border border-border rounded-xl p-6 shadow-lg">
<label className="text-sm font-medium text-foreground mb-2 block">
Describe tu {contentType === 'image' ? 'imagen' : 'video'}
</label>
<div className="space-y-3">
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onKeyPress={handleKeyPress}
placeholder={
contentType === 'image'
? 'Ejemplo: Un atardecer en una playa tropical con palmeras...'
: 'Ejemplo: Un timelapse de una ciudad con tráfico fluido al atardecer...'
}
className="w-full px-4 py-3 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
rows={4}
disabled={isGenerating}
/>
<button
onClick={handleGenerate}
disabled={isGenerating || !prompt.trim()}
className="w-full px-6 py-3 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2"
>
{isGenerating ? (
<>
<Loader2 className="w-5 h-5 animate-spin" />
Generando...
</>
) : (
<>
<Sparkles className="w-5 h-5" />
Generar {contentType === 'image' ? 'Imagen' : 'Video'}
</>
)}
</button>
</div>
{/* Error message */}
{error && (
<div className="mt-4 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
<p className="text-sm text-red-500">
<strong>Error:</strong> {error}
</p>
</div>
)}
</div>
{/* Galería */}
<div>
<h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
{contentType === 'image' ? (
<>
<ImageIcon className="w-5 h-5" />
Galería {generatedImages.length > 0 && `(${generatedImages.length})`}
</>
) : (
<>
<Video className="w-5 h-5" />
Videos {generatedVideos.length > 0 && `(${generatedVideos.length})`}
</>
)}
</h2>
{contentType === 'image' && generatedImages.length === 0 && !isGenerating && (
<div className="bg-card border border-dashed border-border rounded-xl p-12 text-center">
<ImageIcon className="w-16 h-16 text-muted-foreground mx-auto mb-4 opacity-50" />
<p className="text-muted-foreground">
Aún no has generado ninguna imagen.
</p>
<p className="text-sm text-muted-foreground mt-2">
Escribe un prompt y haz clic en &quot;Generar Imagen&quot; para comenzar.
</p>
</div>
)}
{contentType === 'video' && generatedVideos.length === 0 && !isGenerating && (
<div className="bg-card border border-dashed border-border rounded-xl p-12 text-center">
<Video className="w-16 h-16 text-muted-foreground mx-auto mb-4 opacity-50" />
<p className="text-muted-foreground">
Aún no has generado ningún video.
</p>
<p className="text-sm text-muted-foreground mt-2">
Escribe un prompt y haz clic en &quot;Generar Video&quot; para comenzar.
</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{contentType === 'image' && generatedImages.map((image) => (
<ImageCard
key={image.id}
imageData={image.imageData}
prompt={image.prompt}
model={image.model}
/>
))}
{contentType === 'video' && generatedVideos.map((video) => (
<VideoCard
key={video.id}
videoData={video.videoData}
prompt={video.prompt}
model={video.model}
/>
))}
</div>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,98 @@
'use client';
import { Download, Maximize2 } from 'lucide-react';
import { downloadImage, generateImageFilename } from '@/lib/utils';
import { useState } from 'react';
interface ImageCardProps {
imageData: string; // Base64
prompt: string;
model: string;
index?: number;
}
export function ImageCard({ imageData, prompt, model, index = 0 }: ImageCardProps) {
const [isFullscreen, setIsFullscreen] = useState(false);
const handleDownload = () => {
const filename = generateImageFilename(prompt);
downloadImage(imageData, filename);
};
const handleFullscreen = () => {
setIsFullscreen(true);
};
return (
<>
<div className="group relative bg-secondary rounded-lg overflow-hidden border border-border hover:border-primary transition-all">
{/* Imagen */}
<div className="relative aspect-square">
<img
src={`data:image/png;base64,${imageData}`}
alt={prompt}
className="w-full h-full object-cover"
/>
{/* Overlay con acciones */}
<div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
<button
onClick={handleFullscreen}
className="p-3 bg-white/90 hover:bg-white rounded-full transition-all"
title="Ver en pantalla completa"
>
<Maximize2 className="w-5 h-5 text-gray-900" />
</button>
<button
onClick={handleDownload}
className="p-3 bg-white/90 hover:bg-white rounded-full transition-all"
title="Descargar imagen"
>
<Download className="w-5 h-5 text-gray-900" />
</button>
</div>
</div>
{/* Info */}
<div className="p-3 space-y-1">
<p className="text-xs text-muted-foreground line-clamp-2">
{prompt}
</p>
<p className="text-xs text-muted-foreground">
Modelo: {model}
</p>
</div>
</div>
{/* Modal fullscreen */}
{isFullscreen && (
<div
className="fixed inset-0 bg-black/95 z-50 flex items-center justify-center p-4"
onClick={() => setIsFullscreen(false)}
>
<button
onClick={() => setIsFullscreen(false)}
className="absolute top-4 right-4 text-white text-4xl hover:text-gray-300"
>
×
</button>
<img
src={`data:image/png;base64,${imageData}`}
alt={prompt}
className="max-w-full max-h-full object-contain"
/>
<button
onClick={(e) => {
e.stopPropagation();
handleDownload();
}}
className="absolute bottom-4 right-4 px-4 py-2 bg-white text-black rounded-lg hover:bg-gray-200 transition-all flex items-center gap-2"
>
<Download className="w-4 h-4" />
Descargar
</button>
</div>
)}
</>
);
}

View File

@@ -0,0 +1,115 @@
'use client';
import { aspectRatioSizes, isValidAspectRatio } from '@/lib/google-ai';
interface ImageConfigProps {
model: string;
aspectRatio: string;
onAspectRatioChange: (ratio: string) => void;
numberOfImages: number;
onNumberOfImagesChange: (num: number) => void;
negativePrompt: string;
onNegativePromptChange: (prompt: string) => void;
safetyLevel: 'block_none' | 'block_some' | 'block_most';
onSafetyLevelChange: (level: 'block_none' | 'block_some' | 'block_most') => void;
}
export function ImageConfig({
model,
aspectRatio,
onAspectRatioChange,
numberOfImages,
onNumberOfImagesChange,
negativePrompt,
onNegativePromptChange,
safetyLevel,
onSafetyLevelChange,
}: ImageConfigProps) {
const availableRatios = Object.keys(aspectRatioSizes);
const size = aspectRatioSizes[aspectRatio];
return (
<div className="space-y-4">
<h3 className="text-sm font-medium text-foreground">Configuración de Imagen</h3>
{/* Aspect Ratio */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Aspect Ratio
</label>
<div className="grid grid-cols-5 gap-2">
{availableRatios.map((ratio) => (
<button
key={ratio}
onClick={() => onAspectRatioChange(ratio)}
disabled={!isValidAspectRatio(model, ratio) && !model.startsWith('gemini')}
className={`
px-3 py-2 text-xs rounded-lg font-medium transition-all
${aspectRatio === ratio
? 'bg-primary text-primary-foreground'
: 'bg-secondary hover:bg-accent'
}
${!isValidAspectRatio(model, ratio) && !model.startsWith('gemini')
? 'opacity-50 cursor-not-allowed'
: ''
}
`}
>
{ratio}
</button>
))}
</div>
{size && (
<p className="text-xs text-muted-foreground">
Dimensiones: {size.width}x{size.height}px
</p>
)}
</div>
{/* Número de imágenes */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Número de imágenes: {numberOfImages}
</label>
<input
type="range"
min="1"
max="4"
value={numberOfImages}
onChange={(e) => onNumberOfImagesChange(parseInt(e.target.value))}
className="w-full"
/>
</div>
{/* Negative Prompt */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Negative Prompt (opcional)
</label>
<textarea
value={negativePrompt}
onChange={(e) => onNegativePromptChange(e.target.value)}
placeholder="Elementos que NO quieres en la imagen..."
className="w-full px-3 py-2 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
rows={2}
/>
</div>
{/* Safety Level */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Nivel de Seguridad
</label>
<select
value={safetyLevel}
onChange={(e) => onSafetyLevelChange(e.target.value as any)}
className="w-full px-3 py-2 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="block_none">Sin bloqueo</option>
<option value="block_some">Bloqueo moderado</option>
<option value="block_most">Bloqueo alto</option>
</select>
</div>
</div>
);
}

View File

@@ -0,0 +1,50 @@
'use client';
import { geminiImageModels, veoVideoModels } from '@/lib/google-ai';
interface ModelSelectorProps {
selectedModel: string;
onModelChange: (model: string) => void;
contentType: 'image' | 'video';
}
export function ModelSelector({ selectedModel, onModelChange, contentType }: ModelSelectorProps) {
const models = contentType === 'image' ? geminiImageModels : veoVideoModels;
return (
<div className="space-y-3">
<label className="text-sm font-medium text-foreground">
Modelo de IA
</label>
<select
value={selectedModel}
onChange={(e) => onModelChange(e.target.value)}
className="w-full px-4 py-2.5 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary transition-all"
>
{models.map((model) => (
<option key={model.id} value={model.id}>
{model.name} - {model.description}
</option>
))}
</select>
{/* Info del modelo seleccionado */}
<div className="text-xs text-muted-foreground bg-muted p-3 rounded-lg">
{(() => {
const model = models.find(m => m.id === selectedModel);
if (!model) return null;
return (
<div className="space-y-1">
<p><strong>Modelo:</strong> {model.name}</p>
<p><strong>ID:</strong> {model.id}</p>
{model.capabilities && (
<p><strong>Capacidades:</strong> {model.capabilities.join(', ')}</p>
)}
</div>
);
})()}
</div>
</div>
);
}

View File

@@ -0,0 +1,169 @@
'use client';
import { useState } from 'react';
import { Upload, X, Image as ImageIcon } from 'lucide-react';
interface ReferenceImage {
id: string;
data: string; // Base64
mimeType: string;
preview: string; // Data URL para preview
name: string;
}
interface ReferenceImagesProps {
images: ReferenceImage[];
onImagesChange: (images: ReferenceImage[]) => void;
maxImages?: number;
}
export function ReferenceImages({ images, onImagesChange, maxImages = 3 }: ReferenceImagesProps) {
const [isDragging, setIsDragging] = useState(false);
const handleFileSelect = async (files: FileList | null) => {
if (!files || files.length === 0) return;
const newImages: ReferenceImage[] = [];
for (let i = 0; i < Math.min(files.length, maxImages - images.length); i++) {
const file = files[i];
// Validar que sea una imagen
if (!file.type.startsWith('image/')) {
continue;
}
// Validar tamaño (máx 5MB)
if (file.size > 5 * 1024 * 1024) {
continue;
}
try {
// Leer archivo como base64
const base64 = await fileToBase64(file);
newImages.push({
id: `${Date.now()}-${i}`,
data: base64,
mimeType: file.type,
preview: `data:${file.type};base64,${base64}`,
name: file.name,
});
} catch (error) {
}
}
if (newImages.length > 0) {
onImagesChange([...images, ...newImages]);
}
};
const fileToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const result = reader.result as string;
// Remover el prefijo "data:image/...;base64,"
const base64 = result.split(',')[1];
resolve(base64);
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setIsDragging(false);
handleFileSelect(e.dataTransfer.files);
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
setIsDragging(true);
};
const handleDragLeave = () => {
setIsDragging(false);
};
const removeImage = (id: string) => {
onImagesChange(images.filter(img => img.id !== id));
};
return (
<div className="space-y-3">
<label className="text-xs font-medium text-muted-foreground">
Imágenes de Referencia (Opcional) - {images.length}/{maxImages}
</label>
{/* Zona de drop */}
{images.length < maxImages && (
<div
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
className={`
relative border-2 border-dashed rounded-lg p-6 text-center cursor-pointer
transition-all
${isDragging
? 'border-primary bg-primary/10'
: 'border-border hover:border-primary hover:bg-accent'
}
`}
>
<input
type="file"
accept="image/*"
multiple
onChange={(e) => handleFileSelect(e.target.files)}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
/>
<div className="flex flex-col items-center gap-2">
<Upload className="w-8 h-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
Arrastra imágenes aquí o haz clic para seleccionar
</p>
<p className="text-xs text-muted-foreground">
PNG, JPG, WebP (máx 5MB)
</p>
</div>
</div>
)}
{/* Grid de imágenes */}
{images.length > 0 && (
<div className="grid grid-cols-3 gap-2">
{images.map((image) => (
<div
key={image.id}
className="relative group aspect-square bg-secondary rounded-lg overflow-hidden border border-border"
>
<img
src={image.preview}
alt={image.name}
className="w-full h-full object-cover"
/>
<button
onClick={() => removeImage(image.id)}
className="absolute top-1 right-1 p-1 bg-red-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
title="Eliminar imagen"
>
<X className="w-4 h-4" />
</button>
<div className="absolute bottom-0 left-0 right-0 bg-black/60 text-white text-xs p-1 truncate">
{image.name}
</div>
</div>
))}
</div>
)}
{images.length === 0 && (
<p className="text-xs text-muted-foreground italic">
Las imágenes de referencia ayudan a guiar el estilo y composición de la imagen generada
</p>
)}
</div>
);
}

View File

@@ -0,0 +1,79 @@
'use client';
import { Video, Download, Copy, Check } from 'lucide-react';
import { useState } from 'react';
interface VideoCardProps {
videoData: string; // Base64
prompt: string;
model: string;
}
export function VideoCard({ videoData, prompt, model }: VideoCardProps) {
const [copied, setCopied] = useState(false);
const handleDownload = () => {
const link = document.createElement('a');
link.href = `data:video/mp4;base64,${videoData}`;
link.download = `video-${Date.now()}.mp4`;
link.click();
};
const handleCopyPrompt = async () => {
await navigator.clipboard.writeText(prompt);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<div className="bg-card border border-border rounded-xl overflow-hidden shadow-lg group">
{/* Video */}
<div className="relative aspect-video bg-muted">
<video
src={`data:video/mp4;base64,${videoData}`}
controls
className="w-full h-full object-contain"
/>
</div>
{/* Info */}
<div className="p-4 space-y-3">
{/* Prompt */}
<div className="space-y-1">
<div className="flex items-center justify-between">
<p className="text-xs font-medium text-muted-foreground">Prompt</p>
<button
onClick={handleCopyPrompt}
className="p-1 hover:bg-accent rounded transition-colors"
title="Copiar prompt"
>
{copied ? (
<Check className="w-3 h-3 text-green-500" />
) : (
<Copy className="w-3 h-3 text-muted-foreground" />
)}
</button>
</div>
<p className="text-sm text-foreground line-clamp-2">{prompt}</p>
</div>
{/* Model */}
<div className="flex items-center justify-between text-xs">
<span className="text-muted-foreground">Modelo:</span>
<span className="font-medium text-foreground">{model}</span>
</div>
{/* Actions */}
<div className="flex gap-2 pt-2 border-t border-border">
<button
onClick={handleDownload}
className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:opacity-90 transition-opacity"
>
<Download className="w-4 h-4" />
Descargar
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,118 @@
'use client';
import { aspectRatioSizes, videoDurations } from '@/lib/google-ai';
interface VideoConfigProps {
model: string;
aspectRatio: string;
onAspectRatioChange: (ratio: string) => void;
duration: number;
onDurationChange: (duration: number) => void;
negativePrompt: string;
onNegativePromptChange: (prompt: string) => void;
safetyLevel: 'block_none' | 'block_some' | 'block_most';
onSafetyLevelChange: (level: 'block_none' | 'block_some' | 'block_most') => void;
}
export function VideoConfig({
aspectRatio,
onAspectRatioChange,
duration,
onDurationChange,
negativePrompt,
onNegativePromptChange,
safetyLevel,
onSafetyLevelChange,
}: VideoConfigProps) {
const availableRatios = Object.keys(aspectRatioSizes);
const size = aspectRatioSizes[aspectRatio];
return (
<div className="space-y-4">
<h3 className="text-sm font-medium text-foreground">Configuración de Video</h3>
{/* Aspect Ratio */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Aspect Ratio
</label>
<div className="grid grid-cols-5 gap-2">
{availableRatios.map((ratio) => (
<button
key={ratio}
onClick={() => onAspectRatioChange(ratio)}
className={`
px-3 py-2 text-xs rounded-lg font-medium transition-all
${aspectRatio === ratio
? 'bg-primary text-primary-foreground'
: 'bg-secondary hover:bg-accent'
}
`}
>
{ratio}
</button>
))}
</div>
{size && (
<p className="text-xs text-muted-foreground">
Dimensiones: {size.width}x{size.height}px
</p>
)}
</div>
{/* Duración */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Duración: {duration} segundos
</label>
<div className="flex gap-2">
{videoDurations.map((dur) => (
<button
key={dur.value}
onClick={() => onDurationChange(dur.value)}
className={`
flex-1 px-3 py-2 text-xs rounded-lg font-medium transition-all
${duration === dur.value
? 'bg-primary text-primary-foreground'
: 'bg-secondary hover:bg-accent'
}
`}
>
{dur.label}
</button>
))}
</div>
</div>
{/* Negative Prompt */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Negative Prompt (opcional)
</label>
<textarea
value={negativePrompt}
onChange={(e) => onNegativePromptChange(e.target.value)}
placeholder="Elementos que NO quieres en el video..."
className="w-full px-3 py-2 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
rows={2}
/>
</div>
{/* Safety Level */}
<div className="space-y-2">
<label className="text-xs font-medium text-muted-foreground">
Nivel de Seguridad
</label>
<select
value={safetyLevel}
onChange={(e) => onSafetyLevelChange(e.target.value as any)}
className="w-full px-3 py-2 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="block_none">Sin bloqueo</option>
<option value="block_some">Bloqueo moderado</option>
<option value="block_most">Bloqueo alto</option>
</select>
</div>
</div>
);
}

View File

@@ -0,0 +1,29 @@
// Servidor: Configuración de Vertex AI con autenticación
// Este archivo SOLO debe importarse en API routes (server-side)
import { VertexAI } from '@google-cloud/vertexai';
// Leer credenciales desde variables de entorno
export const projectId = process.env.GOOGLE_PROJECT_ID!;
export const location = process.env.GOOGLE_LOCATION || 'us-central1';
// Construir objeto de credenciales desde variables de entorno
export const credentials = {
type: 'service_account',
project_id: process.env.GOOGLE_PROJECT_ID,
client_email: process.env.GOOGLE_CLIENT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
};
console.log(`Configurando Vertex AI - Proyecto: ${projectId}, Location: ${location}`);
// Crear instancia de Vertex AI
export const vertexAI = new VertexAI({
project: projectId,
location: location,
googleAuthOptions: {
credentials: credentials,
},
});
console.log('Cliente de Vertex AI creado correctamente');

180
frontend/lib/google-ai.ts Normal file
View File

@@ -0,0 +1,180 @@
// Cliente: Solo tipos y constantes (sin módulos de Node.js)
// Modelos disponibles para generación de imágenes con Gemini
export const geminiImageModels = [
{
id: 'gemini-2.5-flash-image',
name: 'Gemini 2.5 Flash Image',
description: 'Modelo optimizado para generación de imágenes',
supportsImages: true,
capabilities: ['text-to-image', 'image-generation'],
},
{
id: 'gemini-2.0-flash-exp',
name: 'Gemini 2.0 Flash Experimental',
description: 'Modelo experimental con generación de imágenes rápida',
supportsImages: true,
capabilities: ['text-to-image', 'image-editing'],
},
{
id: 'gemini-exp-1206',
name: 'Gemini Experimental 1206',
description: 'Versión experimental con capacidades mejoradas',
supportsImages: true,
capabilities: ['text-to-image', 'multimodal'],
},
{
id: 'gemini-3-pro-image-preview',
name: 'Gemini 3 Pro Image Preview',
description: 'Vista previa de Gemini 3 Pro para generación de imágenes',
supportsImages: true,
capabilities: ['text-to-image', 'image-generation', 'high-quality'],
},
{
id: 'gemini-1.5-pro',
name: 'Gemini 1.5 Pro',
description: 'Modelo más capaz para tareas complejas',
supportsImages: true,
capabilities: ['multimodal', 'long-context'],
},
{
id: 'gemini-1.5-flash',
name: 'Gemini 1.5 Flash',
description: 'Modelo rápido y eficiente',
supportsImages: true,
capabilities: ['multimodal', 'fast'],
},
] as const;
export type GeminiImageModel = typeof geminiImageModels[number];
// Modelos disponibles para generación de videos con Veo
export const veoVideoModels = [
{
id: 'veo-2.0-generate-001',
name: 'Veo 2.0 Generate',
description: 'Modelo base para generación de videos',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation'],
},
{
id: 'veo-2.0-generate-exp',
name: 'Veo 2.0 Generate Experimental',
description: 'Versión experimental de Veo 2.0',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation'],
},
{
id: 'veo-2.0-generate-preview',
name: 'Veo 2.0 Generate Preview',
description: 'Vista previa de Veo 2.0',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation'],
},
{
id: 'veo-3.0-generate-001',
name: 'Veo 3.0 Generate',
description: 'Modelo de última generación para videos',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation', 'high-quality'],
},
{
id: 'veo-3.0-fast-generate-001',
name: 'Veo 3.0 Fast Generate',
description: 'Generación rápida de videos con Veo 3.0',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation', 'fast'],
},
{
id: 'veo-3.1-generate-preview',
name: 'Veo 3.1 Generate Preview',
description: 'Vista previa de Veo 3.1',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation', 'latest'],
},
{
id: 'veo-3.1-fast-generate-preview',
name: 'Veo 3.1 Fast Generate Preview',
description: 'Generación rápida con Veo 3.1 preview',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation', 'fast', 'latest'],
},
{
id: 'test',
name: 'Vtest',
description: 'Test para probar la api de gemini',
supportsVideo: true,
capabilities: ['text-to-video', 'video-generation', 'fast', 'latest'],
},
] as const;
export type VeoVideoModel = typeof veoVideoModels[number];
// Configuración de dimensiones por aspect ratio
export const aspectRatioSizes: Record<string, { width: number; height: number }> = {
'1:1': { width: 1024, height: 1024 },
'3:4': { width: 768, height: 1024 },
'4:3': { width: 1024, height: 768 },
'9:16': { width: 576, height: 1024 },
'16:9': { width: 1024, height: 576 },
};
// Configuración de duración de videos
export const videoDurations = [
{ value: 5, label: '5 segundos' },
{ value: 8, label: '8 segundos' },
{ value: 10, label: '10 segundos' },
] as const;
// Tipos para la configuración
export interface ImageGenerationConfig {
model: string;
prompt: string;
aspectRatio?: string;
numberOfImages?: number;
negativePrompt?: string;
seed?: number;
guidanceScale?: number;
temperature?: number;
safetyFilterLevel?: 'block_none' | 'block_some' | 'block_most';
referenceImages?: Array<{
data: string; // Base64
mimeType: string;
}>;
}
export interface VideoGenerationConfig {
model: string;
prompt: string;
aspectRatio?: string;
duration?: number; // en segundos
negativePrompt?: string;
seed?: number;
temperature?: number;
safetyFilterLevel?: 'block_none' | 'block_some' | 'block_most';
}
// Helper para obtener información del modelo
export function getModelInfo(modelId: string) {
return geminiImageModels.find(m => m.id === modelId);
}
// Helper para validar aspect ratio
export function isValidAspectRatio(modelId: string, aspectRatio: string): boolean {
return true; // Gemini acepta cualquier aspect ratio
}
// Safety settings helpers
export function getSafetySettings(level: 'block_none' | 'block_some' | 'block_most') {
const threshold =
level === 'block_none' ? 'BLOCK_NONE' :
level === 'block_some' ? 'BLOCK_ONLY_HIGH' :
'BLOCK_MEDIUM_AND_ABOVE';
return [
{ category: 'HARM_CATEGORY_HATE_SPEECH', threshold },
{ category: 'HARM_CATEGORY_DANGEROUS_CONTENT', threshold },
{ category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', threshold },
{ category: 'HARM_CATEGORY_HARASSMENT', threshold },
];
}

26
frontend/lib/utils.ts Normal file
View File

@@ -0,0 +1,26 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Helper para descargar imagen
export function downloadImage(base64Data: string, filename: string) {
const link = document.createElement('a');
link.href = `data:image/png;base64,${base64Data}`;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// Helper para generar nombre de archivo único
export function generateImageFilename(prompt: string): string {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const safePrompt = prompt
.slice(0, 30)
.replace(/[^a-z0-9]/gi, '_')
.toLowerCase();
return `image_${safePrompt}_${timestamp}.png`;
}

6
frontend/next.config.js Normal file
View File

@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
// Server Actions están habilitados por defecto en Next.js 14+
}
module.exports = nextConfig

View File

@@ -0,0 +1,9 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
export default config

View File

@@ -0,0 +1,43 @@
import type { Config } from 'tailwindcss'
const config: Config = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))',
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))',
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))',
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))',
},
},
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
},
},
},
plugins: [],
}
export default config

14
pyproject.toml Normal file
View File

@@ -0,0 +1,14 @@
[project]
name = "bnt-ia-innovacion"
version = "0.1.0"
description = "Proyecto de innovación con IA"
readme = "README.md"
requires-python = ">=3.9"
dependencies = [
"google-genai",
"google-cloud-aiplatform",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

166
test/banana.py Normal file
View File

@@ -0,0 +1,166 @@
import base64
import json
from datetime import datetime
from pathlib import Path
import google.oauth2.service_account as sa
import vertexai
from vertexai.preview.vision_models import ImageGenerationModel
class GeminiImageChat:
"""Chat interactivo para generación de imágenes con Gemini"""
def __init__(self, credentials_path=None):
"""Inicializa el cliente de Gemini"""
# Buscar archivo de credenciales
if credentials_path is None:
credentials_path = Path(__file__).parent.parent / "bnt-ia-innovacion-new.json"
credentials_path = Path(credentials_path)
if not credentials_path.exists():
raise ValueError(f"Archivo de credenciales no encontrado: {credentials_path}")
# Leer credenciales del archivo JSON
with open(credentials_path, 'r') as f:
credentials_json = json.load(f)
# Cargar credenciales usando el método correcto
credentials = sa.Credentials.from_service_account_file(str(credentials_path))
# Inicializar Vertex AI
vertexai.init(
project=credentials_json.get('project_id'),
credentials=credentials,
location='us-central1'
)
# Inicializar modelo de generación de imágenes
self.model = ImageGenerationModel.from_pretrained("gemini-2.5-flash-image")
self.output_dir = Path("generated_images")
self.output_dir.mkdir(exist_ok=True)
def save_image(self, image_data, prompt):
"""Guarda la imagen generada en disco"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Sanitizar el prompt para usar como parte del nombre
safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '_')).rstrip()
safe_prompt = safe_prompt.replace(' ', '_')
filename = f"{timestamp}_{safe_prompt}.png"
filepath = self.output_dir / filename
# Decodificar y guardar la imagen
if isinstance(image_data, str):
# Si es base64
image_bytes = base64.b64decode(image_data)
else:
image_bytes = image_data
with open(filepath, 'wb') as f:
f.write(image_bytes)
return filepath
def generate_image(self, prompt, aspect_ratio="1:1", save=True):
"""Genera una imagen basada en el prompt"""
print(f"\n{'='*60}")
print(f"Generando imagen para: {prompt}")
print(f"{'='*60}\n")
try:
# Generar imágenes usando Vertex AI
images = self.model.generate_images(
prompt=prompt,
number_of_images=1,
language="es",
aspect_ratio=aspect_ratio,
safety_filter_level="block_some",
person_generation="allow_adult",
)
# Guardar imágenes generadas
saved_files = []
if images and save:
for idx, image in enumerate(images.images):
# Convertir imagen a bytes
image_bytes = image._image_bytes
# Guardar usando el método existente
filepath = self.save_image(image_bytes, prompt)
saved_files.append(filepath)
print(f"✓ Imagen {idx + 1} guardada en: {filepath}")
return {
"images": saved_files,
"success": True
}
except Exception as e:
print(f"\n✗ Error al generar imagen: {str(e)}")
return {
"images": [],
"success": False,
"error": str(e)
}
def start_chat(self):
"""Inicia el chat interactivo"""
print("\n" + "="*60)
print("🎨 CHAT DE GENERACIÓN DE IMÁGENES CON GEMINI")
print("="*60)
print("\nComandos disponibles:")
print(" - Escribe un prompt para generar una imagen")
print(" - 'config' - Cambiar configuración de imagen")
print(" - 'salir' - Salir del chat")
print("="*60 + "\n")
aspect_ratio = "1:1"
while True:
try:
user_input = input("\n💭 Prompt: ").strip()
if not user_input:
continue
if user_input.lower() == 'salir':
print("\n👋 ¡Hasta pronto!")
break
elif user_input.lower() == 'config':
print("\nConfiguración actual:")
print(f" Aspect ratio: {aspect_ratio}")
print("\nOpciones de aspect ratio: 1:1, 16:9, 9:16, 3:4, 4:3")
new_ratio = input("\nNuevo aspect ratio (Enter para mantener): ").strip()
if new_ratio:
aspect_ratio = new_ratio
print(f"\n✓ Configuración actualizada: {aspect_ratio}")
else:
# Generar imagen
self.generate_image(user_input, aspect_ratio)
except KeyboardInterrupt:
print("\n\n👋 ¡Hasta pronto!")
break
except Exception as e:
print(f"\n✗ Error: {str(e)}")
def main():
"""Función principal"""
try:
chat = GeminiImageChat()
chat.start_chat()
except ValueError as e:
print(f"✗ Error de configuración: {e}")
print("\nAsegúrate de tener el archivo bnt-ia-innovacion-new.json en el directorio raíz")
except Exception as e:
print(f"✗ Error inesperado: {e}")
if __name__ == "__main__":
main()

273
test/list_models.py Normal file
View File

@@ -0,0 +1,273 @@
import json
import os
import base64
import mimetypes
import time
from datetime import datetime
from pathlib import Path
from google import genai
from google.genai import types
from google.genai.types import GenerateVideosConfig
# Leer credenciales
credentials_path = Path(__file__).parent.parent / "bnt-ia-innovacion-new.json"
with open(credentials_path, 'r') as f:
credentials_json = json.load(f)
# Configurar variable de entorno con las credenciales
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = str(credentials_path)
# Crear cliente de genai
client = genai.Client(
vertexai=True,
project=credentials_json.get('project_id'),
location='us-central1'
)
# Crear directorio para videos
output_dir = Path("generated_videos")
output_dir.mkdir(exist_ok=True)
print("="*60)
print("CHAT DE GENERACIÓN DE VIDEOS CON GOOGLE VEO")
print("="*60)
print(f"\nProyecto: {credentials_json.get('project_id')}")
print(f"Ubicación: us-central1")
print(f"Modelo: veo-002")
print(f"Directorio de salida: {output_dir}")
print("="*60)
def save_video(video_data, prompt, index=0):
"""Guarda el video generado en disco"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Sanitizar el prompt para usar como parte del nombre
safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '_')).rstrip()
safe_prompt = safe_prompt.replace(' ', '_')
filename = f"{timestamp}_{safe_prompt}_{index}.mp4"
filepath = output_dir / filename
# Decodificar y guardar el video
if isinstance(video_data, str):
# Si es base64
video_bytes = base64.b64decode(video_data)
else:
video_bytes = video_data
with open(filepath, 'wb') as f:
f.write(video_bytes)
return filepath
def load_reference_media(media_path):
"""Carga una imagen o video de referencia y la convierte a Part"""
try:
media_path = Path(media_path)
if not media_path.exists():
print(f"✗ Archivo no encontrado: {media_path}")
return None
# Detectar tipo MIME
mime_type, _ = mimetypes.guess_type(str(media_path))
if mime_type is None:
print(f"✗ No se pudo detectar el tipo de archivo: {media_path}")
return None
if not (mime_type.startswith('image/') or mime_type.startswith('video/')):
print(f"✗ Archivo no es una imagen o video válido: {media_path}")
return None
# Leer archivo
with open(media_path, 'rb') as f:
media_bytes = f.read()
# Crear Part con el archivo
return types.Part.from_bytes(
data=media_bytes,
mime_type=mime_type
)
except Exception as e:
print(f"✗ Error al cargar archivo: {e}")
return None
def generate_video(prompt, reference_media=None, duration=5):
"""Genera un video y lo guarda
Args:
prompt: Texto descriptivo para generar el video
reference_media: Lista de rutas a imágenes de referencia (opcional)
duration: Duración del video en segundos (5 u 8)
"""
print(f"\n{'='*60}")
print(f"Generando video: {prompt}")
print(f"Duración: {duration} segundos")
if reference_media:
print(f"Con {len(reference_media)} imagen(es) de referencia")
print(f"{'='*60}\n")
try:
# Configurar bucket de salida (temporal en GCS)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_prompt = "".join(c for c in prompt[:20] if c.isalnum() or c in (' ', '_')).rstrip()
safe_prompt = safe_prompt.replace(' ', '_')
output_gcs_uri = f"gs://bnt-ia-innovacion-videos/veo_output/{timestamp}_{safe_prompt}/"
# Preparar imagen de referencia si existe
reference_image = None
if reference_media and len(reference_media) > 0:
# Para Veo, solo se puede usar una imagen de referencia
img_path = reference_media[0]
print(f"📸 Cargando imagen de referencia: {img_path}")
# Subir imagen a GCS o usar directamente si ya está en GCS
if img_path.startswith('gs://'):
reference_image = types.Image(gcs_uri=img_path)
print(f"✓ Usando imagen de GCS: {img_path}")
else:
# Por ahora mostrar advertencia
print(f"⚠ La imagen debe estar en Google Cloud Storage (gs://)")
print(f"⚠ Continuando sin imagen de referencia...")
reference_image = None
print("\n⏳ Generando video con Veo (esto puede tardar varios minutos)...")
print(f"📂 El video se guardará en: {output_gcs_uri}")
start_time = time.time()
# Configuración de Veo
config = GenerateVideosConfig(
aspect_ratio="16:9",
output_gcs_uri=output_gcs_uri,
)
# Generar video con Veo
if reference_image:
operation = client.models.generate_videos(
model="veo-3.1-generate-001",
prompt=prompt,
reference_image=reference_image,
config=config,
)
else:
operation = client.models.generate_videos(
model="veo-3.1-generate-001",
prompt=prompt,
config=config,
)
print(f"🔄 Operación iniciada: {operation.name}")
print("⏳ Esperando a que se complete la generación...")
# Polling de la operación cada 15 segundos
poll_count = 0
while not operation.done:
time.sleep(15)
operation = client.operations.get(operation)
poll_count += 1
elapsed = time.time() - start_time
print(f"{elapsed:.0f}s - Verificación #{poll_count} - Estado: {'Completado' if operation.done else 'En proceso...'}")
elapsed_time = time.time() - start_time
print(f"\n✓ Generación completada en {elapsed_time:.2f} segundos")
# Obtener el resultado
if hasattr(operation, 'result') and operation.result:
if hasattr(operation.result, 'generated_videos') and operation.result.generated_videos:
video_uri = operation.result.generated_videos[0].video.uri
print(f"\n✓ Video generado exitosamente!")
print(f"📹 URI del video en GCS: {video_uri}")
# Intentar descargar el video de GCS
try:
from google.cloud import storage
# Parsear la URI de GCS
gcs_path = video_uri.replace('gs://', '')
bucket_name = gcs_path.split('/')[0]
blob_name = '/'.join(gcs_path.split('/')[1:])
print(f"\n⬇ Descargando video de GCS...")
storage_client = storage.Client(project=credentials_json.get('project_id'))
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)
# Guardar localmente
local_filename = f"{timestamp}_{safe_prompt}.mp4"
local_filepath = output_dir / local_filename
blob.download_to_filename(str(local_filepath))
print(f"✓ Video descargado en: {local_filepath}")
return True
except ImportError:
print("\n⚠ Para descargar automáticamente, instala: pip install google-cloud-storage")
print(f"📹 Puedes descargar el video manualmente desde: {video_uri}")
return True
except Exception as e:
print(f"\n⚠ No se pudo descargar automáticamente: {e}")
print(f"📹 Puedes descargar el video manualmente desde: {video_uri}")
return True
else:
print("\n⚠ No se generaron videos en la respuesta")
print(f"DEBUG - Resultado: {operation.result}")
return False
else:
print("\n⚠ La operación no tiene resultado")
print(f"DEBUG - Operación: {operation}")
return False
except Exception as e:
print(f"\n✗ Error al generar video: {str(e)}")
import traceback
print("\nTraceback completo:")
traceback.print_exc()
return False
# Chat interactivo
print("\nComandos:")
print(" - Escribe un prompt para generar un video")
print(" - Para especificar duración: prompt [5s] o [8s]")
print(" - Para usar archivos de referencia: prompt | ruta1.jpg | video.mp4")
print(" - Ejemplo: un gato saltando en slow motion [8s] | referencia.jpg")
print(" - 'salir' para terminar\n")
while True:
try:
user_input = input("\n🎬 Prompt: ").strip()
if not user_input:
continue
if user_input.lower() == 'salir':
print("\n👋 ¡Hasta pronto!")
break
# Extraer duración si está especificada
duration = 5 # Por defecto 5 segundos
if '[5s]' in user_input:
duration = 5
user_input = user_input.replace('[5s]', '').strip()
elif '[8s]' in user_input:
duration = 8
user_input = user_input.replace('[8s]', '').strip()
# Verificar si hay archivos de referencia
if '|' in user_input:
parts = [p.strip() for p in user_input.split('|')]
prompt = parts[0]
reference_media = parts[1:] if len(parts) > 1 else None
generate_video(prompt, reference_media, duration)
else:
generate_video(user_input, duration=duration)
except KeyboardInterrupt:
print("\n\n👋 ¡Hasta pronto!")
break
except Exception as e:
print(f"\n✗ Error: {str(e)}")