Trisha Tomy
commited on
Commit
·
90940ac
1
Parent(s):
6170d37
rolling back
Browse files
app.py
CHANGED
|
@@ -1,52 +1,35 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
# IMPORTANT: These two lines MUST be at the very top, before any other imports.
|
| 3 |
-
# They patch asyncio to work cooperatively with gevent workers.
|
| 4 |
import gevent.monkey
|
| 5 |
gevent.monkey.patch_all(asyncio=True)
|
| 6 |
-
|
| 7 |
import asyncio
|
| 8 |
from flask import Flask, request, jsonify
|
| 9 |
from proxy_lite import Runner, RunnerConfig
|
| 10 |
-
from proxy_lite.config import RecorderConfig # Needed for explicit instantiation
|
| 11 |
import os
|
| 12 |
import logging
|
| 13 |
|
| 14 |
-
# Configure logging for better visibility in Hugging Face Space logs
|
| 15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
app = Flask(__name__)
|
| 19 |
|
| 20 |
-
# Global runner instance. It will be initialized once per worker process/greenlet
|
| 21 |
-
# upon the first request to ensure correct event loop binding.
|
| 22 |
_runner = None
|
| 23 |
|
| 24 |
async def initialize_runner():
|
| 25 |
-
"""Initializes the Proxy-lite Runner asynchronously."""
|
| 26 |
global _runner
|
| 27 |
if _runner is None:
|
| 28 |
logger.info("Initializing Proxy-lite Runner...")
|
| 29 |
-
# Retrieve Hugging Face API Token from environment variables (set as Space Secret)
|
| 30 |
hf_api_token = os.environ.get("HF_API_TOKEN")
|
| 31 |
if not hf_api_token:
|
| 32 |
logger.error("HF_API_TOKEN environment variable not set. Cannot initialize Runner.")
|
| 33 |
raise ValueError("HF_API_TOKEN environment variable not set. Please set it as a Space secret.")
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# and passed as a Pydantic object, rather than relying on nested dict parsing.
|
| 38 |
-
recorder_config_instance = RecorderConfig(root_path="/tmp/proxy_lite_runs")
|
| 39 |
-
# --- END EXPLICIT RECORDER_CONFIG ---
|
| 40 |
-
|
| 41 |
-
# --- EXPLICITLY CREATE RUNNER_CONFIG ---
|
| 42 |
-
# Pass all configuration parameters as keyword arguments to the Pydantic model.
|
| 43 |
-
config = RunnerConfig(
|
| 44 |
-
environment={
|
| 45 |
"name": "webbrowser",
|
| 46 |
"homepage": "https://www.google.com",
|
| 47 |
-
"headless": True,
|
| 48 |
},
|
| 49 |
-
solver
|
| 50 |
"name": "simple",
|
| 51 |
"agent": {
|
| 52 |
"name": "proxy_lite",
|
|
@@ -57,36 +40,33 @@ async def initialize_runner():
|
|
| 57 |
"api_key": hf_api_token
|
| 58 |
}
|
| 59 |
}
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
)
|
| 63 |
-
# --- END EXPLICIT RUNNER_CONFIG ---
|
| 64 |
-
|
| 65 |
-
# Instantiate the Runner, passing the config as a keyword argument (Pydantic style)
|
| 66 |
-
_runner = Runner(config=config)
|
| 67 |
logger.info("Proxy-lite Runner initialized successfully.")
|
| 68 |
return _runner
|
| 69 |
|
|
|
|
| 70 |
def run_async_task(coro):
|
| 71 |
"""
|
| 72 |
Helper to run async coroutines in a synchronous context (like Flask routes).
|
| 73 |
-
Ensures an event loop exists
|
| 74 |
-
This addresses the "no current event loop" errors.
|
| 75 |
"""
|
| 76 |
try:
|
| 77 |
# Try to get the running loop (for current thread/greenlet)
|
| 78 |
loop = asyncio.get_running_loop()
|
| 79 |
except RuntimeError:
|
| 80 |
-
# If no loop is running, create a new one for this thread
|
| 81 |
loop = asyncio.new_event_loop()
|
| 82 |
asyncio.set_event_loop(loop)
|
| 83 |
-
|
| 84 |
# Run the coroutine until it completes
|
| 85 |
return loop.run_until_complete(coro)
|
|
|
|
|
|
|
| 86 |
|
| 87 |
@app.route('/run_proxy_task', methods=['POST'])
|
| 88 |
def run_proxy_task_endpoint():
|
| 89 |
-
"""API endpoint to receive a task and execute it with Proxy-lite."""
|
| 90 |
data = request.json
|
| 91 |
task = data.get('task')
|
| 92 |
if not task:
|
|
@@ -95,29 +75,23 @@ def run_proxy_task_endpoint():
|
|
| 95 |
|
| 96 |
logger.info(f"Received task for proxy-lite: '{task}'")
|
| 97 |
try:
|
| 98 |
-
# Ensure runner is initialized (and event loop handled) before use
|
| 99 |
runner = run_async_task(initialize_runner())
|
| 100 |
-
# Run the task using the proxy-lite runner
|
| 101 |
result = run_async_task(runner.run(task))
|
| 102 |
|
| 103 |
-
logger.info(f"Proxy-lite task completed. Output: {result[:200]}...")
|
| 104 |
-
# Return the result as a JSON response
|
| 105 |
return jsonify({"output": result})
|
| 106 |
except Exception as e:
|
| 107 |
-
logger.exception(f"Error processing task '{task}':")
|
| 108 |
return jsonify({"error": f"An error occurred: {str(e)}. Check logs for details."}), 500
|
| 109 |
|
| 110 |
@app.route('/')
|
| 111 |
def root():
|
| 112 |
-
"""Basic root endpoint for health check and user info."""
|
| 113 |
logger.info("Root endpoint accessed.")
|
| 114 |
return "Proxy-lite API is running. Send POST requests to /run_proxy_task with a 'task' in JSON body."
|
| 115 |
|
| 116 |
if __name__ == '__main__':
|
| 117 |
-
# During local development, ensure HF_API_TOKEN is set manually
|
| 118 |
if not os.environ.get("HF_API_TOKEN"):
|
| 119 |
logger.error("HF_API_TOKEN environment variable is not set. Please set it for local testing.")
|
| 120 |
exit(1)
|
| 121 |
logger.info("Starting Flask development server on 0.0.0.0:7860...")
|
| 122 |
-
|
| 123 |
-
app.run(host='0.0.0.0', port=7860, debug=True) # debug=True for local testing, disable for production
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gevent.monkey
|
| 2 |
gevent.monkey.patch_all(asyncio=True)
|
| 3 |
+
# app.py
|
| 4 |
import asyncio
|
| 5 |
from flask import Flask, request, jsonify
|
| 6 |
from proxy_lite import Runner, RunnerConfig
|
|
|
|
| 7 |
import os
|
| 8 |
import logging
|
| 9 |
|
|
|
|
| 10 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
|
|
|
|
|
|
|
| 15 |
_runner = None
|
| 16 |
|
| 17 |
async def initialize_runner():
|
|
|
|
| 18 |
global _runner
|
| 19 |
if _runner is None:
|
| 20 |
logger.info("Initializing Proxy-lite Runner...")
|
|
|
|
| 21 |
hf_api_token = os.environ.get("HF_API_TOKEN")
|
| 22 |
if not hf_api_token:
|
| 23 |
logger.error("HF_API_TOKEN environment variable not set. Cannot initialize Runner.")
|
| 24 |
raise ValueError("HF_API_TOKEN environment variable not set. Please set it as a Space secret.")
|
| 25 |
|
| 26 |
+
config = RunnerConfig.from_dict({
|
| 27 |
+
"environment": {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
"name": "webbrowser",
|
| 29 |
"homepage": "https://www.google.com",
|
| 30 |
+
"headless": True,
|
| 31 |
},
|
| 32 |
+
"solver": {
|
| 33 |
"name": "simple",
|
| 34 |
"agent": {
|
| 35 |
"name": "proxy_lite",
|
|
|
|
| 40 |
"api_key": hf_api_token
|
| 41 |
}
|
| 42 |
}
|
| 43 |
+
}
|
| 44 |
+
})
|
| 45 |
+
_runner = Runner(config)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
logger.info("Proxy-lite Runner initialized successfully.")
|
| 47 |
return _runner
|
| 48 |
|
| 49 |
+
# --- MODIFIED run_async_task FUNCTION ---
|
| 50 |
def run_async_task(coro):
|
| 51 |
"""
|
| 52 |
Helper to run async coroutines in a synchronous context (like Flask routes).
|
| 53 |
+
Ensures an event loop exists and runs the coroutine.
|
|
|
|
| 54 |
"""
|
| 55 |
try:
|
| 56 |
# Try to get the running loop (for current thread/greenlet)
|
| 57 |
loop = asyncio.get_running_loop()
|
| 58 |
except RuntimeError:
|
| 59 |
+
# If no loop is running, create a new one for this thread
|
| 60 |
loop = asyncio.new_event_loop()
|
| 61 |
asyncio.set_event_loop(loop)
|
| 62 |
+
|
| 63 |
# Run the coroutine until it completes
|
| 64 |
return loop.run_until_complete(coro)
|
| 65 |
+
# --- END MODIFIED run_async_task FUNCTION ---
|
| 66 |
+
|
| 67 |
|
| 68 |
@app.route('/run_proxy_task', methods=['POST'])
|
| 69 |
def run_proxy_task_endpoint():
|
|
|
|
| 70 |
data = request.json
|
| 71 |
task = data.get('task')
|
| 72 |
if not task:
|
|
|
|
| 75 |
|
| 76 |
logger.info(f"Received task for proxy-lite: '{task}'")
|
| 77 |
try:
|
|
|
|
| 78 |
runner = run_async_task(initialize_runner())
|
|
|
|
| 79 |
result = run_async_task(runner.run(task))
|
| 80 |
|
| 81 |
+
logger.info(f"Proxy-lite task completed. Output: {result[:200]}...")
|
|
|
|
| 82 |
return jsonify({"output": result})
|
| 83 |
except Exception as e:
|
| 84 |
+
logger.exception(f"Error processing task '{task}':")
|
| 85 |
return jsonify({"error": f"An error occurred: {str(e)}. Check logs for details."}), 500
|
| 86 |
|
| 87 |
@app.route('/')
|
| 88 |
def root():
|
|
|
|
| 89 |
logger.info("Root endpoint accessed.")
|
| 90 |
return "Proxy-lite API is running. Send POST requests to /run_proxy_task with a 'task' in JSON body."
|
| 91 |
|
| 92 |
if __name__ == '__main__':
|
|
|
|
| 93 |
if not os.environ.get("HF_API_TOKEN"):
|
| 94 |
logger.error("HF_API_TOKEN environment variable is not set. Please set it for local testing.")
|
| 95 |
exit(1)
|
| 96 |
logger.info("Starting Flask development server on 0.0.0.0:7860...")
|
| 97 |
+
app.run(host='0.0.0.0', port=7860, debug=True)
|
|
|