broadfield-dev commited on
Commit
e8c80cb
Β·
verified Β·
1 Parent(s): 7fb9f49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -83
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  os.system("playwright install")
 
3
  import re
4
  import urllib.parse
5
  import asyncio
@@ -11,34 +12,25 @@ from playwright.async_api import async_playwright
11
 
12
  # --- 1. GLOBAL RESOURCES & CONFIGURATION ---
13
 
14
- # This dictionary will hold the long-lived Playwright and Browser objects
 
15
  PLAYWRIGHT_STATE: Dict = {}
16
 
17
- # EXPANDED: A comprehensive list of search engines
18
  SEARCH_ENGINES = {
19
- # Original
20
- "DuckDuckGo": "https://duckduckgo.com/html/?q={query}",
21
- "Google": "https://www.google.com/search?q={query}",
22
- "Bing": "https://www.bing.com/search?q={query}",
23
- "Brave": "https://search.brave.com/search?q={query}",
24
- "Ecosia": "https://www.ecosia.org/search?q={query}",
25
- # 10 More Added
26
- "Yahoo": "https://search.yahoo.com/search?p={query}",
27
- "Startpage": "https://www.startpage.com/sp/search?q={query}",
28
- "Qwant": "https://www.qwant.com/?q={query}",
29
- "Swisscows": "https://swisscows.com/web?query={query}",
30
- "You.com": "https://you.com/search?q={query}",
31
- "SearXNG": "https://searx.be/search?q={query}",
32
- "MetaGer": "https://metager.org/meta/meta.ger-en?eingabe={query}",
33
- "Yandex": "https://yandex.com/search/?text={query}",
34
- "Baidu": "https://www.baidu.com/s?wd={query}",
35
  "Perplexity": "https://www.perplexity.ai/search?q={query}"
36
  }
37
 
38
-
39
  # --- 2. ADVANCED HTML-TO-MARKDOWN CONVERTER (Unchanged) ---
40
  class HTML_TO_MARKDOWN_CONVERTER:
41
- # ... [The class code is identical to the previous version and remains unchanged] ...
42
  def __init__(self, soup: BeautifulSoup, base_url: str):
43
  self.soup = soup
44
  self.base_url = base_url
@@ -97,65 +89,69 @@ class HTML_TO_MARKDOWN_CONVERTER:
97
  return inner_md
98
 
99
 
100
- # --- 3. CORE API FUNCTION ---
101
-
102
- async def initialize_playwright():
103
- """Launches Playwright and browser instances if they don't already exist."""
104
- if "playwright" not in PLAYWRIGHT_STATE:
105
- print("πŸš€ First request received, starting up Playwright...")
106
- p = await async_playwright().start()
107
- PLAYWRIGHT_STATE["playwright"] = p
108
- PLAYWRIGHT_STATE["chromium"] = await p.chromium.launch(headless=True)
109
- PLAYWRIGHT_STATE["firefox"] = await p.firefox.launch(headless=True)
110
- PLAYWRIGHT_STATE["webkit"] = await p.webkit.launch(headless=True)
111
- print("βœ… Playwright and browsers are ready.")
112
 
113
  async def perform_web_browse(query: str, browser_name: str, search_engine: str):
114
  """
115
  A stateless function that takes a query, browser, and search engine,
116
  then returns the parsed content of the resulting page.
 
117
  """
118
- await initialize_playwright()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- # Determine if the query is a URL or a search term
121
  is_url = urllib.parse.urlparse(query).scheme in ['http', 'https']
122
  if is_url:
123
  url = query
124
  else:
125
  search_url_template = SEARCH_ENGINES.get(search_engine)
126
  if not search_url_template:
127
- return {"error": f"Invalid search engine: '{search_engine}'. Please choose from the provided list."}
128
  url = search_url_template.format(query=urllib.parse.quote_plus(query))
129
 
130
- browser_instance = PLAYWRIGHT_STATE.get(browser_name.lower())
131
- if not browser_instance:
132
- return {"error": f"Invalid browser: '{browser_name}'. Use 'chromium', 'firefox', or 'webkit'."}
133
-
134
  context = await browser_instance.new_context(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
135
  page = await context.new_page()
136
 
137
  try:
138
  print(f"Navigating to: {url} using {browser_name}...")
139
  await page.goto(url, wait_until='domcontentloaded', timeout=30000)
140
-
141
- final_url = page.url
142
- title = await page.title() or "No Title"
143
  print(f"Arrived at: {final_url}")
144
 
145
- html_content = await page.content()
146
- soup = BeautifulSoup(html_content, 'lxml')
147
-
148
  converter = HTML_TO_MARKDOWN_CONVERTER(soup, base_url=final_url)
149
  markdown_text = converter.convert()
150
 
151
  print("Content parsed successfully.")
152
- return {
153
- "status": "success",
154
- "query": query,
155
- "final_url": final_url,
156
- "page_title": title,
157
- "markdown_content": markdown_text,
158
- }
159
  except Exception as e:
160
  error_message = str(e).splitlines()[0]
161
  print(f"An error occurred: {error_message}")
@@ -166,42 +162,18 @@ async def perform_web_browse(query: str, browser_name: str, search_engine: str):
166
  print("Session context closed.")
167
 
168
 
169
- # --- 4. GRADIO INTERFACE & API LAUNCH ---
170
-
171
  with gr.Blocks(title="Web Browse API", theme=gr.themes.Soft()) as demo:
 
172
  gr.Markdown("# Web Browse API")
173
- gr.Markdown(
174
- "This interface exposes a stateless API endpoint (`/api/web_browse`) to fetch and parse web content."
175
- )
176
-
177
- query_input = gr.Textbox(
178
- label="URL or Search Query",
179
- placeholder="e.g., https://openai.com or 'history of artificial intelligence'"
180
- )
181
-
182
  with gr.Row():
183
- browser_input = gr.Dropdown(
184
- label="Browser",
185
- choices=["firefox", "chromium", "webkit"],
186
- value="firefox",
187
- scale=1
188
- )
189
- search_engine_input = gr.Dropdown(
190
- label="Search Engine (for non-URL queries)",
191
- choices=sorted(list(SEARCH_ENGINES.keys())),
192
- value="DuckDuckGo",
193
- scale=2
194
- )
195
-
196
  submit_button = gr.Button("Browse", variant="primary")
197
  output_json = gr.JSON(label="API Result")
198
-
199
- submit_button.click(
200
- fn=perform_web_browse,
201
- inputs=[query_input, browser_input, search_engine_input],
202
- outputs=output_json,
203
- api_name="web_browse" # Creates the POST /api/web_browse endpoint
204
- )
205
 
206
  if __name__ == "__main__":
207
  demo.launch()
 
1
  import os
2
  os.system("playwright install")
3
+ import os
4
  import re
5
  import urllib.parse
6
  import asyncio
 
12
 
13
  # --- 1. GLOBAL RESOURCES & CONFIGURATION ---
14
 
15
+ # This dictionary will hold the long-lived Playwright and Browser objects.
16
+ # It starts empty and browsers are added on-demand.
17
  PLAYWRIGHT_STATE: Dict = {}
18
 
19
+ # A comprehensive list of search engines
20
  SEARCH_ENGINES = {
21
+ "DuckDuckGo": "https://duckduckgo.com/html/?q={query}", "Google": "https://www.google.com/search?q={query}",
22
+ "Bing": "https://www.bing.com/search?q={query}", "Brave": "https://search.brave.com/search?q={query}",
23
+ "Ecosia": "https://www.ecosia.org/search?q={query}", "Yahoo": "https://search.yahoo.com/search?p={query}",
24
+ "Startpage": "https://www.startpage.com/sp/search?q={query}", "Qwant": "https://www.qwant.com/?q={query}",
25
+ "Swisscows": "https://swisscows.com/web?query={query}", "You.com": "https://you.com/search?q={query}",
26
+ "SearXNG": "https://searx.be/search?q={query}", "MetaGer": "https://metager.org/meta/meta.ger-en?eingabe={query}",
27
+ "Yandex": "https://yandex.com/search/?text={query}", "Baidu": "https://www.baidu.com/s?wd={query}",
 
 
 
 
 
 
 
 
 
28
  "Perplexity": "https://www.perplexity.ai/search?q={query}"
29
  }
30
 
 
31
  # --- 2. ADVANCED HTML-TO-MARKDOWN CONVERTER (Unchanged) ---
32
  class HTML_TO_MARKDOWN_CONVERTER:
33
+ # ... [The class code is identical and correct] ...
34
  def __init__(self, soup: BeautifulSoup, base_url: str):
35
  self.soup = soup
36
  self.base_url = base_url
 
89
  return inner_md
90
 
91
 
92
+ # --- 3. CORE API FUNCTION (WITH LAZY LOADING) ---
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  async def perform_web_browse(query: str, browser_name: str, search_engine: str):
95
  """
96
  A stateless function that takes a query, browser, and search engine,
97
  then returns the parsed content of the resulting page.
98
+ It launches and caches browsers on-demand.
99
  """
100
+ # Step 1: Initialize Playwright process itself if not already running.
101
+ if "playwright" not in PLAYWRIGHT_STATE:
102
+ print("πŸš€ First request received, starting Playwright process...")
103
+ PLAYWRIGHT_STATE["playwright"] = await async_playwright().start()
104
+ print("βœ… Playwright process is running.")
105
+
106
+ # Step 2: Check if the *specific browser requested* has been launched.
107
+ browser_key = browser_name.lower()
108
+ if browser_key not in PLAYWRIGHT_STATE:
109
+ print(f"πŸš€ Launching '{browser_key}' for the first time...")
110
+ try:
111
+ p = PLAYWRIGHT_STATE["playwright"]
112
+ if browser_key == 'firefox':
113
+ browser_instance = await p.firefox.launch(headless=True)
114
+ elif browser_key == 'chromium':
115
+ browser_instance = await p.chromium.launch(headless=True)
116
+ elif browser_key == 'webkit':
117
+ browser_instance = await p.webkit.launch(headless=True)
118
+ else:
119
+ raise ValueError(f"Invalid browser name: {browser_name}")
120
+ PLAYWRIGHT_STATE[browser_key] = browser_instance
121
+ print(f"βœ… '{browser_key}' is now running and cached.")
122
+ except Exception as e:
123
+ error_message = str(e).splitlines()[0]
124
+ print(f"❌ Failed to launch '{browser_key}': {error_message}")
125
+ return {"status": "error", "query": query, "error_message": f"Failed to launch browser '{browser_key}'. Your system might be missing dependencies. Error: {error_message}"}
126
+
127
+ browser_instance = PLAYWRIGHT_STATE[browser_key]
128
 
129
+ # Step 3: Determine URL
130
  is_url = urllib.parse.urlparse(query).scheme in ['http', 'https']
131
  if is_url:
132
  url = query
133
  else:
134
  search_url_template = SEARCH_ENGINES.get(search_engine)
135
  if not search_url_template:
136
+ return {"error": f"Invalid search engine: '{search_engine}'."}
137
  url = search_url_template.format(query=urllib.parse.quote_plus(query))
138
 
139
+ # Step 4: Create isolated context and browse
 
 
 
140
  context = await browser_instance.new_context(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
141
  page = await context.new_page()
142
 
143
  try:
144
  print(f"Navigating to: {url} using {browser_name}...")
145
  await page.goto(url, wait_until='domcontentloaded', timeout=30000)
146
+ final_url, title = page.url, await page.title() or "No Title"
 
 
147
  print(f"Arrived at: {final_url}")
148
 
149
+ soup = BeautifulSoup(await page.content(), 'lxml')
 
 
150
  converter = HTML_TO_MARKDOWN_CONVERTER(soup, base_url=final_url)
151
  markdown_text = converter.convert()
152
 
153
  print("Content parsed successfully.")
154
+ return {"status": "success", "query": query, "final_url": final_url, "page_title": title, "markdown_content": markdown_text}
 
 
 
 
 
 
155
  except Exception as e:
156
  error_message = str(e).splitlines()[0]
157
  print(f"An error occurred: {error_message}")
 
162
  print("Session context closed.")
163
 
164
 
165
+ # --- 4. GRADIO INTERFACE & API LAUNCH (Unchanged) ---
 
166
  with gr.Blocks(title="Web Browse API", theme=gr.themes.Soft()) as demo:
167
+ # ... UI definition is identical ...
168
  gr.Markdown("# Web Browse API")
169
+ gr.Markdown("This interface exposes a stateless API endpoint (`/api/web_browse`) to fetch and parse web content.")
170
+ query_input = gr.Textbox(label="URL or Search Query", placeholder="e.g., https://openai.com or 'history of artificial intelligence'")
 
 
 
 
 
 
 
171
  with gr.Row():
172
+ browser_input = gr.Dropdown(label="Browser", choices=["firefox", "chromium", "webkit"], value="firefox", scale=1)
173
+ search_engine_input = gr.Dropdown(label="Search Engine (for non-URL queries)", choices=sorted(list(SEARCH_ENGINES.keys())), value="DuckDuckGo", scale=2)
 
 
 
 
 
 
 
 
 
 
 
174
  submit_button = gr.Button("Browse", variant="primary")
175
  output_json = gr.JSON(label="API Result")
176
+ submit_button.click(fn=perform_web_browse, inputs=[query_input, browser_input, search_engine_input], outputs=output_json, api_name="web_browse")
 
 
 
 
 
 
177
 
178
  if __name__ == "__main__":
179
  demo.launch()