File size: 5,991 Bytes
db68681
 
 
 
 
 
da04fb3
db68681
da04fb3
 
 
 
 
 
 
 
cb3523c
da04fb3
db68681
 
 
 
 
 
 
 
 
 
 
da04fb3
db68681
 
 
da04fb3
db68681
 
 
da04fb3
db68681
 
 
 
 
 
da04fb3
db68681
 
 
da04fb3
db68681
da04fb3
db68681
 
da04fb3
db68681
 
 
 
 
 
 
 
 
da04fb3
db68681
 
 
 
 
 
da04fb3
db68681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da04fb3
db68681
 
 
 
 
da04fb3
db68681
da04fb3
db68681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da04fb3
db68681
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da04fb3
db68681
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import google.generativeai as genai
import time
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure Gemini
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
model = genai.GenerativeModel('gemini-2.0-flash')

# Initialize Selenium WebDriver
def init_driver():
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--window-size=1920x1080")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    return driver

# Enhanced web search with Selenium
def search_with_selenium(query):
    driver = init_driver()
    try:
        print(f"Searching for: {query}")
        driver.get(f"https://www.google.com/search?q={query}")
        time.sleep(2)  # Wait for results to load
        
        # Accept cookies if popup appears (for EU users)
        try:
            driver.find_element(By.ID, "L2AGLb").click()
            time.sleep(1)
        except:
            pass
        
        # Extract search results
        results = []
        search_items = driver.find_elements(By.CSS_SELECTOR, 'div.g')
        
        for item in search_items[:5]:  # Get top 5 results
            try:
                title = item.find_element(By.CSS_SELECTOR, 'h3').text
                link = item.find_element(By.CSS_SELECTOR, 'a').get_attribute('href')
                
                # Try different selectors for snippet
                snippet = ""
                try:
                    snippet = item.find_element(By.CSS_SELECTOR, 'div.IsZvec').text
                except:
                    try:
                        snippet = item.find_element(By.CSS_SELECTOR, '.VwiC3b').text
                    except:
                        pass
                
                if title and link:
                    results.append({
                        'title': title,
                        'link': link,
                        'snippet': snippet[:200] + "..." if snippet else "No description available"
                    })
            except Exception as e:
                print(f"Error extracting result: {e}")
                continue
                
        return results
    except Exception as e:
        print(f"Search error: {e}")
        return []
    finally:
        driver.quit()

# Chatbot function with enhanced error handling
def chatbot(message, history, use_web_search):
    try:
        search_results = []
        context = message
        
        # Perform web search if enabled
        if use_web_search:
            with gr.Blocks(analytics_enabled=False):
                with gr.Row():
                    gr.Markdown("πŸ” Searching the web...")
            
            search_results = search_with_selenium(message)
            if search_results:
                context += "\n\nWeb search results:\n"
                for i, result in enumerate(search_results, 1):
                    context += f"{i}. {result['title']}\n{result['snippet']}\n\n"
        
        # Generate response
        response = model.generate_content(context)
        bot_message = response.text
        
        # Format response with search results
        if search_results:
            bot_message += "\n\nπŸ“š Sources:\n"
            for result in search_results:
                bot_message += f"- [{result['title']}]({result['link']})\n"
        
        return bot_message
    except Exception as e:
        return f"⚠️ Error: {str(e)}"

# Gradio interface with enhanced UI
with gr.Blocks(
    title="Gemini AI Chatbot with Web Search",
    theme=gr.themes.Soft(),
    css=".gradio-container {max-width: 800px !important}"
) as demo:
    
    gr.Markdown("""
    # πŸ’Ž Gemini AI Chatbot
    **Powered by Google Gemini Pro + Real-time Web Search**
    """)
    
    with gr.Row():
        with gr.Column(scale=4):
            chatbot = gr.Chatbot(
                height=500,
                bubble_full_width=False,
                avatar_images=(
                    "user.png", 
                    "bot.png"
                )
            )
            msg = gr.Textbox(
                label="Your Message",
                placeholder="Ask me anything...",
                lines=2
            )
            
            with gr.Row():
                submit_btn = gr.Button("Send", variant="primary")
                clear_btn = gr.Button("Clear")
                web_search = gr.Checkbox(
                    label="Enable Web Search",
                    value=True,
                    interactive=True
                )
        
        with gr.Column(scale=1):
            gr.Markdown("""
            ### 🌐 Web Search Features
            - Real-time Google results
            - Source citations
            - Toggle on/off
            
            ### βš™οΈ Controls
            - Press Enter or click Send
            - Clear resets conversation
            """)
    
    # Event handlers
    def respond(message, chat_history, use_search):
        bot_message = chatbot(message, chat_history, use_search)
        chat_history.append((message, bot_message))
        return "", chat_history
    
    msg.submit(respond, [msg, chatbot, web_search], [msg, chatbot])
    submit_btn.click(respond, [msg, chatbot, web_search], [msg, chatbot])
    clear_btn.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        favicon_path="favicon.ico"
    )