Notbobjoe commited on
Commit
74e6325
·
verified ·
1 Parent(s): 70a88a6

Create Code

Browse files
Files changed (1) hide show
  1. Code +195 -0
Code ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ # Uninstall googlesearch library if already installed
5
+ os.system(f"{sys.executable} -m pip uninstall -y googlesearch-python")
6
+
7
+ # Function to install a module if missing
8
+ def install_and_import(module_name, package_name=None):
9
+ package_name = package_name if package_name else module_name
10
+ try:
11
+ __import__(module_name)
12
+ except ImportError:
13
+ os.system(f"{sys.executable} -m pip install --upgrade {package_name}")
14
+ __import__(module_name)
15
+
16
+ # Install and import required libraries individually
17
+ install_and_import("tkinter", "tk")
18
+ install_and_import("googlesearch", "googlesearch-python")
19
+ install_and_import("requests")
20
+ install_and_import("bs4", "beautifulsoup4")
21
+
22
+ # Now import installed modules
23
+ import random
24
+ import re
25
+ import tkinter as tk
26
+ from tkinter import scrolledtext
27
+ from googlesearch import search
28
+ import requests
29
+ from bs4 import BeautifulSoup
30
+
31
+ # Function to fetch code snippets
32
+ def fetch_code_snippet(query):
33
+ search_query = f"{query} site:stackoverflow.com OR site:github.com OR site:geeksforgeeks.org OR site:w3schools.com"
34
+
35
+ try:
36
+ results = search(search_query, num_results=5)
37
+ for url in results:
38
+ try:
39
+ response = requests.get(url, timeout=5)
40
+ soup = BeautifulSoup(response.text, "html.parser")
41
+
42
+ # Skip cookie banners
43
+ if any(word in soup.text.lower() for word in ["accept cookies", "cookies", "subscribe", "sign-up", "free trial", "cookies"]):
44
+ continue
45
+
46
+ # Extract code snippets
47
+ code_blocks = soup.find_all("code")
48
+ for code in code_blocks:
49
+ code_text = clean_text(code.get_text())
50
+ if len(code_text.split()) > 5:
51
+ return f"Here's a possible solution from {url}:\n\n```{code_text}```"
52
+ except Exception:
53
+ continue
54
+
55
+ except Exception:
56
+ return "I couldn't find an exact code snippet, but I can help guide you!"
57
+
58
+ return "I searched but didn't find an exact match. Try rephrasing!"
59
+
60
+ # Function to clean up scraped text
61
+ def clean_text(text):
62
+ text = re.sub(r"\s+", " ", text) # Remove extra spaces
63
+ text = re.sub(r"\[.*?\]", "", text) # Remove citation references like [1], [2]
64
+ return text.strip()
65
+
66
+ # Function to fetch Reddit answers while avoiding login-required pages
67
+ def fetch_reddit_response(query):
68
+ search_query = f"{query} site:reddit.com"
69
+
70
+ try:
71
+ results = search(search_query, num_results=5)
72
+ for url in results:
73
+ try:
74
+ response = requests.get(url, timeout=5, headers={"User-Agent": "Mozilla/5.0"})
75
+ soup = BeautifulSoup(response.text, "html.parser")
76
+
77
+ # Avoid cookie banners
78
+ if any(word in soup.text.lower() for word in ["accept cookies", "sign-up", "free trial", "subscribe", "log in"]):
79
+ continue
80
+
81
+ # Extract relevant text (from comments)
82
+ comments = soup.find_all("p")
83
+ for comment in comments:
84
+ text = clean_text(comment.get_text())
85
+ if len(text.split()) > 10: # Avoid short/unrelated results
86
+ return f"Here's a Reddit response from {url}:\n\n{text}"
87
+ except Exception:
88
+ continue
89
+
90
+ except Exception:
91
+ return "I couldn't find any relevant Reddit posts."
92
+
93
+ return "I searched Reddit but didn't find a perfect answer. Try rephrasing!"
94
+
95
+ # Function to generate responses
96
+ def generate_response(user_input):
97
+ if re.search(r"\b(hi|hello|hey)\b", user_input, re.IGNORECASE):
98
+ return random.choice(["Hey there!", "Hello! How can I assist you today?", "Hi! Need help with something?"])
99
+ elif re.search(r"\b(how are you)\b", user_input, re.IGNORECASE):
100
+ return "I'm just a chatbot, but I'm here to help! How about you?"
101
+ elif re.search(r"\b(who are you|what is your name)\b", user_input, re.IGNORECASE):
102
+ return "I'm Google AI, your chatbot assistant!"
103
+ elif re.search(r"\b(exit|quit|bye)\b", user_input, re.IGNORECASE):
104
+ root.destroy()
105
+ return "Goodbye! Have a great day!"
106
+
107
+ # Check for coding-related questions
108
+ if re.search(r"\b(code|example|script|program|how to)\b", user_input, re.IGNORECASE):
109
+ return fetch_code_snippet(user_input)
110
+
111
+ # Check if the user specifically wants Reddit results
112
+ if "reddit" in user_input.lower():
113
+ return fetch_reddit_response(user_input)
114
+
115
+ # Otherwise, fetch general Google results
116
+ return fetch_google_response(user_input)
117
+
118
+ # Function to fetch general answers from Google
119
+ def fetch_google_response(query):
120
+ try:
121
+ results = search(query, num_results=5)
122
+ for url in results:
123
+ try:
124
+ response = requests.get(url, timeout=5)
125
+ soup = BeautifulSoup(response.text, "html.parser")
126
+
127
+ # Avoid cookie banners
128
+ if any(word in soup.text.lower() for word in ["accept cookies", "subscribe", "sign-up", "cookies"]):
129
+ continue
130
+
131
+ # Extract useful content
132
+ paragraphs = soup.find_all("p")
133
+ for p in paragraphs:
134
+ text = clean_text(p.get_text())
135
+ if len(text.split()) > 10 and "subscribe" not in text.lower():
136
+ return text
137
+ except Exception:
138
+ continue
139
+
140
+ except Exception:
141
+ return "I couldn't find an exact answer, but I can help figure it out!"
142
+
143
+ return "I searched but didn't find a perfect match. Try rephrasing!"
144
+
145
+ # Function to send messages
146
+ def send_message(event=None):
147
+ user_text = user_input.get().strip()
148
+ if user_text == "":
149
+ return
150
+
151
+ chat_window.config(state=tk.NORMAL)
152
+ chat_window.insert(tk.END, f"You: {user_text}\n", "user")
153
+ chat_window.insert(tk.END, "Google AI is thinking...\n", "thinking")
154
+ chat_window.see(tk.END)
155
+ root.update()
156
+
157
+ response = generate_response(user_text)
158
+ chat_window.delete("thinking.first", "thinking.last")
159
+ chat_window.insert(tk.END, f"Google AI: {response}\n\n", "bot")
160
+
161
+ chat_window.config(state=tk.DISABLED)
162
+ user_input.delete(0, tk.END)
163
+
164
+ # Create GUI window
165
+ root = tk.Tk()
166
+ root.title("Google AI Chatbot")
167
+ root.geometry("500x600")
168
+ root.configure(bg="#2C3E50")
169
+
170
+ # Chat display
171
+ chat_window = scrolledtext.ScrolledText(root, height=20, width=60, bg="#34495E", fg="white", font=("Helvetica", 12), wrap=tk.WORD, bd=0, relief=tk.FLAT)
172
+ chat_window.tag_config("user", foreground="cyan")
173
+ chat_window.tag_config("bot", foreground="lightgreen")
174
+ chat_window.tag_config("thinking", foreground="yellow")
175
+ chat_window.config(state=tk.DISABLED)
176
+ chat_window.pack(padx=20, pady=20, fill=tk.BOTH, expand=True)
177
+
178
+ # User input field
179
+ input_frame = tk.Frame(root, bg="#34495E")
180
+ input_frame.pack(fill=tk.X, padx=20, pady=5)
181
+
182
+ user_input = tk.Entry(input_frame, width=50, font=("Helvetica", 12), bg="#ECF0F1", fg="#2C3E50", bd=0, relief=tk.FLAT)
183
+ user_input.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=10, pady=5)
184
+
185
+ # Send button
186
+ send_button = tk.Button(input_frame, text="Send", command=send_message, bg="#2980B9", fg="white", font=("Helvetica", 12, "bold"), relief=tk.FLAT)
187
+ send_button.pack(side=tk.RIGHT, padx=10, pady=5)
188
+
189
+ # Bind Enter key to send message
190
+ root.bind("<Return>", send_message)
191
+
192
+ # Focus on input field on startup
193
+ user_input.focus()
194
+
195
+ root.mainloop()