gskdsrikrishna commited on
Commit
ad2bfab
·
verified ·
1 Parent(s): ae769c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -87
app.py CHANGED
@@ -13,27 +13,14 @@ import json
13
  import pandas as pd
14
  import altair as alt
15
  from datetime import date
16
- import pickle
17
 
18
- # Constants and API Keys
19
- API_KEY_YOUTUBE = "AIzaSyA20DXMC3HeqHs9sOMQUQ041wEkgsoFXb4"
20
- HF_API_KEY = os.getenv("KEY")
21
- HF_MISTRAL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
22
- DATA_FILE = "shortcuts_data.pkl"
23
- AUTHOR_PASSWORD = os.getenv("APP_PASSWORD")
24
-
25
- # Initialize services
26
  youtube = build('youtube', 'v3', developerKey=API_KEY_YOUTUBE)
27
 
28
- def load_shortcuts():
29
- if os.path.exists(DATA_FILE):
30
- with open(DATA_FILE, "rb") as f:
31
- return pickle.load(f)
32
- return []
33
-
34
- def save_shortcuts(shortcuts):
35
- with open(DATA_FILE, "wb") as f:
36
- pickle.dump(shortcuts, f)
37
 
38
  def chat_with_mistral_hf(prompt):
39
  if not HF_API_KEY:
@@ -167,92 +154,102 @@ def display_news(articles):
167
  else:
168
  st.error("No news articles found.")
169
 
170
-
171
- # All other functions remain the same (search_youtube, voice_search, get_wikipedia_summary, etc.)
172
-
173
  def main():
174
  st.set_page_config(page_title="Multi-Search Application", layout="wide")
175
 
176
- # Initialize session states
177
  if "chat_history" not in st.session_state:
178
  st.session_state.chat_history = []
179
- if "shortcuts" not in st.session_state:
180
- st.session_state.shortcuts = load_shortcuts()
181
 
182
- # Sidebar setup
183
  st.sidebar.title("Options")
184
- search_type = st.sidebar.radio("Select Search Type",
185
- ("Wikipedia", "Google", "YouTube", "News", "Chat", "Shortcuts"))
186
 
187
- # Voice search and chat title
188
  if st.sidebar.button("Voice Search"):
189
  query = voice_search()
190
  if query:
191
  st.session_state.query = query
192
  else:
193
  st.session_state.query = ""
194
-
 
195
  chat_title = "Temporary Chat"
196
  if search_type == "Chat":
197
  chat_title = st.sidebar.text_input("Rename Chat:", "Temporary Chat")
198
 
199
- # Shortcuts management in sidebar
200
- if search_type == "Shortcuts":
201
- st.sidebar.header("Manage Shortcuts")
202
- name = st.sidebar.text_input("Shortcut Name")
203
- link = st.sidebar.text_input("Website Link (https://...)")
204
- icon_file = st.sidebar.file_uploader("Upload an Icon", type=["png", "jpg", "jpeg"])
205
- password_input_add = st.sidebar.text_input("Enter Password to Add Shortcut", type="password")
206
-
207
- if st.sidebar.button("Add Shortcut"):
208
- if password_input_add:
209
- if name and link and icon_file:
210
- existing_links = [shortcut[1] for shortcut in st.session_state.shortcuts]
211
- if link in existing_links:
212
- st.sidebar.warning("This website already exists.")
213
- else:
214
- st.session_state.shortcuts.append((
215
- name,
216
- link,
217
- icon_file.getvalue(),
218
- password_input_add,
219
- AUTHOR_PASSWORD
220
- ))
221
- save_shortcuts(st.session_state.shortcuts)
222
- st.sidebar.success(f"Shortcut '{name}' added!")
223
- else:
224
- st.sidebar.warning("Please enter all details including an icon.")
225
- else:
226
- st.sidebar.warning("Please enter a password to add the shortcut.")
227
-
228
- # Main content area
229
- if search_type == "Shortcuts":
230
- st.header("Educational Shortcuts")
231
- with st.expander("Click to View Shortcuts", expanded=True):
232
- if st.session_state.shortcuts:
233
- cols = st.columns(4)
234
- for i, (name, link, icon_data, user_password, _) in enumerate(st.session_state.shortcuts):
235
- with cols[i % 4]:
236
- st.image(icon_data, width=100)
237
- st.markdown(f"[{name}]({link})")
238
- password_input_delete = st.text_input(
239
- "Enter Password to Delete",
240
- type="password",
241
- key=f"delete_{i}"
242
- )
243
- if st.button(f"Delete {name}", key=f"delbtn_{i}"):
244
- if password_input_delete in [AUTHOR_PASSWORD, user_password]:
245
- del st.session_state.shortcuts[i]
246
- save_shortcuts(st.session_state.shortcuts)
247
- st.rerun()
248
- else:
249
- st.warning("Incorrect password")
250
- else:
251
- st.write("No shortcuts added yet.")
252
- st.markdown("**Note:** Add educational web links for student learning purposes.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
 
254
  elif search_type == "Chat":
255
  st.title(chat_title)
 
256
  for chat in st.session_state.chat_history:
257
  with st.chat_message(chat["role"]):
258
  st.write(chat["content"])
@@ -263,17 +260,18 @@ def main():
263
  if user_input.strip():
264
  with st.spinner("Generating response..."):
265
  response = chat_with_mistral_hf(user_input)
 
266
  st.session_state.chat_history.append({"role": "user", "content": user_input})
267
  st.session_state.chat_history.append({"role": "assistant", "content": response})
268
  st.rerun()
269
  else:
270
  st.warning("Please enter a prompt before clicking Generate Response.")
271
 
272
- # Other search types (Wikipedia, Google, YouTube, News) remain unchanged
273
-
274
- # PDF saving functionality
275
  if st.button("Save Chat History as PDF"):
276
- chat_history = [(msg['content'], "") for msg in st.session_state.chat_history if msg['role'] == 'user']
 
 
277
  file_name = st.text_input("Enter filename for PDF:", "chat_history.pdf")
278
  pdf_file = save_chat_history_as_pdf(chat_history, file_name)
279
  st.success(f"Chat history saved as PDF: {pdf_file}")
 
13
  import pandas as pd
14
  import altair as alt
15
  from datetime import date
 
16
 
17
+ # Set up YouTube API
18
+ API_KEY_YOUTUBE = "AIzaSyA20DXMC3HeqHs9sOMQUQ041wEkgsoFXb4" # Replace with your YouTube Data API v3 key
 
 
 
 
 
 
19
  youtube = build('youtube', 'v3', developerKey=API_KEY_YOUTUBE)
20
 
21
+ # Hugging Face Setup
22
+ HF_API_KEY = os.getenv("KEY")
23
+ HF_MISTRAL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
 
 
 
 
 
 
24
 
25
  def chat_with_mistral_hf(prompt):
26
  if not HF_API_KEY:
 
154
  else:
155
  st.error("No news articles found.")
156
 
 
 
 
157
  def main():
158
  st.set_page_config(page_title="Multi-Search Application", layout="wide")
159
 
160
+ # Initialize chat history if not present
161
  if "chat_history" not in st.session_state:
162
  st.session_state.chat_history = []
 
 
163
 
164
+ # Sidebar options
165
  st.sidebar.title("Options")
166
+ search_type = st.sidebar.radio("Select Search Type", ("Wikipedia", "Google", "YouTube", "News", "Chat"))
 
167
 
 
168
  if st.sidebar.button("Voice Search"):
169
  query = voice_search()
170
  if query:
171
  st.session_state.query = query
172
  else:
173
  st.session_state.query = ""
174
+
175
+ # Chat-specific sidebar settings
176
  chat_title = "Temporary Chat"
177
  if search_type == "Chat":
178
  chat_title = st.sidebar.text_input("Rename Chat:", "Temporary Chat")
179
 
180
+ # Last seen timestamp
181
+ st.sidebar.write(f"Last seen: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
182
+
183
+ if search_type == "Wikipedia":
184
+ lang_map = {"English": "en", "Spanish": "es", "Chinese": "zh", "Hindi": "hi", "Telugu": "te"}
185
+ selected_lang = st.sidebar.selectbox("Wikipedia Language", list(lang_map.keys()))
186
+ summary_levels = ["Brief", "Detailed", "Bullet Points"]
187
+ summary_level = st.sidebar.selectbox("Summarization Level", summary_levels)
188
+ char_limit = st.sidebar.slider("Character Limit", min_value=100, max_value=2000, value=500, step=100)
189
+
190
+ st.title("Wikipedia Summary & Text-to-Speech")
191
+ query = st.text_input("Enter a topic to search on Wikipedia:", value=st.session_state.query)
192
+
193
+ if query:
194
+ lang_code = lang_map[selected_lang]
195
+ summary = get_wikipedia_summary(query, lang_code, char_limit, summary_level)
196
+ st.markdown(f"### Summary for: {query}")
197
+ st.write(summary)
198
+
199
+ tts_filename = f"{query}_speech.mp3"
200
+ if st.button("Play Text-to-Speech"):
201
+ text_to_speech(summary, tts_filename, lang=lang_code)
202
+ st.audio(tts_filename, format="audio/mp3")
203
+
204
+ st.write("---")
205
+ st.write("### Footer")
206
+ st.write("This is a Wikipedia search section. You can find detailed information and summaries here.")
207
+
208
+ elif search_type == "Google":
209
+ st.title("Google Search")
210
+ query = st.text_input("Enter a search query for Google:", value=st.session_state.query)
211
+ if query and st.button("Search"):
212
+ results = google_search("AIzaSyBvnTpjwspsYBMlHN4nMEvybEmZL8mwAQ4", "464947c4e602c4ee8", query)
213
+ display_google_results(results)
214
+
215
+ st.write("---")
216
+ st.write("### Footer")
217
+ st.write("This is a Google search section. Use it to find websites and online resources.")
218
+
219
+ elif search_type == "YouTube":
220
+ st.title("YouTube Search")
221
+ query = st.text_input("Enter a topic to search on YouTube:", value=st.session_state.query)
222
+ if query and st.button("Search"):
223
+ videos = search_youtube(query)
224
+ if videos:
225
+ for video in videos:
226
+ st.write(f"[{video['title']}]({video['url']})")
227
+ st.image(video['thumbnail'])
228
+ st.video(video['url'])
229
+ st.write("---")
230
+
231
+ st.write("---")
232
+ st.write("### Footer")
233
+ st.write("This is a YouTube search section. Watch videos directly from your search results.")
234
+
235
+ elif search_type == "News":
236
+ st.subheader("Select Date Range")
237
+ start_date = st.date_input("From", datetime.date.today() - datetime.timedelta(days=7))
238
+ end_date = st.date_input("To", datetime.date.today())
239
+
240
+ st.title("News Search")
241
+ query = st.text_input("Enter a news topic to search:", value=st.session_state.query)
242
+ if query and st.button("Search"):
243
+ articles = search_news(query, start_date, end_date)
244
+ display_news(articles)
245
+
246
+ st.write("---")
247
+ st.write("### Footer")
248
+ st.write("This is a news search section. Find the latest news articles here.")
249
 
250
  elif search_type == "Chat":
251
  st.title(chat_title)
252
+
253
  for chat in st.session_state.chat_history:
254
  with st.chat_message(chat["role"]):
255
  st.write(chat["content"])
 
260
  if user_input.strip():
261
  with st.spinner("Generating response..."):
262
  response = chat_with_mistral_hf(user_input)
263
+
264
  st.session_state.chat_history.append({"role": "user", "content": user_input})
265
  st.session_state.chat_history.append({"role": "assistant", "content": response})
266
  st.rerun()
267
  else:
268
  st.warning("Please enter a prompt before clicking Generate Response.")
269
 
270
+ # Save chat history as PDF
 
 
271
  if st.button("Save Chat History as PDF"):
272
+ chat_history = []
273
+ if st.session_state.query:
274
+ chat_history.append((st.session_state.query, "Your response here"))
275
  file_name = st.text_input("Enter filename for PDF:", "chat_history.pdf")
276
  pdf_file = save_chat_history_as_pdf(chat_history, file_name)
277
  st.success(f"Chat history saved as PDF: {pdf_file}")