Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,11 @@
|
|
1 |
-
import
|
|
|
|
|
|
|
|
|
|
|
2 |
import google.generativeai as genai
|
3 |
-
|
4 |
-
import requests
|
5 |
import os
|
6 |
from dotenv import load_dotenv
|
7 |
|
@@ -10,172 +14,166 @@ load_dotenv()
|
|
10 |
|
11 |
# Configure Gemini
|
12 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
|
|
13 |
|
14 |
-
#
|
15 |
-
|
16 |
-
|
17 |
-
"
|
18 |
-
"
|
19 |
-
"
|
20 |
-
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
26 |
-
},
|
27 |
-
{
|
28 |
-
"category": "HARM_CATEGORY_HATE_SPEECH",
|
29 |
-
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
30 |
-
},
|
31 |
-
{
|
32 |
-
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
33 |
-
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
34 |
-
},
|
35 |
-
{
|
36 |
-
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
37 |
-
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
38 |
-
},
|
39 |
-
]
|
40 |
-
|
41 |
-
model = genai.GenerativeModel(
|
42 |
-
model_name="gemini-1.5-flash",
|
43 |
-
generation_config=generation_config,
|
44 |
-
safety_settings=safety_settings
|
45 |
-
)
|
46 |
-
|
47 |
-
# Function to perform web search (using SerpAPI)
|
48 |
-
def search_web(query):
|
49 |
try:
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
params = {
|
55 |
-
'q': query,
|
56 |
-
'api_key': api_key,
|
57 |
-
'engine': 'google'
|
58 |
-
}
|
59 |
|
60 |
-
|
61 |
-
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
except Exception as e:
|
67 |
-
st.error(f"Search error: {e}")
|
68 |
-
return None
|
69 |
-
|
70 |
-
# Initialize chat history
|
71 |
-
if "messages" not in st.session_state:
|
72 |
-
st.session_state.messages = [
|
73 |
-
{
|
74 |
-
"role": "assistant",
|
75 |
-
"content": "Hello! I'm Gemini AI with web search capabilities. How can I help you today?",
|
76 |
-
"timestamp": datetime.now().strftime("%H:%M")
|
77 |
-
}
|
78 |
-
]
|
79 |
-
|
80 |
-
# App title and sidebar
|
81 |
-
st.set_page_config(page_title="Gemini AI Chatbot", page_icon="π€")
|
82 |
-
st.title("π Gemini AI Chatbot")
|
83 |
-
st.caption("Powered by Gemini 1.5 Flash with web search capabilities")
|
84 |
-
|
85 |
-
# Sidebar controls
|
86 |
-
with st.sidebar:
|
87 |
-
st.header("Settings")
|
88 |
-
web_search = st.toggle("Enable Web Search", value=True)
|
89 |
-
st.divider()
|
90 |
-
if st.button("New Chat"):
|
91 |
-
st.session_state.messages = [
|
92 |
-
{
|
93 |
-
"role": "assistant",
|
94 |
-
"content": "Hello! I'm Gemini AI with web search capabilities. How can I help you today?",
|
95 |
-
"timestamp": datetime.now().strftime("%H:%M")
|
96 |
-
}
|
97 |
-
]
|
98 |
-
st.divider()
|
99 |
-
st.markdown("### About")
|
100 |
-
st.markdown("This chatbot uses Google's Gemini 1.5 Flash model and can perform web searches when enabled.")
|
101 |
-
|
102 |
-
# Display chat messages
|
103 |
-
for message in st.session_state.messages:
|
104 |
-
avatar = "π€" if message["role"] == "assistant" else "π€"
|
105 |
-
with st.chat_message(message["role"], avatar=avatar):
|
106 |
-
st.markdown(message["content"])
|
107 |
-
if "search_results" in message:
|
108 |
-
st.divider()
|
109 |
-
st.markdown("**Web Search Results**")
|
110 |
-
for result in message["search_results"]:
|
111 |
-
with st.expander(result.get("title", "No title")):
|
112 |
-
st.markdown(f"**Snippet:** {result.get('snippet', 'No snippet available')}")
|
113 |
-
st.markdown(f"**Link:** [{result.get('link', 'No link')}]({result.get('link', '#')})")
|
114 |
-
st.caption(f"{message['timestamp']} β’ {message['role'].capitalize()}")
|
115 |
-
|
116 |
-
# Accept user input
|
117 |
-
if prompt := st.chat_input("Ask me anything..."):
|
118 |
-
# Add user message to chat history
|
119 |
-
st.session_state.messages.append({
|
120 |
-
"role": "user",
|
121 |
-
"content": prompt,
|
122 |
-
"timestamp": datetime.now().strftime("%H:%M")
|
123 |
-
})
|
124 |
-
|
125 |
-
# Display user message
|
126 |
-
with st.chat_message("user", avatar="π€"):
|
127 |
-
st.markdown(prompt)
|
128 |
-
st.caption(f"{datetime.now().strftime('%H:%M')} β’ User")
|
129 |
-
|
130 |
-
# Display assistant response
|
131 |
-
with st.chat_message("assistant", avatar="π€"):
|
132 |
-
message_placeholder = st.empty()
|
133 |
-
full_response = ""
|
134 |
-
|
135 |
-
# If web search is enabled, perform search first
|
136 |
-
search_results = None
|
137 |
-
if web_search:
|
138 |
-
with st.spinner("Searching the web..."):
|
139 |
-
search_results = search_web(prompt)
|
140 |
|
141 |
-
#
|
142 |
-
with st.spinner("Thinking..."):
|
143 |
try:
|
144 |
-
|
145 |
-
|
146 |
-
if search_results:
|
147 |
-
chat_prompt += "\n\nHere are some web search results to help with your response:\n"
|
148 |
-
for i, result in enumerate(search_results, 1):
|
149 |
-
chat_prompt += f"\n{i}. {result.get('title', 'No title')}\n{result.get('snippet', 'No snippet')}\n"
|
150 |
|
151 |
-
#
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
except Exception as e:
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
|
164 |
-
#
|
|
|
|
|
|
|
|
|
165 |
if search_results:
|
166 |
-
|
167 |
-
st.markdown("**Web Search Results**")
|
168 |
for result in search_results:
|
169 |
-
|
170 |
-
|
171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
172 |
|
173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from selenium import webdriver
|
3 |
+
from selenium.webdriver.common.by import By
|
4 |
+
from selenium.webdriver.chrome.options import Options
|
5 |
+
from selenium.webdriver.chrome.service import Service
|
6 |
+
from webdriver_manager.chrome import ChromeDriverManager
|
7 |
import google.generativeai as genai
|
8 |
+
import time
|
|
|
9 |
import os
|
10 |
from dotenv import load_dotenv
|
11 |
|
|
|
14 |
|
15 |
# Configure Gemini
|
16 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
17 |
+
model = genai.GenerativeModel('gemini-pro')
|
18 |
|
19 |
+
# Initialize Selenium WebDriver
|
20 |
+
def init_driver():
|
21 |
+
chrome_options = Options()
|
22 |
+
chrome_options.add_argument("--headless")
|
23 |
+
chrome_options.add_argument("--disable-gpu")
|
24 |
+
chrome_options.add_argument("--window-size=1920x1080")
|
25 |
+
chrome_options.add_argument("--no-sandbox")
|
26 |
+
chrome_options.add_argument("--disable-dev-shm-usage")
|
27 |
+
service = Service(ChromeDriverManager().install())
|
28 |
+
driver = webdriver.Chrome(service=service, options=chrome_options)
|
29 |
+
return driver
|
30 |
|
31 |
+
# Enhanced web search with Selenium
|
32 |
+
def search_with_selenium(query):
|
33 |
+
driver = init_driver()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
try:
|
35 |
+
print(f"Searching for: {query}")
|
36 |
+
driver.get(f"https://www.google.com/search?q={query}")
|
37 |
+
time.sleep(2) # Wait for results to load
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
# Accept cookies if popup appears (for EU users)
|
40 |
+
try:
|
41 |
+
driver.find_element(By.ID, "L2AGLb").click()
|
42 |
+
time.sleep(1)
|
43 |
+
except:
|
44 |
+
pass
|
45 |
|
46 |
+
# Extract search results
|
47 |
+
results = []
|
48 |
+
search_items = driver.find_elements(By.CSS_SELECTOR, 'div.g')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
+
for item in search_items[:5]: # Get top 5 results
|
|
|
51 |
try:
|
52 |
+
title = item.find_element(By.CSS_SELECTOR, 'h3').text
|
53 |
+
link = item.find_element(By.CSS_SELECTOR, 'a').get_attribute('href')
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
# Try different selectors for snippet
|
56 |
+
snippet = ""
|
57 |
+
try:
|
58 |
+
snippet = item.find_element(By.CSS_SELECTOR, 'div.IsZvec').text
|
59 |
+
except:
|
60 |
+
try:
|
61 |
+
snippet = item.find_element(By.CSS_SELECTOR, '.VwiC3b').text
|
62 |
+
except:
|
63 |
+
pass
|
64 |
|
65 |
+
if title and link:
|
66 |
+
results.append({
|
67 |
+
'title': title,
|
68 |
+
'link': link,
|
69 |
+
'snippet': snippet[:200] + "..." if snippet else "No description available"
|
70 |
+
})
|
71 |
except Exception as e:
|
72 |
+
print(f"Error extracting result: {e}")
|
73 |
+
continue
|
74 |
+
|
75 |
+
return results
|
76 |
+
except Exception as e:
|
77 |
+
print(f"Search error: {e}")
|
78 |
+
return []
|
79 |
+
finally:
|
80 |
+
driver.quit()
|
81 |
+
|
82 |
+
# Chatbot function with enhanced error handling
|
83 |
+
def chatbot(message, history, use_web_search):
|
84 |
+
try:
|
85 |
+
search_results = []
|
86 |
+
context = message
|
87 |
+
|
88 |
+
# Perform web search if enabled
|
89 |
+
if use_web_search:
|
90 |
+
with gr.Blocks(analytics_enabled=False):
|
91 |
+
with gr.Row():
|
92 |
+
gr.Markdown("π Searching the web...")
|
93 |
+
|
94 |
+
search_results = search_with_selenium(message)
|
95 |
+
if search_results:
|
96 |
+
context += "\n\nWeb search results:\n"
|
97 |
+
for i, result in enumerate(search_results, 1):
|
98 |
+
context += f"{i}. {result['title']}\n{result['snippet']}\n\n"
|
99 |
|
100 |
+
# Generate response
|
101 |
+
response = model.generate_content(context)
|
102 |
+
bot_message = response.text
|
103 |
+
|
104 |
+
# Format response with search results
|
105 |
if search_results:
|
106 |
+
bot_message += "\n\nπ Sources:\n"
|
|
|
107 |
for result in search_results:
|
108 |
+
bot_message += f"- [{result['title']}]({result['link']})\n"
|
109 |
+
|
110 |
+
return bot_message
|
111 |
+
except Exception as e:
|
112 |
+
return f"β οΈ Error: {str(e)}"
|
113 |
+
|
114 |
+
# Gradio interface with enhanced UI
|
115 |
+
with gr.Blocks(
|
116 |
+
title="Gemini AI Chatbot with Web Search",
|
117 |
+
theme=gr.themes.Soft(),
|
118 |
+
css=".gradio-container {max-width: 800px !important}"
|
119 |
+
) as demo:
|
120 |
+
|
121 |
+
gr.Markdown("""
|
122 |
+
# π Gemini AI Chatbot
|
123 |
+
**Powered by Google Gemini Pro + Real-time Web Search**
|
124 |
+
""")
|
125 |
+
|
126 |
+
with gr.Row():
|
127 |
+
with gr.Column(scale=4):
|
128 |
+
chatbot = gr.Chatbot(
|
129 |
+
height=500,
|
130 |
+
bubble_full_width=False,
|
131 |
+
avatar_images=(
|
132 |
+
"user.png",
|
133 |
+
"bot.png"
|
134 |
+
)
|
135 |
+
)
|
136 |
+
msg = gr.Textbox(
|
137 |
+
label="Your Message",
|
138 |
+
placeholder="Ask me anything...",
|
139 |
+
lines=2
|
140 |
+
)
|
141 |
+
|
142 |
+
with gr.Row():
|
143 |
+
submit_btn = gr.Button("Send", variant="primary")
|
144 |
+
clear_btn = gr.Button("Clear")
|
145 |
+
web_search = gr.Checkbox(
|
146 |
+
label="Enable Web Search",
|
147 |
+
value=True,
|
148 |
+
interactive=True
|
149 |
+
)
|
150 |
|
151 |
+
with gr.Column(scale=1):
|
152 |
+
gr.Markdown("""
|
153 |
+
### π Web Search Features
|
154 |
+
- Real-time Google results
|
155 |
+
- Source citations
|
156 |
+
- Toggle on/off
|
157 |
+
|
158 |
+
### βοΈ Controls
|
159 |
+
- Press Enter or click Send
|
160 |
+
- Clear resets conversation
|
161 |
+
""")
|
162 |
+
|
163 |
+
# Event handlers
|
164 |
+
def respond(message, chat_history, use_search):
|
165 |
+
bot_message = chatbot(message, chat_history, use_search)
|
166 |
+
chat_history.append((message, bot_message))
|
167 |
+
return "", chat_history
|
168 |
|
169 |
+
msg.submit(respond, [msg, chatbot, web_search], [msg, chatbot])
|
170 |
+
submit_btn.click(respond, [msg, chatbot, web_search], [msg, chatbot])
|
171 |
+
clear_btn.click(lambda: None, None, chatbot, queue=False)
|
172 |
+
|
173 |
+
if __name__ == "__main__":
|
174 |
+
demo.launch(
|
175 |
+
server_name="0.0.0.0",
|
176 |
+
server_port=7860,
|
177 |
+
share=False,
|
178 |
+
favicon_path="favicon.ico"
|
179 |
+
)
|