broadfield-dev commited on
Commit
31d5b37
·
verified ·
1 Parent(s): 8662903

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +232 -217
app.py CHANGED
@@ -1,228 +1,246 @@
1
  # app.py
2
 
3
  import gradio as gr
4
- import time
 
 
5
  import datetime
6
-
7
- # --- Core Browser Logic (Slightly modified for Gradio) ---
8
- # Changes:
9
- # - Removed print() statements. Methods now return status/log messages.
10
- # - Removed time.sleep() as Gradio handles user feedback.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  class Tab:
13
- """Represents a single browser tab with its own history."""
14
- def __init__(self, homepage):
15
- self.history = []
16
- self.current_index = -1
17
- self.homepage = homepage
18
- self.navigate(self.homepage)
19
-
20
- def navigate(self, url):
21
- """Navigates to a new URL, clearing any 'forward' history."""
22
- if self.current_index < len(self.history) - 1:
23
- self.history = self.history[:self.current_index + 1]
24
- self.history.append(url)
25
- self.current_index += 1
26
- return f"Navigating to {url}..."
27
-
28
- def go_back(self):
29
- if self.current_index > 0:
30
- self.current_index -= 1
31
- return f"Going back to {self.current_url()}"
32
- return "No more history to go back to."
33
-
34
- def go_forward(self):
35
- if self.current_index < len(self.history) - 1:
36
- self.current_index += 1
37
- return f"Going forward to {self.current_url()}"
38
- return "No more history to go forward to."
39
-
40
- def current_url(self):
41
- return self.history[self.current_index] if self.current_index != -1 else "about:blank"
42
-
43
- class PseudoBrowser:
44
- """Simulates a web browser's core functionality."""
45
  def __init__(self):
46
- self.homepage = "https://www.startpage.com"
47
- self.tabs = [Tab(self.homepage)]
48
- self.active_tab_index = 0
49
  self.bookmarks = set()
50
  self.global_history = []
51
- self.cache = {}
52
 
53
  def _get_active_tab(self):
 
 
54
  return self.tabs[self.active_tab_index]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- def _fetch_content(self, url, refresh=False):
57
- """Simulates fetching content, using a cache."""
58
- log = ""
59
- if url in self.cache and not refresh:
60
- log += f"⚡️ Loading '{url}' from cache.\n"
61
- content = self.cache[url]
62
- else:
63
- log += f"☁️ Fetching '{url}' from network...\n"
64
- content = f"<html><body><h1>Welcome to {url}</h1><p><i>Content 'rendered' at {datetime.datetime.now().strftime('%H:%M:%S')}</i></p></body></html>"
65
- self.cache[url] = content
66
- return content, log
67
-
68
- def open_url(self, url):
69
  tab = self._get_active_tab()
70
- log = tab.navigate(url)
 
 
 
 
 
 
 
 
71
  self.global_history.append((datetime.datetime.now(), url))
72
- content, fetch_log = self._fetch_content(url)
73
- return content, log + "\n" + fetch_log
74
 
75
  def back(self):
76
  tab = self._get_active_tab()
77
- log = tab.go_back()
78
- content, fetch_log = self._fetch_content(tab.current_url())
79
- return content, log + "\n" + fetch_log
 
 
80
 
81
  def forward(self):
82
  tab = self._get_active_tab()
83
- log = tab.go_forward()
84
- content, fetch_log = self._fetch_content(tab.current_url())
85
- return content, log + "\n" + fetch_log
86
-
 
87
  def refresh(self):
88
  tab = self._get_active_tab()
89
- url = tab.current_url()
90
- log = f"🔄 Refreshing {url}..."
91
- content, fetch_log = self._fetch_content(url, refresh=True)
92
- return content, log + "\n" + fetch_log
93
 
94
  def new_tab(self):
95
- new_tab = Tab(self.homepage)
96
- self.tabs.append(new_tab)
 
 
97
  self.active_tab_index = len(self.tabs) - 1
98
- content, fetch_log = self._fetch_content(new_tab.current_url())
99
- return content, f"✨ New tab opened.\n" + fetch_log
100
 
101
  def close_tab(self):
102
- if len(self.tabs) == 1:
103
- return None, "Cannot close the last tab!"
104
 
105
- closed_tab = self.tabs.pop(self.active_tab_index)
106
- log = f"💣 Tab ({closed_tab.current_url()}) closed."
 
107
  if self.active_tab_index >= len(self.tabs):
108
  self.active_tab_index = len(self.tabs) - 1
109
 
110
- active_tab = self._get_active_tab()
111
- content, fetch_log = self._fetch_content(active_tab.current_url())
112
- return content, log + "\n" + fetch_log
113
-
114
- def switch_tab(self, tab_label):
115
- # The label is "Tab 0: https://..."
116
- index = int(tab_label.split(":")[0].replace("Tab", "").strip())
117
- if 0 <= index < len(self.tabs):
118
- self.active_tab_index = index
119
- tab = self._get_active_tab()
120
- content, fetch_log = self._fetch_content(tab.current_url())
121
- return content, f"Switched to Tab {index}.\n" + fetch_log
122
- return None, "❌ Invalid tab index."
123
-
124
- def add_bookmark(self):
125
- url = self._get_active_tab().current_url()
126
- if url not in self.bookmarks:
127
- self.bookmarks.add(url)
128
- return f"⭐ Bookmarked: {url}"
129
- return f"ℹ️ Already bookmarked: {url}"
130
 
 
 
 
 
 
 
 
 
 
 
131
  # --- Gradio UI and Event Handlers ---
132
 
133
- def update_ui_components(browser: PseudoBrowser):
134
  """Generates all UI component values from the browser state."""
135
- # Main Content
136
- active_tab = browser._get_active_tab()
137
- content, _ = browser._fetch_content(active_tab.current_url())
138
- url_text = active_tab.current_url()
139
-
140
- # Tab Selector
141
- tab_choices = [f"Tab {i}: {tab.current_url()}" for i, tab in enumerate(browser.tabs)]
142
- active_tab_label = f"Tab {browser.active_tab_index}: {active_tab.current_url()}"
143
-
144
- # History
145
- history_md = "### 📜 Global History\n"
146
- if not browser.global_history:
147
- history_md += "_(empty)_"
148
- else:
149
- for ts, url in reversed(browser.global_history[-10:]): # Show last 10
150
- history_md += f"- `{ts.strftime('%H:%M:%S')}`: {url}\n"
151
 
152
- # Bookmarks
153
- bookmarks_md = "### 📚 Bookmarks\n"
154
- if not browser.bookmarks:
155
- bookmarks_md += "_(empty)_"
 
 
 
 
 
156
  else:
157
- for bm in sorted(list(browser.bookmarks)):
158
- bookmarks_md += f"- ⭐ {bm}\n"
159
-
160
  return {
161
- html_view: gr.HTML(value=content),
162
- url_textbox: gr.Textbox(value=url_text),
 
163
  tab_selector: gr.Radio(choices=tab_choices, value=active_tab_label, label="Active Tabs"),
164
- history_display: gr.Markdown(history_md),
165
- bookmarks_display: gr.Markdown(bookmarks_md)
166
  }
167
 
168
  # --- Event Handlers ---
169
-
170
- def handle_go(browser_state, url):
171
- content, log = browser_state.open_url(url)
172
- return {
173
- **update_ui_components(browser_state),
174
- log_display: gr.Textbox(log)
175
- }
176
-
177
- def handle_back(browser_state):
178
- content, log = browser_state.back()
179
- return {
180
- **update_ui_components(browser_state),
181
- log_display: gr.Textbox(log)
182
- }
183
-
184
- def handle_forward(browser_state):
185
- content, log = browser_state.forward()
186
- return {
187
- **update_ui_components(browser_state),
188
- log_display: gr.Textbox(log)
189
- }
190
-
191
- def handle_refresh(browser_state):
192
- content, log = browser_state.refresh()
193
- return {
194
- **update_ui_components(browser_state),
195
- log_display: gr.Textbox(log)
196
- }
197
-
198
- def handle_new_tab(browser_state):
199
- content, log = browser_state.new_tab()
200
- return {
201
- **update_ui_components(browser_state),
202
- log_display: gr.Textbox(log)
203
- }
204
-
205
- def handle_close_tab(browser_state):
206
- content, log = browser_state.close_tab()
207
- # Update UI components. If content is None, it means the last tab wasn't closed.
208
- updated_components = update_ui_components(browser_state)
209
- if content is not None:
210
- updated_components[html_view] = gr.HTML(value=content)
211
 
212
- return {
213
- **updated_components,
214
- log_display: gr.Textbox(log)
215
- }
216
-
217
- def handle_switch_tab(browser_state, tab_label):
218
- content, log = browser_state.switch_tab(tab_label)
219
- return {
220
- **update_ui_components(browser_state),
221
- log_display: gr.Textbox(log)
222
- }
223
-
224
- def handle_add_bookmark(browser_state):
225
- log = browser_state.add_bookmark()
226
  return {
227
  **update_ui_components(browser_state),
228
  log_display: gr.Textbox(log)
@@ -230,65 +248,62 @@ def handle_add_bookmark(browser_state):
230
 
231
  # --- Gradio Interface Layout ---
232
 
233
- with gr.Blocks(theme=gr.themes.Soft(), title="Pseudo Browser") as demo:
234
- browser_state = gr.State(PseudoBrowser())
 
235
 
236
- gr.Markdown("# 🌐 Pseudo Browser Demo")
237
- gr.Markdown("A simulation of a web browser's state and actions, built with Python and Gradio.")
238
 
239
  with gr.Row():
240
  with gr.Column(scale=3):
241
- # URL and Navigation Controls
242
  with gr.Row():
243
- back_btn = gr.Button("◀")
244
- forward_btn = gr.Button("▶")
245
- refresh_btn = gr.Button("🔄")
246
- url_textbox = gr.Textbox(label="URL", placeholder="https://example.com", interactive=True)
247
- go_btn = gr.Button("Go", variant="primary")
248
- bookmark_btn = gr.Button("")
249
 
250
- # Main "rendered" content view
251
- html_view = gr.HTML(value="<html><body><h1>Welcome!</h1></body></html>")
252
 
253
- # Log display
254
- log_display = gr.Textbox(label="Log", interactive=False)
255
 
256
  with gr.Column(scale=1):
257
- # Tab Management
258
  with gr.Row():
259
  new_tab_btn = gr.Button("➕ New Tab")
260
- close_tab_btn = gr.Button("❌ Close Active Tab")
261
  tab_selector = gr.Radio(choices=[], label="Active Tabs", interactive=True)
262
 
263
- # Accordion for History and Bookmarks
264
- with gr.Accordion("History & Bookmarks", open=True):
265
- history_display = gr.Markdown("...")
266
- bookmarks_display = gr.Markdown("...")
 
267
 
268
  # --- Component Wiring ---
269
-
270
- # Define all outputs that can be updated
271
- outputs = [html_view, url_textbox, tab_selector, history_display, bookmarks_display, log_display]
272
 
273
  # Initial load
274
  demo.load(
275
- fn=lambda state: {**update_ui_components(state), log_display: "🚀 Browser Initialized!"},
276
  inputs=[browser_state],
277
- outputs=outputs
278
  )
279
 
280
- # Wire up buttons
281
- go_btn.click(handle_go, [browser_state, url_textbox], outputs)
282
- url_textbox.submit(handle_go, [browser_state, url_textbox], outputs)
283
- back_btn.click(handle_back, [browser_state], outputs)
284
- forward_btn.click(handle_forward, [browser_state], outputs)
285
- refresh_btn.click(handle_refresh, [browser_state], outputs)
286
 
287
- new_tab_btn.click(handle_new_tab, [browser_state], outputs)
288
- close_tab_btn.click(handle_close_tab, [browser_state], outputs)
289
- tab_selector.input(handle_switch_tab, [browser_state, tab_selector], outputs)
290
 
291
- bookmark_btn.click(handle_add_bookmark, [browser_state], outputs)
 
 
292
 
293
 
294
  demo.launch()
 
1
  # app.py
2
 
3
  import gradio as gr
4
+ from playwright.sync_api import sync_playwright, Error as PlaywrightError
5
+ from bs4 import BeautifulSoup
6
+ import urllib.parse
7
  import datetime
8
+ import atexit
9
+ import re
10
+
11
+ # --- GLOBAL PLAYWRIGHT SETUP ---
12
+ # Launch Playwright and a browser instance once when the app starts.
13
+ # This is crucial for performance and state management.
14
+ try:
15
+ p = sync_playwright().start()
16
+ # Using Firefox can sometimes be less prone to bot detection than Chromium.
17
+ # headless=True is essential for running on a server like Hugging Face Spaces.
18
+ browser = p.firefox.launch(headless=True, timeout=60000)
19
+ print("✅ Playwright browser launched successfully.")
20
+ except Exception as e:
21
+ print(f"❌ Could not launch Playwright browser: {e}")
22
+ # You might want to handle this more gracefully, but for a demo, exiting is fine.
23
+ exit()
24
+
25
+ # Ensure the browser is closed gracefully when the app exits.
26
+ def cleanup():
27
+ print("🧹 Cleaning up: Closing Playwright browser...")
28
+ browser.close()
29
+ p.stop()
30
+ atexit.register(cleanup)
31
+
32
+
33
+ # --- Core Browser Logic (Powered by Playwright) ---
34
 
35
  class Tab:
36
+ """Represents a single browser tab, now backed by a Playwright Page."""
37
+ def __init__(self, playwright_page):
38
+ self.page = playwright_page # The actual Playwright page object
39
+ self.title = "New Tab"
40
+ self.url = "about:blank"
41
+ self.parsed_text = "Welcome! Navigate to a URL or search to get started."
42
+ self.links = [] # A list of {'text': str, 'url': str}
43
+
44
+ def close(self):
45
+ """Closes the underlying Playwright page."""
46
+ if not self.page.is_closed():
47
+ self.page.close()
48
+
49
+ class RealBrowser:
50
+ """Manages multiple tabs and browser-level state."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def __init__(self):
52
+ self.tabs = []
53
+ self.active_tab_index = -1
 
54
  self.bookmarks = set()
55
  self.global_history = []
56
+ self.new_tab() # Start with one tab
57
 
58
  def _get_active_tab(self):
59
+ if self.active_tab_index == -1 or self.active_tab_index >= len(self.tabs):
60
+ return None
61
  return self.tabs[self.active_tab_index]
62
+
63
+ def _fetch_and_parse(self, tab, url):
64
+ """Uses Playwright to navigate and BeautifulSoup to parse."""
65
+ log = f"▶️ Navigating to {url}..."
66
+ try:
67
+ # Navigate the page, waiting until the page is fully loaded.
68
+ # wait_until='domcontentloaded' is a good balance of speed and completeness.
69
+ tab.page.goto(url, wait_until='domcontentloaded', timeout=30000)
70
+
71
+ # Update tab state with the final URL after any redirects
72
+ tab.url = tab.page.url
73
+ tab.title = tab.page.title() or "No Title"
74
+ log += f"\n✅ Arrived at: {tab.url}"
75
+ log += f"\n📄 Title: {tab.title}"
76
+
77
+ # Get the fully-rendered HTML and parse it
78
+ html_content = tab.page.content()
79
+ soup = BeautifulSoup(html_content, 'lxml')
80
+
81
+ # Extract and clean text
82
+ for script in soup(["script", "style", "nav", "footer"]):
83
+ script.extract()
84
+ text = soup.get_text(separator='\n', strip=True)
85
+ tab.parsed_text = text
86
+
87
+ # Extract links
88
+ tab.links = []
89
+ for link in soup.find_all('a', href=True):
90
+ href = link['href']
91
+ absolute_url = urllib.parse.urljoin(tab.url, href)
92
+ # Filter out useless links
93
+ if absolute_url.startswith('http') and not re.match(r'javascript:|mailto:', absolute_url):
94
+ link_text = link.get_text(strip=True) or "[No Link Text]"
95
+ tab.links.append({'text': link_text, 'url': absolute_url})
96
+ log += f"\n🔗 Found {len(tab.links)} links."
97
+
98
+ except PlaywrightError as e:
99
+ error_message = str(e)
100
+ if "net::ERR" in error_message:
101
+ error_message = "Network error: Could not resolve host or connect."
102
+ elif "Timeout" in error_message:
103
+ error_message = f"Timeout: The page took too long to load."
104
+
105
+ tab.title = "Error"
106
+ tab.url = url
107
+ tab.parsed_text = f"❌ Failed to load page.\n\nError: {error_message}"
108
+ tab.links = []
109
+ log += f"\n❌ {error_message}"
110
+
111
+ return log
112
 
113
+ def go(self, term_or_url):
114
+ """Opens a URL or performs a search in the active tab."""
 
 
 
 
 
 
 
 
 
 
 
115
  tab = self._get_active_tab()
116
+ if not tab: return "No active tab."
117
+
118
+ # Check if it's a URL or a search term
119
+ parsed_url = urllib.parse.urlparse(term_or_url)
120
+ if parsed_url.scheme and parsed_url.netloc:
121
+ url = term_or_url
122
+ else:
123
+ url = f"https://duckduckgo.com/html/?q={urllib.parse.quote_plus(term_or_url)}"
124
+
125
  self.global_history.append((datetime.datetime.now(), url))
126
+ return self._fetch_and_parse(tab, url)
 
127
 
128
  def back(self):
129
  tab = self._get_active_tab()
130
+ if tab and tab.page.can_go_back():
131
+ # Playwright's go_back is async-like, we need to re-parse
132
+ tab.page.go_back(wait_until='domcontentloaded')
133
+ return self._fetch_and_parse(tab, tab.page.url)
134
+ return "Cannot go back."
135
 
136
  def forward(self):
137
  tab = self._get_active_tab()
138
+ if tab and tab.page.can_go_forward():
139
+ tab.page.go_forward(wait_until='domcontentloaded')
140
+ return self._fetch_and_parse(tab, tab.page.url)
141
+ return "Cannot go forward."
142
+
143
  def refresh(self):
144
  tab = self._get_active_tab()
145
+ if tab:
146
+ tab.page.reload(wait_until='domcontentloaded')
147
+ return self._fetch_and_parse(tab, tab.page.url)
148
+ return "No active tab."
149
 
150
  def new_tab(self):
151
+ # Create a new page in the persistent browser context
152
+ page = browser.new_page()
153
+ tab = Tab(page)
154
+ self.tabs.append(tab)
155
  self.active_tab_index = len(self.tabs) - 1
156
+ return self.go("https://duckduckgo.com/html/?q=news") # Navigate new tab to a default search
 
157
 
158
  def close_tab(self):
159
+ if len(self.tabs) <= 1:
160
+ return "Cannot close the last tab."
161
 
162
+ tab_to_close = self.tabs.pop(self.active_tab_index)
163
+ tab_to_close.close()
164
+
165
  if self.active_tab_index >= len(self.tabs):
166
  self.active_tab_index = len(self.tabs) - 1
167
 
168
+ # No need to re-fetch, just update the UI state
169
+ return f"Tab closed. Switched to Tab {self.active_tab_index}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
+ def switch_tab(self, tab_label):
172
+ try:
173
+ index = int(tab_label.split(":")[0].replace("Tab", "").strip())
174
+ if 0 <= index < len(self.tabs):
175
+ self.active_tab_index = index
176
+ return f"Switched to Tab {index}."
177
+ return "Invalid tab index."
178
+ except (ValueError, IndexError):
179
+ return "Invalid tab format."
180
+
181
  # --- Gradio UI and Event Handlers ---
182
 
183
+ def update_ui_components(browser_state: RealBrowser):
184
  """Generates all UI component values from the browser state."""
185
+ active_tab = browser_state._get_active_tab()
186
+ if not active_tab:
187
+ return {
188
+ page_content: gr.Markdown("No active tabs. Please create a new one."),
189
+ url_textbox: "",
190
+ links_display: "",
191
+ tab_selector: gr.Radio(choices=[], label="Active Tabs"),
192
+ }
 
 
 
 
 
 
 
 
193
 
194
+ # Tab Selector
195
+ tab_choices = [f"Tab {i}: {tab.title[:40]}..." for i, tab in enumerate(browser_state.tabs)]
196
+ active_tab_label = f"Tab {browser_state.active_tab_index}: {active_tab.title[:40]}..."
197
+
198
+ # Links Display
199
+ links_md = "### 🔗 Links on Page\n"
200
+ if active_tab.links:
201
+ for i, link in enumerate(active_tab.links[:25]): # Show first 25 links
202
+ links_md += f"{i}. [{link['text'][:80]}]({link['url']})\n"
203
  else:
204
+ links_md += "_No links found or page failed to load._"
205
+
 
206
  return {
207
+ page_content: gr.Markdown(f"# {active_tab.title}\n**URL:** {active_tab.url}\n\n---\n\n{active_tab.parsed_text[:2000]}..."),
208
+ url_textbox: gr.Textbox(value=active_tab.url),
209
+ links_display: gr.Markdown(links_md),
210
  tab_selector: gr.Radio(choices=tab_choices, value=active_tab_label, label="Active Tabs"),
 
 
211
  }
212
 
213
  # --- Event Handlers ---
214
+ def handle_action(browser_state, action, value=None):
215
+ if action == "go":
216
+ log = browser_state.go(value)
217
+ elif action == "click":
218
+ tab = browser_state._get_active_tab()
219
+ try:
220
+ link_index = int(value)
221
+ if tab and 0 <= link_index < len(tab.links):
222
+ link_url = tab.links[link_index]['url']
223
+ log = browser_state.go(link_url)
224
+ else:
225
+ log = "Invalid link number."
226
+ except (ValueError, TypeError):
227
+ log = "Please enter a valid number to click."
228
+ elif action == "back":
229
+ log = browser_state.back()
230
+ elif action == "forward":
231
+ log = browser_state.forward()
232
+ elif action == "refresh":
233
+ log = browser_state.refresh()
234
+ elif action == "new_tab":
235
+ log = browser_state.new_tab()
236
+ elif action == "close_tab":
237
+ log = browser_state.close_tab()
238
+ elif action == "switch_tab":
239
+ log = browser_state.switch_tab(value)
240
+ else:
241
+ log = "Unknown action."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
+ # After any action, update the entire UI based on the new state
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  return {
245
  **update_ui_components(browser_state),
246
  log_display: gr.Textbox(log)
 
248
 
249
  # --- Gradio Interface Layout ---
250
 
251
+ with gr.Blocks(theme=gr.themes.Soft(), title="Real Browser Demo") as demo:
252
+ # The gr.State holds our Python class instance, persisting it across calls.
253
+ browser_state = gr.State(RealBrowser())
254
 
255
+ gr.Markdown("# 🌐 Real Browser Demo (Powered by Playwright)")
256
+ gr.Markdown("Type a URL or search term. This demo runs a real headless browser on the server to fetch and parse live websites.")
257
 
258
  with gr.Row():
259
  with gr.Column(scale=3):
 
260
  with gr.Row():
261
+ back_btn = gr.Button("◀ Back")
262
+ forward_btn = gr.Button("▶ Forward")
263
+ refresh_btn = gr.Button("🔄 Refresh")
264
+
265
+ url_textbox = gr.Textbox(label="URL or Search Term", placeholder="https://news.ycombinator.com or 'best python libraries'", interactive=True)
266
+ go_btn = gr.Button("Go", variant="primary")
267
 
268
+ with gr.Accordion("Page Content (Text Only)", open=True):
269
+ page_content = gr.Markdown("Loading...")
270
 
271
+ log_display = gr.Textbox(label="Status Log", interactive=False)
 
272
 
273
  with gr.Column(scale=1):
 
274
  with gr.Row():
275
  new_tab_btn = gr.Button("➕ New Tab")
276
+ close_tab_btn = gr.Button("❌ Close Tab")
277
  tab_selector = gr.Radio(choices=[], label="Active Tabs", interactive=True)
278
 
279
+ with gr.Accordion("Clickable Links", open=True):
280
+ links_display = gr.Markdown("...")
281
+ with gr.Row():
282
+ click_num_box = gr.Number(label="Link #", scale=1, minimum=0, step=1)
283
+ click_btn = gr.Button("Click Link", scale=2)
284
 
285
  # --- Component Wiring ---
286
+ all_outputs = [page_content, url_textbox, links_display, tab_selector, log_display]
 
 
287
 
288
  # Initial load
289
  demo.load(
290
+ lambda state: {**update_ui_components(state), log_display: "🚀 Browser Initialized! Ready to navigate."},
291
  inputs=[browser_state],
292
+ outputs=all_outputs
293
  )
294
 
295
+ # Event listeners
296
+ go_btn.click(lambda s, v: handle_action(s, "go", v), [browser_state, url_textbox], all_outputs, show_progress="full")
297
+ url_textbox.submit(lambda s, v: handle_action(s, "go", v), [browser_state, url_textbox], all_outputs, show_progress="full")
298
+ click_btn.click(lambda s, v: handle_action(s, "click", v), [browser_state, click_num_box], all_outputs, show_progress="full")
 
 
299
 
300
+ back_btn.click(lambda s: handle_action(s, "back"), [browser_state], all_outputs, show_progress="full")
301
+ forward_btn.click(lambda s: handle_action(s, "forward"), [browser_state], all_outputs, show_progress="full")
302
+ refresh_btn.click(lambda s: handle_action(s, "refresh"), [browser_state], all_outputs, show_progress="full")
303
 
304
+ new_tab_btn.click(lambda s: handle_action(s, "new_tab"), [browser_state], all_outputs, show_progress="full")
305
+ close_tab_btn.click(lambda s: handle_action(s, "close_tab"), [browser_state], all_outputs)
306
+ tab_selector.input(lambda s, v: handle_action(s, "switch_tab", v), [browser_state, tab_selector], all_outputs)
307
 
308
 
309
  demo.launch()