-
Notifications
You must be signed in to change notification settings - Fork 0
/
webtalk_python_code_base.py
139 lines (116 loc) · 6.01 KB
/
webtalk_python_code_base.py
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
from selenium import webdriver
from bs4 import BeautifulSoup
import anthropic
import time
from dotenv import load_dotenv
import os
from selenium.webdriver.common.alert import Alert
from selenium.common.exceptions import NoAlertPresentException
# Load environment variables from .env file
load_dotenv()
# Access your environment variable
anthropic_api_key = os.getenv('Anthropic_API_Key')
def initialize_driver():
"""Initialize and return a Chrome WebDriver."""
driver = webdriver.Chrome()
return driver
def open_webpage(driver, url):
"""Open a webpage using the provided driver and URL."""
driver.get(url)
def inject_chatbox(driver):
"""Inject a chatbox into the webpage."""
chatbox_html = """
<div id="chatbox" style="position: fixed; bottom: 10px; right: 10px; width: 300px; height: 400px; background-color: white; border: 1px solid #ccc; z-index: 1000; overflow: auto;">
<div id="messages" style="padding: 10px;">Loading Summary...</div>
<input type="text" id="chatbox_input" style="width: 100%; box-sizing: border-box; display: none;" placeholder="Type here...">
<button id="submit_button" style="width: 100%; display: none;">Submit</button>
</div>
"""
driver.execute_script("document.body.innerHTML += arguments[0];", chatbox_html)
def get_page_summary(driver, api_key):
"""Generate a summary of the webpage using Anthropic API and return it."""
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
client = anthropic.Anthropic(api_key=api_key)
prompt = ("You are an AI helper.\nI want you to prepare the 2 line summary of webpage for an old person who is not tech savvy and potentially vision disabled.\n"
"Follow the instructions below carefully:\nRequirements:\n Generate the 2 line summary of webpage.\n Workflow:\n Ask for clarification if my webpage does not contain anything. \n"
"Focus on actionable items for an elderly person. \n Ignore Javascript if it is not tied to any actionable item on page.\nGenerate the summary based on your assumptions for for an old person who is not tech savvy and potentially vision disabled.\n"
"Follow the above carefully and think step by step. I will tip you $200 if you do a great job and don't miss anything.\n HTML Content starts from here:" + str(soup))
response = client.messages.create(
model="claude-2.1",
max_tokens=4096,
messages=[{"role": "user", "content": prompt}]
)
content_block = response.content[0]
return content_block.text
def wait_for_user_input(driver):
while True:
try:
Alert(driver).accept() # Close the alert if present
except NoAlertPresentException:
pass # If no alert is present, just ignore
is_submitted = driver.execute_script("return document.getElementById('is_submitted').value;")
if is_submitted == 'yes':
user_input = driver.execute_script("return document.getElementById('chatbox_input').value;")
return user_input
time.sleep(1) # Wait a bit before checking again to reduce load
def update_chatbox_prompt_1(driver, summary):
"""Update the chatbox to hide the submit button and clear the summary after submission, then show 'working on it', while retaining button aesthetics."""
escaped_text = summary.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
# Update the chatbox content and make input field and button visible
update_script = f"""
document.getElementById('messages').innerText = '{escaped_text}';
document.getElementById('chatbox_input').style.display = 'block';
document.getElementById('submit_button').style.display = 'block';
document.getElementById('submit_button').style.backgroundColor = '#f0f0f0';
document.getElementById('submit_button').style.border = '1px solid #ccc';
document.getElementById('submit_button').style.padding = '10px';
document.getElementById('submit_button').style.cursor = 'pointer';
"""
driver.execute_script(update_script)
# Modify script for button click to hide the submit button, display "working on it..." message, and retain aesthetics
input_script = """
var input = document.getElementById('chatbox_input');
var button = document.getElementById('submit_button');
var messages = document.getElementById('messages');
input.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
button.click();
}
});
button.addEventListener('click', function() {
document.getElementById('is_submitted').value = 'yes';
messages.innerText = 'Working on it...';
input.style.display = 'none'; // Optionally hide the input as well
// Hide the button by setting display to 'none'
this.style.display = 'none';
});
// Add the aesthetics and functionality to handle mouse down and up events for the button
button.onmousedown = function() {
this.style.backgroundColor = '#d0d0d0';
};
button.onmouseup = function() {
this.style.backgroundColor = '#f0f0f0';
};
if (!document.getElementById('is_submitted')) {
var hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.id = 'is_submitted';
hiddenInput.value = 'no';
document.body.appendChild(hiddenInput);
}
"""
driver.execute_script(input_script)
# Main execution
if __name__ == "__main__":
driver = initialize_driver()
open_webpage(driver, "https://www.google.com")
inject_chatbox(driver)
summary = get_page_summary(driver, anthropic_api_key) # Replace "YOUR_API_KEY_HERE" with your actual API key
update_chatbox_prompt_1(driver, summary)
# The browser will stay open until manually closed.
# Wait for and get user input
user_input = wait_for_user_input(driver)
print(f"User input received: {user_input}")
print("Waiting for 1000 seconds. Close the browser manually if needed.")
time.sleep(1000) # Wait for 1000 seconds before ending the script