File size: 5,097 Bytes
bf88000
e300f37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import requests
import speech_recognition as sr
import pandas as pd
import altair as alt
from PIL import Image
from io import BytesIO

# Ensure set_page_config is the first Streamlit command
st.set_page_config(page_title="Google Search App", layout="wide")

# Function to perform Google Search
def google_search(api_key, cse_id, query, num_results=10):
    url = "https://www.googleapis.com/customsearch/v1"
    params = {'key': api_key, 'cx': cse_id, 'q': query, 'num': num_results}
    response = requests.get(url, params=params)
    return response.json()

# Initialize search history and data storage for analytics
if 'search_history' not in st.session_state:
    st.session_state.search_history = []
if 'search_data' not in st.session_state:
    st.session_state.search_data = pd.DataFrame(columns=["Query", "Source", "Timestamp"])

def main():
    st.title("Enhanced Google Search Application")

    # User inputs for API key, CSE ID, and search query
    api_key = st.secrets["GOOGLE_API_KEY"]  # Use Streamlit secrets for security
    cse_id = st.secrets["CSE_ID"]
    
    query = st.text_input("Enter your search query", "", key='query_input')

    # Voice search feature
    if st.button("Use Voice Search"):
        recognizer = sr.Recognizer()
        with sr.Microphone() as source:
            st.write("Listening...")
            audio = recognizer.listen(source)
            try:
                query = recognizer.recognize_google(audio)
                st.write(f"You said: {query}")
                if api_key and cse_id and query:
                    results = google_search(api_key, cse_id, query)
                    update_search_history(query, "Voice")
                    display_results(results)
            except sr.UnknownValueError:
                st.error("Could not understand audio.")
            except sr.RequestError:
                st.error("Could not request results from Google.")

    # Trigger search when clicking the search button
    if st.button("Search") and query:
        if api_key and cse_id:
            results = google_search(api_key, cse_id, query)
            update_search_history(query, "Text")
            display_results(results)
        else:
            st.error("Please enter API Key, CSE ID, and a search query.")
    
    # Show search history
    if st.button("Show Search History"):
        if st.session_state.search_history:
            st.write("Search History:")
            for h in st.session_state.search_history:
                st.write(h)
        else:
            st.write("No search history found.")

    # Clear search history
    if st.button("Clear Search History"):
        st.session_state.search_history.clear()
        st.session_state.search_data = pd.DataFrame(columns=["Query", "Source", "Timestamp"])
        st.success("Search history cleared.")

    # Interactive Analytics Dashboard
    st.subheader("Search Analytics")
    if not st.session_state.search_data.empty:
        search_trends = alt.Chart(st.session_state.search_data).mark_line().encode(
            x='Timestamp:T',
            y='count():Q',
            color='Source:N',
            tooltip=['Query:N', 'count():Q', 'Source:N']
        ).properties(width=600, height=300)
        st.altair_chart(search_trends, use_container_width=True)

        # Most popular queries
        st.write("**Top Search Queries**")
        top_queries = (
            st.session_state.search_data['Query']
            .value_counts()
            .head(5)
            .reset_index()
            .rename(columns={'index': 'Query', 'Query': 'Count'})
        )
        st.write(top_queries)

def display_results(results):
    if results and 'items' in results:
        for i, item in enumerate(results['items']):
            st.write(f"**{i + 1}. {item['title']}**")
            st.write(f"[Link]({item['link']})")
            st.write(f"{item['snippet']}\n")
            
            # Display image if available
            if 'pagemap' in item and 'cse_image' in item['pagemap']:
                image_data = item['pagemap']['cse_image'][0]
                image_url = image_data.get('src')  
                
                if image_url:
                    try:
                        response = requests.get(image_url)
                        img = Image.open(BytesIO(response.content))
                        st.image(img, width=100)
                    except Exception:
                        st.write("**Image could not be loaded.**")
                else:
                    st.write("**Image source not available.**")
            else:
                st.write("No image available for this result.")
    else:
        st.write("No results found.")

def update_search_history(query, source):
    st.session_state.search_history.append(query)
    new_data = pd.DataFrame({
        "Query": [query],
        "Source": [source],
        "Timestamp": [pd.Timestamp.now()]
    })
    st.session_state.search_data = pd.concat([st.session_state.search_data, new_data], ignore_index=True)

if __name__ == "__main__":
    main()