File size: 13,954 Bytes
3ef37b3 4053004 b4399d0 4053004 4270cd0 4053004 0d5589a 4053004 0d5589a 4053004 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
import streamlit as st
import os
import json5
from agents import Seeker
from qwen_agent.tools.base import BaseTool, register_tool
import os
import re
import json
import asyncio
from utils import *
import base64
from PIL import Image
import subprocess
def run_command(command):
try:
# Run the shell command
result = subprocess.run(command, shell=True, text=True, capture_output=True)
# Print the output of the command
print("Command Output:")
print(result.stdout)
# Print the error if there is any
if result.stderr:
print("Command Error:")
print(result.stderr)
except Exception as e:
print(f"An error occurred: {e}")
# Run crawl4ai-setup
def init_crawl4ai():
try:
# 使用 subprocess 执行命令
result = subprocess.run(
["python", "-m", "playwright", "install", "--with-deps", "chromium"],
check=True, # 如果命令失败,抛出 CalledProcessError
text=True, # 输出以文本形式返回
capture_output=True # 捕获输出
)
print("Success!")
print(result.stdout)
except subprocess.CalledProcessError as e:
print("Error!")
print(e.stderr)
model = "qwen-max"
llm_cfg = {
'model': model,
'api_key': os.getenv('API_KEY'),
'model_server': "https://dashscope.aliyuncs.com/compatible-mode/v1" ,
'generate_cfg': {
'top_p': 0.8,
'max_input_tokens': 120000,
'max_retries': 20
},
}
def extract_links_with_text(html):
with open("ROOT_URL.txt", "r") as f:
ROOT_URL = f.read()
soup = BeautifulSoup(html, 'html.parser')
links = []
# 常规的<a>标签
for a_tag in soup.find_all('a', href=True):
url = a_tag['href']
text = ''.join(a_tag.stripped_strings)
# 过滤掉图片链接和javascript链接
if text and "javascript" not in url and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
if process_url(ROOT_URL, url).startswith(ROOT_URL):
links.append({'url': process_url(ROOT_URL, url), 'text': text})
# 特殊情况1: 使用onclick事件的链接
for a_tag in soup.find_all('a', onclick=True):
onclick_text = a_tag['onclick']
text = ''.join(a_tag.stripped_strings)
# 使用正则表达式提取url
match = re.search(r"window\.location\.href='([^']*)'", onclick_text)
if match:
url = match.group(1)
if url and text and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
if process_url(ROOT_URL, url).startswith(ROOT_URL):
links.append({'url': process_url(ROOT_URL, url), 'text': text})
# 特殊情况2: data-url属性的链接
for a_tag in soup.find_all('a', attrs={'data-url': True}):
url = a_tag['data-url']
text = ''.join(a_tag.stripped_strings)
if url and text and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
if process_url(ROOT_URL, url).startswith(ROOT_URL):
links.append({'url': process_url(ROOT_URL, url), 'text': text})
# 特殊情况3: class为"herf-mask"的链接
for a_tag in soup.find_all('a', class_='herf-mask'):
url = a_tag.get('href')
text = a_tag.get('title') or ''.join(a_tag.stripped_strings)
if url and text and not url.endswith(('.jpg', '.png', '.gif', '.jpeg', '.pdf')):
if process_url(ROOT_URL, url).startswith(ROOT_URL):
links.append({'url': process_url(ROOT_URL, url), 'text': text})
# 特殊情况4: <button>标签作为链接
for button in soup.find_all('button', onclick=True):
onclick_text = button['onclick']
text = button.get('title') or button.get('aria-label') or ''.join(button.stripped_strings)
match = re.search(r"window\.location\.href='([^']*)'", onclick_text)
if match:
url = match.group(1)
if url and text:
if process_url(ROOT_URL, url).startswith(ROOT_URL):
links.append({'url': process_url(ROOT_URL, url), 'text': text})
# 过滤重复链接
if "Welcome!" in html:
print(links)
links.remove({'url': 'https://2025.aclweb.org/calls/industry_track/', 'text': 'Call for Industry Track'})
unique_links = {f"{item['url']}_{item['text']}": item for item in links} # 去重
if not os.path.exists("BUTTON_URL_ADIC.json"):
with open("BUTTON_URL_ADIC.json", "w") as f:
json.dump({}, f)
with open("BUTTON_URL_ADIC.json", "r") as f:
BUTTON_URL_ADIC = json.load(f)
for temp in list(unique_links.values()):
BUTTON_URL_ADIC[temp["text"]] = temp["url"]
with open("BUTTON_URL_ADIC.json", "w") as f:
json.dump(BUTTON_URL_ADIC, f)
info = ""
for i in list(unique_links.values()):
info += "<button>" + i["text"] + "<button>" + "\n"
return info
flag = 0
if __name__ == "__main__":
st.title('🤝WebWalker')
st.markdown("### 📚Introduction")
st.markdown("👋Welcome to WebWalker! WebWalker is a web-based conversational agent that can help you navigate websites and find information.")
st.markdown("📑The paper of WebWalker is available at [arXiv](https://arxiv.org/pdf/2501.07572).")
st.markdown("✨You can bulid your own WebWalker by following the [instruction](https://github.com/Alibaba-NLP/WebWalker).")
st.markdown("🙋If you have any questions, please feel free to contact us via the [Github issue](https://github.com/Alibaba-NLP/WebWalker/issues).")
st.markdown("### 🚀Let's start exploring the website!")
if 'form_1_text' not in st.session_state:
st.session_state.form_1_text = ""
if 'form_2_text' not in st.session_state:
st.session_state.form_2_text = ""
with st.sidebar:
MAX_ROUNDS = st.number_input('Max Count Count:', min_value=1, max_value=15, value=10, step=1)
website_example = st.sidebar.selectbox('Example Website:', ['https://2025.aclweb.org/'])
question_example = st.sidebar.selectbox('Example Query:', ["When is the paper submission deadline for ACL 2025 Industry Track, and what is the venue specific address?", "Who is the general chair of ACL 2025?", "What is the spcial theme of ACL 2025?"])
col1, col2 = st.columns([3, 1])
with col1:
with st.form(key='my_form'):
form_1_text = st.text_area("**🤯Memory**", value="No Memory", height=68)
website = st.text_area('👉Website', value=website_example, placeholder='Input the website you want to walk through.')
query = st.text_area('🤔Query', value=question_example, placeholder='Input the query you want to ask.')
submit_button = st.form_submit_button('Start!!!!')
if submit_button:
if website and query:
tools = ["visit_page"]
K = 15
llm_cfg["query"] = query
bot = Seeker(llm=llm_cfg,
function_list=tools,
)
BUTTON_URL_ADIC = {}
ROOT_URL = website
with open("ROOT_URL.txt", "w") as f:
f.write("https://2025.aclweb.org/")
messages = [] # This stores the chat history.
visited_links = []
start_prompt = "query:\n{query} \nofficial website:\n{website}".format(query=query, website=website)
# print(website_adic[query])
st.markdown('**🌐Now visit**')
st.write(website)
html, markdown, screenshot = asyncio.run(get_info(website))
with col2:
st.markdown('**📸Observation**')
if screenshot:
st.session_state.image_index = 0
print("get screenshot!")
image_folder = "./"
with open(image_folder+str(st.session_state.image_index)+".png", "wb") as f:
f.write(base64.b64decode(screenshot))
image_files = os.listdir(image_folder)
image_files = [f for f in image_files if f.endswith(('.png', '.jpg', '.jpeg'))]
image_path = os.path.join(image_folder, image_files[st.session_state.image_index])
image = Image.open(image_folder+str(st.session_state.image_index)+".png")
st.image(image, caption='Start Obervation', width=400)
buttons = extract_links_with_text(html)
response = "website information:\n\n" + markdown + "\n\n"
response += "clickable button:\n\n" + buttons + "\n\nEach button is wrapped in a <button> tag"
start_prompt += "\nObservation:" + response + "\n\n"
messages.append({'role': 'user', 'content':start_prompt})
cnt = 0
response = []
response = bot.run(messages=messages, lang = "zh")
for i in response:
if "\"}" in i[0]["content"] and "Memory" not in i[0]["content"]:
st.markdown('**💭Thoughts**')
st.markdown(i[0]["content"].split("Action")[0])
elif "\"}" in i[0]["content"] and "Memory" in i[0]["content"]:
st.text_area('**🤯Memory Update**', i[0]["content"][:-2])
if "Final Answer" in i[0]["content"]:
st.session_state.answer = i[0]["content"]
st.markdown('**🙋Anwser**')
st.write(st.session_state.answer)
else:
st.error('Please input the website and query.')
def get_content_between_a_b(start_tag, end_tag, text):
"""
Args:
start_tag (str): start_tag
end_tag (str): end_tag
text (str): complete sentence
Returns:
str: the content between start_tag and end_tag
"""
extracted_text = ""
start_index = text.find(start_tag)
while start_index != -1:
end_index = text.find(end_tag, start_index + len(start_tag))
if end_index != -1:
extracted_text += text[start_index + len(start_tag) : end_index] + " "
start_index = text.find(start_tag, end_index + len(end_tag))
else:
break
return extracted_text.strip()
@register_tool('visit_page',allow_overwrite=True)
class VisitPage(BaseTool):
description = 'A tool analyzes the content of a webpage and extracts buttons associated with sublinks. Simply input the button which you want to explore, and the tool will return both the markdown-formatted content of the corresponding page of button and a list of new clickable buttons found on the new page.'
parameters = [{
'name': 'button',
'type': 'string',
'description': 'the button you want to click',
'required': True
}]
def call(self, params: str, **kwargs) -> str:
if not params.strip().endswith("}"):
if "}" in params.strip():
params = "{" + get_content_between_a_b("{","}",params) + "}"
else:
if not params.strip().endswith("\""):
params = params.strip() + "\"}"
else:
params = params.strip() + "}"
params = "{" + get_content_between_a_b("{","}",params) + "}"
if 'button' in json5.loads(params):
# `params` are the arguments generated by the LLM agent.
with open("BUTTON_URL_ADIC.json", "r") as f:
BUTTON_URL_ADIC = json.load(f)
if json5.loads(params)['button'].replace("<button>","") in BUTTON_URL_ADIC:
st.markdown('**👆Click Button**')
st.write(json5.loads(params)['button'].replace("<button>",""))
url = BUTTON_URL_ADIC[json5.loads(params)['button'].replace("<button>","")]
html, markdown, screenshot = asyncio.run(get_info(url))
st.markdown('**🌐Now Visit**')
st.write(url)
with col2:
st.write("")
st.markdown('**📸Observation**')
if screenshot:
print("get screenshot!")
image_folder = "./"
with open(image_folder+str(st.session_state.image_index+1)+".png", "wb") as f:
f.write(base64.b64decode(screenshot))
st.session_state.image_index += 1
# st.write(st.session_state.image_index)
image = Image.open(image_folder+str(st.session_state.image_index)+".png")
st.image(image, caption='Step ' + str(st.session_state.image_index) + ' Obervation', width=400)
response_bottons = extract_links_with_text(html)
response_content = markdown
if response_content:
response = "当前页面的信息是:\n\n" + response_content + "\n\n"
else:
response = "当前页面的信息不可访问\n\n"
response += "可以点击的按钮有\n\n" + response_bottons + "\n\n每个按钮由<button>..<button>包裹\n"
return response
else:
return "the button can not be clicked, please retry a new botton!"
else:
return "your input is invalid, plase output the action input correctly!" |