Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Add video generation cost estimation

Claude8e25a3021ec3
diff --git a/backend/models/gemini.py b/backend/models/gemini.py
index 5a16362d..fcb7a9f1 100644
--- a/backend/models/gemini.py
+++ b/backend/models/gemini.py
@@ -5,6 +5,12 @@ from openai.types.chat import ChatCompletionMessageParam
from google import genai
from google.genai import types
from llm import Completion, Llm
+from video.cost_estimation import (
+ estimate_video_generation_cost,
+ format_cost_estimate,
+ get_video_duration_from_bytes,
+ MediaResolution,
+)
# Set to True to print debug messages for Gemini requests
DEBUG_GEMINI = False
@@ -18,6 +24,16 @@ def get_gemini_api_model_name(model: Llm) -> str:
return model.value
+def get_thinking_level_for_model(model: Llm) -> str:
+ if model in [Llm.GEMINI_3_FLASH_PREVIEW_HIGH, Llm.GEMINI_3_PRO_PREVIEW_HIGH]:
+ return "high"
+ elif model == Llm.GEMINI_3_PRO_PREVIEW_LOW:
+ return "low"
+ elif model == Llm.GEMINI_3_FLASH_PREVIEW_MINIMAL:
+ return "minimal"
+ return "high"
+
+
def extract_text_from_content(content: str | List[Dict[str, Any]]) -> str:
"""
Extracts text from message content, handling both string and list formats.
@@ -283,16 +299,39 @@ async def stream_gemini_response_video(
) -> Completion:
start_time = time.time()
+ # Video generation settings
+ VIDEO_FPS = 20
+ MAX_OUTPUT_TOKENS = 50000
+
+ # Get video duration and estimate cost
+ video_duration = get_video_duration_from_bytes(video_bytes)
+ if video_duration:
+ thinking_level = get_thinking_level_for_model(model)
+ estimated_cost = estimate_video_generation_cost(
+ video_duration_seconds=video_duration,
+ model=model,
+ fps=VIDEO_FPS,
+ media_resolution=MediaResolution.HIGH,
+ max_output_tokens=MAX_OUTPUT_TOKENS,
+ thinking_level=thinking_level,
+ )
+ print(f"\n=== Video Generation Cost Estimate ({model.value}) ===")
+ print(f"Video duration: {video_duration:.2f} seconds")
+ print(format_cost_estimate(estimated_cost))
+ print("=" * 50)
+ else:
+ print("Warning: Could not determine video duration for cost estimation")
+
client = genai.Client(api_key=api_key)
full_response = ""
- # Create content with video inline data at 10fps for better fidelity
+ # Create content with video inline data at specified FPS for better fidelity
contents = types.Content(
role="user",
parts=[
types.Part(
inline_data=types.Blob(data=video_bytes, mime_type=video_mime_type),
- video_metadata=types.VideoMetadata(fps=20),
+ video_metadata=types.VideoMetadata(fps=VIDEO_FPS),
media_resolution=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_HIGH
),
types.Part(text="Analyze this video and generate the code."),
@@ -303,7 +342,7 @@ async def stream_gemini_response_video(
if model == Llm.GEMINI_3_FLASH_PREVIEW_HIGH:
config = types.GenerateContentConfig(
temperature=1.0,
- max_output_tokens=50000,
+ max_output_tokens=MAX_OUTPUT_TOKENS,
system_instruction=system_prompt,
thinking_config=types.ThinkingConfig(
thinking_level="high", include_thoughts=True
@@ -312,7 +351,7 @@ async def stream_gemini_response_video(
elif model == Llm.GEMINI_3_FLASH_PREVIEW_MINIMAL:
config = types.GenerateContentConfig(
temperature=1.0,
- max_output_tokens=50000,
+ max_output_tokens=MAX_OUTPUT_TOKENS,
system_instruction=system_prompt,
thinking_config=types.ThinkingConfig(
thinking_level="minimal", include_thoughts=True
@@ -321,7 +360,7 @@ async def stream_gemini_response_video(
elif model == Llm.GEMINI_3_PRO_PREVIEW_HIGH:
config = types.GenerateContentConfig(
temperature=1.0,
- max_output_tokens=50000,
+ max_output_tokens=MAX_OUTPUT_TOKENS,
system_instruction=system_prompt,
thinking_config=types.ThinkingConfig(
thinking_level="high", include_thoughts=True
@@ -330,7 +369,7 @@ async def stream_gemini_response_video(
elif model == Llm.GEMINI_3_PRO_PREVIEW_LOW:
config = types.GenerateContentConfig(
temperature=1.0,
- max_output_tokens=50000,
+ max_output_tokens=MAX_OUTPUT_TOKENS,
system_instruction=system_prompt,
thinking_config=types.ThinkingConfig(
thinking_level="low", include_thoughts=True
@@ -340,7 +379,7 @@ async def stream_gemini_response_video(
# Default config for other models
config = types.GenerateContentConfig(
temperature=1.0,
- max_output_tokens=50000,
+ max_output_tokens=MAX_OUTPUT_TOKENS,
system_instruction=system_prompt,
)
@@ -353,11 +392,22 @@ async def stream_gemini_response_video(
print(f"System prompt (first 200 chars): {system_prompt[:200]}...")
print("=" * 50)
+ # Track actual token usage from the response
+ actual_input_tokens = 0
+ actual_output_tokens = 0
+
async for chunk in await client.aio.models.generate_content_stream(
model=api_model_name,
contents=contents,
config=config,
):
+ # Capture usage metadata when available
+ if hasattr(chunk, "usage_metadata") and chunk.usage_metadata:
+ if hasattr(chunk.usage_metadata, "prompt_token_count"):
+ actual_input_tokens = chunk.usage_metadata.prompt_token_count or 0
+ if hasattr(chunk.usage_metadata, "candidates_token_count"):
+ actual_output_tokens = chunk.usage_metadata.candidates_token_count or 0
+
if chunk.candidates and len(chunk.candidates) > 0:
for part in chunk.candidates[0].content.parts:
if not part.text:
@@ -374,4 +424,16 @@ async def stream_gemini_response_video(
await callback(part.text)
completion_time = time.time() - start_time
+
+ # Log actual token usage and cost
+ if actual_input_tokens > 0 or actual_output_tokens > 0:
+ from video.cost_estimation import calculate_cost
+ actual_cost = calculate_cost(actual_input_tokens, actual_output_tokens, model)
+ print(f"\n=== Video Generation Actual Usage ({model.value}) ===")
+ print(f"Input tokens: {actual_input_tokens:,} (${actual_cost.input_cost:.4f})")
+ print(f"Output tokens: {actual_output_tokens:,} (${actual_cost.output_cost:.4f})")
+ print(f"Total actual cost: ${actual_cost.total_cost:.4f}")
+ print(f"Generation time: {completion_time:.2f} seconds")
+ print("=" * 50)
+
return {"duration": completion_time, "code": full_response}
diff --git a/backend/video/__init__.py b/backend/video/__init__.py
new file mode 100644
index 00000000..f00dc74c
--- /dev/null
+++ b/backend/video/__init__.py
@@ -0,0 +1,33 @@
+from video.cost_estimation import (
+ CostEstimate,
+ MediaResolution,
+ TokenEstimate,
+ calculate_cost,
+ estimate_video_generation_cost,
+ estimate_video_input_tokens,
+ format_cost_estimate,
+ get_video_duration_from_bytes,
+)
+from video.utils import (
+ assemble_claude_prompt_video,
+ extract_tag_content,
+ get_video_bytes_and_mime_type,
+ split_video_into_screenshots,
+)
+
+__all__ = [
+ # Cost estimation
+ "CostEstimate",
+ "MediaResolution",
+ "TokenEstimate",
+ "calculate_cost",
+ "estimate_video_generation_cost",
+ "estimate_video_input_tokens",
+ "format_cost_estimate",
+ "get_video_duration_from_bytes",
+ # Video utilities
+ "assemble_claude_prompt_video",
+ "extract_tag_content",
+ "get_video_bytes_and_mime_type",
+ "split_video_into_screenshots",
+]
diff --git a/backend/video/cost_estimation.py b/backend/video/cost_estimation.py
new file mode 100644
index 00000000..fa48a9cc
--- /dev/null
+++ b/backend/video/cost_estimation.py
@@ -0,0 +1,194 @@
+from dataclasses import dataclass
+from enum import Enum
+from typing import Tuple
+from llm import Llm
+
+
+class MediaResolution(Enum):
+ LOW = "low"
+ MEDIUM = "medium"
+ HIGH = "high"
+
+
+@dataclass
+class TokenEstimate:
+ input_tokens: int
+ estimated_output_tokens: int
+ total_tokens: int
+
+
+@dataclass
+class CostEstimate:
+ input_cost: float
+ output_cost: float
+ total_cost: float
+ input_tokens: int
+ output_tokens: int
+
+
+# Gemini 3 video token rates per frame (from documentation)
+# https://ai.google.dev/gemini-api/docs/media-resolution#token-counts
+VIDEO_TOKENS_PER_FRAME = {
+ MediaResolution.LOW: 70,
+ MediaResolution.MEDIUM: 70, # Same as LOW for video
+ MediaResolution.HIGH: 280,
+}
+
+# Audio tokens per second
+AUDIO_TOKENS_PER_SECOND = 32
+
+# System prompt tokens (approximate, varies by prompt length)
+SYSTEM_PROMPT_TOKENS_ESTIMATE = 2000
+
+# Pricing per million tokens (USD)
+# https://ai.google.dev/gemini-api/docs/pricing
+GEMINI_PRICING = {
+ # Gemini 3 Flash Preview
+ "gemini-3-flash-preview": {
+ "input_per_million": 0.50, # text/image/video
+ "output_per_million": 3.00, # including thinking tokens
+ },
+ # Gemini 3 Pro Preview
+ "gemini-3-pro-preview": {
+ "input_per_million": 2.00, # prompts <= 200k tokens
+ "output_per_million": 12.00, # including thinking tokens
+ },
+ # Gemini 2.5 Flash
+ "gemini-2.5-flash": {
+ "input_per_million": 0.30, # text/image/video
+ "output_per_million": 2.50,
+ },
+}
+
+
+def get_model_api_name(model: Llm) -> str:
+ if model in [Llm.GEMINI_3_FLASH_PREVIEW_HIGH, Llm.GEMINI_3_FLASH_PREVIEW_MINIMAL]:
+ return "gemini-3-flash-preview"
+ elif model in [Llm.GEMINI_3_PRO_PREVIEW_HIGH, Llm.GEMINI_3_PRO_PREVIEW_LOW]:
+ return "gemini-3-pro-preview"
+ elif model == Llm.GEMINI_2_5_FLASH_PREVIEW_05_20:
+ return "gemini-2.5-flash"
+ return model.value
+
+
+def estimate_video_input_tokens(
+ video_duration_seconds: float,
+ fps: int = 20,
+ media_resolution: MediaResolution = MediaResolution.HIGH,
+ include_audio: bool = True,
+) -> int:
+ tokens_per_frame = VIDEO_TOKENS_PER_FRAME[media_resolution]
+ total_frames = int(video_duration_seconds * fps)
+ visual_tokens = total_frames * tokens_per_frame
+
+ audio_tokens = 0
+ if include_audio:
+ audio_tokens = int(video_duration_seconds * AUDIO_TOKENS_PER_SECOND)
+
+ # Add system prompt tokens
+ total_tokens = visual_tokens + audio_tokens + SYSTEM_PROMPT_TOKENS_ESTIMATE
+
+ return total_tokens
+
+
+def estimate_output_tokens(
+ max_output_tokens: int = 50000,
+ thinking_level: str = "high",
+) -> int:
+ # Rough estimation: thinking takes up significant portion of output
+ # High thinking: ~60-70% of output may be thinking tokens
+ # Low thinking: ~30-40% of output may be thinking tokens
+ # Minimal thinking: ~10-20% of output may be thinking tokens
+ thinking_multipliers = {
+ "high": 0.7,
+ "low": 0.5,
+ "minimal": 0.3,
+ }
+
+ multiplier = thinking_multipliers.get(thinking_level, 0.5)
+
+ # Assume we use roughly 60% of max output tokens on average
+ estimated_usage = int(max_output_tokens * 0.6)
+
+ return estimated_usage
+
+
+def calculate_cost(
+ input_tokens: int,
+ output_tokens: int,
+ model: Llm,
+) -> CostEstimate:
+ model_name = get_model_api_name(model)
+ pricing = GEMINI_PRICING.get(model_name, GEMINI_PRICING["gemini-3-flash-preview"])
+
+ input_cost = (input_tokens / 1_000_000) * pricing["input_per_million"]
+ output_cost = (output_tokens / 1_000_000) * pricing["output_per_million"]
+ total_cost = input_cost + output_cost
+
+ return CostEstimate(
+ input_cost=input_cost,
+ output_cost=output_cost,
+ total_cost=total_cost,
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ )
+
+
+def estimate_video_generation_cost(
+ video_duration_seconds: float,
+ model: Llm,
+ fps: int = 20,
+ media_resolution: MediaResolution = MediaResolution.HIGH,
+ max_output_tokens: int = 50000,
+ thinking_level: str = "high",
+) -> CostEstimate:
+ input_tokens = estimate_video_input_tokens(
+ video_duration_seconds=video_duration_seconds,
+ fps=fps,
+ media_resolution=media_resolution,
+ include_audio=True,
+ )
+
+ output_tokens = estimate_output_tokens(
+ max_output_tokens=max_output_tokens,
+ thinking_level=thinking_level,
+ )
+
+ return calculate_cost(
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ model=model,
+ )
+
+
+def format_cost_estimate(cost: CostEstimate) -> str:
+ return (
+ f"Estimated Cost:\n"
+ f" Input tokens: {cost.input_tokens:,} (${cost.input_cost:.4f})\n"
+ f" Output tokens: {cost.output_tokens:,} (${cost.output_cost:.4f})\n"
+ f" Total estimated cost: ${cost.total_cost:.4f}"
+ )
+
+
+def get_video_duration_from_bytes(video_bytes: bytes) -> float | None:
+ try:
+ import tempfile
+ import os
+ from moviepy.editor import VideoFileClip
+
+ # Write bytes to a temporary file
+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp_file:
+ tmp_file.write(video_bytes)
+ tmp_path = tmp_file.name
+
+ try:
+ clip = VideoFileClip(tmp_path)
+ duration = clip.duration
+ clip.close()
+ return duration
+ finally:
+ os.unlink(tmp_path)
+
+ except Exception as e:
+ print(f"Error getting video duration: {e}")
+ return None