Firoj112 commited on
Commit
b74e4ee
·
verified ·
1 Parent(s): 6a667fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -50
app.py CHANGED
@@ -1,64 +1,166 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
38
 
39
- response += token
40
- yield response
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import os
2
  import gradio as gr
3
+ from smolagents import CodeAgent, LiteLLMModel, tool
4
+ from smolagents.agents import ActionStep
5
+ import helium
6
+ from selenium import webdriver
7
+ from selenium.webdriver.common.by import By
8
+ from selenium.webdriver.common.keys import Keys
9
+ from io import BytesIO
10
+ from PIL import Image
11
+ from datetime import datetime
12
+ from dotenv import load_dotenv
13
+ from huggingface_hub import login
14
+ import tempfile
15
 
16
+ # Load environment variables
17
+ load_dotenv()
18
+ hf_token = os.getenv("HF_TOKEN")
19
+ gemini_api_key = os.getenv("GEMINI_API_KEY")
20
 
21
+ if hf_token:
22
+ login(hf_token, add_to_git_credential=False)
23
+ else:
24
+ raise ValueError("HF_TOKEN environment variable not set.")
25
 
26
+ if not gemini_api_key:
27
+ raise ValueError("GEMINI_API_KEY environment variable not set.")
 
 
 
 
 
 
 
28
 
29
+ # Define tools
30
+ @tool
31
+ def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
32
+ elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
33
+ if nth_result > len(elements):
34
+ raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
35
+ result = f"Found {len(elements)} matches for '{text}'."
36
+ elem = elements[nth_result - 1]
37
+ driver.execute_script("arguments[0].scrollIntoView(true);", elem)
38
+ result += f"Focused on element {nth_result} of {len(elements)}"
39
+ return result
40
 
41
+ @tool
42
+ def go_back() -> None:
43
+ driver.back()
44
 
45
+ @tool
46
+ def close_popups() -> str:
47
+ webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
48
 
49
+ # Initialize Chrome driver
50
+ chrome_options = webdriver.ChromeOptions()
51
+ chrome_options.add_argument("--force-device-scale-factor=1")
52
+ chrome_options.add_argument("--window-size=1000,1350")
53
+ chrome_options.add_argument("--disable-pdf-viewer")
54
+ chrome_options.add_argument("--no-sandbox")
55
+ chrome_options.add_argument("--disable-dev-shm-usage")
56
+ chrome_options.add_argument("--window-position=0,0")
57
+ chrome_options.add_argument("--headless")
58
 
59
+ driver = helium.start_chrome(headless=True, options=chrome_options)
 
60
 
61
+ # Screenshot callback
62
+ def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> Image.Image:
63
+ from time import sleep
64
+ sleep(1.0)
65
+ driver = helium.get_driver()
66
+ current_step = memory_step.step_number
67
+ if driver is not None:
68
+ for previous_memory_step in agent.memory.steps:
69
+ if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:
70
+ previous_memory_step.observations_images = None
71
+ png_bytes = driver.get_screenshot_as_png()
72
+ image = Image.open(BytesIO(png_bytes))
73
+ screenshot_dir = tempfile.gettempdir()
74
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
75
+ screenshot_path = f"{screenshot_dir}/screenshot_step_{current_step}_{timestamp}.png"
76
+ image.save(screenshot_path)
77
+ url_info = f"Current url: {driver.current_url}"
78
+ memory_step.observations = (
79
+ url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info
80
+ )
81
+ return image
82
 
83
+ # Initialize model and agent
84
+ model = LiteLLMModel("gemini/gemini-2.0-flash")
85
+ agent = CodeAgent(
86
+ tools=[go_back, close_popups, search_item_ctrl_f],
87
+ model=model,
88
+ additional_authorized_imports=["helium"],
89
+ step_callbacks=[save_screenshot],
90
+ max_steps=20,
91
+ verbosity_level=2,
 
 
 
 
 
 
 
 
92
  )
93
+ agent.python_executor("from helium import *")
94
+
95
+ # Helium instructions
96
+ helium_instructions = """
97
+ You can use helium to access websites. Don't bother about the helium driver, it's already managed.
98
+ We've already ran "from helium import *"
99
+ Then you can go to pages!
100
+ Code:
101
+ go_to('github.com/trending')
102
+ ```<end_code>
103
+
104
+ You can directly click clickable elements by inputting the text that appears on them.
105
+ Code:
106
+ click("Top products")
107
+ ```<end_code>
108
+
109
+ If it's a link:
110
+ Code:
111
+ click(Link("Top products"))
112
+ ```<end_code>
113
+
114
+ If you try to interact with an element and it's not found, you'll get a LookupError.
115
+ In general stop your action after each button click to see what happens on your screenshot.
116
+ Never try to login in a page.
117
+
118
+ To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
119
+ Code:
120
+ scroll_down(num_pixels=1200) # This will scroll one viewport down
121
+ ```<end_code>
122
+
123
+ When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
124
+ Just use your built-in tool `close_popups` to close them:
125
+ Code:
126
+ close_popups()
127
+ ```<end_code>
128
+
129
+ You can use .exists() to check for the existence of an element. For example:
130
+ Code:
131
+ if Text('Accept cookies?').exists():
132
+ click('I accept')
133
+ ```<end_code>
134
+ """
135
+
136
+ # Gradio interface function
137
+ def run_agent(url: str, request: str):
138
+ try:
139
+ search_request = f"Please go to {url}. {request}"
140
+ agent_output = agent.run(search_request + helium_instructions)
141
+ screenshot_path = next(
142
+ (f"{tempfile.gettempdir()}/screenshot_step_{step.step_number}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
143
+ for step in agent.memory.steps if isinstance(step, ActionStep) and step.observations_images),
144
+ None
145
+ )
146
+ return agent_output, screenshot_path
147
+ except Exception as e:
148
+ return f"Error: {str(e)}", None
149
+ finally:
150
+ driver.quit()
151
 
152
+ # Gradio interface
153
+ with gr.Blocks() as demo:
154
+ gr.Markdown("# Web Navigation Agent")
155
+ url_input = gr.Textbox(label="Enter URL", placeholder="https://example.com")
156
+ request_input = gr.Textbox(label="Enter Request", placeholder="Describe what to do on the website")
157
+ submit_button = gr.Button("Run Agent")
158
+ output_text = gr.Textbox(label="Agent Output")
159
+ output_image = gr.Image(label="Screenshot")
160
+ submit_button.click(
161
+ fn=run_agent,
162
+ inputs=[url_input, request_input],
163
+ outputs=[output_text, output_image]
164
+ )
165
 
166
+ demo.launch()