Update app.py
Browse files
app.py
CHANGED
|
@@ -8,37 +8,46 @@ from threading import Thread
|
|
| 8 |
from playwright.async_api import async_playwright
|
| 9 |
from playwright_stealth import stealth
|
| 10 |
|
| 11 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
os.system("playwright install chromium")
|
| 13 |
|
| 14 |
# --- AI Model Setup ---
|
| 15 |
-
#
|
| 16 |
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 17 |
|
| 18 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 19 |
-
# Model ko CPU par load karenge, @spaces.GPU isse khud GPU par le jayega
|
| 20 |
model = AutoModelForCausalLM.from_pretrained(
|
| 21 |
-
MODEL_ID,
|
| 22 |
-
torch_dtype=torch.bfloat16,
|
| 23 |
-
device_map=None
|
| 24 |
).to("cpu")
|
| 25 |
|
| 26 |
@spaces.GPU
|
| 27 |
def chat_fn(message, history):
|
| 28 |
-
# Convert Gradio history to Llama format
|
| 29 |
messages = []
|
| 30 |
-
for
|
| 31 |
-
messages.append({"role": "user", "content":
|
| 32 |
-
messages.append({"role": "assistant", "content":
|
| 33 |
messages.append({"role": "user", "content": message})
|
| 34 |
|
| 35 |
-
# Move
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
input_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda")
|
| 39 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
|
|
|
| 40 |
|
| 41 |
-
gen_kwargs = dict(input_ids=input_ids, streamer=streamer, max_new_tokens=512, temperature=0.7)
|
| 42 |
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 43 |
thread.start()
|
| 44 |
|
|
@@ -47,60 +56,72 @@ def chat_fn(message, history):
|
|
| 47 |
response += new_text
|
| 48 |
yield response
|
| 49 |
|
| 50 |
-
# --- Browser Logic ---
|
| 51 |
async def browser_task(url, selector=None, text=None, action="nav"):
|
| 52 |
async with async_playwright() as p:
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
page = await context.new_page()
|
| 56 |
await stealth(page)
|
| 57 |
|
| 58 |
try:
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
if action == "click" and selector:
|
|
|
|
| 61 |
await page.click(selector)
|
| 62 |
-
await asyncio.sleep(
|
| 63 |
elif action == "type" and selector and text:
|
|
|
|
| 64 |
await page.fill(selector, text)
|
| 65 |
await page.keyboard.press("Enter")
|
| 66 |
-
await asyncio.sleep(
|
| 67 |
|
| 68 |
screenshot = await page.screenshot()
|
| 69 |
await browser.close()
|
| 70 |
return screenshot
|
| 71 |
except Exception as e:
|
|
|
|
| 72 |
await browser.close()
|
| 73 |
return None
|
| 74 |
|
| 75 |
def web_run(url, sel, txt, action):
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
# ---
|
| 79 |
-
with gr.Blocks() as demo:
|
| 80 |
-
gr.
|
| 81 |
|
| 82 |
with gr.Row():
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
url_box = gr.Textbox(label="URL", value="https://www.google.com")
|
| 90 |
with gr.Row():
|
| 91 |
-
|
| 92 |
-
|
| 93 |
|
| 94 |
with gr.Row():
|
| 95 |
-
|
| 96 |
-
btn_click = gr.Button("
|
| 97 |
-
btn_type = gr.Button("
|
| 98 |
|
| 99 |
-
|
| 100 |
|
| 101 |
-
#
|
| 102 |
-
|
| 103 |
-
btn_click.click(
|
| 104 |
-
btn_type.click(
|
| 105 |
|
| 106 |
-
|
|
|
|
|
|
| 8 |
from playwright.async_api import async_playwright
|
| 9 |
from playwright_stealth import stealth
|
| 10 |
|
| 11 |
+
# --- Playwright Installation Check ---
|
| 12 |
+
try:
|
| 13 |
+
import playwright
|
| 14 |
+
except ImportError:
|
| 15 |
+
os.system("pip install playwright playwright-stealth")
|
| 16 |
+
|
| 17 |
+
# Space startup par browser install karein
|
| 18 |
os.system("playwright install chromium")
|
| 19 |
|
| 20 |
# --- AI Model Setup ---
|
| 21 |
+
# Qwen 2.5 1.5B - Best balance for ZeroGPU RAM
|
| 22 |
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 23 |
|
| 24 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
|
|
|
| 25 |
model = AutoModelForCausalLM.from_pretrained(
|
| 26 |
+
MODEL_ID,
|
| 27 |
+
torch_dtype=torch.bfloat16, # torch_dtype fix
|
| 28 |
+
device_map=None # Manual control
|
| 29 |
).to("cpu")
|
| 30 |
|
| 31 |
@spaces.GPU
|
| 32 |
def chat_fn(message, history):
|
|
|
|
| 33 |
messages = []
|
| 34 |
+
for h in history:
|
| 35 |
+
messages.append({"role": "user", "content": h[0]})
|
| 36 |
+
messages.append({"role": "assistant", "content": h[1]})
|
| 37 |
messages.append({"role": "user", "content": message})
|
| 38 |
|
| 39 |
+
model.to("cuda") # Move to GPU only when needed
|
| 40 |
+
|
| 41 |
+
input_ids = tokenizer.apply_chat_template(
|
| 42 |
+
messages,
|
| 43 |
+
tokenize=True,
|
| 44 |
+
add_generation_prompt=True,
|
| 45 |
+
return_tensors="pt"
|
| 46 |
+
).to("cuda")
|
| 47 |
|
|
|
|
| 48 |
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
|
| 49 |
+
gen_kwargs = dict(input_ids=input_ids, streamer=streamer, max_new_tokens=1024, temperature=0.7)
|
| 50 |
|
|
|
|
| 51 |
thread = Thread(target=model.generate, kwargs=gen_kwargs)
|
| 52 |
thread.start()
|
| 53 |
|
|
|
|
| 56 |
response += new_text
|
| 57 |
yield response
|
| 58 |
|
| 59 |
+
# --- Improved Browser Logic ---
|
| 60 |
async def browser_task(url, selector=None, text=None, action="nav"):
|
| 61 |
async with async_playwright() as p:
|
| 62 |
+
# Browser launch with args to prevent sandbox crashes
|
| 63 |
+
browser = await p.chromium.launch(headless=True, args=["--no-sandbox", "--disable-setuid-sandbox"])
|
| 64 |
+
context = await browser.new_context(
|
| 65 |
+
viewport={'width': 1280, 'height': 720},
|
| 66 |
+
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
|
| 67 |
+
)
|
| 68 |
page = await context.new_page()
|
| 69 |
await stealth(page)
|
| 70 |
|
| 71 |
try:
|
| 72 |
+
# Timeout barha diya hai
|
| 73 |
+
await page.goto(url, wait_until="load", timeout=60000)
|
| 74 |
+
|
| 75 |
if action == "click" and selector:
|
| 76 |
+
await page.wait_for_selector(selector, timeout=5000)
|
| 77 |
await page.click(selector)
|
| 78 |
+
await asyncio.sleep(2)
|
| 79 |
elif action == "type" and selector and text:
|
| 80 |
+
await page.wait_for_selector(selector, timeout=5000)
|
| 81 |
await page.fill(selector, text)
|
| 82 |
await page.keyboard.press("Enter")
|
| 83 |
+
await asyncio.sleep(3)
|
| 84 |
|
| 85 |
screenshot = await page.screenshot()
|
| 86 |
await browser.close()
|
| 87 |
return screenshot
|
| 88 |
except Exception as e:
|
| 89 |
+
print(f"Browser Error: {e}")
|
| 90 |
await browser.close()
|
| 91 |
return None
|
| 92 |
|
| 93 |
def web_run(url, sel, txt, action):
|
| 94 |
+
try:
|
| 95 |
+
return asyncio.run(browser_task(url, sel, txt, action))
|
| 96 |
+
except Exception as e:
|
| 97 |
+
return None
|
| 98 |
|
| 99 |
+
# --- Custom UI with Gradio ---
|
| 100 |
+
with gr.Blocks(theme=gr.themes.Default()) as demo:
|
| 101 |
+
gr.HTML("<h1 style='text-align:center;'>π AI Agent + Web Stealth Browser</h1>")
|
| 102 |
|
| 103 |
with gr.Row():
|
| 104 |
+
with gr.Column(scale=1):
|
| 105 |
+
# Standard Chatbot logic
|
| 106 |
+
chat_ui = gr.ChatInterface(fn=chat_fn, type="messages")
|
| 107 |
|
| 108 |
+
with gr.Column(scale=1):
|
| 109 |
+
url_input = gr.Textbox(label="π Website URL", value="https://google.com")
|
|
|
|
| 110 |
with gr.Row():
|
| 111 |
+
sel_input = gr.Textbox(label="π Selector (ID/Class)", placeholder="e.g. input[name='q']")
|
| 112 |
+
txt_input = gr.Textbox(label="β¨οΈ Text to Type", placeholder="Search query...")
|
| 113 |
|
| 114 |
with gr.Row():
|
| 115 |
+
btn_visit = gr.Button("Visit", variant="primary")
|
| 116 |
+
btn_click = gr.Button("Click")
|
| 117 |
+
btn_type = gr.Button("Type & Enter")
|
| 118 |
|
| 119 |
+
browser_img = gr.Image(label="Live View", type="numpy")
|
| 120 |
|
| 121 |
+
# Handlers
|
| 122 |
+
btn_visit.click(lambda u: web_run(u, None, None, "nav"), [url_input], browser_img)
|
| 123 |
+
btn_click.click(lambda u, s: web_run(u, s, None, "click"), [url_input, sel_input], browser_img)
|
| 124 |
+
btn_type.click(lambda u, s, t: web_run(u, s, t, "type"), [url_input, sel_input, txt_input], browser_img)
|
| 125 |
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
demo.launch()
|