Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,16 +6,20 @@ from typing import Dict, Optional
|
|
| 6 |
from itertools import cycle
|
| 7 |
|
| 8 |
# Install playwright if not present
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
from flask import Flask, request, jsonify
|
| 12 |
from bs4 import BeautifulSoup, NavigableString
|
| 13 |
-
from playwright.async_api import async_playwright
|
| 14 |
|
| 15 |
# --- Flask App Initialization ---
|
| 16 |
app = Flask(__name__)
|
| 17 |
|
| 18 |
-
# --- Credential and State Management (
|
| 19 |
class CredentialRevolver:
|
| 20 |
def __init__(self, proxy_string: str):
|
| 21 |
self.proxies = self._parse_proxies(proxy_string)
|
|
@@ -43,6 +47,7 @@ class CredentialRevolver:
|
|
| 43 |
return len(self.proxies)
|
| 44 |
|
| 45 |
PLAYWRIGHT_STATE: Dict = {}
|
|
|
|
| 46 |
REVOLVER = CredentialRevolver(os.getenv("PROXY_LIST", ""))
|
| 47 |
|
| 48 |
SEARCH_ENGINES = {
|
|
@@ -121,24 +126,25 @@ async def perform_web_browse(action: str, query: str, browser_name: str, search_
|
|
| 121 |
if "playwright" not in PLAYWRIGHT_STATE:
|
| 122 |
PLAYWRIGHT_STATE["playwright"] = await async_playwright().start()
|
| 123 |
|
|
|
|
| 124 |
if browser_key not in PLAYWRIGHT_STATE:
|
| 125 |
try:
|
| 126 |
p = PLAYWRIGHT_STATE["playwright"]
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
| 131 |
PLAYWRIGHT_STATE[browser_key] = browser_instance
|
| 132 |
except Exception as e:
|
| 133 |
return {"status": "error", "query": query, "error_message": f"Failed to launch '{browser_key}'. Error: {str(e).splitlines()[0]}"}
|
| 134 |
|
| 135 |
browser_instance = PLAYWRIGHT_STATE[browser_key]
|
| 136 |
|
| 137 |
-
if action == "Scrape":
|
| 138 |
-
|
| 139 |
-
url = f"http://{query}"
|
| 140 |
-
else:
|
| 141 |
-
url = query
|
| 142 |
else: # action == "Search"
|
| 143 |
url_template = SEARCH_ENGINES.get(search_engine_name)
|
| 144 |
if not url_template:
|
|
@@ -156,7 +162,6 @@ async def perform_web_browse(action: str, query: str, browser_name: str, search_
|
|
| 156 |
|
| 157 |
try:
|
| 158 |
response = await page.goto(url, wait_until='domcontentloaded', timeout=25000)
|
| 159 |
-
|
| 160 |
html_content = await page.content()
|
| 161 |
|
| 162 |
if any(phrase in html_content for phrase in ["unusual traffic", "CAPTCHA", "are you human", "not a robot"]):
|
|
@@ -178,27 +183,31 @@ async def perform_web_browse(action: str, query: str, browser_name: str, search_
|
|
| 178 |
if 'page' in locals() and not page.is_closed(): await page.close()
|
| 179 |
if 'context' in locals(): await context.close()
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
# --- API Endpoint Definition ---
|
| 183 |
@app.route('/web_browse', methods=['POST'])
|
| 184 |
def web_browse():
|
| 185 |
"""
|
| 186 |
API endpoint to perform a web search or scrape a URL.
|
| 187 |
-
This endpoint expects a JSON payload with the following parameters:
|
| 188 |
-
- "action": "Search" or "Scrape URL" (required)
|
| 189 |
-
- "query": The search term or the URL to scrape (required)
|
| 190 |
-
- "browser_name": "firefox", "chromium", or "webkit" (optional, default: "firefox")
|
| 191 |
-
- "search_engine_name": Name of the search engine (optional, default: "DuckDuckGo")
|
| 192 |
-
|
| 193 |
-
Example usage with curl:
|
| 194 |
-
curl -X POST http://127.0.0.1:5000/web_browse \
|
| 195 |
-
-H "Content-Type: application/json" \
|
| 196 |
-
-d '{
|
| 197 |
-
"action": "Search",
|
| 198 |
-
"query": "latest news on AI",
|
| 199 |
-
"browser_name": "firefox",
|
| 200 |
-
"search_engine_name": "Google"
|
| 201 |
-
}'
|
| 202 |
"""
|
| 203 |
if not request.is_json:
|
| 204 |
return jsonify({"status": "error", "error_message": "Invalid input: payload must be JSON"}), 400
|
|
@@ -206,8 +215,8 @@ def web_browse():
|
|
| 206 |
data = request.get_json()
|
| 207 |
action = data.get('action')
|
| 208 |
query = data.get('query')
|
| 209 |
-
browser_name = data.get('browser_name', 'firefox')
|
| 210 |
-
search_engine_name = data.get('search_engine_name', 'DuckDuckGo')
|
| 211 |
|
| 212 |
if not action or not query:
|
| 213 |
return jsonify({"status": "error", "error_message": "Missing required parameters: 'action' and 'query' are mandatory."}), 400
|
|
@@ -215,17 +224,20 @@ def web_browse():
|
|
| 215 |
if action not in ["Search", "Scrape URL"]:
|
| 216 |
return jsonify({"status": "error", "error_message": "Invalid 'action'. Must be 'Search' or 'Scrape URL'."}), 400
|
| 217 |
|
| 218 |
-
# Run the async function in the current event loop
|
| 219 |
try:
|
|
|
|
| 220 |
result = asyncio.run(perform_web_browse(action, query, browser_name, search_engine_name))
|
| 221 |
-
|
| 222 |
-
return jsonify(result),
|
| 223 |
except Exception as e:
|
|
|
|
| 224 |
return jsonify({"status": "error", "query": query, "error_message": f"An unexpected server error occurred: {str(e)}"}), 500
|
| 225 |
|
| 226 |
-
|
| 227 |
# --- Main Application Runner ---
|
| 228 |
if __name__ == "__main__":
|
| 229 |
-
|
| 230 |
-
print("
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from itertools import cycle
|
| 7 |
|
| 8 |
# Install playwright if not present
|
| 9 |
+
# This is often needed in environments like HF Spaces
|
| 10 |
+
if os.getenv("PLAYWRIGHT_INSTALL_RUN", "false").lower() != "true":
|
| 11 |
+
os.system("playwright install --with-deps")
|
| 12 |
+
os.environ["PLAYWRIGHT_INSTALL_RUN"] = "true"
|
| 13 |
+
|
| 14 |
|
| 15 |
from flask import Flask, request, jsonify
|
| 16 |
from bs4 import BeautifulSoup, NavigableString
|
| 17 |
+
from playwright.async_api import async_playwright
|
| 18 |
|
| 19 |
# --- Flask App Initialization ---
|
| 20 |
app = Flask(__name__)
|
| 21 |
|
| 22 |
+
# --- Credential and State Management (unchanged) ---
|
| 23 |
class CredentialRevolver:
|
| 24 |
def __init__(self, proxy_string: str):
|
| 25 |
self.proxies = self._parse_proxies(proxy_string)
|
|
|
|
| 47 |
return len(self.proxies)
|
| 48 |
|
| 49 |
PLAYWRIGHT_STATE: Dict = {}
|
| 50 |
+
# For Hugging Face Spaces, it's better to use Space secrets for PROXY_LIST
|
| 51 |
REVOLVER = CredentialRevolver(os.getenv("PROXY_LIST", ""))
|
| 52 |
|
| 53 |
SEARCH_ENGINES = {
|
|
|
|
| 126 |
if "playwright" not in PLAYWRIGHT_STATE:
|
| 127 |
PLAYWRIGHT_STATE["playwright"] = await async_playwright().start()
|
| 128 |
|
| 129 |
+
# Use a persistent browser instance to avoid re-launching on every call
|
| 130 |
if browser_key not in PLAYWRIGHT_STATE:
|
| 131 |
try:
|
| 132 |
p = PLAYWRIGHT_STATE["playwright"]
|
| 133 |
+
browser_map = {'firefox': p.firefox, 'chromium': p.chromium, 'webkit': p.webkit}
|
| 134 |
+
browser_launcher = browser_map.get(browser_key)
|
| 135 |
+
if not browser_launcher:
|
| 136 |
+
raise ValueError(f"Invalid browser name: {browser_name}")
|
| 137 |
+
# In some containerized environments, --no-sandbox is needed for chromium
|
| 138 |
+
launch_args = ['--no-sandbox'] if browser_key == 'chromium' else []
|
| 139 |
+
browser_instance = await browser_launcher.launch(headless=True, args=launch_args)
|
| 140 |
PLAYWRIGHT_STATE[browser_key] = browser_instance
|
| 141 |
except Exception as e:
|
| 142 |
return {"status": "error", "query": query, "error_message": f"Failed to launch '{browser_key}'. Error: {str(e).splitlines()[0]}"}
|
| 143 |
|
| 144 |
browser_instance = PLAYWRIGHT_STATE[browser_key]
|
| 145 |
|
| 146 |
+
if action == "Scrape URL":
|
| 147 |
+
url = query if query.startswith(('http://', 'https://')) else f"http://{query}"
|
|
|
|
|
|
|
|
|
|
| 148 |
else: # action == "Search"
|
| 149 |
url_template = SEARCH_ENGINES.get(search_engine_name)
|
| 150 |
if not url_template:
|
|
|
|
| 162 |
|
| 163 |
try:
|
| 164 |
response = await page.goto(url, wait_until='domcontentloaded', timeout=25000)
|
|
|
|
| 165 |
html_content = await page.content()
|
| 166 |
|
| 167 |
if any(phrase in html_content for phrase in ["unusual traffic", "CAPTCHA", "are you human", "not a robot"]):
|
|
|
|
| 183 |
if 'page' in locals() and not page.is_closed(): await page.close()
|
| 184 |
if 'context' in locals(): await context.close()
|
| 185 |
|
| 186 |
+
# --- API Endpoint Definitions ---
|
| 187 |
+
|
| 188 |
+
@app.route('/', methods=['GET'])
|
| 189 |
+
def index():
|
| 190 |
+
"""
|
| 191 |
+
Root endpoint to provide API status and usage instructions.
|
| 192 |
+
"""
|
| 193 |
+
return jsonify({
|
| 194 |
+
"status": "online",
|
| 195 |
+
"message": "Welcome to the Web Browse API!",
|
| 196 |
+
"api_endpoint": "/web_browse",
|
| 197 |
+
"instructions": "Send a POST request to /web_browse with a JSON payload to use the service.",
|
| 198 |
+
"payload_format": {
|
| 199 |
+
"action": "string (required: 'Search' or 'Scrape URL')",
|
| 200 |
+
"query": "string (required: a search term or a full URL)",
|
| 201 |
+
"browser_name": "string (optional, default: 'firefox'; options: 'firefox', 'chromium', 'webkit')",
|
| 202 |
+
"search_engine_name": "string (optional, default: 'DuckDuckGo'; see code for all options)"
|
| 203 |
+
},
|
| 204 |
+
"example_curl": """curl -X POST YOUR_SPACE_URL/web_browse -H "Content-Type: application/json" -d '{"action": "Search", "query": "latest news on AI"}'"""
|
| 205 |
+
})
|
| 206 |
|
|
|
|
| 207 |
@app.route('/web_browse', methods=['POST'])
|
| 208 |
def web_browse():
|
| 209 |
"""
|
| 210 |
API endpoint to perform a web search or scrape a URL.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
"""
|
| 212 |
if not request.is_json:
|
| 213 |
return jsonify({"status": "error", "error_message": "Invalid input: payload must be JSON"}), 400
|
|
|
|
| 215 |
data = request.get_json()
|
| 216 |
action = data.get('action')
|
| 217 |
query = data.get('query')
|
| 218 |
+
browser_name = data.get('browser_name', 'firefox')
|
| 219 |
+
search_engine_name = data.get('search_engine_name', 'DuckDuckGo')
|
| 220 |
|
| 221 |
if not action or not query:
|
| 222 |
return jsonify({"status": "error", "error_message": "Missing required parameters: 'action' and 'query' are mandatory."}), 400
|
|
|
|
| 224 |
if action not in ["Search", "Scrape URL"]:
|
| 225 |
return jsonify({"status": "error", "error_message": "Invalid 'action'. Must be 'Search' or 'Scrape URL'."}), 400
|
| 226 |
|
|
|
|
| 227 |
try:
|
| 228 |
+
# Use asyncio.run() to execute the async function within the sync Flask route
|
| 229 |
result = asyncio.run(perform_web_browse(action, query, browser_name, search_engine_name))
|
| 230 |
+
response_status_code = 200 if result.get("status") == "success" else 500
|
| 231 |
+
return jsonify(result), response_status_code
|
| 232 |
except Exception as e:
|
| 233 |
+
app.logger.error(f"An unexpected server error occurred: {str(e)}")
|
| 234 |
return jsonify({"status": "error", "query": query, "error_message": f"An unexpected server error occurred: {str(e)}"}), 500
|
| 235 |
|
|
|
|
| 236 |
# --- Main Application Runner ---
|
| 237 |
if __name__ == "__main__":
|
| 238 |
+
port = int(os.environ.get("PORT", 7860))
|
| 239 |
+
print(f"Flask server starting on port {port}... {REVOLVER.count()} proxies loaded.")
|
| 240 |
+
print(f"API instructions available at GET http://0.0.0.0:{port}/")
|
| 241 |
+
print(f"API endpoint available at POST http://0.0.0.0:{port}/web_browse")
|
| 242 |
+
# For production, consider using a more robust WSGI server like Gunicorn or Waitress
|
| 243 |
+
app.run(host='0.0.0.0', port=port)
|