browser-director 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ """
2
+ browser-director: operate a site, then direct a narrated demo of it.
3
+
4
+ Control a browser from the CLI or from one MCP server. The same server
5
+ spotlights elements, moves the camera, drives a cursor, and records a
6
+ voiceover. The previous import name was ``agent_browser``.
7
+ """
8
+
9
+ from .driver import BrowserDriver
10
+ from .interactive import InteractiveRunner
11
+ from .mcp import BrowserServer, URLValidator
12
+ from .utils import (
13
+ PathTraversalError,
14
+ resize_screenshot_if_needed,
15
+ sanitize_filename,
16
+ validate_path,
17
+ validate_path_in_sandbox,
18
+ validate_output_dir,
19
+ )
20
+ from .version import __version__
21
+ __all__ = [
22
+ "__version__",
23
+ "BrowserDriver",
24
+ "BrowserServer",
25
+ "InteractiveRunner",
26
+ "PathTraversalError",
27
+ "URLValidator",
28
+ "resize_screenshot_if_needed",
29
+ "sanitize_filename",
30
+ "validate_path",
31
+ "validate_path_in_sandbox",
32
+ "validate_output_dir",
33
+ ]
@@ -0,0 +1,205 @@
1
+ """
2
+ Cinematic Engine - Video production tools for AI agents.
3
+
4
+ This package provides tools for creating marketing-grade video content:
5
+ - Phase 1: Voice & Timing (TTS, audio duration)
6
+ - Phase 2: Recording & Virtual Actor (video capture, cursor, annotations)
7
+ - Phase 3: Camera Control (zoom, pan)
8
+ - Phase 4: Post-Production (audio/video merging, background music, stock music library)
9
+ - Phase 5: Polish (smooth scrolling, human-like typing, presentation mode)
10
+
11
+ Usage:
12
+ class BrowserServer(CinematicMixin):
13
+ def __init__(self):
14
+ # Initialize cinematic state
15
+ self._init_cinematic_state()
16
+ ...
17
+
18
+ # Then register tools:
19
+ server.tool()(self.generate_voiceover)
20
+ server.tool()(self.start_recording)
21
+ ...
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ from pathlib import Path
28
+ from typing import Any, Optional, TYPE_CHECKING
29
+
30
+ from .tts import TTSMixin
31
+ from .recording import RecordingMixin
32
+ from .annotations import AnnotationMixin
33
+ from .camera import CameraMixin
34
+ from .postproduction import PostProductionMixin
35
+ from .polish import PolishMixin
36
+
37
+ if TYPE_CHECKING:
38
+ from playwright.async_api import Browser, BrowserContext, Page
39
+
40
+ __all__ = [
41
+ "CinematicMixin",
42
+ "TTSMixin",
43
+ "RecordingMixin",
44
+ "AnnotationMixin",
45
+ "CameraMixin",
46
+ "PostProductionMixin",
47
+ "PolishMixin",
48
+ ]
49
+
50
+
51
+ class CinematicMixin(TTSMixin, RecordingMixin, AnnotationMixin, CameraMixin, PostProductionMixin, PolishMixin):
52
+ """
53
+ Combined mixin providing all Cinematic Engine tools for video production.
54
+
55
+ ## WORKFLOW GUIDE (Critical - Read This First!)
56
+
57
+ Creating a marketing video follows this 3-phase workflow:
58
+
59
+ ### Phase 1: PREPARATION (do first!)
60
+ 1. check_environment() - Verify ffmpeg and API keys
61
+ 2. generate_voiceover() - Create narration FIRST (duration drives pacing)
62
+ 3. get_audio_duration() - Know exact timing for video actions
63
+ 4. list_stock_music() + download_stock_music() - Get background music
64
+
65
+ ### Phase 2: RECORDING
66
+ 1. start_recording(width=1920, height=1080) - Begin capture
67
+ 2. set_presentation_mode(enabled=True) - Hide scrollbars
68
+ 3. goto() - Navigate to your page
69
+ 4. annotate() - Add floating text callouts
70
+ 5. spotlight() - Highlight elements (ring, spotlight, focus styles)
71
+ 6. camera_zoom() / camera_pan() - Cinematic camera effects
72
+ 7. smooth_scroll() - Professional scrolling
73
+ 8. wait() - Let animations complete (wait > animation duration!)
74
+ 9. clear_spotlight() / clear_annotations() - Clean up effects
75
+ 10. stop_recording() - End capture, get video path
76
+
77
+ ### Phase 3: POST-PRODUCTION
78
+ 1. convert_to_mp4() - Convert WebM to MP4 (recommended first step)
79
+ 2. merge_audio_video() - Add voiceover at specific timestamps (fast=True default)
80
+ 3. add_background_music() - Layer music (15% volume, voice at 130%)
81
+ 4. add_text_overlay() - Add titles, captions with fade effects
82
+ 5. concatenate_videos() - Join multiple scenes with transitions
83
+
84
+ ## KEY BEST PRACTICES
85
+ - Generate voiceover FIRST - audio duration determines video pacing
86
+ - Convert WebM to MP4 after recording for faster processing
87
+ - Use merge_audio_video(fast=True) to skip video re-encoding (default)
88
+ - Control per-track volume: audio_tracks=[{path, start_ms, volume: 1.2}]
89
+ - Always wait() after effects - let animations complete
90
+ - Keep music at 10-15% volume - voice should dominate
91
+ - Silent videos work - add_background_music() handles them gracefully
92
+ - Use spotlight(style="focus") for maximum visual impact
93
+ - Clear effects before switching to new ones
94
+ - Use presentation_mode for cleaner visuals
95
+
96
+ ## Tool Categories
97
+
98
+ Voice & Timing: generate_voiceover, get_audio_duration
99
+ Recording: start_recording, stop_recording, recording_status
100
+ Annotations: annotate, clear_annotations
101
+ Spotlight: spotlight, clear_spotlight (ring/spotlight/focus effects)
102
+ Camera: camera_zoom, camera_pan, camera_reset
103
+ Post-Production: convert_to_mp4, merge_audio_video, add_background_music, add_text_overlay
104
+ Transitions: concatenate_videos (fade/wipe/slide/dissolve)
105
+ Stock Music: list_stock_music, download_stock_music
106
+ Polish: smooth_scroll, type_human, set_presentation_mode, freeze_time
107
+
108
+ Required state variables (call _init_cinematic_state() in __init__):
109
+ - _tts_client: Optional[Any] - Lazy-loaded TTS client
110
+ - _audio_cache_dir: Path - Directory for cached audio files
111
+ - _recording: bool - Recording state flag
112
+ - _video_dir: Path - Directory for video files
113
+ - _video_path: Optional[Path] - Current video file path
114
+ - _recording_start_time: Optional[float] - Recording start timestamp
115
+ - _cursor_injected: bool - Whether cursor is injected
116
+ - _saved_url: Optional[str] - URL saved before context recreation
117
+ - _lock: asyncio.Lock - Thread safety lock
118
+
119
+ Required from host class:
120
+ - browser: Optional[Browser] - Playwright browser
121
+ - context: Optional[BrowserContext] - Browser context
122
+ - page: Optional[Page] - Current page
123
+ - headless: bool - Headless mode flag
124
+ - start(headless: bool) - Method to start browser
125
+ - _ensure_page() -> Page - Method to get current page
126
+ - _handle_console - Console event handler
127
+ - _handle_request_finished - Network event handler
128
+ """
129
+
130
+ # Type hints for state variables
131
+ _tts_client: Optional[Any]
132
+ _audio_cache_dir: Path
133
+ _recording: bool
134
+ _video_dir: Path
135
+ _video_path: Optional[Path]
136
+ _recording_start_time: Optional[float]
137
+ _cursor_injected: bool
138
+ _saved_url: Optional[str]
139
+ _lock: asyncio.Lock
140
+ browser: Optional["Browser"]
141
+ context: Optional["BrowserContext"]
142
+ page: Optional["Page"]
143
+ headless: bool
144
+
145
+ def _init_cinematic_state(self) -> None:
146
+ """
147
+ Initialize all Cinematic Engine state variables.
148
+
149
+ Call this in your __init__ method before _register_tools().
150
+ """
151
+ # Phase 1: Voice & Timing
152
+ self._tts_client: Optional[Any] = None
153
+ self._audio_cache_dir = Path("audio_cache")
154
+
155
+ # Phase 2: Recording & Virtual Actor
156
+ self._recording = False
157
+ self._video_dir = Path("videos")
158
+ self._video_path: Optional[Path] = None
159
+ self._recording_start_time: Optional[float] = None
160
+ self._cursor_injected = False
161
+ self._saved_url: Optional[str] = None
162
+
163
+ def _register_cinematic_tools(self, server: Any) -> None:
164
+ """
165
+ Register all Cinematic Engine tools with the MCP server.
166
+
167
+ Call this in your _register_tools() method.
168
+
169
+ Args:
170
+ server: MCPServer instance
171
+ """
172
+
173
+ from ..registry import EFFECT, READ, READ_NET, WRITE, WRITE_NET, register
174
+
175
+ # Phase 1: Voice & Timing
176
+ register(server, self.generate_voiceover, annotations=WRITE_NET)
177
+ register(server, self.get_audio_duration, annotations=READ)
178
+
179
+ # Phase 2: Recording & Virtual Actor
180
+ register(server, self.start_recording, annotations=WRITE)
181
+ register(server, self.stop_recording, annotations=WRITE)
182
+ register(server, self.recording_status, annotations=READ)
183
+ register(server, self.annotate, annotations=EFFECT)
184
+ register(server, self.clear_annotations, annotations=EFFECT)
185
+ register(server, self.spotlight, annotations=EFFECT)
186
+ register(server, self.clear_spotlight, annotations=EFFECT)
187
+
188
+ # Phase 3: Camera Control
189
+ register(server, self.camera_zoom, annotations=EFFECT)
190
+ register(server, self.camera_pan, annotations=EFFECT)
191
+ register(server, self.camera_reset, annotations=EFFECT)
192
+
193
+ # Phase 4: Post-production. render_demo covers the common mux.
194
+ # Ken Burns, titles, and multi-clip edits stay as ffmpeg examples.
195
+ register(server, self.check_environment, annotations=READ)
196
+ register(server, self.get_video_duration, annotations=READ)
197
+ register(server, self.list_stock_music, annotations=READ_NET)
198
+ register(server, self.download_stock_music, annotations=WRITE_NET)
199
+ register(server, self.render_demo, annotations=WRITE)
200
+
201
+ # Phase 5: Polish
202
+ register(server, self.smooth_scroll, annotations=WRITE)
203
+ register(server, self.type_human, annotations=WRITE)
204
+ register(server, self.set_presentation_mode, annotations=EFFECT)
205
+ register(server, self.freeze_time, annotations=EFFECT)
@@ -0,0 +1,268 @@
1
+ """
2
+ Annotation tools for the Cinematic Engine.
3
+
4
+ Provides floating text annotations that appear on screen during recording
5
+ to highlight features or explain what's happening.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import time
12
+ from typing import Optional, TYPE_CHECKING
13
+ from ..results import ToolResult
14
+
15
+ from .scripts import ANNOTATION_SCRIPT, HIGHLIGHT_SCRIPT
16
+
17
+ if TYPE_CHECKING:
18
+ from playwright.async_api import Page
19
+
20
+
21
+ class AnnotationMixin:
22
+ """
23
+ Mixin class providing annotation tools.
24
+
25
+ Expects the host class to have:
26
+ - self._lock: asyncio.Lock - Thread safety lock
27
+ - self._ensure_page() -> Page - Method to get current page
28
+ """
29
+
30
+ _lock: asyncio.Lock
31
+
32
+ async def _ensure_page(self) -> "Page":
33
+ """Get the current page, starting browser if needed."""
34
+ raise NotImplementedError("Host class must implement _ensure_page")
35
+
36
+ async def annotate(
37
+ self,
38
+ text: str,
39
+ target: Optional[str] = None,
40
+ position: str = "above",
41
+ style: str = "light",
42
+ duration_ms: int = 0,
43
+ ) -> ToolResult:
44
+ """
45
+ [Cinematic Engine - PHASE 2] Add a floating text annotation to the video.
46
+
47
+ Annotations are visual labels that appear on screen during recording
48
+ to highlight features or explain what's happening. Use with spotlight()
49
+ for maximum impact.
50
+
51
+ Args:
52
+ text: The annotation text to display
53
+ target: Optional CSS selector to position near (if omitted, uses center)
54
+ position: Where to place relative to target: "above", "below", "left", "right"
55
+ style: Visual style: "light" (white bg) or "dark" (dark bg)
56
+ duration_ms: Auto-remove after ms (0 = permanent until clear_annotations)
57
+
58
+ Returns:
59
+ {"success": True, "data": {"id": "...", "position": {...}}}
60
+ """
61
+
62
+ try:
63
+ async with self._lock:
64
+ page = await self._ensure_page()
65
+
66
+ # Inject annotation script
67
+ await page.evaluate(ANNOTATION_SCRIPT)
68
+
69
+ # Calculate position
70
+ x, y = 100.0, 100.0 # Default position
71
+
72
+ if target:
73
+ try:
74
+ box = await page.locator(target).first.bounding_box()
75
+ if box:
76
+ if position == "above":
77
+ x = box["x"] + box["width"] / 2 - 75
78
+ y = box["y"] - 50
79
+ elif position == "below":
80
+ x = box["x"] + box["width"] / 2 - 75
81
+ y = box["y"] + box["height"] + 10
82
+ elif position == "left":
83
+ x = box["x"] - 170
84
+ y = box["y"] + box["height"] / 2 - 20
85
+ elif position == "right":
86
+ x = box["x"] + box["width"] + 10
87
+ y = box["y"] + box["height"] / 2 - 20
88
+ except Exception: # pylint: disable=broad-except
89
+ pass
90
+ else:
91
+ # Center of viewport
92
+ viewport = page.viewport_size
93
+ if viewport:
94
+ x = viewport["width"] / 2 - 75
95
+ y = viewport["height"] / 2 - 20
96
+
97
+ # Generate unique ID
98
+ annotation_id = f"__annotation_{int(time.time() * 1000)}__"
99
+
100
+ # Escape text for JavaScript
101
+ escaped_text = text.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
102
+
103
+ # Add annotation
104
+ await page.evaluate(
105
+ f"window.__agentAnnotations.add('{annotation_id}', '{escaped_text}', {x}, {y}, '{style}', {duration_ms})"
106
+ )
107
+
108
+ return {
109
+ "success": True,
110
+ "message": f"Added annotation: {text[:30]}...",
111
+ "data": {
112
+ "id": annotation_id,
113
+ "position": {"x": x, "y": y},
114
+ "style": style,
115
+ "duration_ms": duration_ms,
116
+ },
117
+ }
118
+
119
+ except Exception as exc: # pylint: disable=broad-except
120
+ return {"success": False, "message": f"Failed to add annotation: {exc}"}
121
+
122
+ async def clear_annotations(self) -> ToolResult:
123
+ """
124
+ [Cinematic Engine] Remove all annotations from the page.
125
+
126
+ Returns:
127
+ {"success": True, "message": "Cleared all annotations"}
128
+ """
129
+
130
+ try:
131
+ async with self._lock:
132
+ page = await self._ensure_page()
133
+ await page.evaluate(ANNOTATION_SCRIPT)
134
+ await page.evaluate("window.__agentAnnotations.clear()")
135
+
136
+ return {
137
+ "success": True,
138
+ "message": "Cleared all annotations",
139
+ }
140
+
141
+ except Exception as exc: # pylint: disable=broad-except
142
+ return {"success": False, "message": f"Failed to clear annotations: {exc}"}
143
+
144
+ async def spotlight(
145
+ self,
146
+ selector: str,
147
+ style: str = "ring",
148
+ color: str = "#3b82f6",
149
+ pulse_ms: int = 1500,
150
+ dim_opacity: float = 0.5,
151
+ ) -> ToolResult:
152
+ """
153
+ [Cinematic Engine - PHASE 2] Create cinematic spotlight/highlight effects.
154
+
155
+ Creates attention-grabbing visual effects around an element to
156
+ draw viewer focus during video recording. Use during recording phase
157
+ after start_recording().
158
+
159
+ IMPORTANT:
160
+ - Always call clear_spotlight() before applying a new spotlight
161
+ - Wait at least 2-3 seconds after spotlight for viewers to notice
162
+ - Combine with annotate() for maximum impact
163
+
164
+ Args:
165
+ selector: CSS selector for the element to spotlight
166
+ style: Effect style:
167
+ - "ring": Glowing pulsing border around element
168
+ - "spotlight": Dims page except element (cinematic focus)
169
+ - "focus": Both ring and spotlight combined (MAXIMUM IMPACT)
170
+ color: Highlight color (hex or CSS color, default blue #3b82f6)
171
+ pulse_ms: Pulse animation duration in ms (default 1500)
172
+ dim_opacity: Spotlight dimness 0.0-1.0 (default 0.5, higher = darker)
173
+
174
+ Returns:
175
+ {"success": True, "data": {"style": "ring", "selector": "..."}}
176
+
177
+ Example:
178
+ # Ring highlight with annotation
179
+ spotlight(selector="button.cta", style="ring", color="#3b82f6")
180
+ annotate("Click here!", position="above", style="dark")
181
+ wait(3000) # Let viewers see it
182
+ clear_spotlight()
183
+ clear_annotations()
184
+
185
+ # Dramatic focus effect (ring + dim)
186
+ spotlight(selector="#hero", style="focus", dim_opacity=0.7)
187
+ wait(3000)
188
+ clear_spotlight()
189
+ """
190
+
191
+ try:
192
+ async with self._lock:
193
+ page = await self._ensure_page()
194
+
195
+ # Use Playwright's locator to find element and get bounding box
196
+ # This supports all Playwright selectors including :has-text()
197
+ try:
198
+ locator = page.locator(selector).first
199
+ box = await locator.bounding_box(timeout=5000)
200
+ except Exception:
201
+ box = None
202
+
203
+ if not box:
204
+ return {
205
+ "success": False,
206
+ "message": f"Element not found: {selector}",
207
+ }
208
+
209
+ # Inject highlight script
210
+ await page.evaluate(HIGHLIGHT_SCRIPT)
211
+
212
+ # Pass bounding box to JavaScript (avoids selector escaping issues)
213
+ rect_json = f"{{x: {box['x']}, y: {box['y']}, width: {box['width']}, height: {box['height']}}}"
214
+
215
+ # Apply the requested effect using rect-based functions
216
+ if style == "ring":
217
+ await page.evaluate(
218
+ f"window.__agentHighlight.ringWithRect({rect_json}, '{color}', {pulse_ms})"
219
+ )
220
+ elif style == "spotlight":
221
+ await page.evaluate(
222
+ f"window.__agentHighlight.spotlightWithRect({rect_json}, {dim_opacity})"
223
+ )
224
+ elif style == "focus":
225
+ await page.evaluate(
226
+ f"window.__agentHighlight.focusWithRect({rect_json}, '{color}', {dim_opacity}, {pulse_ms})"
227
+ )
228
+ else:
229
+ return {
230
+ "success": False,
231
+ "message": f"Unknown highlight style: {style}. Use 'ring', 'spotlight', or 'focus'.",
232
+ }
233
+
234
+ return {
235
+ "success": True,
236
+ "message": f"Applied {style} highlight to {selector}",
237
+ "data": {
238
+ "style": style,
239
+ "selector": selector,
240
+ "color": color,
241
+ "bounding_box": box,
242
+ },
243
+ }
244
+
245
+ except Exception as exc: # pylint: disable=broad-except
246
+ return {"success": False, "message": f"Failed to highlight: {exc}"}
247
+
248
+ async def clear_spotlight(self) -> ToolResult:
249
+ """
250
+ [Cinematic Engine] Remove all spotlight/highlight effects from the page.
251
+
252
+ Returns:
253
+ {"success": True, "message": "Cleared all spotlight effects"}
254
+ """
255
+
256
+ try:
257
+ async with self._lock:
258
+ page = await self._ensure_page()
259
+ await page.evaluate(HIGHLIGHT_SCRIPT)
260
+ await page.evaluate("window.__agentHighlight.clear()")
261
+
262
+ return {
263
+ "success": True,
264
+ "message": "Cleared all spotlight effects",
265
+ }
266
+
267
+ except Exception as exc: # pylint: disable=broad-except
268
+ return {"success": False, "message": f"Failed to clear spotlight: {exc}"}