Copyright 2026 Google LLC.
# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Si estás leyendo este notebook en Github, ábrelo en Colab haciendo clic en el botón de arriba para ver los videos generados.
Nota: Veo es una función de pago. Este notebook no se ejecutará con la versión gratuita. (Consulta precios para más detalles).
# Change that value if you want to run the colab
I_am_aware_that_veo_is_a_paid_feature = False # @param {type:"boolean"}
¿Qué es Veo?
Veo permite a los creadores generar videos de alta calidad con detalles increíbles, artefactos mínimos y duraciones extendidas en resoluciones de hasta 1080p. Veo es compatible con la conversión de texto a video y de imágenes a video.
Con Veo 3 , puedes crear videos con:
Comprensión avanzada del lenguaje : Veo comprende profundamente el lenguaje natural y la semántica visual, capturando los matices y el tono de prompts complejos para renderizar detalles intrincados en escenas extendidas, incluyendo términos cinematográficos como "timelapse" o "tomas aéreas".
Control creativo sin precedentes : Veo ofrece un nivel de control creativo sin precedentes, comprendiendo prompts para todo tipo de efectos cinematográficos, como timelapses o tomas aéreas de un paisaje.
Videos con audio : Veo 3 genera videos con audio automáticamente, sin esfuerzo adicional por parte del desarrollador.
Controles de video más precisos : Veo 3 es más preciso en la iluminación, la física y los controles de cámara.
Veo 3.1 trae nuevas capacidades:
La familia de modelos Veo 3 incluye Veo 3/3.1 , Veo 3.1 Lite y Veo 3/3.1 Fast , que son versiones más rápidas y accesibles de los modelos. Los modelos Veo Lite y Fast son ideales para servicios de backend que generan anuncios programáticamente, herramientas para pruebas A/B rápidas de conceptos creativos o aplicaciones que necesitan producir contenido para redes sociales rápidamente. Veo 3.1 Lite es particularmente rentable, optimizado para la generación de video de alta capacidad de procesamiento en 720p y 1080p.
La seguridad es un enfoque central , con medidas robustas para prevenir contenido inapropiado o dañino, y todos los videos generados están marcados digitalmente con SynthID de Google DeepMind .
Ten en cuenta que la generación de modelos anterior, Veo 2 , todavía está disponible para desarrolladores a través de la API de Gemini por un tiempo. Sin embargo, a diferencia de Veo 3, los videos generados por Veo 2 no contienen audio.
Configuración
Instalar el SDK
Instala el SDK desde PyPI .
%pip install -U -q "google-genai>=2.9.0" # Minimum version 1.44 for video extension # 2.0 is needed to use the interactions API
[2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m45.3/45.3 kB[0m [31m1.1 MB/s[0m eta [36m0:00:00[0m
[2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m237.3/237.3 kB[0m [31m13.4 MB/s[0m eta [36m0:00:00[0m
[?25h
Configura tu clave de API e inicializa el cliente
Para ejecutar la siguiente celda, tu clave de API debe estar almacenada en un Secreto de Colab llamado GEMINI_API_KEY. Si aún no tienes una clave de API, o no estás seguro de cómo crear un Secreto de Colab, consulta Autenticación para ver un tutorial.
from google.colab import userdata
from google import genai
from google.genai import types
GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')
client = genai.Client(api_key=GEMINI_API_KEY)
Selecciona el modelo Veo
VEO_MODEL_ID = "veo-3.1-lite-generate-preview" # @param ["veo-3.1-generate-preview", "veo-3.1-fast-generate-preview", "veo-3.1-lite-generate-preview"] {"allow-input":true, isTemplate: true}
Texto a video
Describe la escena que deseas, ya sea creada por ti o con la ayuda de Gemini, y Veo 3 la hará realidad.
Consejos de prompting para Veo
Para aprovechar al máximo Veo, considera incorporar terminología de video específica en tus prompts. Veo comprende una amplia gama de términos relacionados con:
Composición de la toma : Especifica el encuadre y el número de sujetos en la toma (por ejemplo, "toma única ", "toma de dos ", "toma por encima del hombro ").
Posicionamiento y movimiento de la cámara : Controla la ubicación y el movimiento de la cámara usando términos como "a la altura de los ojos ", "ángulo alto ", "ángulo bajo ", "dolly shot ", "zoom shot ", "pan shot " y "tracking shot ".
Efectos de enfoque y lente : Usa términos como "enfoque superficial ", "enfoque profundo ", "enfoque suave ", "lente macro " y "lente gran angular " para lograr efectos visuales específicos.
Estilo general y tema : Guía la dirección creativa de Veo especificando estilos como "ciencia ficción ", "comedia romántica ", "película de acción " o "animación ". También puedes describir los sujetos y fondos que deseas, como "paisaje urbano ", "naturaleza ", "vehículos " o "animales".
Consulta la guía de prompts de Veo para más detalles y consejos.
Parámetros opcionales
El prompt es el único parámetro obligatorio, los demás son todos opcionales.
negative_prompt : Lo que no quieres ver en el video.
person_generation : Dile a tu modelo si se le permite generar adultos en los videos o no. Los niños siempre están bloqueados.
duration_seconds : 4, 6 u 8 segundos con Veo 3.1 (siempre 8 segundos para Veo 3 y 7 segundos al extender).
aspect ratio : Ya sea 16:9 (horizontal) o 9:16 (vertical).
resolution : Ya sea 720p o 1080p.
Más detalles sobre cada parámetro en la sección relacionada de la documentación .
Crea un video a partir de un simple prompt de texto
La generación del video tarda aproximadamente un minuto.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "a close-up shot of a golden retriever playing in a field of sunflowers" # @param {type: "string"}
# Optional parameters
negative_prompt = "barking, woofing" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Consejo: Webhooks
Gemini es compatible con Webhooks para procesar las finalizaciones de forma asíncrona. En lugar de llamar continuamente a las operaciones GET /, suscríbete a video.generated directamente para permitir que la API de Gemini envíe notificaciones en tiempo real a tu servidor cuando las operaciones asíncronas o de larga duración se completen.
Consulta el cookbook de Webhooks para ver un tutorial detallado.
webhook = client.webhooks.create(
name="MyVideoGenerationWebhook",
subscribed_events=["video.generated"],
uri="https://my-api.com/gemini-callback",
)
print(f"Created webhook: {webhook}")
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un golden retriever jugando en un campo de girasoles .
Selecciona tu resolución y relación de aspecto
Para videos horizontales, puedes seleccionar las resoluciones 720p o 1080p. Pero si prefieres un video vertical, puedes establecer el aspect_ratio en 9:16 y obtener un video vertical.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "a unicorn takes off from the top of the arc de triomphe and fly to the Eiffel tower." # @param {type: "string"}
# Optional parameters
negative_prompt = "airplanes" # @param {type: "string"}
aspect_ratio = "9:16" # @param ["16:9","9:16"]
resolution = "720p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un unicornio despega de la cima del Arco del Triunfo y vuela hacia la Torre Eiffel. .
Controla la iluminación
Veo 3 también te permite tener un buen control sobre la iluminación del video que se está generando.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "a solitary, ancient oak tree silhouetted against a dramatic sunset. Emphasize the exquisite control over lighting: capture the deep, warm hues of the setting sun backlighting the tree, with subtle rays of light piercing through the branches, highlighting the texture of the bark and leaves with a golden glow. The sky should transition from fiery orange at the horizon to soft purples and blues overhead, with a single, faint star appearing as dusk deepens. Include the gentle sound of a breeze rustling through the leaves, and the distant call of an owl." # @param {type: "string"}
# Optional parameters
negative_prompt = "" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un solitario y antiguo roble silueteado contra un dramático atardecer .
Controla la cámara
Veo 3 también te permite tener un buen control sobre las tomas de cámara y el comportamiento del video que se está generando.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "a realistic video of a futuristic red sportscar speeding down a winding coastal highway at dusk. Begin with a high-angle drone shot that slowly descends, transitioning into a close-up, low-angle tracking shot that perfectly follows the car as it rounds a curve, emphasizing its speed and the gleam of its paint under the fading light. Then, execute a smooth, rapid dolly zoom, making the background compress as the car remains the same size, conveying a sense of intense focus and speed. Finally, end with a perfectly stable, slow-motion shot from a fixed roadside perspective as the car blurs past, its taillights streaking across the frame. Include the immersive sound of the engine roaring, the tires gripping the asphalt, and the distant crash of waves." # @param {type: "string"}
# Optional parameters
negative_prompt = "" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: un coche deportivo rojo futurista acelerando por una sinuosa carretera costera .
Controla el audio
Veo 3 también te permite controlar los detalles de audio en tu video generado.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "fireworks at a beautiful city skyline scene with many different fireworks colors and sounds. sounds from excited people enjoying the show surrounding the camera POV can be heard too." # @param {type: "string"}
# Optional parameters
negative_prompt = "" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: fuegos artificiales en una hermosa escena del horizonte de la ciudad .
Gestiona tus diálogos
También tienes la flexibilidad de definir el diálogo en tus videos.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "Two charismatic and funny raindrops like coloured characters. The first character start saying \"oh my god, it is really hot in here!\" - then the second answers \"right? I'm melting down! then it melts down completely." # @param {type: "string"}
# Optional parameters
negative_prompt = "texts, captions, subtitles" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un diálogo de dos carismáticas y divertidas gotas de lluvia como personajes de colores .
Imagen a video
También puedes generar videos a partir de una imagen base y un prompt. Aquí tienes tres ejemplos, uno en el que proporcionas la imagen y otro en el que usarás Gemini Flash Image para generar la imagen. ¡El último mezclará varias imágenes de referencia en un video!
Usa tus propias imágenes
Si quieres usar tu propia imagen, súbela a Colab haciendo clic en el icono de carpeta en el menú izquierdo (debería ser la 5ª opción), luego en el icono de subir (el primero) en la parte superior del panel izquierdo que debería haberse abierto.
Tus imágenes se subirán a la carpeta /content de esta instancia de Colab.
Alternativamente, puedes usar el código de esta celda para subir tu imagen:
import os
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
os.rename(fn, 'image.jpg')
<IPython.core.display.HTML object>
El widget de carga solo está disponible cuando la celda se ha ejecutado en la
sesión actual del navegador. Vuelve a ejecutar esta celda para habilitarlo.
Saving ginger.jpeg to ginger.jpeg
Ahora que tienes tu propia imagen, puedes añadirla a tu prompt de Veo.
Si no sabes qué prompt usar para tu imagen, deja el prompt vacío y el modelo se encargará de generar el contenido.
from IPython.display import display, Image as Img
display(Img('image.jpg', width=600)) # display the uploaded image
<IPython.core.display.Image object>
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
from PIL import Image
import io
prompt = "" # @param {"type":"string","placeholder":"Write your own prompt or leave empty to let the model decide"}
image_name = "" # @param {type: "string", "placeholder":"Enter the name of your image or leave empty for the one you just uploaded."}
# Optional parameters
negative_prompt = "ugly, low quality" # @param {type: "string"}
aspect_ratio = "9:16" # @param ["16:9","9:16"]
resolution = "720p" # @param ["720p","1080p"]
# Loading the image
if image_name=="":
image_name = "image.jpg"
im = Image.open(image_name)
# converting the image to bytes
image_bytes_io = io.BytesIO()
im.save(image_bytes_io, format=im.format)
image_bytes = image_bytes_io.getvalue()
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
image=types.Image(image_bytes=image_bytes, mime_type=im.format),
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Displays the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un video generado a partir de la imagen subida .
Usa Gemini Image para generar la imagen base
Esta vez vas a generar una imagen base con Gemini Image y, cuando estés satisfecho con ella, crear un video a partir de ella.
Si quieres saber más sobre la capacidad de generación de imágenes integrada de Gemini, consulta el notebook dedicado .
⚠️ Ten cuidado, la generación de imágenes es una función de pago (consulta precios ).
if not I_am_aware_that_veo_is_a_paid_feature:
print("Image generation is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
prompt = "A high quality photorealistic front image of a ginger cat driving a red convertible racing car on the French riviera coast" # @param {type: "string"}
# Optional parameters
negative_prompt = "ugly, low quality, static, weird physics" # @param {type: "string"}
aspect_ratio = "16:9" # @param {type: "string"}
number_of_videos = 1
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=[prompt],
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
)
)
)
for part in response.parts:
if part.inline_data:
gemini_image = part.as_image()
break
gemini_image.show()
gemini_image.save("cat_car.png")
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=1344x768>
Cuando estés satisfecho con tu imagen, puedes usar Veo para crear un video a partir de ella.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "The car races along the coast as the cat purrs in delight" # @param {type: "string"}
# Optional parameters
negative_prompt = "ugly, low quality, static, weird physics" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
image=gemini_image,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Display the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un video generado a partir de la imagen generada por Gemini .
Añade una imagen final
Ahora, añadamos una imagen final para controlar cómo debe terminar el video. Esto se puede usar para asegurar que el video se integre con tu contenido existente.
Ten en cuenta que no puedes usar solo una imagen final; siempre necesitas añadir también una inicial.
import PIL
if not I_am_aware_that_veo_is_a_paid_feature:
print("Image generation is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
prompt = "Show what happens afterwards when the car take off from a cliff." # @param {type: "string"}
# Optional parameters
negative_prompt = "ugly, low quality, static, weird physics" # @param {type: "string"}
aspect_ratio = "16:9" # @param {type: "string"}
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=[prompt, PIL.Image.open("cat_car.png")],
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
)
)
)
for part in response.parts:
if part.inline_data:
ending_image = part.as_image()
break
ending_image.show()
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=1344x768>
Cuando estés satisfecho con tu imagen final, puedes usar Veo para crear un video que sirva de puente entre tus dos imágenes. Solo necesitas pasar la imagen final usando config.last_frame como puedes ver a continuación:
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
# Optional parameters
prompt = "" # @param {"type":"string","placeholder":"Prompt is optional here"}
negative_prompt = "ugly, low quality, static, weird physics" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9","9:16"]
resolution = "1080p" # @param ["720p","1080p"]
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
prompt=prompt,
image=gemini_image,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
last_frame=ending_image
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'flying_car_{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Display the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un video generado con un fotograma inicial y uno final .
Referencias a video
También puedes enviar varias imágenes de referencia al modelo; pueden ser personajes u objetos que quieras ver en el video o un estilo al que quieras adherirte.
Ten en cuenta que solo está disponible usando Veo 3.1 (no Fast) y en 720p y horizontal (16:9).
Añade múltiples referencias a tus videos
Empecemos generando un par de imágenes de referencia.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Image generation is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=["A red and black backpack"],
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
)
)
)
for part in response.parts:
if part.inline_data:
backpack_image = part.as_image()
break
backpack_image.show()
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=["Tanned guy in a leather jacket and a motorbike"],
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
)
)
)
for part in response.parts:
if part.inline_data:
actor_image = part.as_image()
break
actor_image.show()
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=1344x768>
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=1344x768>
Ahora crea un video usando esas dos imágenes de referencia. Ten en cuenta que necesitas convertir tus imágenes a un VideoGenerationReferenceImage e indicar que son assets.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "A caricatural commercial video for this backpack. The actor puts on the backpack, jumps on his motorbike and starts off with a bang and an epic music" # @param {"type":"string","placeholder":"Write your own prompt or leave empty to let the model decide"}
# Optional parameters
negative_prompt = "ugly, low quality, static, weird physics" # @param {type: "string"}
aspect_ratio = "16:9" # @param ["16:9"] # Only landscape is supported
resolution = "720p" # @param ["720p"] # Only 720p is supported
backpack_reference = types.VideoGenerationReferenceImage(
image=backpack_image,
reference_type="asset"
)
actor_reference = types.VideoGenerationReferenceImage(
image=actor_image,
reference_type="asset"
)
operation = client.models.generate_videos(
model="veo-3.1-generate-preview", # Reference to video only wirk with Veo 3.1 at the moment
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio=aspect_ratio,
resolution=resolution,
negative_prompt=negative_prompt,
reference_images=[backpack_reference, actor_reference],
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Display the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 El video que generarás será similar a este: Un video generado a partir de múltiples imágenes .
Extender videos (en desarrollo)
También puedes pasar un video para extenderlo 7 segundos. Esto se puede hacer varias veces, o comenzando con un video de más de 8 segundos. La principal restricción es que la duración final del video solo puede ser de hasta 148 segundos , lo que significa que puedes extender tu primer video de 8 segundos unas 20 veces.
Las restricciones sobre el video que quieres extender son:
Solo con resolución 720p
El video de entrada debe ser generado por Veo
Menos de 141 segundos de duración
Solo necesitas pasarlo usando el parámetro video.
if not I_am_aware_that_veo_is_a_paid_feature:
print("Veo is a paid feature. Please change the variable 'I_am_aware_that_veo_is_a_paid_feature' to True if you are okay with paying to run it.")
else:
import time
prompt = "" # @param {"type":"string","placeholder":"Prompt is optional."}
# Optional parameters
negative_prompt = "ugly, low quality, static, weird physics" # @param {type: "string"}
operation = client.models.generate_videos(
model=VEO_MODEL_ID,
video=generated_video.video,
prompt=prompt,
config=types.GenerateVideosConfig(
number_of_videos=1,
resolution="720p",
negative_prompt=negative_prompt,
),
)
# Waiting for the video(s) to be generated
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
print(operation)
print(operation.result.generated_videos)
for n, generated_video in enumerate(operation.result.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f'video{n}.mp4') # Saves the video(s)
display(generated_video.video.show()) # Display the video(s) in a notebook
Mira una generación de muestra 🎥
🍿 Aquí tienes un video que ha sido extendido varias veces: El coche de un gato despega, varias veces
Próximos pasos
Referencias útiles de la API:
Consulta la documentación de Veo y la guía de prompts para obtener más detalles sobre cómo usar Veo y cómo hacer los mejores prompts.
Usa Webhooks
Puedes usar Webhooks para recibir notificaciones cuando finalice la generación de un video. Consulta el cookbook de Webhooks para obtener más información.
Continúa tu descubrimiento de la API de Gemini
Aquí tienes otras características interesantes de Gemini que podrían interesarte:
La salida de imágenes integrada de Gemini Image-out puede generar imágenes con detalles finos y te permite iterar sobre ellas chateando con el modelo;
Imagen también puede generar imágenes;
La salida de audio integrada Audio-out también es una gran capacidad de salida multimodal con la que es bastante divertido jugar.
# To prevent you from running the notebook by mistake
I_am_aware_that_veo_is_a_paid_feature = False