Spaces:
Build error
Build error
File size: 14,096 Bytes
13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa 13bcdd9 ed0a3fa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
#!/usr/bin/env python3
"""
Enhanced Computer-Using Agent with VNC Integration
Combines browser automation with full desktop environment access
"""
import asyncio
import json
import base64
import io
import os
import time
import threading
from typing import Dict, List, Optional, Any
from dataclasses import dataclass
from pathlib import Path
import logging
import gradio as gr
import cv2
import numpy as np
from PIL import Image
from playwright.async_api import async_playwright, Browser, BrowserContext, Page
import requests
from huggingface_hub import hf_hub_download, login
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class AgentState:
"""State management for the computer agent"""
browser: Optional[Browser] = None
context: Optional[BrowserContext] = None
page: Optional[Page] = None
is_running: bool = False
screenshot_count: int = 0
action_history: List[str] = None
vnc_port: int = 5901
def __post_init__(self):
if self.action_history is None:
self.action_history = []
class ComputerUsingAgent:
"""Enhanced Computer-Using Agent with VNC Integration"""
def __init__(self):
self.state = AgentState()
self.setup_logging()
self.vnc_url = f"http://localhost:{self.state.vnc_port}/vnc.html"
def setup_logging(self):
"""Setup logging configuration"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agent.log'),
logging.StreamHandler()
]
)
async def initialize_browser(self, headless: bool = True, viewport_width: int = 1280, viewport_height: int = 720):
"""Initialize browser with specified settings"""
try:
logger.info("Initializing browser...")
playwright = await async_playwright().start()
# Launch browser with enhanced settings
self.state.browser = await playwright.chromium.launch(
headless=headless,
args=[
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-web-security",
"--disable-features=VizDisplayCompositor",
"--disable-blink-features=AutomationControlled",
"--disable-infobars",
"--disable-background-timer-throttling",
"--disable-popup-blocking",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
"--disable-window-activation",
"--disable-focus-on-load",
"--no-first-run",
"--no-default-browser-check",
"--window-position=0,0",
]
)
# Create context with persistent user data
self.state.context = await self.state.browser.new_context(
viewport={'width': viewport_width, 'height': viewport_height},
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'
)
# Create a new page
self.state.page = await self.state.context.new_page()
self.state.is_running = True
logger.info("Browser initialized successfully")
return True
except Exception as e:
logger.error(f"Failed to initialize browser: {str(e)}")
return False
async def navigate_to_url(self, url: str) -> Dict[str, Any]:
"""Navigate to a URL and return status"""
if not self.state.page:
return {"success": False, "message": "Browser not initialized"}
try:
# Add protocol if missing
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
await self.state.page.goto(url, wait_until='networkidle', timeout=30000)
await self.state.page.wait_for_timeout(2000)
# Get page title and URL
title = await self.state.page.title()
current_url = self.state.page.url
self.state.action_history.append(f"Navigated to: {url}")
return {
"success": True,
"message": f"Successfully navigated to {url}",
"title": title,
"current_url": current_url
}
except Exception as e:
logger.error(f"Failed to navigate to {url}: {str(e)}")
return {"success": False, "message": f"Failed to navigate: {str(e)}"}
async def take_screenshot(self) -> str:
"""Take a screenshot and return base64 encoded image"""
if not self.state.page:
return ""
try:
# Take screenshot
screenshot_bytes = await self.state.page.screenshot(type='png')
# Convert to base64
base64_image = base64.b64encode(screenshot_bytes).decode('utf-8')
self.state.screenshot_count += 1
self.state.action_history.append(f"Screenshot taken (Total: {self.state.screenshot_count})")
return base64_image
except Exception as e:
logger.error(f"Failed to take screenshot: {str(e)}")
return ""
async def get_vnc_status(self) -> Dict[str, Any]:
"""Get VNC connection status"""
try:
# Check if VNC port is accessible
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', self.state.vnc_port))
vnc_running = result == 0
sock.close()
return {
"vnc_running": vnc_running,
"vnc_port": self.state.vnc_port,
"vnc_url": self.vnc_url,
"status": "VNC Server Active" if vnc_running else "VNC Server Not Available"
}
except Exception as e:
return {
"vnc_running": False,
"vnc_port": self.state.vnc_port,
"error": str(e)
}
def get_status(self) -> Dict[str, Any]:
"""Get current agent status including VNC info"""
vnc_status = asyncio.run(self.get_vnc_status())
return {
"is_running": self.state.is_running,
"browser_initialized": self.state.browser is not None,
"page_loaded": self.state.page is not None,
"screenshot_count": self.state.screenshot_count,
"action_history": self.state.action_history[-10:],
"current_url": self.state.page.url if self.state.page else "None",
"vnc_info": vnc_status
}
# Global agent instance
agent = ComputerUsingAgent()
def process_action(action_type: str, **kwargs):
"""Process agent actions"""
try:
if action_type == "initialize":
headless = kwargs.get("headless", True)
result = asyncio.run(agent.initialize_browser(headless=headless))
return "Browser initialized successfully" if result else "Failed to initialize browser"
elif action_type == "navigate":
url = kwargs.get("url", "")
if not url:
return "URL is required"
result = asyncio.run(agent.navigate_to_url(url))
return result["message"]
elif action_type == "screenshot":
image_base64 = asyncio.run(agent.take_screenshot())
if image_base64:
return "Screenshot taken successfully", image_base64
else:
return "Failed to take screenshot"
elif action_type == "status":
status = agent.get_status()
return json.dumps(status, indent=2)
elif action_type == "vnc_status":
vnc_status = asyncio.run(agent.get_vnc_status())
return json.dumps(vnc_status, indent=2)
else:
return f"Unknown action: {action_type}"
except Exception as e:
logger.error(f"Error processing action {action_type}: {str(e)}")
return f"Error: {str(e)}"
def gradio_interface():
"""Create enhanced Gradio interface with VNC integration"""
with gr.Blocks(title="Enhanced Computer-Using Agent with VNC", theme=gr.themes.Soft()) as interface:
gr.Markdown("# π₯οΈ Enhanced Computer-Using Agent with VNC")
gr.Markdown("π€ **AI-powered browser automation with full desktop environment access**")
with gr.Tab("π Browser Automation"):
with gr.Row():
initialize_btn = gr.Button("Initialize Browser", variant="primary")
status_btn = gr.Button("Get Status", variant="secondary")
status_display = gr.Textbox(label="Agent Status", lines=8)
with gr.Row():
url_input = gr.Textbox(label="URL", placeholder="https://example.com")
navigate_btn = gr.Button("Navigate", variant="primary")
navigation_status = gr.Textbox(label="Navigation Status")
with gr.Row():
screenshot_btn = gr.Button("Take Screenshot", variant="primary")
screenshot_output = gr.Image(label="Current Screenshot")
screenshot_status = gr.Textbox(label="Screenshot Status")
with gr.Tab("π₯οΈ VNC Desktop"):
with gr.Row():
vnc_status_btn = gr.Button("Check VNC Status", variant="primary")
open_vnc_btn = gr.Button("Open VNC Viewer", variant="secondary")
vnc_status_display = gr.Textbox(label="VNC Status", lines=6)
with gr.Row():
gr.HTML("""
<div style="text-align: center; padding: 20px; background-color: #f0f0f0; border-radius: 10px;">
<h3>π VNC Web Access</h3>
<p>Click the button above to open the VNC web viewer in a new tab</p>
<p><strong>Port:</strong> 5901 | <strong>Password:</strong> computer-agent</p>
</div>
""")
# VNC viewer iframe (placeholder - will be populated dynamically)
vnc_viewer = gr.HTML("""
<div style="width: 100%; height: 600px; border: 2px solid #ccc; border-radius: 10px; background-color: #f9f9f9;">
<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #666;">
<div style="text-align: center;">
<h4>π₯οΈ VNC Desktop Environment</h4>
<p>Desktop environment will be accessible here once VNC server is running</p>
<p><em>Use the "Open VNC Viewer" button to access full desktop</em></p>
</div>
</div>
</div>
""")
with gr.Tab("π System Info"):
with gr.Row():
system_info_btn = gr.Button("Get System Info", variant="primary")
system_info_display = gr.Textbox(label="System Information", lines=10)
with gr.Row():
gr.HTML("""
<div style="background-color: #e8f5e8; padding: 20px; border-radius: 10px; margin-top: 20px;">
<h4>π Features Available</h4>
<ul>
<li>β
Browser Automation with Playwright</li>
<li>β
Screenshot Capture</li>
<li>β
VNC Desktop Environment (XFCE4)</li>
<li>β
Web-based VNC Access</li>
<li>β
Real-time Status Monitoring</li>
<li>β
Action History Tracking</li>
</ul>
</div>
""")
# Event handlers
initialize_btn.click(
fn=lambda: process_action("initialize"),
outputs=status_display
)
status_btn.click(
fn=lambda: process_action("status"),
outputs=status_display
)
navigate_btn.click(
fn=lambda url: process_action("navigate", url=url),
inputs=url_input,
outputs=navigation_status
)
screenshot_btn.click(
fn=lambda: process_action("screenshot"),
outputs=[screenshot_status, screenshot_output]
)
vnc_status_btn.click(
fn=lambda: process_action("vnc_status"),
outputs=vnc_status_display
)
open_vnc_btn.click(
fn=lambda: f"window.open('{agent.vnc_url}', '_blank')",
outputs=gr.HTML()
)
system_info_btn.click(
fn=lambda: json.dumps({
"platform": "Hugging Face Spaces",
"docker": True,
"vnc_enabled": True,
"desktop_env": "XFCE4",
"python_version": "3.10",
"features": ["browser_automation", "vnc_desktop", "web_interface"]
}, indent=2),
outputs=system_info_display
)
return interface
if __name__ == "__main__":
# Create and launch enhanced Gradio interface
interface = gradio_interface()
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
debug=True,
show_error=True
) |