Spaces:
Sleeping
Sleeping
normanedev02 commited on
Commit ·
970fff8
1
Parent(s): 2951a90
Upgrade to Imagen 4 + Veo 3.1 with REST API polling
Browse files- Update image generation to imagen-4.0-generate-001 (latest model)
- Update video generation to veo-3.1-generate-001 with native audio
- Implement proper REST API polling for Veo long-running operations
- Add test reference images (robot, scientist, laboratory)
- Verify multi-character support working with ref_character_keys array
- Characters/robot.png +3 -0
- Characters/scientist.png +3 -0
- Locations/laboratory.png +3 -0
- app.py +4 -3
- veo_video_generator.py +132 -70
Characters/robot.png
ADDED
|
Git LFS Details
|
Characters/scientist.png
ADDED
|
Git LFS Details
|
Locations/laboratory.png
ADDED
|
Git LFS Details
|
app.py
CHANGED
|
@@ -12,7 +12,7 @@ PHASE 1 (Complete):
|
|
| 12 |
|
| 13 |
PHASE 2 (Complete):
|
| 14 |
- Google Vertex AI Imagen 3 integration
|
| 15 |
-
- Model: imagen-
|
| 16 |
- API key authentication (VERTEX_API_KEY)
|
| 17 |
- Prompt-based character consistency via Gemini description injection
|
| 18 |
- Converts approved images to short video clips (9:16) with camera motion
|
|
@@ -754,7 +754,8 @@ def generate_t2i(prompt: str, scene_id: str, variant: str,
|
|
| 754 |
print(f"🎨 Generating image via Vertex AI Imagen for {scene_id}_{variant}...")
|
| 755 |
|
| 756 |
# Use Imagen 3 via Vertex AI Express REST API
|
| 757 |
-
|
|
|
|
| 758 |
|
| 759 |
payload = {
|
| 760 |
"instances": [{"prompt": full_prompt}],
|
|
@@ -2501,7 +2502,7 @@ def get_generation_mode_status() -> str:
|
|
| 2501 |
lines.append("🔶 **Phase 2: Prompt-based Consistency** (Active)")
|
| 2502 |
lines.append(" - Character consistency via Gemini descriptions")
|
| 2503 |
lines.append(" - API key authentication")
|
| 2504 |
-
lines.append(f" - Model: `imagen-
|
| 2505 |
if not PHASE3_AVAILABLE:
|
| 2506 |
# Provide guidance on enabling Phase 3
|
| 2507 |
creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
|
|
|
|
| 12 |
|
| 13 |
PHASE 2 (Complete):
|
| 14 |
- Google Vertex AI Imagen 3 integration
|
| 15 |
+
- Model: imagen-4.0-generate-001 (Imagen 4 - latest)
|
| 16 |
- API key authentication (VERTEX_API_KEY)
|
| 17 |
- Prompt-based character consistency via Gemini description injection
|
| 18 |
- Converts approved images to short video clips (9:16) with camera motion
|
|
|
|
| 754 |
print(f"🎨 Generating image via Vertex AI Imagen for {scene_id}_{variant}...")
|
| 755 |
|
| 756 |
# Use Imagen 3 via Vertex AI Express REST API
|
| 757 |
+
# Updated to Imagen 4 - the latest and highest quality image generation model
|
| 758 |
+
url = f"https://aiplatform.googleapis.com/v1/publishers/google/models/imagen-4.0-generate-001:predict?key={VERTEX_API_KEY}"
|
| 759 |
|
| 760 |
payload = {
|
| 761 |
"instances": [{"prompt": full_prompt}],
|
|
|
|
| 2502 |
lines.append("🔶 **Phase 2: Prompt-based Consistency** (Active)")
|
| 2503 |
lines.append(" - Character consistency via Gemini descriptions")
|
| 2504 |
lines.append(" - API key authentication")
|
| 2505 |
+
lines.append(f" - Model: `imagen-4.0-generate-001` (Imagen 4)")
|
| 2506 |
if not PHASE3_AVAILABLE:
|
| 2507 |
# Provide guidance on enabling Phase 3
|
| 2508 |
creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
|
veo_video_generator.py
CHANGED
|
@@ -33,7 +33,8 @@ GCP_PROJECT_ID = os.getenv("GCP_PROJECT_ID")
|
|
| 33 |
GCP_LOCATION = os.getenv("GCP_LOCATION", "us-central1")
|
| 34 |
|
| 35 |
# Veo model configuration
|
| 36 |
-
|
|
|
|
| 37 |
|
| 38 |
# Output directory
|
| 39 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
@@ -171,21 +172,27 @@ def generate_video_with_veo(
|
|
| 171 |
camera_type: str = "medium",
|
| 172 |
camera_motion: str = "zoom-in",
|
| 173 |
duration: int = DEFAULT_VIDEO_DURATION,
|
| 174 |
-
scene_id: str = "scene"
|
|
|
|
|
|
|
| 175 |
) -> Optional[str]:
|
| 176 |
"""
|
| 177 |
-
Generate a video from an image using Vertex AI Veo.
|
|
|
|
|
|
|
| 178 |
|
| 179 |
Args:
|
| 180 |
image_path: Path to the source image
|
| 181 |
prompt: Scene description for motion guidance
|
| 182 |
camera_type: Wide, Medium, or Close-up
|
| 183 |
camera_motion: Type of camera movement
|
| 184 |
-
duration: Target duration in seconds (Veo
|
| 185 |
scene_id: Scene identifier for output naming
|
|
|
|
|
|
|
| 186 |
|
| 187 |
Returns:
|
| 188 |
-
Path to generated video file, or None on failure
|
| 189 |
"""
|
| 190 |
global VEO_AVAILABLE
|
| 191 |
|
|
@@ -198,29 +205,25 @@ def generate_video_with_veo(
|
|
| 198 |
return None
|
| 199 |
|
| 200 |
try:
|
| 201 |
-
import vertexai
|
| 202 |
-
from vertexai.preview.vision_models import ImageGenerationModel, Image as VertexImage
|
| 203 |
-
from google.cloud import aiplatform
|
| 204 |
import requests
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
print(f"🎬 Veo: Generating video for {scene_id}...")
|
|
|
|
| 207 |
print(f" Camera: {camera_type} / {camera_motion}")
|
|
|
|
|
|
|
| 208 |
|
| 209 |
# Build motion-enhanced prompt
|
| 210 |
motion_prompt = build_motion_prompt(prompt, camera_type, camera_motion)
|
| 211 |
-
print(f" Prompt: {motion_prompt[:
|
| 212 |
-
|
| 213 |
-
# Load the source image
|
| 214 |
-
source_image = VertexImage.load_from_file(image_path)
|
| 215 |
|
| 216 |
# Get project and location
|
| 217 |
project_id = os.getenv("GCP_PROJECT_ID")
|
| 218 |
location = os.getenv("GCP_LOCATION", "us-central1")
|
| 219 |
|
| 220 |
-
#
|
| 221 |
-
# Veo uses a different endpoint than Imagen
|
| 222 |
-
|
| 223 |
-
# Read and encode image
|
| 224 |
with open(image_path, 'rb') as f:
|
| 225 |
image_data = base64.b64encode(f.read()).decode('utf-8')
|
| 226 |
|
|
@@ -232,14 +235,18 @@ def generate_video_with_veo(
|
|
| 232 |
'.jpeg': 'image/jpeg',
|
| 233 |
}.get(ext, 'image/png')
|
| 234 |
|
| 235 |
-
#
|
| 236 |
-
|
|
|
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
-
credentials, _ = default()
|
| 243 |
credentials.refresh(Request())
|
| 244 |
access_token = credentials.token
|
| 245 |
|
|
@@ -248,6 +255,10 @@ def generate_video_with_veo(
|
|
| 248 |
"Content-Type": "application/json"
|
| 249 |
}
|
| 250 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
payload = {
|
| 252 |
"instances": [{
|
| 253 |
"prompt": motion_prompt,
|
|
@@ -258,65 +269,116 @@ def generate_video_with_veo(
|
|
| 258 |
}],
|
| 259 |
"parameters": {
|
| 260 |
"aspectRatio": "9:16",
|
| 261 |
-
"sampleCount": 1
|
|
|
|
|
|
|
|
|
|
| 262 |
}
|
| 263 |
}
|
| 264 |
|
| 265 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
-
|
|
|
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
-
|
| 278 |
-
poll_endpoint = f"https://{location}-aiplatform.googleapis.com/v1/{operation_name}"
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
if poll_response.status_code == 200:
|
| 286 |
-
poll_data = poll_response.json()
|
| 287 |
|
| 288 |
-
if
|
| 289 |
-
|
| 290 |
-
if "response" in poll_data:
|
| 291 |
-
predictions = poll_data["response"].get("predictions", [])
|
| 292 |
-
if predictions and "bytesBase64Encoded" in predictions[0]:
|
| 293 |
-
# Decode and save video
|
| 294 |
-
video_data = base64.b64decode(predictions[0]["bytesBase64Encoded"])
|
| 295 |
-
output_path = os.path.join(
|
| 296 |
-
OUTPUT_DIR_VIDEO,
|
| 297 |
-
f"{scene_id}_veo_{uuid.uuid4().hex[:8]}.mp4"
|
| 298 |
-
)
|
| 299 |
-
|
| 300 |
-
with open(output_path, 'wb') as f:
|
| 301 |
-
f.write(video_data)
|
| 302 |
-
|
| 303 |
-
print(f"✅ Veo: Video generated: {output_path}")
|
| 304 |
-
return output_path
|
| 305 |
|
| 306 |
-
if
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
return None
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
|
|
|
| 320 |
|
| 321 |
except ImportError as e:
|
| 322 |
print(f"❌ Veo: Missing dependency - {e}")
|
|
|
|
| 33 |
GCP_LOCATION = os.getenv("GCP_LOCATION", "us-central1")
|
| 34 |
|
| 35 |
# Veo model configuration
|
| 36 |
+
# Updated to Veo 3.1 - latest model with native audio, better physics, and 4K support
|
| 37 |
+
VEO_MODEL_ID = "veo-3.1-generate-001" # Latest I2V model (supports 4, 6, 8 second videos)
|
| 38 |
|
| 39 |
# Output directory
|
| 40 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
| 172 |
camera_type: str = "medium",
|
| 173 |
camera_motion: str = "zoom-in",
|
| 174 |
duration: int = DEFAULT_VIDEO_DURATION,
|
| 175 |
+
scene_id: str = "scene",
|
| 176 |
+
timeout_seconds: int = 300, # 5 minute timeout (Veo 3.1 can take longer)
|
| 177 |
+
generate_audio: bool = True # Veo 3.1 native audio feature
|
| 178 |
) -> Optional[str]:
|
| 179 |
"""
|
| 180 |
+
Generate a video from an image using Vertex AI Veo 3.1.
|
| 181 |
+
|
| 182 |
+
Uses REST API with fetchPredictOperation for reliable polling.
|
| 183 |
|
| 184 |
Args:
|
| 185 |
image_path: Path to the source image
|
| 186 |
prompt: Scene description for motion guidance
|
| 187 |
camera_type: Wide, Medium, or Close-up
|
| 188 |
camera_motion: Type of camera movement
|
| 189 |
+
duration: Target duration in seconds (Veo 3.1: 4, 6, or 8)
|
| 190 |
scene_id: Scene identifier for output naming
|
| 191 |
+
timeout_seconds: Max time to wait for video generation
|
| 192 |
+
generate_audio: Enable native audio generation (Veo 3.1 feature)
|
| 193 |
|
| 194 |
Returns:
|
| 195 |
+
Path to generated video file, or None on failure/timeout
|
| 196 |
"""
|
| 197 |
global VEO_AVAILABLE
|
| 198 |
|
|
|
|
| 205 |
return None
|
| 206 |
|
| 207 |
try:
|
|
|
|
|
|
|
|
|
|
| 208 |
import requests
|
| 209 |
+
from google.oauth2 import service_account
|
| 210 |
+
from google.auth.transport.requests import Request
|
| 211 |
|
| 212 |
+
print(f"🎬 Veo 3.1: Generating video for {scene_id}...")
|
| 213 |
+
print(f" Model: {VEO_MODEL_ID}")
|
| 214 |
print(f" Camera: {camera_type} / {camera_motion}")
|
| 215 |
+
print(f" Audio: {'Enabled' if generate_audio else 'Disabled'}")
|
| 216 |
+
print(f" Timeout: {timeout_seconds}s")
|
| 217 |
|
| 218 |
# Build motion-enhanced prompt
|
| 219 |
motion_prompt = build_motion_prompt(prompt, camera_type, camera_motion)
|
| 220 |
+
print(f" Prompt: {motion_prompt[:60]}...")
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
# Get project and location
|
| 223 |
project_id = os.getenv("GCP_PROJECT_ID")
|
| 224 |
location = os.getenv("GCP_LOCATION", "us-central1")
|
| 225 |
|
| 226 |
+
# Load and encode image
|
|
|
|
|
|
|
|
|
|
| 227 |
with open(image_path, 'rb') as f:
|
| 228 |
image_data = base64.b64encode(f.read()).decode('utf-8')
|
| 229 |
|
|
|
|
| 235 |
'.jpeg': 'image/jpeg',
|
| 236 |
}.get(ext, 'image/png')
|
| 237 |
|
| 238 |
+
# Get access token with proper scopes
|
| 239 |
+
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
|
| 240 |
+
creds_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
|
| 241 |
|
| 242 |
+
if creds_path and os.path.exists(creds_path):
|
| 243 |
+
credentials = service_account.Credentials.from_service_account_file(
|
| 244 |
+
creds_path, scopes=SCOPES
|
| 245 |
+
)
|
| 246 |
+
else:
|
| 247 |
+
from google.auth import default
|
| 248 |
+
credentials, _ = default(scopes=SCOPES)
|
| 249 |
|
|
|
|
| 250 |
credentials.refresh(Request())
|
| 251 |
access_token = credentials.token
|
| 252 |
|
|
|
|
| 255 |
"Content-Type": "application/json"
|
| 256 |
}
|
| 257 |
|
| 258 |
+
# Veo 3.1 supports duration: 4, 6, or 8 seconds
|
| 259 |
+
veo_duration = 8 if duration >= 8 else (6 if duration >= 6 else 4)
|
| 260 |
+
|
| 261 |
+
# Build request payload for Veo 3.1
|
| 262 |
payload = {
|
| 263 |
"instances": [{
|
| 264 |
"prompt": motion_prompt,
|
|
|
|
| 269 |
}],
|
| 270 |
"parameters": {
|
| 271 |
"aspectRatio": "9:16",
|
| 272 |
+
"sampleCount": 1,
|
| 273 |
+
"durationSeconds": veo_duration,
|
| 274 |
+
"generateAudio": generate_audio,
|
| 275 |
+
"resolution": "720p" # 720p, 1080p, or 4k
|
| 276 |
}
|
| 277 |
}
|
| 278 |
|
| 279 |
+
# Start video generation
|
| 280 |
+
endpoint = f"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/publishers/google/models/{VEO_MODEL_ID}:predictLongRunning"
|
| 281 |
+
|
| 282 |
+
print(f" 🔄 Starting Veo generation...")
|
| 283 |
+
start_time = time.time()
|
| 284 |
+
|
| 285 |
+
response = requests.post(endpoint, headers=headers, json=payload, timeout=60)
|
| 286 |
+
|
| 287 |
+
if response.status_code != 200:
|
| 288 |
+
print(f"❌ Veo API error: {response.status_code}")
|
| 289 |
+
print(f" Response: {response.text[:300]}")
|
| 290 |
+
return None
|
| 291 |
+
|
| 292 |
+
operation = response.json()
|
| 293 |
+
operation_name = operation.get("name")
|
| 294 |
+
|
| 295 |
+
if not operation_name:
|
| 296 |
+
print(f"❌ Veo: No operation name returned")
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
# Extract operation ID for polling
|
| 300 |
+
operation_id = operation_name.split("/operations/")[-1]
|
| 301 |
+
print(f" ⏳ Operation started: {operation_id[:20]}...")
|
| 302 |
|
| 303 |
+
# Poll using fetchPredictOperation (correct endpoint per docs)
|
| 304 |
+
poll_endpoint = f"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/publishers/google/models/{VEO_MODEL_ID}:fetchPredictOperation"
|
| 305 |
|
| 306 |
+
poll_payload = {
|
| 307 |
+
"operationName": operation_name
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
poll_interval = 15 # seconds
|
| 311 |
+
while True:
|
| 312 |
+
elapsed = time.time() - start_time
|
| 313 |
+
|
| 314 |
+
if elapsed > timeout_seconds:
|
| 315 |
+
print(f" ⏰ Timeout after {elapsed:.0f}s - will use MoviePy fallback")
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
time.sleep(poll_interval)
|
| 319 |
+
|
| 320 |
+
# Refresh token if needed
|
| 321 |
+
if credentials.expired:
|
| 322 |
+
credentials.refresh(Request())
|
| 323 |
+
headers["Authorization"] = f"Bearer {credentials.token}"
|
| 324 |
|
| 325 |
+
poll_response = requests.post(poll_endpoint, headers=headers, json=poll_payload, timeout=30)
|
| 326 |
+
|
| 327 |
+
if poll_response.status_code == 200:
|
| 328 |
+
poll_data = poll_response.json()
|
| 329 |
+
is_done = poll_data.get("done", False)
|
| 330 |
|
| 331 |
+
print(f" ⏳ Generating... ({elapsed:.0f}s) done={is_done}")
|
|
|
|
| 332 |
|
| 333 |
+
if is_done:
|
| 334 |
+
# Check for response
|
| 335 |
+
if "response" in poll_data:
|
| 336 |
+
videos = poll_data["response"].get("videos", [])
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
+
if videos:
|
| 339 |
+
video_info = videos[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
+
# Check if video is in GCS or base64
|
| 342 |
+
if "gcsUri" in video_info:
|
| 343 |
+
# Download from GCS
|
| 344 |
+
gcs_uri = video_info["gcsUri"]
|
| 345 |
+
print(f" 📥 Downloading from: {gcs_uri}")
|
| 346 |
+
# For now, we'd need to download from GCS
|
| 347 |
+
# This requires additional handling
|
| 348 |
+
print(f" ⚠️ GCS download not implemented, use storageUri parameter")
|
| 349 |
return None
|
| 350 |
+
elif "bytesBase64Encoded" in video_info:
|
| 351 |
+
video_data = base64.b64decode(video_info["bytesBase64Encoded"])
|
| 352 |
+
output_path = os.path.join(
|
| 353 |
+
OUTPUT_DIR_VIDEO,
|
| 354 |
+
f"{scene_id}_veo_{uuid.uuid4().hex[:8]}.mp4"
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
with open(output_path, 'wb') as f:
|
| 358 |
+
f.write(video_data)
|
| 359 |
+
|
| 360 |
+
size_kb = os.path.getsize(output_path) / 1024
|
| 361 |
+
print(f"✅ Veo 3.1: Video saved: {output_path} ({size_kb:.1f} KB)")
|
| 362 |
+
return output_path
|
| 363 |
+
else:
|
| 364 |
+
# Check for filtered content
|
| 365 |
+
filtered = poll_data["response"].get("raiMediaFilteredCount", 0)
|
| 366 |
+
if filtered > 0:
|
| 367 |
+
reasons = poll_data["response"].get("raiMediaFilteredReasons", [])
|
| 368 |
+
print(f" ⚠️ Content filtered by safety: {reasons}")
|
| 369 |
+
else:
|
| 370 |
+
print(f" ⚠️ No videos in response")
|
| 371 |
+
return None
|
| 372 |
|
| 373 |
+
elif "error" in poll_data:
|
| 374 |
+
print(f"❌ Veo error: {poll_data['error']}")
|
| 375 |
+
return None
|
| 376 |
+
|
| 377 |
+
break
|
| 378 |
+
else:
|
| 379 |
+
print(f" ⚠️ Poll error: {poll_response.status_code}")
|
| 380 |
+
|
| 381 |
+
return None
|
| 382 |
|
| 383 |
except ImportError as e:
|
| 384 |
print(f"❌ Veo: Missing dependency - {e}")
|