gskdsrikrishna commited on
Commit
e300f37
·
verified ·
1 Parent(s): 46c3f1b

Update google.py

Browse files
Files changed (1) hide show
  1. google.py +136 -136
google.py CHANGED
@@ -1,136 +1,136 @@
1
- import streamlit as st
2
- import requests
3
- import json
4
- import os
5
- import speech_recognition as sr
6
- import pandas as pd
7
- import altair as alt
8
- from PIL import Image
9
- from io import BytesIO
10
-
11
- # Function to perform Google Search
12
- def google_search(api_key, cse_id, query, num_results=10):
13
- url = "https://www.googleapis.com/customsearch/v1"
14
- params = {'key': api_key, 'cx': cse_id, 'q': query, 'num': num_results}
15
- response = requests.get(url, params=params)
16
- return response.json()
17
-
18
- # Initialize search history and data storage for analytics
19
- if 'search_history' not in st.session_state:
20
- st.session_state.search_history = []
21
- if 'search_data' not in st.session_state:
22
- st.session_state.search_data = pd.DataFrame(columns=["Query", "Source", "Timestamp"])
23
-
24
- def main():
25
- st.title("Enhanced Google Search Application")
26
-
27
- # User inputs for API key, CSE ID, and search query
28
- api_key = "AIzaSyBvnTpjwspsYBMlHN4nMEvybEmZL8mwAQ4"
29
- cse_id = "464947c4e602c4ee8"
30
- query = st.text_input("Enter your search query", "", key='query_input')
31
-
32
- # Voice search feature
33
- if st.button("Use Voice Search"):
34
- recognizer = sr.Recognizer()
35
- with sr.Microphone() as source:
36
- st.write("Listening...")
37
- audio = recognizer.listen(source)
38
- try:
39
- query = recognizer.recognize_google(audio)
40
- st.write(f"You said: {query}")
41
- if api_key and cse_id and query:
42
- results = google_search(api_key, cse_id, query)
43
- update_search_history(query, "Voice")
44
- display_results(results)
45
- except sr.UnknownValueError:
46
- st.error("Could not understand audio.")
47
- except sr.RequestError:
48
- st.error("Could not request results from Google.")
49
-
50
- # Trigger search on Enter or when search button is clicked
51
- if st.button("Search") or st.session_state.get('query_input'):
52
- if api_key and cse_id and query:
53
- results = google_search(api_key, cse_id, query)
54
- update_search_history(query, "Text")
55
- display_results(results)
56
- else:
57
- st.error("Please enter API Key, CSE ID, and a search query.")
58
-
59
- # Button to show search history
60
- if st.button("Show Search History"):
61
- if st.session_state.search_history:
62
- st.write("Search History:")
63
- for h in st.session_state.search_history:
64
- st.write(h)
65
- else:
66
- st.write("No search history found.")
67
-
68
- # Button to clear search history
69
- if st.button("Clear Search History"):
70
- st.session_state.search_history.clear()
71
- st.session_state.search_data = pd.DataFrame(columns=["Query", "Source", "Timestamp"])
72
- st.success("Search history cleared.")
73
-
74
- # Interactive Analytics Dashboard
75
- st.subheader("Search Analytics")
76
- if not st.session_state.search_data.empty:
77
- # Chart of search counts over time
78
- search_trends = alt.Chart(st.session_state.search_data).mark_line().encode(
79
- x='Timestamp:T',
80
- y='count():Q',
81
- color='Source:N',
82
- tooltip=['Query:N', 'count():Q', 'Source:N']
83
- ).properties(width=600, height=300)
84
- st.altair_chart(search_trends, use_container_width=True)
85
-
86
- # Most popular queries
87
- st.write("**Top Search Queries**")
88
- top_queries = (
89
- st.session_state.search_data['Query']
90
- .value_counts()
91
- .head(5)
92
- .reset_index()
93
- .rename(columns={'index': 'Query', 'Query': 'Count'})
94
- )
95
- st.write(top_queries)
96
-
97
- def display_results(results):
98
- if results and 'items' in results:
99
- st.session_state.results = results
100
- for i, item in enumerate(results['items']):
101
- st.write(f"**{i + 1}. {item['title']}**")
102
- st.write(f"[Link]({item['link']})")
103
- st.write(f"{item['snippet']}\n")
104
-
105
- # Check if 'pagemap' and 'cse_image' exist and if 'src' is in 'cse_image'
106
- if 'pagemap' in item and 'cse_image' in item['pagemap']:
107
- image_data = item['pagemap']['cse_image'][0]
108
- image_url = image_data.get('src') # Use .get() to avoid KeyError
109
-
110
- # Try to load and display the image if 'src' exists
111
- if image_url:
112
- try:
113
- response = requests.get(image_url)
114
- img = Image.open(BytesIO(response.content))
115
- st.image(img, width=100)
116
- except Exception as e:
117
- st.write("**Image could not be loaded.**")
118
- else:
119
- st.write("**Image source not available.**")
120
- else:
121
- st.write("No image available for this result.")
122
- else:
123
- st.write("No results found.")
124
-
125
- def update_search_history(query, source):
126
- # Update search history and analytics data
127
- st.session_state.search_history.append(query)
128
- new_data = pd.DataFrame({
129
- "Query": [query],
130
- "Source": [source],
131
- "Timestamp": [pd.Timestamp.now()]
132
- })
133
- st.session_state.search_data = pd.concat([st.session_state.search_data, new_data], ignore_index=True)
134
-
135
- if __name__ == "__main__":
136
- main()
 
1
+ api_key = "AIzaSyBvnTpjwspsYBMlHN4nMEvybEmZL8mwAQ4"
2
+ cse_id = "464947c4e602c4ee8"
3
+ import streamlit as st
4
+ import requests
5
+ import speech_recognition as sr
6
+ import pandas as pd
7
+ import altair as alt
8
+ from PIL import Image
9
+ from io import BytesIO
10
+
11
+ # Ensure set_page_config is the first Streamlit command
12
+ st.set_page_config(page_title="Google Search App", layout="wide")
13
+
14
+ # Function to perform Google Search
15
+ def google_search(api_key, cse_id, query, num_results=10):
16
+ url = "https://www.googleapis.com/customsearch/v1"
17
+ params = {'key': api_key, 'cx': cse_id, 'q': query, 'num': num_results}
18
+ response = requests.get(url, params=params)
19
+ return response.json()
20
+
21
+ # Initialize search history and data storage for analytics
22
+ if 'search_history' not in st.session_state:
23
+ st.session_state.search_history = []
24
+ if 'search_data' not in st.session_state:
25
+ st.session_state.search_data = pd.DataFrame(columns=["Query", "Source", "Timestamp"])
26
+
27
+ def main():
28
+ st.title("Enhanced Google Search Application")
29
+
30
+ # User inputs for API key, CSE ID, and search query
31
+ api_key = st.secrets["GOOGLE_API_KEY"] # Use Streamlit secrets for security
32
+ cse_id = st.secrets["CSE_ID"]
33
+
34
+ query = st.text_input("Enter your search query", "", key='query_input')
35
+
36
+ # Voice search feature
37
+ if st.button("Use Voice Search"):
38
+ recognizer = sr.Recognizer()
39
+ with sr.Microphone() as source:
40
+ st.write("Listening...")
41
+ audio = recognizer.listen(source)
42
+ try:
43
+ query = recognizer.recognize_google(audio)
44
+ st.write(f"You said: {query}")
45
+ if api_key and cse_id and query:
46
+ results = google_search(api_key, cse_id, query)
47
+ update_search_history(query, "Voice")
48
+ display_results(results)
49
+ except sr.UnknownValueError:
50
+ st.error("Could not understand audio.")
51
+ except sr.RequestError:
52
+ st.error("Could not request results from Google.")
53
+
54
+ # Trigger search when clicking the search button
55
+ if st.button("Search") and query:
56
+ if api_key and cse_id:
57
+ results = google_search(api_key, cse_id, query)
58
+ update_search_history(query, "Text")
59
+ display_results(results)
60
+ else:
61
+ st.error("Please enter API Key, CSE ID, and a search query.")
62
+
63
+ # Show search history
64
+ if st.button("Show Search History"):
65
+ if st.session_state.search_history:
66
+ st.write("Search History:")
67
+ for h in st.session_state.search_history:
68
+ st.write(h)
69
+ else:
70
+ st.write("No search history found.")
71
+
72
+ # Clear search history
73
+ if st.button("Clear Search History"):
74
+ st.session_state.search_history.clear()
75
+ st.session_state.search_data = pd.DataFrame(columns=["Query", "Source", "Timestamp"])
76
+ st.success("Search history cleared.")
77
+
78
+ # Interactive Analytics Dashboard
79
+ st.subheader("Search Analytics")
80
+ if not st.session_state.search_data.empty:
81
+ search_trends = alt.Chart(st.session_state.search_data).mark_line().encode(
82
+ x='Timestamp:T',
83
+ y='count():Q',
84
+ color='Source:N',
85
+ tooltip=['Query:N', 'count():Q', 'Source:N']
86
+ ).properties(width=600, height=300)
87
+ st.altair_chart(search_trends, use_container_width=True)
88
+
89
+ # Most popular queries
90
+ st.write("**Top Search Queries**")
91
+ top_queries = (
92
+ st.session_state.search_data['Query']
93
+ .value_counts()
94
+ .head(5)
95
+ .reset_index()
96
+ .rename(columns={'index': 'Query', 'Query': 'Count'})
97
+ )
98
+ st.write(top_queries)
99
+
100
+ def display_results(results):
101
+ if results and 'items' in results:
102
+ for i, item in enumerate(results['items']):
103
+ st.write(f"**{i + 1}. {item['title']}**")
104
+ st.write(f"[Link]({item['link']})")
105
+ st.write(f"{item['snippet']}\n")
106
+
107
+ # Display image if available
108
+ if 'pagemap' in item and 'cse_image' in item['pagemap']:
109
+ image_data = item['pagemap']['cse_image'][0]
110
+ image_url = image_data.get('src')
111
+
112
+ if image_url:
113
+ try:
114
+ response = requests.get(image_url)
115
+ img = Image.open(BytesIO(response.content))
116
+ st.image(img, width=100)
117
+ except Exception:
118
+ st.write("**Image could not be loaded.**")
119
+ else:
120
+ st.write("**Image source not available.**")
121
+ else:
122
+ st.write("No image available for this result.")
123
+ else:
124
+ st.write("No results found.")
125
+
126
+ def update_search_history(query, source):
127
+ st.session_state.search_history.append(query)
128
+ new_data = pd.DataFrame({
129
+ "Query": [query],
130
+ "Source": [source],
131
+ "Timestamp": [pd.Timestamp.now()]
132
+ })
133
+ st.session_state.search_data = pd.concat([st.session_state.search_data, new_data], ignore_index=True)
134
+
135
+ if __name__ == "__main__":
136
+ main()