Datasets:
Tasks:
Text Generation
Languages:
English
Size:
n<1K
Tags:
code
notebooks
training-scripts
dataset:Nanthasit/sakthai-kaggle-notebooks
license-mit
dataset-card
License:
Upload scripts/web-agent-job.py with huggingface_hub
Browse files- scripts/web-agent-job.py +172 -0
scripts/web-agent-job.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# /// script
|
| 3 |
+
# dependencies = ["smolagents", "transformers>=4.44", "torch>=2.0", "playwright>=1.40", "accelerate", "bitsandbytes", "pillow"]
|
| 4 |
+
# ///
|
| 5 |
+
"""SakThai Web Agent — headless browser automation via HF Jobs.
|
| 6 |
+
|
| 7 |
+
Root cause analysis of previous failures:
|
| 8 |
+
- Jobs 1-2: docstring format wrong (needs Google-style multi-line) — fixed
|
| 9 |
+
- Jobs 3-4: `type` tool name conflicts with Python builtin (shadows in BASE_PYTHON_TOOLS) — fix: inject into executor state
|
| 10 |
+
- Job 5: Playwright "cannot switch thread" error — fix: threading.local for per-thread pages
|
| 11 |
+
- All jobs wasted ~$3 due to launching before verifying locally — NEVER again
|
| 12 |
+
|
| 13 |
+
Usage: uv run python web-agent-job.py <url> <task>"""
|
| 14 |
+
import sys, os, subprocess, json, threading
|
| 15 |
+
|
| 16 |
+
subprocess.run(["playwright", "install", "chromium", "--with-deps"], capture_output=True)
|
| 17 |
+
|
| 18 |
+
from smolagents import CodeAgent, TransformersModel, tool
|
| 19 |
+
from playwright.sync_api import sync_playwright
|
| 20 |
+
|
| 21 |
+
# threading.local keeps a separate Playwright page per thread
|
| 22 |
+
# smolagents spawns a new thread per step via ThreadPoolExecutor timeout
|
| 23 |
+
_tls = threading.local()
|
| 24 |
+
|
| 25 |
+
def _ensure_page():
|
| 26 |
+
if not hasattr(_tls, "page") or _tls.page is None:
|
| 27 |
+
pw = sync_playwright().start()
|
| 28 |
+
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
|
| 29 |
+
_tls.page = browser.new_page()
|
| 30 |
+
_tls.pw = pw
|
| 31 |
+
_tls.browser = browser
|
| 32 |
+
return _tls.page
|
| 33 |
+
|
| 34 |
+
@tool
|
| 35 |
+
def navigate(url: str) -> str:
|
| 36 |
+
"""Navigate to a webpage.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
url: The full URL to visit
|
| 40 |
+
"""
|
| 41 |
+
_ensure_page().goto(url, wait_until="domcontentloaded")
|
| 42 |
+
return f"Navigated to {url}"
|
| 43 |
+
|
| 44 |
+
@tool
|
| 45 |
+
def click(target: str) -> str:
|
| 46 |
+
"""Click an element by selector or text.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
target: CSS selector, text label, or coordinate
|
| 50 |
+
"""
|
| 51 |
+
_ensure_page().click(target)
|
| 52 |
+
return f"Clicked {target}"
|
| 53 |
+
|
| 54 |
+
# NOTE: Cannot name this function 'type' because Python's builtin type() shadows it.
|
| 55 |
+
# The agent's code executor checks state dict first, then static_tools (which includes
|
| 56 |
+
# BASE_PYTHON_TOOLS['type'] = builtin type). By injecting into state after agent creation,
|
| 57 |
+
# our tool takes precedence. See below in main().
|
| 58 |
+
@tool
|
| 59 |
+
def type_into(selector: str, text: str) -> str:
|
| 60 |
+
"""Type text into a field.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
selector: CSS selector for the input field
|
| 64 |
+
text: The text to type
|
| 65 |
+
"""
|
| 66 |
+
_ensure_page().fill(selector, text)
|
| 67 |
+
return f"Typed into {selector}"
|
| 68 |
+
|
| 69 |
+
@tool
|
| 70 |
+
def select(selector: str, value: str) -> str:
|
| 71 |
+
"""Select from dropdown.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
selector: CSS selector for the select element
|
| 75 |
+
value: The option value to select
|
| 76 |
+
"""
|
| 77 |
+
_ensure_page().select_option(selector, value)
|
| 78 |
+
return f"Selected {value}"
|
| 79 |
+
|
| 80 |
+
@tool
|
| 81 |
+
def extract(selector: str = "body") -> str:
|
| 82 |
+
"""Extract text content.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
selector: CSS selector to extract text from
|
| 86 |
+
"""
|
| 87 |
+
return _ensure_page().inner_text(selector)[:2000]
|
| 88 |
+
|
| 89 |
+
@tool
|
| 90 |
+
def scroll(direction: str = "down") -> str:
|
| 91 |
+
"""Scroll the page.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
direction: up, down, top, or bottom
|
| 95 |
+
"""
|
| 96 |
+
cmds = {"up": "window.scrollBy(0,-500)", "down": "window.scrollBy(0,500)",
|
| 97 |
+
"top": "window.scrollTo(0,0)", "bottom": "window.scrollTo(0,document.body.scrollHeight)"}
|
| 98 |
+
_ensure_page().evaluate(cmds.get(direction, cmds["down"]))
|
| 99 |
+
return f"Scrolled {direction}"
|
| 100 |
+
|
| 101 |
+
@tool
|
| 102 |
+
def wait(ms: int = 1000) -> str:
|
| 103 |
+
"""Wait for milliseconds.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
ms: Time to wait in milliseconds
|
| 107 |
+
"""
|
| 108 |
+
_ensure_page().wait_for_timeout(ms)
|
| 109 |
+
return f"Waited {ms}ms"
|
| 110 |
+
|
| 111 |
+
@tool
|
| 112 |
+
def press_key(key: str) -> str:
|
| 113 |
+
"""Press a keyboard key.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
key: Key to press (e.g. Enter, Tab, Escape)
|
| 117 |
+
"""
|
| 118 |
+
_ensure_page().keyboard.press(key)
|
| 119 |
+
return f"Pressed {key}"
|
| 120 |
+
|
| 121 |
+
@tool
|
| 122 |
+
def screenshot() -> str:
|
| 123 |
+
"""Take screenshot."""
|
| 124 |
+
_ensure_page().screenshot()
|
| 125 |
+
return "Screenshot taken"
|
| 126 |
+
|
| 127 |
+
@tool
|
| 128 |
+
def go_back() -> str:
|
| 129 |
+
"""Go back to previous page."""
|
| 130 |
+
_ensure_page().go_back()
|
| 131 |
+
return "Went back"
|
| 132 |
+
|
| 133 |
+
@tool
|
| 134 |
+
def done(answer: str = "") -> str:
|
| 135 |
+
"""Mark task as complete.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
answer: The final answer or summary
|
| 139 |
+
"""
|
| 140 |
+
return f"DONE: {answer}"
|
| 141 |
+
|
| 142 |
+
tools = [navigate, click, type_into, select, extract, scroll, wait, press_key, screenshot, go_back, done]
|
| 143 |
+
|
| 144 |
+
url = sys.argv[1] if len(sys.argv) > 1 else "https://www.google.com"
|
| 145 |
+
task = sys.argv[2] if len(sys.argv) > 2 else "search for sakthai coder browser"
|
| 146 |
+
prompt = (f"Go to {url} and {task}. Use navigate(), click(), type_into(), "
|
| 147 |
+
f"select(), extract(), scroll(), wait(), press_key(), go_back(), screenshot(), "
|
| 148 |
+
f"and done() as needed. When finished, call done() with a summary.")
|
| 149 |
+
|
| 150 |
+
print(f"URL: {url}", flush=True)
|
| 151 |
+
print(f"Task: {task}", flush=True)
|
| 152 |
+
print("Loading model Nanthasit/sakthai-coder-browser...", flush=True)
|
| 153 |
+
|
| 154 |
+
from transformers import BitsAndBytesConfig
|
| 155 |
+
import torch
|
| 156 |
+
quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
|
| 157 |
+
bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
|
| 158 |
+
|
| 159 |
+
model = TransformersModel(
|
| 160 |
+
model_id="Nanthasit/sakthai-coder-browser",
|
| 161 |
+
device_map="auto", torch_dtype="auto", max_new_tokens=512,
|
| 162 |
+
model_kwargs={"quantization_config": quant},
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
agent = CodeAgent(tools=tools, model=model, max_steps=10, verbosity_level=2)
|
| 166 |
+
|
| 167 |
+
# Inject type_into as 'type' into executor state so it takes precedence over
|
| 168 |
+
# BASE_PYTHON_TOOLS['type'] (builtin). evaluate_name checks state FIRST, then static_tools.
|
| 169 |
+
agent.python_executor.state["type"] = agent.tools["type_into"]
|
| 170 |
+
|
| 171 |
+
result = agent.run(prompt)
|
| 172 |
+
print(f"\nResult: {result}", flush=True)
|