broadfield-dev commited on
Commit
15fdb32
·
verified ·
1 Parent(s): a97ce92

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -174
app.py CHANGED
@@ -7,201 +7,215 @@ 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]}..."),
@@ -210,100 +224,58 @@ def update_ui_components(browser_state: RealBrowser):
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)
247
- }
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()
 
7
  import datetime
8
  import atexit
9
  import re
10
+ import os
11
+ from itertools import cycle
12
+
13
+ # --- NEW: Credential Revolver Class ---
14
+ class CredentialRevolver:
15
+ """Manages a rotating list of proxies."""
16
+ def __init__(self, proxy_string: str):
17
+ self.proxies = self._parse_proxies(proxy_string)
18
+ if self.proxies:
19
+ self.proxy_cycler = cycle(self.proxies)
20
+ print(f"✅ CredentialRevolver initialized with {len(self.proxies)} proxies.")
21
+ else:
22
+ self.proxy_cycler = None
23
+ print("⚠️ CredentialRevolver initialized with no proxies. Using direct connection.")
24
+
25
+ def _parse_proxies(self, proxy_string: str):
26
+ """Parses a multi-line string of proxies into a list of dicts."""
27
+ proxies = []
28
+ for line in proxy_string.strip().splitlines():
29
+ line = line.strip()
30
+ if not line:
31
+ continue
32
+ try:
33
+ # Format: http://user:pass@host:port
34
+ parsed = urllib.parse.urlparse(f"//{line}") # Add // to help parsing
35
+ server = f"{parsed.scheme or 'http'}://{parsed.hostname}:{parsed.port}"
36
+ proxy_dict = {
37
+ "server": server,
38
+ "username": parsed.username,
39
+ "password": parsed.password,
40
+ }
41
+ proxies.append(proxy_dict)
42
+ except Exception as e:
43
+ print(f"Could not parse proxy line: '{line}'. Error: {e}")
44
+ return proxies
45
+
46
+ def get_next(self):
47
+ """Returns the next proxy configuration in a round-robin fashion."""
48
+ if self.proxy_cycler:
49
+ return next(self.proxy_cycler)
50
+ return None # No proxy
51
+
52
+ def count(self):
53
+ return len(self.proxies)
54
+
55
+ # --- GLOBAL PLAYWRIGHT AND REVOLVER SETUP ---
56
  try:
57
  p = sync_playwright().start()
58
+ browser = p.firefox.launch(headless=True, timeout=60000)
 
 
59
  print("✅ Playwright browser launched successfully.")
60
  except Exception as e:
61
+ print(f"❌ Could not launch Playwright browser: {e}"); exit()
62
+
63
+ # Load proxies from Hugging Face Secrets (environment variable)
64
+ proxy_list_str = os.getenv("PROXY_LIST", "")
65
+ revolver = CredentialRevolver(proxy_list_str)
66
 
 
67
  def cleanup():
68
+ print("🧹 Cleaning up: Closing Playwright browser..."); browser.close(); p.stop()
 
 
69
  atexit.register(cleanup)
70
 
71
 
72
+ # --- Core Browser Logic (Upgraded with Proxy Contexts) ---
73
 
74
  class Tab:
75
+ """Represents a single browser tab, now tied to a BrowserContext."""
76
+ def __init__(self, context, page, proxy_used):
77
+ self.context = context # The isolated browser context (has the proxy)
78
+ self.page = page # The Playwright page object within the context
79
+ self.proxy_used = proxy_used # Info for logging
80
  self.title = "New Tab"
81
  self.url = "about:blank"
82
  self.parsed_text = "Welcome! Navigate to a URL or search to get started."
83
+ self.links = []
84
 
85
  def close(self):
86
+ """Closes the underlying BrowserContext, which also closes the page."""
87
+ if not self.context.is_closed():
88
+ self.context.close()
89
 
90
  class RealBrowser:
91
+ """Manages multiple tabs, each potentially with its own proxy."""
92
  def __init__(self):
93
  self.tabs = []
94
  self.active_tab_index = -1
 
 
95
  self.new_tab() # Start with one tab
96
 
97
  def _get_active_tab(self):
98
+ if self.active_tab_index == -1 or self.active_tab_index >= len(self.tabs): return None
 
99
  return self.tabs[self.active_tab_index]
100
 
101
  def _fetch_and_parse(self, tab, url):
102
+ # (This function remains largely the same as the previous version)
103
  log = f"▶️ Navigating to {url}..."
104
  try:
 
 
105
  tab.page.goto(url, wait_until='domcontentloaded', timeout=30000)
 
 
106
  tab.url = tab.page.url
107
  tab.title = tab.page.title() or "No Title"
108
  log += f"\n✅ Arrived at: {tab.url}"
109
  log += f"\n📄 Title: {tab.title}"
110
 
 
111
  html_content = tab.page.content()
112
  soup = BeautifulSoup(html_content, 'lxml')
113
+ for script in soup(["script", "style", "nav", "footer"]): script.extract()
114
+ tab.parsed_text = soup.get_text(separator='\n', strip=True)
 
 
 
 
115
 
 
116
  tab.links = []
117
  for link in soup.find_all('a', href=True):
118
  href = link['href']
119
  absolute_url = urllib.parse.urljoin(tab.url, href)
 
120
  if absolute_url.startswith('http') and not re.match(r'javascript:|mailto:', absolute_url):
121
  link_text = link.get_text(strip=True) or "[No Link Text]"
122
  tab.links.append({'text': link_text, 'url': absolute_url})
123
  log += f"\n🔗 Found {len(tab.links)} links."
 
124
  except PlaywrightError as e:
125
+ error_message = str(e); tab.title = "Error"; tab.url = url
 
 
 
 
 
 
 
126
  tab.parsed_text = f"❌ Failed to load page.\n\nError: {error_message}"
127
+ tab.links = []; log += f"\n❌ {error_message}"
 
 
128
  return log
129
 
130
  def go(self, term_or_url):
 
131
  tab = self._get_active_tab()
132
  if not tab: return "No active tab."
 
 
133
  parsed_url = urllib.parse.urlparse(term_or_url)
134
+ url = term_or_url if (parsed_url.scheme and parsed_url.netloc) else f"https://duckduckgo.com/html/?q={urllib.parse.quote_plus(term_or_url)}"
 
 
 
 
 
135
  return self._fetch_and_parse(tab, url)
136
 
137
+ def new_tab(self):
138
+ """CRITICAL CHANGE: Creates a new tab with the next available proxy."""
139
+ proxy_config = revolver.get_next()
140
+ log = ""
141
+
142
+ try:
143
+ # Create a new context with the proxy settings
144
+ context = browser.new_context(proxy=proxy_config)
145
+ page = context.new_page()
146
+
147
+ proxy_info = proxy_config['server'] if proxy_config else "Direct Connection"
148
+ log += f"✨ New tab opened.\n🔒 Using proxy: {proxy_info}"
149
+
150
+ tab = Tab(context, page, proxy_info)
151
+ self.tabs.append(tab)
152
+ self.active_tab_index = len(self.tabs) - 1
153
+
154
+ # Navigate to a default page
155
+ log += "\n" + self.go("https://www.whatsmyip.org/")
156
+ except Exception as e:
157
+ log += f"\n❌ Failed to create new tab/context: {e}"
158
+ if 'context' in locals() and not context.is_closed():
159
+ context.close()
160
+ return log
161
+
162
+ def close_tab(self):
163
+ if len(self.tabs) <= 1: return "Cannot close the last tab."
164
+
165
+ tab_to_close = self.tabs.pop(self.active_tab_index)
166
+ tab_to_close.close() # This now closes the context and the page
167
+
168
+ if self.active_tab_index >= len(self.tabs):
169
+ self.active_tab_index = len(self.tabs) - 1
170
+ return f"💣 Tab closed. Switched to Tab {self.active_tab_index}."
171
+
172
+ # Other methods (back, forward, refresh, switch_tab) remain the same
173
+ # as they operate on the tab's page object, which is now correctly context-aware.
174
  def back(self):
175
  tab = self._get_active_tab()
176
  if tab and tab.page.can_go_back():
177
+ tab.page.go_back(wait_until='domcontentloaded'); return self._fetch_and_parse(tab, tab.page.url)
 
 
178
  return "Cannot go back."
179
 
180
  def forward(self):
181
  tab = self._get_active_tab()
182
  if tab and tab.page.can_go_forward():
183
+ tab.page.go_forward(wait_until='domcontentloaded'); return self._fetch_and_parse(tab, tab.page.url)
 
184
  return "Cannot go forward."
185
 
186
  def refresh(self):
187
  tab = self._get_active_tab()
188
  if tab:
189
+ tab.page.reload(wait_until='domcontentloaded'); return self._fetch_and_parse(tab, tab.page.url)
 
190
  return "No active tab."
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  def switch_tab(self, tab_label):
193
  try:
194
  index = int(tab_label.split(":")[0].replace("Tab", "").strip())
195
+ if 0 <= index < len(self.tabs): self.active_tab_index = index; return f"Switched to Tab {index}."
 
 
196
  return "Invalid tab index."
197
+ except: return "Invalid tab format."
 
 
 
198
 
199
+ # --- Gradio UI and Event Handlers (mostly unchanged, but with proxy info) ---
200
  def update_ui_components(browser_state: RealBrowser):
 
201
  active_tab = browser_state._get_active_tab()
202
  if not active_tab:
203
+ # Handle case where all tabs are closed
204
  return {
205
  page_content: gr.Markdown("No active tabs. Please create a new one."),
206
  url_textbox: "",
207
  links_display: "",
208
  tab_selector: gr.Radio(choices=[], label="Active Tabs"),
209
  }
210
+
211
+ # Add proxy info to the tab selector for clarity
212
+ tab_choices = [f"Tab {i}: {tab.title[:30]}... (via {tab.proxy_used.split('//')[1].split('@')[-1] if tab.proxy_used != 'Direct Connection' else 'Direct'})" for i, tab in enumerate(browser_state.tabs)]
213
+ active_tab_label = tab_choices[browser_state.active_tab_index]
214
 
 
 
 
 
 
215
  links_md = "### 🔗 Links on Page\n"
216
  if active_tab.links:
217
+ for i, link in enumerate(active_tab.links[:25]): links_md += f"{i}. [{link['text'][:80]}]({link['url']})\n"
218
+ else: links_md += "_No links found._"
 
 
219
 
220
  return {
221
  page_content: gr.Markdown(f"# {active_tab.title}\n**URL:** {active_tab.url}\n\n---\n\n{active_tab.parsed_text[:2000]}..."),
 
224
  tab_selector: gr.Radio(choices=tab_choices, value=active_tab_label, label="Active Tabs"),
225
  }
226
 
227
+ # The handle_action function remains the same as it's a generic dispatcher
228
  def handle_action(browser_state, action, value=None):
229
+ # ... (same as previous version)
230
+ if action == "go": log = browser_state.go(value)
231
  elif action == "click":
232
  tab = browser_state._get_active_tab()
233
  try:
234
  link_index = int(value)
235
  if tab and 0 <= link_index < len(tab.links):
236
+ log = browser_state.go(tab.links[link_index]['url'])
237
+ else: log = "Invalid link number."
238
+ except: log = "Please enter a valid number to click."
239
+ elif action == "back": log = browser_state.back()
240
+ elif action == "forward": log = browser_state.forward()
241
+ elif action == "refresh": log = browser_state.refresh()
242
+ elif action == "new_tab": log = browser_state.new_tab()
243
+ elif action == "close_tab": log = browser_state.close_tab()
244
+ elif action == "switch_tab": log = browser_state.switch_tab(value)
245
+ else: log = "Unknown action."
 
 
 
 
 
 
 
 
 
 
246
 
247
+ return {**update_ui_components(browser_state), log_display: gr.Textbox(log)}
 
 
 
 
 
 
248
 
249
+ # The Gradio Blocks layout remains the same
250
  with gr.Blocks(theme=gr.themes.Soft(), title="Real Browser Demo") as demo:
251
+ # ... (same as previous version)
252
  browser_state = gr.State(RealBrowser())
253
+ gr.Markdown("# 🛰️ Real Browser Demo (with Proxy Revolver)")
254
+ gr.Markdown(f"Type a URL or search term. This demo runs a real headless browser with **{revolver.count()} proxies loaded**.")
 
 
255
  with gr.Row():
256
  with gr.Column(scale=3):
257
+ with gr.Row(): back_btn = gr.Button("◀ Back"); forward_btn = gr.Button("▶ Forward"); refresh_btn = gr.Button("🔄 Refresh")
258
+ url_textbox = gr.Textbox(label="URL or Search Term", interactive=True)
 
 
 
 
259
  go_btn = gr.Button("Go", variant="primary")
260
+ with gr.Accordion("Page Content (Text Only)", open=True): page_content = gr.Markdown("Loading...")
 
 
 
261
  log_display = gr.Textbox(label="Status Log", interactive=False)
 
262
  with gr.Column(scale=1):
263
+ with gr.Row(): new_tab_btn = gr.Button("➕ New Tab"); close_tab_btn = gr.Button("❌ Close Tab")
 
 
264
  tab_selector = gr.Radio(choices=[], label="Active Tabs", interactive=True)
 
265
  with gr.Accordion("Clickable Links", open=True):
266
  links_display = gr.Markdown("...")
267
+ with gr.Row(): click_num_box = gr.Number(label="Link #", scale=1, minimum=0, step=1); click_btn = gr.Button("Click Link", scale=2)
268
+
 
 
 
269
  all_outputs = [page_content, url_textbox, links_display, tab_selector, log_display]
270
+ demo.load(lambda s: {**update_ui_components(s), log_display: f"🚀 Browser Initialized! {revolver.count()} proxies loaded. A new tab has been opened to check the IP."}, inputs=[browser_state], outputs=all_outputs)
 
 
 
 
 
 
 
 
271
  go_btn.click(lambda s, v: handle_action(s, "go", v), [browser_state, url_textbox], all_outputs, show_progress="full")
272
  url_textbox.submit(lambda s, v: handle_action(s, "go", v), [browser_state, url_textbox], all_outputs, show_progress="full")
273
  click_btn.click(lambda s, v: handle_action(s, "click", v), [browser_state, click_num_box], all_outputs, show_progress="full")
 
274
  back_btn.click(lambda s: handle_action(s, "back"), [browser_state], all_outputs, show_progress="full")
275
  forward_btn.click(lambda s: handle_action(s, "forward"), [browser_state], all_outputs, show_progress="full")
276
  refresh_btn.click(lambda s: handle_action(s, "refresh"), [browser_state], all_outputs, show_progress="full")
 
277
  new_tab_btn.click(lambda s: handle_action(s, "new_tab"), [browser_state], all_outputs, show_progress="full")
278
  close_tab_btn.click(lambda s: handle_action(s, "close_tab"), [browser_state], all_outputs)
279
  tab_selector.input(lambda s, v: handle_action(s, "switch_tab", v), [browser_state, tab_selector], all_outputs)
280
 
 
281
  demo.launch()