Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,6 +4,7 @@ import urllib.parse
|
|
| 4 |
import asyncio
|
| 5 |
from typing import Dict, Optional
|
| 6 |
from itertools import cycle
|
|
|
|
| 7 |
|
| 8 |
# Install playwright if not present
|
| 9 |
if os.getenv("PLAYWRIGHT_INSTALL_RUN", "false").lower() != "true":
|
|
@@ -42,18 +43,13 @@ class CredentialRevolver:
|
|
| 42 |
def count(self) -> int:
|
| 43 |
return len(self.proxies)
|
| 44 |
|
| 45 |
-
# <<< REMOVED >>> The global PLAYWRIGHT_STATE is removed to prevent event loop conflicts.
|
| 46 |
-
# PLAYWRIGHT_STATE: Dict = {}
|
| 47 |
REVOLVER = CredentialRevolver(os.getenv("PROXY_LIST", ""))
|
| 48 |
|
| 49 |
SEARCH_ENGINES = {
|
| 50 |
-
# ... (this dictionary is unchanged)
|
| 51 |
"Google": "https://www.google.com/search?q={query}&hl=en", "DuckDuckGo": "https://duckduckgo.com/html/?q={query}", "Bing": "https://www.bing.com/search?q={query}", "Brave": "https://search.brave.com/search?q={query}", "Ecosia": "https://www.ecosia.org/search?q={query}", "Yahoo": "https://search.yahoo.com/search?p={query}", "Startpage": "https://www.startpage.com/sp/search?q={query}", "Qwant": "https://www.qwant.com/?q={query}", "Swisscows": "https://swisscows.com/web?query={query}", "You.com": "https://you.com/search?q={query}", "SearXNG": "https://searx.be/search?q={query}", "MetaGer": "https://metager.org/meta/meta.ger-en?eingabe={query}", "Yandex": "https://yandex.com/search/?text={query}", "Baidu": "https://www.baidu.com/s?wd={query}", "Perplexity": "https://www.perplexity.ai/search?q={query}",
|
| 52 |
}
|
| 53 |
|
| 54 |
-
# --- HTML to Markdown Conversion (unchanged) ---
|
| 55 |
class HTML_TO_MARKDOWN_CONVERTER:
|
| 56 |
-
# ... (this class is unchanged)
|
| 57 |
def __init__(self, soup: BeautifulSoup, base_url: str): self.soup = soup; self.base_url = base_url
|
| 58 |
def _cleanup_html(self): selectors_to_remove = ['nav', 'footer', 'header', 'aside', 'form', 'script', 'style', 'svg', 'button', 'input', 'textarea', '[role="navigation"]', '[role="search"]', '[id*="comment"]', '[class*="comment-"]', '[id*="sidebar"]', '[class*="sidebar"]', '[id*="related"]', '[class*="related"]', '[id*="share"]', '[class*="share"]', '[id*="social"]', '[class*="social"]', '[id*="cookie"]', '[class*="cookie"]', '[aria-hidden="true"]']; [element.decompose() for selector in selectors_to_remove for element in self.soup.select(selector)]
|
| 59 |
def convert(self): self._cleanup_html(); content_node = self.soup.find('main') or self.soup.find('article') or self.soup.find('body'); return re.sub(r'\n{3,}', '\n\n', self._process_node(content_node)).strip() if content_node else ""
|
|
@@ -83,9 +79,7 @@ class HTML_TO_MARKDOWN_CONVERTER:
|
|
| 83 |
async def perform_web_browse(action: str, query: str, browser_name: str, search_engine: str):
|
| 84 |
playwright = None
|
| 85 |
browser = None
|
| 86 |
-
# <<< CHANGE >>> Use a try/finally block to ensure resources are always cleaned up.
|
| 87 |
try:
|
| 88 |
-
# <<< CHANGE >>> Start Playwright inside the function.
|
| 89 |
playwright = await async_playwright().start()
|
| 90 |
|
| 91 |
browser_key = browser_name.lower()
|
|
@@ -136,12 +130,10 @@ async def perform_web_browse(action: str, query: str, browser_name: str, search_
|
|
| 136 |
if 'page' in locals() and not page.is_closed(): await page.close()
|
| 137 |
if 'context' in locals(): await context.close()
|
| 138 |
|
| 139 |
-
# <<< CHANGE >>> This block now handles errors during browser launch as well.
|
| 140 |
except Exception as e:
|
| 141 |
app.logger.error(f"A critical error occurred in perform_web_browse: {e}", exc_info=True)
|
| 142 |
return {"status": "error", "query": query, "error_message": f"Failed to initialize browser resources: {str(e).splitlines()[0]}"}
|
| 143 |
|
| 144 |
-
# <<< CHANGE >>> Ensure browser and playwright are always closed down.
|
| 145 |
finally:
|
| 146 |
if browser:
|
| 147 |
await browser.close()
|
|
@@ -149,15 +141,12 @@ async def perform_web_browse(action: str, query: str, browser_name: str, search_
|
|
| 149 |
await playwright.stop()
|
| 150 |
|
| 151 |
|
| 152 |
-
# --- API Endpoint Definitions (unchanged) ---
|
| 153 |
@app.route('/', methods=['GET'])
|
| 154 |
def index():
|
| 155 |
-
|
| 156 |
-
return jsonify({ "status": "online", "message": "Welcome to the Web Browse API!", "api_endpoint": "/web_browse", "instructions": "Send a POST request to /web_browse with a JSON payload to use the service.", "payload_format": { "action": "string (required: 'Search' or 'Scrape URL')", "query": "string (required: a search term or a full URL)", "browser": "string (optional, default: 'firefox'; options: 'firefox', 'chromium', 'webkit')", "search_engine": "string (optional, default: 'DuckDuckGo'; see code for all options)" }, "example_curl": """curl -X POST YOUR_SPACE_URL/web_browse -H "Content-Type: application/json" -d '{"action": "Search", "query": "latest news on AI", "browser": "webkit"}'""" })
|
| 157 |
|
| 158 |
@app.route('/web_browse', methods=['POST'])
|
| 159 |
def web_browse():
|
| 160 |
-
# ... (this function is unchanged)
|
| 161 |
if not request.is_json: return jsonify({"status": "error", "error_message": "Invalid input: payload must be JSON"}), 400
|
| 162 |
data = request.get_json()
|
| 163 |
action = data.get('action')
|
|
@@ -174,7 +163,6 @@ def web_browse():
|
|
| 174 |
app.logger.error(f"An unexpected server error occurred: {e}", exc_info=True)
|
| 175 |
return jsonify({"status": "error", "query": query, "error_message": f"An unexpected server error occurred: {str(e)}"}), 500
|
| 176 |
|
| 177 |
-
# --- Main Application Runner (unchanged) ---
|
| 178 |
if __name__ == "__main__":
|
| 179 |
port = int(os.environ.get("PORT", 7860))
|
| 180 |
print(f"Flask server starting on port {port}... {REVOLVER.count()} proxies loaded.")
|
|
|
|
| 4 |
import asyncio
|
| 5 |
from typing import Dict, Optional
|
| 6 |
from itertools import cycle
|
| 7 |
+
import json
|
| 8 |
|
| 9 |
# Install playwright if not present
|
| 10 |
if os.getenv("PLAYWRIGHT_INSTALL_RUN", "false").lower() != "true":
|
|
|
|
| 43 |
def count(self) -> int:
|
| 44 |
return len(self.proxies)
|
| 45 |
|
|
|
|
|
|
|
| 46 |
REVOLVER = CredentialRevolver(os.getenv("PROXY_LIST", ""))
|
| 47 |
|
| 48 |
SEARCH_ENGINES = {
|
|
|
|
| 49 |
"Google": "https://www.google.com/search?q={query}&hl=en", "DuckDuckGo": "https://duckduckgo.com/html/?q={query}", "Bing": "https://www.bing.com/search?q={query}", "Brave": "https://search.brave.com/search?q={query}", "Ecosia": "https://www.ecosia.org/search?q={query}", "Yahoo": "https://search.yahoo.com/search?p={query}", "Startpage": "https://www.startpage.com/sp/search?q={query}", "Qwant": "https://www.qwant.com/?q={query}", "Swisscows": "https://swisscows.com/web?query={query}", "You.com": "https://you.com/search?q={query}", "SearXNG": "https://searx.be/search?q={query}", "MetaGer": "https://metager.org/meta/meta.ger-en?eingabe={query}", "Yandex": "https://yandex.com/search/?text={query}", "Baidu": "https://www.baidu.com/s?wd={query}", "Perplexity": "https://www.perplexity.ai/search?q={query}",
|
| 50 |
}
|
| 51 |
|
|
|
|
| 52 |
class HTML_TO_MARKDOWN_CONVERTER:
|
|
|
|
| 53 |
def __init__(self, soup: BeautifulSoup, base_url: str): self.soup = soup; self.base_url = base_url
|
| 54 |
def _cleanup_html(self): selectors_to_remove = ['nav', 'footer', 'header', 'aside', 'form', 'script', 'style', 'svg', 'button', 'input', 'textarea', '[role="navigation"]', '[role="search"]', '[id*="comment"]', '[class*="comment-"]', '[id*="sidebar"]', '[class*="sidebar"]', '[id*="related"]', '[class*="related"]', '[id*="share"]', '[class*="share"]', '[id*="social"]', '[class*="social"]', '[id*="cookie"]', '[class*="cookie"]', '[aria-hidden="true"]']; [element.decompose() for selector in selectors_to_remove for element in self.soup.select(selector)]
|
| 55 |
def convert(self): self._cleanup_html(); content_node = self.soup.find('main') or self.soup.find('article') or self.soup.find('body'); return re.sub(r'\n{3,}', '\n\n', self._process_node(content_node)).strip() if content_node else ""
|
|
|
|
| 79 |
async def perform_web_browse(action: str, query: str, browser_name: str, search_engine: str):
|
| 80 |
playwright = None
|
| 81 |
browser = None
|
|
|
|
| 82 |
try:
|
|
|
|
| 83 |
playwright = await async_playwright().start()
|
| 84 |
|
| 85 |
browser_key = browser_name.lower()
|
|
|
|
| 130 |
if 'page' in locals() and not page.is_closed(): await page.close()
|
| 131 |
if 'context' in locals(): await context.close()
|
| 132 |
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
app.logger.error(f"A critical error occurred in perform_web_browse: {e}", exc_info=True)
|
| 135 |
return {"status": "error", "query": query, "error_message": f"Failed to initialize browser resources: {str(e).splitlines()[0]}"}
|
| 136 |
|
|
|
|
| 137 |
finally:
|
| 138 |
if browser:
|
| 139 |
await browser.close()
|
|
|
|
| 141 |
await playwright.stop()
|
| 142 |
|
| 143 |
|
|
|
|
| 144 |
@app.route('/', methods=['GET'])
|
| 145 |
def index():
|
| 146 |
+
return json.dumps({ "status": "online", "message": "Welcome to the Web Browse API!", "api_endpoint": "/web_browse", "instructions": "Send a POST request to /web_browse with a JSON payload to use the service.", "payload_format": { "action": "string (required: 'Search' or 'Scrape URL')", "query": "string (required: a search term or a full URL)", "browser": "string (optional, default: 'firefox'; options: 'firefox', 'chromium', 'webkit')", "search_engine": "string (optional, default: 'DuckDuckGo'; see code for all options)" }, "example_curl": """curl -X POST YOUR_SPACE_URL/web_browse -H "Content-Type: application/json" -d '{"action": "Search", "query": "latest news on AI", "browser": "webkit"}'""" })
|
|
|
|
| 147 |
|
| 148 |
@app.route('/web_browse', methods=['POST'])
|
| 149 |
def web_browse():
|
|
|
|
| 150 |
if not request.is_json: return jsonify({"status": "error", "error_message": "Invalid input: payload must be JSON"}), 400
|
| 151 |
data = request.get_json()
|
| 152 |
action = data.get('action')
|
|
|
|
| 163 |
app.logger.error(f"An unexpected server error occurred: {e}", exc_info=True)
|
| 164 |
return jsonify({"status": "error", "query": query, "error_message": f"An unexpected server error occurred: {str(e)}"}), 500
|
| 165 |
|
|
|
|
| 166 |
if __name__ == "__main__":
|
| 167 |
port = int(os.environ.get("PORT", 7860))
|
| 168 |
print(f"Flask server starting on port {port}... {REVOLVER.count()} proxies loaded.")
|