Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Update ad-use to use Veo3

avocardiof284afd461ea
diff --git a/docs/examples/apps/ad-use.mdx b/docs/examples/apps/ad-use.mdx
index 1893a8824..5849ef769 100644
--- a/docs/examples/apps/ad-use.mdx
+++ b/docs/examples/apps/ad-use.mdx
@@ -1,6 +1,6 @@
---
title: "Ad-Use (Ad Generator)"
-description: "Generate Instagram ads from landing pages using browser agents and Google's Nano Banana 🍌."
+description: "Generate Instagram image ads and TikTok video ads from landing pages using browser agents, Google's Nano Banana 🍌, and Veo3."
icon: "image"
mode: "wide"
---
@@ -20,7 +20,9 @@ This demo requires browser-use v0.7.6+.
1. Agent visits your target website
2. Captures brand name, tagline, and key selling points
3. Takes a clean screenshot for design reference
-4. Creates a scroll-stopping Instagram ad with 🍌
+4. Creates scroll-stopping Instagram image ads with 🍌
+5. Generates viral TikTok video ads with Veo3
+6. Supports parallel generation of multiple ads
## Setup
@@ -43,13 +45,28 @@ cd browser-use/examples/apps/ad-use
## Normal Usage
```bash
-# Basic - Generate ad from any website
-python ad_generator.py https://www.apple.com/iphone-16-pro/
+# Basic - Generate Instagram image ad (default)
+python ad_generator.py --url https://www.apple.com/iphone-16-pro/
+
+# Generate TikTok video ad with Veo3
+python ad_generator.py --tiktok --url https://www.apple.com/iphone-16-pro/
+
+# Generate multiple ads in parallel
+python ad_generator.py --instagram --count 3 --url https://www.apple.com/iphone-16-pro/
+python ad_generator.py --tiktok --count 2 --url https://www.apple.com/iphone-16-pro/
# Debug Mode - See the browser in action
-python ad_generator.py https://www.apple.com/iphone-16-pro/ --debug
+python ad_generator.py --url https://www.apple.com/iphone-16-pro/ --debug
```
+## Command Line Options
+
+- `--url`: Landing page URL to analyze
+- `--instagram`: Generate Instagram image ad (default if no flag specified)
+- `--tiktok`: Generate TikTok video ad using Veo3
+- `--count N`: Generate N ads in parallel (default: 1)
+- `--debug`: Show browser window and enable verbose logging
+
## Programmatic Usage
```python
import asyncio
@@ -68,9 +85,10 @@ asyncio.run(main())
## Output
Generated ads are saved in the `output/` directory with:
-- **PNG image files** (ad_style_timestamp.png) - Actual generated ads from Gemini 2.5 Flash Image
-- **Prompt files** (ad_style_timestamp_prompt.txt) - The prompts used for generation
-- **Landing page screenshots** for reference
+- **PNG image files** (ad_timestamp.png) - Instagram ads generated with Gemini 2.5 Flash Image
+- **MP4 video files** (ad_timestamp.mp4) - TikTok ads generated with Veo3
+- **Analysis files** (analysis_timestamp.txt) - Browser agent analysis and prompts used
+- **Landing page screenshots** (landing_page_timestamp.png) - Reference screenshots
## Source Code
diff --git a/examples/apps/ad-use/README.md b/examples/apps/ad-use/README.md
index 9a155a2ec..9f5e5b376 100644
--- a/examples/apps/ad-use/README.md
+++ b/examples/apps/ad-use/README.md
@@ -1,6 +1,6 @@
# Ad-Use
-Automatically generate Instagram ads from any landing page using browser agents and Google's Nano Banana 🍌 image generation model.
+Automatically generate Instagram image ads and TikTok video ads from any landing page using browser agents, Google's Nano Banana 🍌, and Veo3.
> [!WARNING]
> This demo requires browser-use v0.7.7+.
@@ -12,7 +12,9 @@ https://github.com/user-attachments/assets/7fab54a9-b36b-4fba-ab98-a438f2b86b7e
1. Agent visits your target website
2. Captures brand name, tagline, and key selling points
3. Takes a clean screenshot for design reference
-4. Creates a scroll-stopping Instagram ad with 🍌
+4. Creates scroll-stopping Instagram image ads with 🍌
+5. Generates viral TikTok video ads with Veo3
+6. Supports parallel generation of multiple ads
## Setup
@@ -35,13 +37,28 @@ cd browser-use/examples/apps/ad-use
## Normal Usage
```bash
-# Basic - Generate ad from any website
-python ad_generator.py https://www.apple.com/iphone-17-pro/
+# Basic - Generate Instagram image ad (default)
+python ad_generator.py --url https://www.apple.com/iphone-17-pro/
+
+# Generate TikTok video ad with Veo3
+python ad_generator.py --tiktok --url https://www.apple.com/iphone-17-pro/
+
+# Generate multiple ads in parallel
+python ad_generator.py --instagram --count 3 --url https://www.apple.com/iphone-17-pro/
+python ad_generator.py --tiktok --count 2 --url https://www.apple.com/iphone-17-pro/
# Debug Mode - See the browser in action
-python ad_generator.py https://www.apple.com/iphone-17-pro/ --debug
+python ad_generator.py --url https://www.apple.com/iphone-17-pro/ --debug
```
+## Command Line Options
+
+- `--url`: Landing page URL to analyze
+- `--instagram`: Generate Instagram image ad (default if no flag specified)
+- `--tiktok`: Generate TikTok video ad using Veo3
+- `--count N`: Generate N ads in parallel (default: 1)
+- `--debug`: Show browser window and enable verbose logging
+
## Programmatic Usage
```python
import asyncio
@@ -60,9 +77,10 @@ asyncio.run(main())
## Output
Generated ads are saved in the `output/` directory with:
-- **PNG image files** (ad_style_timestamp.png) - Actual generated ads from Gemini 2.5 Flash Image
-- **Prompt files** (ad_style_timestamp_prompt.txt) - The prompts used for generation
-- **Landing page screenshots** for reference
+- **PNG image files** (ad_timestamp.png) - Instagram ads generated with Gemini 2.5 Flash Image
+- **MP4 video files** (ad_timestamp.mp4) - TikTok ads generated with Veo3
+- **Analysis files** (analysis_timestamp.txt) - Browser agent analysis and prompts used
+- **Landing page screenshots** (landing_page_timestamp.png) - Reference screenshots
## License
diff --git a/examples/apps/ad-use/ad_generator.py b/examples/apps/ad-use/ad_generator.py
index b6f8e84e4..e9a6068f2 100644
--- a/examples/apps/ad-use/ad_generator.py
+++ b/examples/apps/ad-use/ad_generator.py
@@ -19,11 +19,20 @@ def setup_environment(debug: bool):
parser = argparse.ArgumentParser(description='Generate ads from landing pages using browser-use + 🍌')
-parser.add_argument('url', nargs='?', help='Landing page URL to analyze')
+parser.add_argument('--url', nargs='?', help='Landing page URL to analyze')
parser.add_argument('--debug', action='store_true', default=False, help='Enable debug mode (show browser, verbose logs)')
+parser.add_argument('--count', type=int, default=1, help='Number of ads to generate in parallel (default: 1)')
+group = parser.add_mutually_exclusive_group()
+group.add_argument('--instagram', action='store_true', default=False, help='Generate Instagram image ad (default)')
+group.add_argument('--tiktok', action='store_true', default=False, help='Generate TikTok video ad using Veo3')
args = parser.parse_args()
+if not args.instagram and not args.tiktok:
+ args.instagram = True
setup_environment(args.debug)
+import time
+from typing import Any, cast
+
import aiofiles
from google import genai
from PIL import Image
@@ -41,9 +50,9 @@ class LandingPageAnalyzer:
self.output_dir = Path('output')
self.output_dir.mkdir(exist_ok=True)
- async def analyze_landing_page(self, url: str) -> dict:
+ async def analyze_landing_page(self, url: str, mode: str = 'instagram') -> dict:
browser_session = BrowserSession(
- headless=not self.debug, # headless=False only when debug=True
+ headless=not self.debug,
)
agent = Agent(
@@ -73,42 +82,34 @@ Return ONLY the key brand info, not page structure details.""",
async def screenshot_callback(agent_instance):
nonlocal screenshot_path
- import asyncio
-
await asyncio.sleep(4)
screenshot_path = self.output_dir / f'landing_page_{timestamp}.png'
- active_session = agent_instance.browser_session
- screenshot_data = await active_session.take_screenshot(path=str(screenshot_path), full_page=False)
-
- import asyncio
+ await agent_instance.browser_session.take_screenshot(path=str(screenshot_path), full_page=False)
screenshot_task = asyncio.create_task(screenshot_callback(agent))
-
history = await agent.run()
-
try:
await screenshot_task
except Exception as e:
print(f'Screenshot task failed: {e}')
- analysis = history.final_result()
- if not analysis:
- analysis = 'No analysis content extracted'
-
+ analysis = history.final_result() or 'No analysis content extracted'
return {'url': url, 'analysis': analysis, 'screenshot_path': screenshot_path, 'timestamp': timestamp}
class AdGenerator:
- def __init__(self, api_key: str | None = GOOGLE_API_KEY):
+ def __init__(self, api_key: str | None = GOOGLE_API_KEY, mode: str = 'instagram'):
if not api_key:
raise ValueError('GOOGLE_API_KEY is missing or empty – set the environment variable or pass api_key explicitly')
self.client = genai.Client(api_key=api_key)
self.output_dir = Path('output')
self.output_dir.mkdir(exist_ok=True)
+ self.mode = mode
def create_ad_prompt(self, browser_analysis: str) -> str:
- prompt = f"""Create an Instagram ad for this brand:
+ if self.mode == 'instagram':
+ prompt = f"""Create an Instagram ad for this brand:
{browser_analysis}
@@ -125,28 +126,35 @@ Create a vibrant, eye-catching Instagram ad image with:
- Use color psychology to drive action
Style: Modern Instagram advertisement, (1:1), scroll-stopping, professional but playful, conversion-focused"""
+ else: # tiktok
+ prompt = f"""Create a viral TikTok video ad for this brand:
+
+{browser_analysis}
+
+Create a dynamic, engaging vertical video with:
+- Quick hook opening that grabs attention immediately
+- Minimal text overlays (focus on visual storytelling)
+- Fast-paced but not overwhelming editing
+- Authentic, relatable energy that appeals to Gen Z
+- Vertical 9:16 format optimized for mobile
+- High energy but professional execution
+
+Style: Modern TikTok advertisement, viral potential, authentic energy, minimal text, maximum visual impact"""
return prompt
async def generate_ad_image(self, prompt: str, screenshot_path: Path | None = None) -> bytes | None:
"""Generate ad image bytes using Gemini. Returns None on failure."""
-
try:
from typing import Any
contents: list[Any] = [prompt]
if screenshot_path and screenshot_path.exists():
- screenshot_prompt = (
- '\n\nHere is the actual landing page screenshot to reference for design inspiration, '
- 'colors, layout, and visual style:'
- )
-
img = Image.open(screenshot_path)
w, h = img.size
side = min(w, h)
img = img.crop(((w - side) // 2, (h - side) // 2, (w + side) // 2, (h + side) // 2))
-
- contents = [prompt + screenshot_prompt, img]
+ contents = [prompt + '\n\nHere is the actual landing page screenshot to reference for design inspiration:', img]
response = await self.client.aio.models.generate_content(
model='gemini-2.5-flash-image-preview',
@@ -159,16 +167,71 @@ Style: Modern Instagram advertisement, (1:1), scroll-stopping, professional but
inline = getattr(part, 'inline_data', None)
if inline:
return inline.data
-
except Exception as e:
print(f'❌ Image generation failed: {e}')
-
return None
- async def save_results(self, ad_image: bytes, prompt: str, analysis: str, url: str, timestamp: str) -> str:
- image_path = self.output_dir / f'ad_{timestamp}.png'
- async with aiofiles.open(image_path, 'wb') as f:
- await f.write(ad_image)
+ async def generate_ad_video(self, prompt: str, screenshot_path: Path | None = None, ad_id: int = 1) -> bytes:
+ """Generate ad video using Veo3."""
+ sync_client = genai.Client(api_key=GOOGLE_API_KEY)
+
+ # Commented out image input for now - it was using the screenshot as first frame
+ # if screenshot_path and screenshot_path.exists():
+ # import base64
+ # import io
+
+ # img = Image.open(screenshot_path)
+ # img_buffer = io.BytesIO()
+ # img.save(img_buffer, format='PNG')
+ # img_bytes = img_buffer.getvalue()
+
+ # operation = sync_client.models.generate_videos(
+ # model='veo-3.0-generate-001',
+ # prompt=prompt,
+ # image=cast(Any, {
+ # 'imageBytes': base64.b64encode(img_bytes).decode('utf-8'),
+ # 'mimeType': 'image/png'
+ # }),
+ # config=cast(Any, {'aspectRatio': '9:16', 'resolution': '720p'}),
+ # )
+ # else:
+ operation = sync_client.models.generate_videos(
+ model='veo-3.0-generate-001',
+ prompt=prompt,
+ config=cast(Any, {'aspectRatio': '9:16', 'resolution': '720p'}),
+ )
+
+ if ad_id == 1:
+ print('⏳ Generating video (this may take 1-2 minutes)...')
+ start_time = time.time()
+ while not operation.done:
+ await asyncio.sleep(10)
+ operation = sync_client.operations.get(operation)
+ if ad_id == 1:
+ elapsed = int(time.time() - start_time)
+ print(f'⏳ Still generating... ({elapsed}s elapsed)')
+
+ if not operation.response or not operation.response.generated_videos:
+ raise RuntimeError('No videos generated')
+ videos = operation.response.generated_videos
+ video = videos[0]
+ video_file = getattr(video, 'video', None)
+ if not video_file:
+ raise RuntimeError('No video file in response')
+ sync_client.files.download(file=video_file)
+ video_bytes = getattr(video_file, 'video_bytes', None)
+ if not video_bytes:
+ raise RuntimeError('No video bytes in response')
+ return video_bytes
+
+ async def save_results(self, ad_content: bytes, prompt: str, analysis: str, url: str, timestamp: str) -> str:
+ if self.mode == 'instagram':
+ content_path = self.output_dir / f'ad_{timestamp}.png'
+ else: # tiktok
+ content_path = self.output_dir / f'ad_{timestamp}.mp4'
+
+ async with aiofiles.open(content_path, 'wb') as f:
+ await f.write(ad_content)
analysis_path = self.output_dir / f'analysis_{timestamp}.txt'
async with aiofiles.open(analysis_path, 'w', encoding='utf-8') as f:
@@ -178,54 +241,141 @@ Style: Modern Instagram advertisement, (1:1), scroll-stopping, professional but
await f.write('\n\nGENERATED PROMPT:\n')
await f.write(prompt)
- return str(image_path)
+ return str(content_path)
-def open_image(image_path: str):
- """Open image with default system viewer"""
+def open_file(file_path: str):
+ """Open file with default system viewer"""
try:
if sys.platform.startswith('darwin'):
- # macOS
- subprocess.run(['open', image_path], check=True)
+ subprocess.run(['open', file_path], check=True)
elif sys.platform.startswith('win'):
- # Windows
- subprocess.run(['cmd', '/c', 'start', '', image_path], check=True)
+ subprocess.run(['cmd', '/c', 'start', '', file_path], check=True)
else:
- # Linux
- subprocess.run(['xdg-open', image_path], check=True)
+ subprocess.run(['xdg-open', file_path], check=True)
except Exception as e:
- print(f'❌ Could not open image: {e}')
+ print(f'❌ Could not open file: {e}')
-async def create_ad_from_landing_page(url: str, debug: bool = False):
+async def create_ad_from_landing_page(url: str, debug: bool = False, mode: str = 'instagram', ad_id: int = 1):
analyzer = LandingPageAnalyzer(debug=debug)
- generator = AdGenerator()
try:
- print(f'πŸš€ Analyzing {url}...')
- page_data = await analyzer.analyze_landing_page(url)
+ if ad_id == 1:
+ print(f'πŸš€ Analyzing {url} for {mode.capitalize()} ad...')
+ page_data = await analyzer.analyze_landing_page(url, mode=mode)
+ else:
+ analyzer_temp = LandingPageAnalyzer(debug=debug)
+ page_data = await analyzer_temp.analyze_landing_page(url, mode=mode)
+ generator = AdGenerator(mode=mode)
prompt = generator.create_ad_prompt(page_data['analysis'])
- ad_image = await generator.generate_ad_image(prompt, page_data.get('screenshot_path'))
- if ad_image is None:
- raise RuntimeError('Ad image generation failed')
- result_path = await generator.save_results(ad_image, prompt, page_data['analysis'], url, page_data['timestamp'])
- print(f'🎨 Generated ad: {result_path}')
- if page_data.get('screenshot_path'):
+ if mode == 'instagram':
+ ad_content = await generator.generate_ad_image(prompt, page_data.get('screenshot_path'))
+ if ad_content is None:
+ raise RuntimeError(f'Ad image generation failed for ad #{ad_id}')
+ else: # tiktok
+ ad_content = await generator.generate_ad_video(prompt, page_data.get('screenshot_path'), ad_id)
+
+ result_path = await generator.save_results(ad_content, prompt, page_data['analysis'], url, page_data['timestamp'])
+
+ if mode == 'instagram':
+ print(f'🎨 Generated image ad #{ad_id}: {result_path}')
+ else:
+ print(f'🎬 Generated video ad #{ad_id}: {result_path}')
+
+ open_file(result_path)
+
+ return result_path
+
+ except Exception as e:
+ print(f'❌ Error for ad #{ad_id}: {e}')
+ raise
+ finally:
+ if ad_id == 1 and page_data.get('screenshot_path'):
print(f'πŸ“Έ Page screenshot: {page_data["screenshot_path"]}')
- open_image(result_path)
+
+
+async def generate_single_ad(page_data: dict, mode: str, ad_id: int):
+ """Generate a single ad using pre-analyzed page data"""
+ generator = AdGenerator(mode=mode)
+
+ try:
+ prompt = generator.create_ad_prompt(page_data['analysis'])
+
+ if mode == 'instagram':
+ ad_content = await generator.generate_ad_image(prompt, page_data.get('screenshot_path'))
+ if ad_content is None:
+ raise RuntimeError(f'Ad image generation failed for ad #{ad_id}')
+ else: # tiktok
+ ad_content = await generator.generate_ad_video(prompt, page_data.get('screenshot_path'), ad_id)
+
+ # Create unique timestamp for each ad
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') + f'_{ad_id}'
+ result_path = await generator.save_results(ad_content, prompt, page_data['analysis'], page_data['url'], timestamp)
+
+ if mode == 'instagram':
+ print(f'🎨 Generated image ad #{ad_id}: {result_path}')
+ else:
+ print(f'🎬 Generated video ad #{ad_id}: {result_path}')
return result_path
except Exception as e:
- print(f'❌ Error: {e}')
+ print(f'❌ Error for ad #{ad_id}: {e}')
raise
+async def create_multiple_ads(url: str, debug: bool = False, mode: str = 'instagram', count: int = 1):
+ """Generate multiple ads in parallel using asyncio concurrency"""
+ if count == 1:
+ return await create_ad_from_landing_page(url, debug, mode, 1)
+
+ print(f'πŸš€ Analyzing {url} for {count} {mode} ads...')
+
+ analyzer = LandingPageAnalyzer(debug=debug)
+ page_data = await analyzer.analyze_landing_page(url, mode=mode)
+
+ print(f'🎯 Generating {count} {mode} ads in parallel...')
+
+ tasks = []
+ for i in range(count):
+ task = asyncio.create_task(generate_single_ad(page_data, mode, i + 1))
+ tasks.append(task)
+
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ successful = []
+ failed = []
+
+ for i, result in enumerate(results):
+ if isinstance(result, Exception):
+ failed.append(i + 1)
+ else:
+ successful.append(result)
+
+ print(f'\nβœ… Successfully generated {len(successful)}/{count} ads')
+ if failed:
+ print(f'❌ Failed ads: {failed}')
+
+ if page_data.get('screenshot_path'):
+ print(f'πŸ“Έ Page screenshot: {page_data["screenshot_path"]}')
+
+ for ad_path in successful:
+ open_file(ad_path)
+
+ return successful
+
+
if __name__ == '__main__':
url = args.url
if not url:
url = input('πŸ”— Enter URL: ').strip() or 'https://www.apple.com/iphone-17-pro/'
- asyncio.run(create_ad_from_landing_page(url, debug=args.debug))
+ if args.tiktok:
+ mode = 'tiktok'
+ else:
+ mode = 'instagram'
+
+ asyncio.run(create_multiple_ads(url, debug=args.debug, mode=mode, count=args.count))