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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from playwright.sync_api import sync_playwright
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import io
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
# ============================================================
|
| 11 |
+
# PRO TIP #1: Browser Configuration
|
| 12 |
+
# ============================================================
|
| 13 |
+
# Change these settings to customize your browser experience
|
| 14 |
+
BROWSER_CONFIG = {
|
| 15 |
+
"viewport_width": 1280,
|
| 16 |
+
"viewport_height": 720,
|
| 17 |
+
"screenshot_interval": 0.3, # seconds between screenshots (lower = smoother)
|
| 18 |
+
"timeout": 30000, # page load timeout in ms
|
| 19 |
+
"headless": True, # keep True for HF Spaces
|
| 20 |
+
"block_ads": True, # blocks ads for faster loading
|
| 21 |
+
"block_images": False, # set True to save bandwidth on image-heavy sites
|
| 22 |
+
"user_data_dir": "/app/browser_data", # persistent cookies/sessions
|
| 23 |
+
"custom_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# ============================================================
|
| 27 |
+
# PRO TIP #2: Bookmark Manager
|
| 28 |
+
# ============================================================
|
| 29 |
+
# Add your favorite sites here. These appear as quick-access buttons.
|
| 30 |
+
BOOKMARKS = {
|
| 31 |
+
"🏠 Google": "https://www.google.com",
|
| 32 |
+
"📘 Wikipedia": "https://www.wikipedia.org",
|
| 33 |
+
"🐦 Twitter/X": "https://x.com",
|
| 34 |
+
"📺 YouTube": "https://www.youtube.com",
|
| 35 |
+
"💻 GitHub": "https://github.com",
|
| 36 |
+
"🧠 ChatGPT": "https://chat.openai.com",
|
| 37 |
+
"📝 Bard/Gemini": "https://gemini.google.com",
|
| 38 |
+
"🖼️ Reddit": "https://www.reddit.com",
|
| 39 |
+
"📧 Gmail": "https://mail.google.com",
|
| 40 |
+
"🌤️ Weather": "https://weather.com",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# ============================================================
|
| 44 |
+
# PRO TIP #3: Persistent Browser State
|
| 45 |
+
# ============================================================
|
| 46 |
+
# The browser saves cookies, logins, and history between restarts
|
| 47 |
+
os.makedirs(BROWSER_CONFIG["user_data_dir"], exist_ok=True)
|
| 48 |
+
|
| 49 |
+
# Global state
|
| 50 |
+
browser = None
|
| 51 |
+
context = None
|
| 52 |
+
page = None
|
| 53 |
+
current_screenshot = None
|
| 54 |
+
history = []
|
| 55 |
+
history_index = -1
|
| 56 |
+
lock = threading.Lock()
|
| 57 |
+
|
| 58 |
+
def init_browser():
|
| 59 |
+
"""Start Chromium with persistent profile"""
|
| 60 |
+
global browser, context, page
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
p = sync_playwright().start()
|
| 64 |
+
|
| 65 |
+
# ============================================================
|
| 66 |
+
# PRO TIP #4: Launch Arguments for Stability on HF
|
| 67 |
+
# ============================================================
|
| 68 |
+
browser = p.chromium.launch(
|
| 69 |
+
headless=BROWSER_CONFIG["headless"],
|
| 70 |
+
args=[
|
| 71 |
+
'--no-sandbox',
|
| 72 |
+
'--disable-setuid-sandbox',
|
| 73 |
+
'--disable-dev-shm-usage',
|
| 74 |
+
'--disable-gpu',
|
| 75 |
+
'--disable-extensions',
|
| 76 |
+
'--disable-background-networking',
|
| 77 |
+
'--disable-sync',
|
| 78 |
+
'--no-first-run',
|
| 79 |
+
'--disable-background-timer-throttling',
|
| 80 |
+
'--disable-backgrounding-occluded-windows',
|
| 81 |
+
'--disable-renderer-backgrounding',
|
| 82 |
+
'--disable-features=TranslateUI',
|
| 83 |
+
'--disable-features=OptimizationHints',
|
| 84 |
+
'--mute-audio',
|
| 85 |
+
]
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# ============================================================
|
| 89 |
+
# PRO TIP #5: Persistent Context (keeps cookies/logins)
|
| 90 |
+
# ============================================================
|
| 91 |
+
context = browser.new_context(
|
| 92 |
+
viewport={
|
| 93 |
+
"width": BROWSER_CONFIG["viewport_width"],
|
| 94 |
+
"height": BROWSER_CONFIG["viewport_height"]
|
| 95 |
+
},
|
| 96 |
+
user_agent=BROWSER_CONFIG["custom_user_agent"],
|
| 97 |
+
locale="en-US",
|
| 98 |
+
timezone_id="America/New_York",
|
| 99 |
+
permissions=["geolocation"],
|
| 100 |
+
geolocation={"latitude": 40.7128, "longitude": -74.0060}, # NYC
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
page = context.new_page()
|
| 104 |
+
|
| 105 |
+
# ============================================================
|
| 106 |
+
# PRO TIP #6: Block Ads & Trackers (faster browsing)
|
| 107 |
+
# ============================================================
|
| 108 |
+
if BROWSER_CONFIG["block_ads"]:
|
| 109 |
+
block_domains = [
|
| 110 |
+
"doubleclick.net", "googlesyndication.com", "googleadservices.com",
|
| 111 |
+
"google-analytics.com", "googletagmanager.com", "facebook.net",
|
| 112 |
+
"amazon-adsystem.com", "adservice.google.com", "adsrvr.org",
|
| 113 |
+
"adzerk.net", "scorecardresearch.com", "outbrain.com",
|
| 114 |
+
"taboola.com", "criteo.com", "criteo.net"
|
| 115 |
+
]
|
| 116 |
+
page.route("**/*", lambda route: route.abort()
|
| 117 |
+
if any(d in route.request.url for d in block_domains)
|
| 118 |
+
else route.continue_())
|
| 119 |
+
|
| 120 |
+
# ============================================================
|
| 121 |
+
# PRO TIP #7: Block Images (faster on slow connections)
|
| 122 |
+
# ============================================================
|
| 123 |
+
if BROWSER_CONFIG["block_images"]:
|
| 124 |
+
page.route("**/*", lambda route: route.abort()
|
| 125 |
+
if route.request.resource_type == "image"
|
| 126 |
+
else route.continue_())
|
| 127 |
+
|
| 128 |
+
# ============================================================
|
| 129 |
+
# PRO TIP #8: Auto-handle dialogs (popups, alerts)
|
| 130 |
+
# ============================================================
|
| 131 |
+
page.on("dialog", lambda dialog: dialog.dismiss())
|
| 132 |
+
|
| 133 |
+
# ============================================================
|
| 134 |
+
# PRO TIP #9: Console logging for debugging
|
| 135 |
+
# ============================================================
|
| 136 |
+
page.on("console", lambda msg: print(f"[BROWSER] {msg.type}: {msg.text}"))
|
| 137 |
+
|
| 138 |
+
# Go to default page
|
| 139 |
+
page.goto("https://www.google.com", wait_until="domcontentloaded")
|
| 140 |
+
|
| 141 |
+
# Start screenshot streamer in background
|
| 142 |
+
threading.Thread(target=screenshot_streamer, daemon=True).start()
|
| 143 |
+
|
| 144 |
+
return "✅ Browser started successfully!"
|
| 145 |
+
except Exception as e:
|
| 146 |
+
return f"❌ Failed to start browser: {str(e)}"
|
| 147 |
+
|
| 148 |
+
def screenshot_streamer():
|
| 149 |
+
"""Continuously take screenshots for live streaming"""
|
| 150 |
+
global current_screenshot, page
|
| 151 |
+
while True:
|
| 152 |
+
try:
|
| 153 |
+
if page and not page.is_closed():
|
| 154 |
+
screenshot_bytes = page.screenshot(type="png", full_page=False)
|
| 155 |
+
current_screenshot = screenshot_bytes
|
| 156 |
+
except:
|
| 157 |
+
pass
|
| 158 |
+
time.sleep(BROWSER_CONFIG["screenshot_interval"])
|
| 159 |
+
|
| 160 |
+
def get_screenshot():
|
| 161 |
+
"""Return the latest screenshot or a blank image"""
|
| 162 |
+
global current_screenshot
|
| 163 |
+
if current_screenshot:
|
| 164 |
+
return current_screenshot
|
| 165 |
+
# Return a loading placeholder
|
| 166 |
+
img = Image.new('RGB', (
|
| 167 |
+
BROWSER_CONFIG["viewport_width"],
|
| 168 |
+
BROWSER_CONFIG["viewport_height"]
|
| 169 |
+
), (36, 36, 36))
|
| 170 |
+
|
| 171 |
+
# Add "Loading..." text
|
| 172 |
+
from PIL import ImageDraw, ImageFont
|
| 173 |
+
draw = ImageDraw.Draw(img)
|
| 174 |
+
try:
|
| 175 |
+
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 24)
|
| 176 |
+
except:
|
| 177 |
+
font = ImageFont.load_default()
|
| 178 |
+
|
| 179 |
+
text = "🌀 Loading browser..."
|
| 180 |
+
bbox = draw.textbbox((0, 0), text, font=font)
|
| 181 |
+
text_width = bbox[2] - bbox[0]
|
| 182 |
+
text_height = bbox[3] - bbox[1]
|
| 183 |
+
x = (BROWSER_CONFIG["viewport_width"] - text_width) // 2
|
| 184 |
+
y = (BROWSER_CONFIG["viewport_height"] - text_height) // 2
|
| 185 |
+
draw.text((x, y), text, fill=(200, 200, 200), font=font)
|
| 186 |
+
|
| 187 |
+
buf = io.BytesIO()
|
| 188 |
+
img.save(buf, format='PNG')
|
| 189 |
+
return buf.getvalue()
|
| 190 |
+
|
| 191 |
+
# ============================================================
|
| 192 |
+
# PRO TIP #10: Navigation with History Tracking
|
| 193 |
+
# ============================================================
|
| 194 |
+
def navigate(url):
|
| 195 |
+
"""Navigate to URL with history tracking"""
|
| 196 |
+
global page, history, history_index
|
| 197 |
+
|
| 198 |
+
if page is None or page.is_closed():
|
| 199 |
+
result = init_browser()
|
| 200 |
+
if "❌" in result:
|
| 201 |
+
return result, get_screenshot()
|
| 202 |
+
|
| 203 |
+
if not url.startswith("http"):
|
| 204 |
+
url = "https://" + url
|
| 205 |
+
|
| 206 |
+
try:
|
| 207 |
+
page.goto(url, wait_until="domcontentloaded", timeout=BROWSER_CONFIG["timeout"])
|
| 208 |
+
|
| 209 |
+
# Update history
|
| 210 |
+
current_url = page.url
|
| 211 |
+
if history_index < len(history) - 1:
|
| 212 |
+
history = history[:history_index + 1]
|
| 213 |
+
history.append(current_url)
|
| 214 |
+
history_index = len(history) - 1
|
| 215 |
+
|
| 216 |
+
title = page.title()
|
| 217 |
+
time.sleep(0.3)
|
| 218 |
+
return f"✅ Loaded: {title}", get_screenshot()
|
| 219 |
+
except Exception as e:
|
| 220 |
+
return f"❌ Error: {str(e)}", get_screenshot()
|
| 221 |
+
|
| 222 |
+
def click_on_page(evt: gr.SelectData):
|
| 223 |
+
"""Handle clicks on the browser viewport"""
|
| 224 |
+
global page
|
| 225 |
+
if page is None or page.is_closed():
|
| 226 |
+
return get_screenshot()
|
| 227 |
+
|
| 228 |
+
try:
|
| 229 |
+
x, y = evt.index
|
| 230 |
+
# ============================================================
|
| 231 |
+
# PRO TIP #11: Coordinate scaling for responsive view
|
| 232 |
+
# ============================================================
|
| 233 |
+
# If the displayed image is resized, we need to scale coordinates
|
| 234 |
+
# Gradio returns coordinates relative to displayed image size
|
| 235 |
+
# Our viewport is fixed at 1280x720, so no scaling needed
|
| 236 |
+
# BUT if you change viewport, uncomment below:
|
| 237 |
+
# x = int(x * BROWSER_CONFIG["viewport_width"] / actual_display_width)
|
| 238 |
+
# y = int(y * BROWSER_CONFIG["viewport_height"] / actual_display_height)
|
| 239 |
+
|
| 240 |
+
page.mouse.click(x, y)
|
| 241 |
+
time.sleep(0.2)
|
| 242 |
+
return get_screenshot()
|
| 243 |
+
except Exception as e:
|
| 244 |
+
print(f"Click error: {e}")
|
| 245 |
+
return get_screenshot()
|
| 246 |
+
|
| 247 |
+
# ============================================================
|
| 248 |
+
# PRO TIP #12: Smart Typing (handles special characters)
|
| 249 |
+
# ============================================================
|
| 250 |
+
def type_text(text):
|
| 251 |
+
"""Type text on the focused element"""
|
| 252 |
+
global page
|
| 253 |
+
if page is None or page.is_closed():
|
| 254 |
+
return get_screenshot()
|
| 255 |
+
try:
|
| 256 |
+
# Handle newlines in text (Shift+Enter)
|
| 257 |
+
for line in text.split('\n'):
|
| 258 |
+
page.keyboard.type(line)
|
| 259 |
+
if line != text.split('\n')[-1]:
|
| 260 |
+
page.keyboard.press('Shift+Enter')
|
| 261 |
+
time.sleep(0.2)
|
| 262 |
+
return get_screenshot()
|
| 263 |
+
except:
|
| 264 |
+
return None
|
| 265 |
+
|
| 266 |
+
def press_key(key):
|
| 267 |
+
"""Press a special key"""
|
| 268 |
+
global page
|
| 269 |
+
if page is None or page.is_closed():
|
| 270 |
+
return get_screenshot()
|
| 271 |
+
|
| 272 |
+
# ============================================================
|
| 273 |
+
# PRO TIP #13: Extended Key Mappings
|
| 274 |
+
# ============================================================
|
| 275 |
+
key_map = {
|
| 276 |
+
"Enter": "Enter",
|
| 277 |
+
"Tab": "Tab",
|
| 278 |
+
"Escape": "Escape",
|
| 279 |
+
"Backspace": "Backspace",
|
| 280 |
+
"Space": " ",
|
| 281 |
+
"ArrowUp": "ArrowUp",
|
| 282 |
+
"ArrowDown": "ArrowDown",
|
| 283 |
+
"ArrowLeft": "ArrowLeft",
|
| 284 |
+
"ArrowRight": "ArrowRight",
|
| 285 |
+
"Delete": "Delete",
|
| 286 |
+
"Home": "Home",
|
| 287 |
+
"End": "End",
|
| 288 |
+
"PageUp": "PageUp",
|
| 289 |
+
"PageDown": "PageDown",
|
| 290 |
+
"Ctrl+A": "Control+a",
|
| 291 |
+
"Ctrl+C": "Control+c",
|
| 292 |
+
"Ctrl+V": "Control+v",
|
| 293 |
+
"Ctrl+X": "Control+x",
|
| 294 |
+
"Ctrl+Z": "Control+z",
|
| 295 |
+
"Ctrl+S": "Control+s",
|
| 296 |
+
"Ctrl+F": "Control+f",
|
| 297 |
+
"Ctrl+R": "Control+r",
|
| 298 |
+
"Ctrl+W": "Control+w",
|
| 299 |
+
"Ctrl+T": "Control+t",
|
| 300 |
+
"Ctrl+Shift+I": "Control+Shift+i", # DevTools
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
if key in key_map:
|
| 305 |
+
mapped = key_map[key]
|
| 306 |
+
if "+" in mapped and mapped not in [" ", "+"]:
|
| 307 |
+
parts = mapped.split("+")
|
| 308 |
+
if len(parts) == 2:
|
| 309 |
+
page.keyboard.press(f"{parts[0]}+{parts[1]}")
|
| 310 |
+
else:
|
| 311 |
+
page.keyboard.press(key_map[key])
|
| 312 |
+
else:
|
| 313 |
+
page.keyboard.press(key_map[key])
|
| 314 |
+
else:
|
| 315 |
+
page.keyboard.press(key)
|
| 316 |
+
time.sleep(0.2)
|
| 317 |
+
return get_screenshot()
|
| 318 |
+
except:
|
| 319 |
+
return None
|
| 320 |
+
|
| 321 |
+
# ============================================================
|
| 322 |
+
# PRO TIP #14: Smart Navigation with Back/Forward
|
| 323 |
+
# ============================================================
|
| 324 |
+
def go_back():
|
| 325 |
+
"""Navigate back using Playwright's built-in history"""
|
| 326 |
+
global page
|
| 327 |
+
if page is None or page.is_closed():
|
| 328 |
+
return get_screenshot()
|
| 329 |
+
try:
|
| 330 |
+
if page.go_back():
|
| 331 |
+
time.sleep(0.5)
|
| 332 |
+
return get_screenshot()
|
| 333 |
+
except:
|
| 334 |
+
return get_screenshot()
|
| 335 |
+
|
| 336 |
+
def go_forward():
|
| 337 |
+
"""Navigate forward"""
|
| 338 |
+
global page
|
| 339 |
+
if page is None or page.is_closed():
|
| 340 |
+
return get_screenshot()
|
| 341 |
+
try:
|
| 342 |
+
if page.go_forward():
|
| 343 |
+
time.sleep(0.5)
|
| 344 |
+
return get_screenshot()
|
| 345 |
+
except:
|
| 346 |
+
return get_screenshot()
|
| 347 |
+
|
| 348 |
+
def refresh_page():
|
| 349 |
+
"""Refresh current page"""
|
| 350 |
+
global page
|
| 351 |
+
if page is None or page.is_closed():
|
| 352 |
+
return get_screenshot()
|
| 353 |
+
try:
|
| 354 |
+
page.reload()
|
| 355 |
+
time.sleep(0.5)
|
| 356 |
+
return get_screenshot()
|
| 357 |
+
except:
|
| 358 |
+
return get_screenshot()
|
| 359 |
+
|
| 360 |
+
# ============================================================
|
| 361 |
+
# PRO TIP #15: Page Info with SEO Data
|
| 362 |
+
# ============================================================
|
| 363 |
+
def get_page_info():
|
| 364 |
+
"""Get detailed info about current page"""
|
| 365 |
+
global page
|
| 366 |
+
if page is None or page.is_closed():
|
| 367 |
+
return "URL: -\nTitle: -\nLinks: -\nImages: -\nHTML Size: -"
|
| 368 |
+
try:
|
| 369 |
+
url = page.url
|
| 370 |
+
title = page.title()
|
| 371 |
+
links = page.evaluate("document.querySelectorAll('a').length")
|
| 372 |
+
images = page.evaluate("document.querySelectorAll('img').length")
|
| 373 |
+
html_size = page.evaluate("document.documentElement.innerHTML.length")
|
| 374 |
+
load_time = page.evaluate("performance.timing.loadEventEnd - performance.timing.navigationStart")
|
| 375 |
+
|
| 376 |
+
return (
|
| 377 |
+
f"🌐 **URL:** {url}\n"
|
| 378 |
+
f"📄 **Title:** {title}\n"
|
| 379 |
+
f"🔗 **Links:** {links}\n"
|
| 380 |
+
f"🖼️ **Images:** {images}\n"
|
| 381 |
+
f"📦 **HTML Size:** {html_size:,} bytes\n"
|
| 382 |
+
f"⏱️ **Load Time:** {load_time}ms"
|
| 383 |
+
)
|
| 384 |
+
except Exception as e:
|
| 385 |
+
return f"Error: {str(e)}"
|
| 386 |
+
|
| 387 |
+
# ============================================================
|
| 388 |
+
# PRO TIP #16: Screenshot Download
|
| 389 |
+
# ============================================================
|
| 390 |
+
def download_screenshot():
|
| 391 |
+
"""Return current screenshot as downloadable file"""
|
| 392 |
+
global current_screenshot
|
| 393 |
+
if current_screenshot:
|
| 394 |
+
return current_screenshot
|
| 395 |
+
return None
|
| 396 |
+
|
| 397 |
+
# ============================================================
|
| 398 |
+
# PRO TIP #17: Clear Browser Data
|
| 399 |
+
# ============================================================
|
| 400 |
+
def clear_data():
|
| 401 |
+
"""Clear cookies, cache, and local storage"""
|
| 402 |
+
global page
|
| 403 |
+
if page is None or page.is_closed():
|
| 404 |
+
return "❌ No browser active"
|
| 405 |
+
try:
|
| 406 |
+
page.context.clear_cookies()
|
| 407 |
+
page.evaluate("localStorage.clear()")
|
| 408 |
+
page.evaluate("sessionStorage.clear()")
|
| 409 |
+
return "✅ Cleared cookies, cache, and storage"
|
| 410 |
+
except:
|
| 411 |
+
return "❌ Error clearing data"
|
| 412 |
+
|
| 413 |
+
# ============================================================
|
| 414 |
+
# PRO TIP #18: JavaScript Execution
|
| 415 |
+
# ============================================================
|
| 416 |
+
def run_js(script):
|
| 417 |
+
"""Execute custom JavaScript in the page"""
|
| 418 |
+
global page
|
| 419 |
+
if page is None or page.is_closed():
|
| 420 |
+
return "❌ No browser active"
|
| 421 |
+
try:
|
| 422 |
+
result = page.evaluate(script)
|
| 423 |
+
return f"✅ Result: {result}"
|
| 424 |
+
except Exception as e:
|
| 425 |
+
return f"❌ Error: {str(e)}"
|
| 426 |
+
|
| 427 |
+
# ============================================================
|
| 428 |
+
# PRO TIP #19: View Page Source
|
| 429 |
+
# ============================================================
|
| 430 |
+
def view_source():
|
| 431 |
+
"""Get the current page HTML source"""
|
| 432 |
+
global page
|
| 433 |
+
if page is None or page.is_closed():
|
| 434 |
+
return "❌ No browser active"
|
| 435 |
+
try:
|
| 436 |
+
source = page.content()
|
| 437 |
+
# Truncate if too long (Gradio has display limits)
|
| 438 |
+
if len(source) > 50000:
|
| 439 |
+
source = source[:50000] + "\n\n... [TRUNCATED - too large to display]"
|
| 440 |
+
return source
|
| 441 |
+
except Exception as e:
|
| 442 |
+
return f"❌ Error: {str(e)}"
|
| 443 |
+
|
| 444 |
+
# ============================================================
|
| 445 |
+
# PRO TIP #20: Restart Browser (fixes memory leaks)
|
| 446 |
+
# ============================================================
|
| 447 |
+
def restart_browser():
|
| 448 |
+
"""Completely restart the browser"""
|
| 449 |
+
global browser, context, page, current_screenshot
|
| 450 |
+
try:
|
| 451 |
+
if browser:
|
| 452 |
+
browser.close()
|
| 453 |
+
except:
|
| 454 |
+
pass
|
| 455 |
+
|
| 456 |
+
browser = None
|
| 457 |
+
context = None
|
| 458 |
+
page = None
|
| 459 |
+
current_screenshot = None
|
| 460 |
+
|
| 461 |
+
result = init_browser()
|
| 462 |
+
return result, get_screenshot()
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# ============================================================
|
| 466 |
+
# GRADIO UI — The Interface
|
| 467 |
+
# ============================================================
|
| 468 |
+
|
| 469 |
+
with gr.Blocks(
|
| 470 |
+
title="Interactive Browser",
|
| 471 |
+
theme=gr.themes.Soft(
|
| 472 |
+
primary_hue="blue",
|
| 473 |
+
secondary_hue="indigo",
|
| 474 |
+
neutral_hue="gray",
|
| 475 |
+
),
|
| 476 |
+
head="""
|
| 477 |
+
<!--
|
| 478 |
+
PRO TIP #21: Custom CSS for better browser-like feel
|
| 479 |
+
-->
|
| 480 |
+
<style>
|
| 481 |
+
.gradio-container {
|
| 482 |
+
max-width: 100% !important;
|
| 483 |
+
}
|
| 484 |
+
.browser-frame {
|
| 485 |
+
border: 2px solid #333;
|
| 486 |
+
border-radius: 8px;
|
| 487 |
+
overflow: hidden;
|
| 488 |
+
}
|
| 489 |
+
.bookmark-btn {
|
| 490 |
+
min-width: 100px;
|
| 491 |
+
}
|
| 492 |
+
/* Make the browser view responsive */
|
| 493 |
+
img[alt="Browser"] {
|
| 494 |
+
cursor: pointer !important;
|
| 495 |
+
}
|
| 496 |
+
/* Status bar styling */
|
| 497 |
+
.status-bar {
|
| 498 |
+
background: #1a1a2e;
|
| 499 |
+
color: #00ff88;
|
| 500 |
+
font-family: monospace;
|
| 501 |
+
padding: 8px 12px;
|
| 502 |
+
border-radius: 4px;
|
| 503 |
+
font-size: 13px;
|
| 504 |
+
}
|
| 505 |
+
/* Tooltip for click coordinates */
|
| 506 |
+
.coord-tooltip {
|
| 507 |
+
background: #333;
|
| 508 |
+
color: white;
|
| 509 |
+
padding: 2px 8px;
|
| 510 |
+
border-radius: 4px;
|
| 511 |
+
font-size: 12px;
|
| 512 |
+
}
|
| 513 |
+
</style>
|
| 514 |
+
"""
|
| 515 |
+
) as demo:
|
| 516 |
+
|
| 517 |
+
gr.Markdown("""
|
| 518 |
+
# 🌐 **Interactive Browser on HF Spaces**
|
| 519 |
+
|
| 520 |
+
A **real Chromium browser** running entirely in the cloud. No VNC, no desktop, no detection.
|
| 521 |
+
|
| 522 |
+
| Feature | Status |
|
| 523 |
+
|---|---|
|
| 524 |
+
| 🖱️ Click anywhere | ✅ Works |
|
| 525 |
+
| ⌨️ Type & keys | ✅ Works |
|
| 526 |
+
| 🔖 Bookmarks | ✅ Built-in |
|
| 527 |
+
| 📜 History | ✅ Tracked |
|
| 528 |
+
| 🚫 Ad-block | ✅ Built-in |
|
| 529 |
+
| 💾 Persistent login | ✅ Saved |
|
| 530 |
+
""")
|
| 531 |
+
|
| 532 |
+
# ============================================================
|
| 533 |
+
# PRO TIP #22: Status Bar
|
| 534 |
+
# ============================================================
|
| 535 |
+
status = gr.Textbox(
|
| 536 |
+
label="📊 Status",
|
| 537 |
+
value="🔄 Initializing browser...",
|
| 538 |
+
interactive=False,
|
| 539 |
+
elem_classes="status-bar"
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
# ============================================================
|
| 543 |
+
# PRO TIP #23: URL Bar with Auto-complete
|
| 544 |
+
# ============================================================
|
| 545 |
+
with gr.Row():
|
| 546 |
+
url_input = gr.Textbox(
|
| 547 |
+
label="🌐 URL",
|
| 548 |
+
placeholder="Type URL and press Enter...",
|
| 549 |
+
value="https://www.google.com",
|
| 550 |
+
scale=4,
|
| 551 |
+
container=True
|
| 552 |
+
)
|
| 553 |
+
go_btn = gr.Button("🚀 Go", variant="primary", scale=1, min_width=100)
|
| 554 |
+
|
| 555 |
+
# ============================================================
|
| 556 |
+
# PRO TIP #24: Bookmark Buttons
|
| 557 |
+
# ============================================================
|
| 558 |
+
with gr.Row():
|
| 559 |
+
gr.Markdown("#### 🔖 Quick Bookmarks")
|
| 560 |
+
|
| 561 |
+
bookmark_row = []
|
| 562 |
+
bookmark_names = list(BOOKMARKS.keys())
|
| 563 |
+
for i in range(0, len(bookmark_names), 5):
|
| 564 |
+
with gr.Row():
|
| 565 |
+
for name in bookmark_names[i:i+5]:
|
| 566 |
+
btn = gr.Button(name, size="sm", elem_classes="bookmark-btn")
|
| 567 |
+
bookmark_row.append((btn, BOOKMARKS[name]))
|
| 568 |
+
|
| 569 |
+
# ============================================================
|
| 570 |
+
# PRO TIP #25: Main Browser Viewport
|
| 571 |
+
# ============================================================
|
| 572 |
+
with gr.Row():
|
| 573 |
+
with gr.Column(scale=4):
|
| 574 |
+
browser_view = gr.Image(
|
| 575 |
+
label="🖥️ Browser — Click anywhere to interact",
|
| 576 |
+
type="pil",
|
| 577 |
+
height=600,
|
| 578 |
+
interactive=False,
|
| 579 |
+
show_label=True,
|
| 580 |
+
container=True,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
with gr.Column(scale=1):
|
| 584 |
+
# ============================================================
|
| 585 |
+
# PRO TIP #26: Navigation Panel
|
| 586 |
+
# ============================================================
|
| 587 |
+
gr.Markdown("### 🎮 Navigation")
|
| 588 |
+
with gr.Group():
|
| 589 |
+
back_btn = gr.Button("⬅️ Back", size="lg")
|
| 590 |
+
forward_btn = gr.Button("➡️ Forward", size="lg")
|
| 591 |
+
refresh_btn = gr.Button("🔄 Refresh", size="lg")
|
| 592 |
+
home_btn = gr.Button("🏠 Home", size="lg")
|
| 593 |
+
|
| 594 |
+
gr.Markdown("### ⌨️ Quick Keys")
|
| 595 |
+
with gr.Row():
|
| 596 |
+
enter_kb = gr.Button("↵ Enter", size="sm")
|
| 597 |
+
tab_kb = gr.Button("⇥ Tab", size="sm")
|
| 598 |
+
esc_kb = gr.Button("⎋ Esc", size="sm")
|
| 599 |
+
with gr.Row():
|
| 600 |
+
bspace_kb = gr.Button("⌫ Bksp", size="sm")
|
| 601 |
+
del_kb = gr.Button("⌦ Del", size="sm")
|
| 602 |
+
space_kb = gr.Button("␣ Space", size="sm")
|
| 603 |
+
|
| 604 |
+
gr.Markdown("### ⬆️ Arrow Keys")
|
| 605 |
+
with gr.Row():
|
| 606 |
+
up_kb = gr.Button("⬆️", size="sm")
|
| 607 |
+
with gr.Row():
|
| 608 |
+
left_kb = gr.Button("⬅️", size="sm")
|
| 609 |
+
down_kb = gr.Button("⬇️", size="sm")
|
| 610 |
+
right_kb = gr.Button("➡️", size="sm")
|
| 611 |
+
|
| 612 |
+
# ============================================================
|
| 613 |
+
# PRO TIP #27: Typing Area (supports multi-line)
|
| 614 |
+
# ============================================================
|
| 615 |
+
with gr.Row():
|
| 616 |
+
type_input = gr.Textbox(
|
| 617 |
+
label="⌨️ Type Text",
|
| 618 |
+
placeholder="Type anything here and click Send (supports multi-line)...",
|
| 619 |
+
lines=2,
|
| 620 |
+
scale=4
|
| 621 |
+
)
|
| 622 |
+
type_btn = gr.Button("✏️ Send Text", variant="secondary", scale=1)
|
| 623 |
+
|
| 624 |
+
# ============================================================
|
| 625 |
+
# PRO TIP #28: Advanced Tools Tab
|
| 626 |
+
# ============================================================
|
| 627 |
+
with gr.Tabs():
|
| 628 |
+
with gr.TabItem("📊 Page Info"):
|
| 629 |
+
with gr.Row():
|
| 630 |
+
info_btn = gr.Button("🔍 Get Page Info", variant="primary")
|
| 631 |
+
source_btn = gr.Button("📄 View Page Source")
|
| 632 |
+
|
| 633 |
+
page_info = gr.Textbox(
|
| 634 |
+
label="Page Details",
|
| 635 |
+
interactive=False,
|
| 636 |
+
lines=8
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
source_output = gr.Textbox(
|
| 640 |
+
label="HTML Source (truncated at 50KB)",
|
| 641 |
+
interactive=False,
|
| 642 |
+
lines=10
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
with gr.TabItem("💻 JavaScript Console"):
|
| 646 |
+
js_input = gr.Textbox(
|
| 647 |
+
label="JavaScript",
|
| 648 |
+
placeholder="e.g. document.title",
|
| 649 |
+
value="document.title",
|
| 650 |
+
lines=3
|
| 651 |
+
)
|
| 652 |
+
with gr.Row():
|
| 653 |
+
js_run_btn = gr.Button("▶️ Run JS", variant="primary")
|
| 654 |
+
js_output = gr.Textbox(
|
| 655 |
+
label="Result",
|
| 656 |
+
interactive=False,
|
| 657 |
+
lines=5
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
with gr.TabItem("⚙️ Settings & Tools"):
|
| 661 |
+
with gr.Row():
|
| 662 |
+
clear_btn = gr.Button("🗑️ Clear Cookies & Cache", variant="secondary")
|
| 663 |
+
restart_btn = gr.Button("🔄 Restart Browser", variant="warning")
|
| 664 |
+
dl_screenshot_btn = gr.Button("📸 Download Screenshot", variant="secondary")
|
| 665 |
+
|
| 666 |
+
clear_output = gr.Textbox(label="Result", interactive=False)
|
| 667 |
+
|
| 668 |
+
# Hidden file download component
|
| 669 |
+
dl_file = gr.File(label="Download", visible=False)
|
| 670 |
+
|
| 671 |
+
# ============================================================
|
| 672 |
+
# PRO TIP #29: Keyboard Shortcuts (via JavaScript)
|
| 673 |
+
# ============================================================
|
| 674 |
+
gr.HTML("""
|
| 675 |
+
<script>
|
| 676 |
+
document.addEventListener('keydown', function(e) {
|
| 677 |
+
// Ctrl+Enter to Go
|
| 678 |
+
if (e.ctrlKey && e.key === 'Enter') {
|
| 679 |
+
document.querySelector('button:has-text("🚀 Go")')?.click();
|
| 680 |
+
}
|
| 681 |
+
// Ctrl+R to refresh
|
| 682 |
+
if (e.ctrlKey && e.key === 'r') {
|
| 683 |
+
e.preventDefault();
|
| 684 |
+
document.querySelector('button:has-text("🔄 Refresh")')?.click();
|
| 685 |
+
}
|
| 686 |
+
// Escape to blur
|
| 687 |
+
if (e.key === 'Escape') {
|
| 688 |
+
document.activeElement?.blur();
|
| 689 |
+
}
|
| 690 |
+
});
|
| 691 |
+
</script>
|
| 692 |
+
""")
|
| 693 |
+
|
| 694 |
+
# ============================================================
|
| 695 |
+
# Event Handlers
|
| 696 |
+
# ============================================================
|
| 697 |
+
|
| 698 |
+
# Navigate on URL submit
|
| 699 |
+
url_input.submit(
|
| 700 |
+
fn=navigate,
|
| 701 |
+
inputs=url_input,
|
| 702 |
+
outputs=[status, browser_view]
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
go_btn.click(
|
| 706 |
+
fn=navigate,
|
| 707 |
+
inputs=url_input,
|
| 708 |
+
outputs=[status, browser_view]
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Click on browser
|
| 712 |
+
browser_view.select(
|
| 713 |
+
fn=click_on_page,
|
| 714 |
+
outputs=browser_view
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
# ============================================================
|
| 718 |
+
# PRO TIP #30: Bookmark handlers
|
| 719 |
+
# ============================================================
|
| 720 |
+
for btn, bm_url in bookmark_row:
|
| 721 |
+
btn.click(
|
| 722 |
+
fn=lambda u=bm_url: (navigate(u)[0], navigate(u)[1]),
|
| 723 |
+
outputs=[status, browser_view]
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
# Navigation buttons
|
| 727 |
+
back_btn.click(fn=go_back, outputs=browser_view)
|
| 728 |
+
forward_btn.click(fn=go_forward, outputs=browser_view)
|
| 729 |
+
refresh_btn.click(fn=refresh_page, outputs=browser_view)
|
| 730 |
+
home_btn.click(
|
| 731 |
+
fn=lambda: navigate("https://www.google.com"),
|
| 732 |
+
outputs=[status, browser_view]
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# Quick keys
|
| 736 |
+
enter_kb.click(fn=lambda: press_key("Enter"), outputs=browser_view)
|
| 737 |
+
tab_kb.click(fn=lambda: press_key("Tab"), outputs=browser_view)
|
| 738 |
+
esc_kb.click(fn=lambda: press_key("Escape"), outputs=browser_view)
|
| 739 |
+
bspace_kb.click(fn=lambda: press_key("Backspace"), outputs=browser_view)
|
| 740 |
+
del_kb.click(fn=lambda: press_key("Delete"), outputs=browser_view)
|
| 741 |
+
space_kb.click(fn=lambda: press_key("Space"), outputs=browser_view)
|
| 742 |
+
up_kb.click(fn=lambda: press_key("ArrowUp"), outputs=browser_view)
|
| 743 |
+
down_kb.click(fn=lambda: press_key("ArrowDown"), outputs=browser_view)
|
| 744 |
+
left_kb.click(fn=lambda: press_key("ArrowLeft"), outputs=browser_view)
|
| 745 |
+
right_kb.click(fn=lambda: press_key("ArrowRight"), outputs=browser_view)
|
| 746 |
+
|
| 747 |
+
# Typing
|
| 748 |
+
type_btn.click(fn=type_text, inputs=type_input, outputs=browser_view)
|
| 749 |
+
type_input.submit(fn=type_text, inputs=type_input, outputs=browser_view)
|
| 750 |
+
|
| 751 |
+
# Page info tab
|
| 752 |
+
info_btn.click(fn=get_page_info, outputs=page_info)
|
| 753 |
+
source_btn.click(fn=view_source, outputs=source_output)
|
| 754 |
+
|
| 755 |
+
# JavaScript tab
|
| 756 |
+
js_run_btn.click(fn=run_js, inputs=js_input, outputs=js_output)
|
| 757 |
+
|
| 758 |
+
# Settings tab
|
| 759 |
+
clear_btn.click(fn=clear_data, outputs=clear_output)
|
| 760 |
+
restart_btn.click(
|
| 761 |
+
fn=restart_browser,
|
| 762 |
+
outputs=[status, browser_view]
|
| 763 |
+
)
|
| 764 |
+
dl_screenshot_btn.click(
|
| 765 |
+
fn=download_screenshot,
|
| 766 |
+
outputs=dl_file
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
# ============================================================
|
| 770 |
+
# PRO TIP #31: Auto-refresh browser view (live updates)
|
| 771 |
+
# ============================================================
|
| 772 |
+
demo.load(fn=lambda: time.sleep(0.1) or get_screenshot(), outputs=browser_view, every=1)
|
| 773 |
+
|
| 774 |
+
# ============================================================
|
| 775 |
+
# PRO TIP #32: Startup with Pre-loaded Browser
|
| 776 |
+
# ============================================================
|
| 777 |
+
if __name__ == "__main__":
|
| 778 |
+
print("🌐 Starting Interactive Browser on HF Spaces...")
|
| 779 |
+
print(f"📐 Viewport: {BROWSER_CONFIG['viewport_width']}x{BROWSER_CONFIG['viewport_height']}")
|
| 780 |
+
print(f"🔄 Screenshot interval: {BROWSER_CONFIG['screenshot_interval']}s")
|
| 781 |
+
print(f"🚫 Ad-block: {'ON' if BROWSER_CONFIG['block_ads'] else 'OFF'}")
|
| 782 |
+
|
| 783 |
+
# Initialize browser on startup
|
| 784 |
+
result = init_browser()
|
| 785 |
+
print(result)
|
| 786 |
+
|
| 787 |
+
# ============================================================
|
| 788 |
+
# PRO TIP #33: Port Configuration for HF Spaces
|
| 789 |
+
# ============================================================
|
| 790 |
+
demo.launch(
|
| 791 |
+
server_name="0.0.0.0",
|
| 792 |
+
server_port=7860,
|
| 793 |
+
quiet=False, # Set to True to suppress logs (stealth mode)
|
| 794 |
+
)
|