import os import streamlit as st from googleapiclient.discovery import build import speech_recognition as sr import wikipediaapi import datetime from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas import tempfile from gtts import gTTS import requests import json import pandas as pd import altair as alt from datetime import date import pickle # Set up YouTube API API_KEY_YOUTUBE = os.getenv("YT") # Replace with your YouTube Data API v3 key youtube = build('youtube', 'v3', developerKey=API_KEY_YOUTUBE) # Hugging Face Setup HF_API_KEY = os.getenv("HF_API") HF_MISTRAL_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3" AI_IMAGE_API_KEY = os.getenv("IMG_API")# Hugging Face or RapidAPI key LOGO_API_KEY = os.getenv("LOGO_API") # API key for logo generation def chat_with_mistral_hf(prompt): if not HF_API_KEY: return "Error: API key not found. Please set it in Hugging Face Secrets." headers = {"Authorization": f"Bearer {HF_API_KEY}"} payload = {"inputs": prompt, "parameters": {"max_length": 200, "temperature": 0.7}} response = requests.post(HF_MISTRAL_URL, json=payload, headers=headers) if response.status_code == 200: return response.json()[0]["generated_text"] else: return f"Error: {response.json()}" # Function to search YouTube videos def search_youtube(query, max_results=5): try: request = youtube.search().list( q=query, part='id,snippet', maxResults=max_results, type='video' ) response = request.execute() videos = [] for item in response['items']: video_id = item['id']['videoId'] title = item['snippet']['title'] thumbnail = item['snippet']['thumbnails']['default']['url'] url = f'https://www.youtube.com/watch?v={video_id}' videos.append({'title': title, 'url': url, 'video_id': video_id, 'thumbnail': thumbnail}) return videos except Exception as e: st.write(f"Error fetching videos: {e}") return [] # # Function for voice recognition # # This feature is available only , when running locally # def voice_search(): # recognizer = sr.Recognizer() # with sr.Microphone() as source: # st.write("Listening...") # audio = recognizer.listen(source) # try: # query = recognizer.recognize_google(audio) # st.success(f"You said: {query}") # return query # except sr.UnknownValueError: # st.error("Could not understand audio") # return "" # except sr.RequestError as e: # st.error(f"Could not request results from Google Speech Recognition service; {e}") # return "" # Wikipedia summary function with character limit and summary levels def get_wikipedia_summary(query, lang_code, char_limit, summary_level): user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)" wiki = wikipediaapi.Wikipedia(language=lang_code, extract_format=wikipediaapi.ExtractFormat.WIKI, user_agent=user_agent) page = wiki.page(query) if not page.exists(): return "Page not found." if summary_level == "Brief": return page.summary[:char_limit] elif summary_level == "Detailed": return page.summary # Full summary elif summary_level == "Bullet Points": points = page.summary.split('. ') return '\n'.join(f"- {p.strip()}" for p in points if p)[:char_limit] # Save chat history as PDF with a user-defined filename def save_chat_history_as_pdf(chat_history, file_name): timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file: pdf = canvas.Canvas(tmp_file.name, pagesize=letter) pdf.setTitle(file_name) pdf.drawString(30, 750, f"{file_name} - Saved on {timestamp}") y_position = 720 for query, response in chat_history: pdf.drawString(30, y_position, f"User: {query}") y_position -= 20 pdf.drawString(30, y_position, f"Bot: {response}") y_position -= 40 if y_position < 40: pdf.showPage() y_position = 750 pdf.save() return tmp_file.name # Text-to-speech using gTTS def text_to_speech(text, filename, lang="en"): tts = gTTS(text=text, lang=lang) tts.save(filename) return filename # 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() # Display Google Search Results def display_google_results(results): if "items" in results: for item in results['items']: st.write(f"**{item['title']}**") st.write(item['snippet']) st.write(f"[Read more]({item['link']})") st.write("---") else: st.error("No results found.") # News Search Function def search_news(query, from_date=None, to_date=None): api_key = os.getenv("NEWS_API") # Replace with your News API key url = f"https://newsapi.org/v2/everything?q={query}&apiKey={api_key}" if from_date and to_date: url += f"&from={from_date}&to={to_date}" response = requests.get(url) return response.json() # Display News Results def display_news(articles): if "articles" in articles: for article in articles['articles']: st.write(f"**{article['title']}**") st.write(article['description']) st.write(f"[Read more]({article['url']})") st.write("---") else: st.error("No news articles found.") # File to store shortcut data DATA_FILE = "shortcuts_data.pkl" def load_shortcuts(): if os.path.exists(DATA_FILE): with open(DATA_FILE, "rb") as f: return pickle.load(f) return [] def save_shortcuts(shortcuts): with open(DATA_FILE, "wb") as f: pickle.dump(shortcuts, f) if "shortcuts" not in st.session_state: st.session_state["shortcuts"] = load_shortcuts() def main(): st.set_page_config(page_title="Multi-Search Application", layout="wide") # **Show Saved Shortcuts** st.header("Multimodal Query Processing & Knowledge Retrieval Sys") with st.expander("Click to View Shortcuts"): if st.session_state.shortcuts: num_columns = 4 cols = st.columns(num_columns) for i, (name, link, icon_data, user_password) in enumerate(st.session_state.shortcuts): col = cols[i % num_columns] with col: st.image(icon_data, width=100) st.markdown(f"[{name}]({link})", unsafe_allow_html=True) password_input_delete = st.text_input("Enter Password to Delete", type="password", key=f"delete_password_{i}") if password_input_delete == user_password: if st.button(f"Delete {name}", key=f"delete_{i}"): st.session_state.shortcuts.pop(i) save_shortcuts(st.session_state.shortcuts) st.experimental_rerun() elif password_input_delete: st.warning("Incorrect password. You cannot delete this shortcut.") else: st.write("No shortcuts added yet.") st.markdown("Note: Add best web links for student education purposes.") if "query" not in st.session_state: st.session_state.query = "" # Initialize chat history if not present if "chat_history" not in st.session_state: st.session_state.chat_history = [] # Sidebar options st.sidebar.title("Options") search_type = st.sidebar.radio("Select Search Type", ("Wikipedia", "Google", "YouTube", "News", "Chat","Image Generation", "Logo Generation")) # **Add this block after st.sidebar.title("Options")** st.sidebar.header("Only Add Best Web Links") name = st.sidebar.text_input("Shortcut Name") link = st.sidebar.text_input("Website Link (https://...)") icon_file = st.sidebar.file_uploader("Upload an Icon", type=["png", "jpg", "jpeg"]) password_input_add = st.sidebar.text_input("Enter Password to Add Shortcut", type="password") if st.sidebar.button("Add Shortcut"): if password_input_add: if name and link and icon_file: existing_links = [shortcut[1] for shortcut in st.session_state.shortcuts] if link in existing_links: st.sidebar.warning("This website already exists.") else: st.session_state.shortcuts.append((name, link, icon_file.getvalue(), password_input_add)) save_shortcuts(st.session_state.shortcuts) st.sidebar.success(f"Shortcut '{name}' added!") else: st.sidebar.warning("Please enter all details including an icon.") else: st.sidebar.warning("Please enter a password to add the shortcut.") # if st.sidebar.button("Voice Search"): # query = voice_search() # if query: # st.session_state.query = query # else: # st.session_state.query = "" # Chat-specific sidebar settings chat_title = "Temporary Chat" if search_type == "Chat": chat_title = st.sidebar.text_input("Rename Chat:", "Temporary Chat") # Last seen timestamp st.sidebar.write(f"Last seen: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") if search_type == "Wikipedia": lang_map = {"English": "en", "Spanish": "es", "Chinese": "zh", "Hindi": "hi", "Telugu": "te"} selected_lang = st.sidebar.selectbox("Wikipedia Language", list(lang_map.keys())) summary_levels = ["Brief", "Detailed", "Bullet Points"] summary_level = st.sidebar.selectbox("Summarization Level", summary_levels) char_limit = st.sidebar.slider("Character Limit", min_value=100, max_value=2000, value=500, step=100) st.title("Wikipedia Summary & Text-to-Speech") query = st.text_input("Enter a topic to search on Wikipedia:", value=st.session_state.query) if query: lang_code = lang_map[selected_lang] summary = get_wikipedia_summary(query, lang_code, char_limit, summary_level) st.markdown(f"### Summary for: {query}") st.write(summary) tts_filename = f"{query}_speech.mp3" if st.button("Play Text-to-Speech"): text_to_speech(summary, tts_filename, lang=lang_code) st.audio(tts_filename, format="audio/mp3") st.write("---") st.write("### Footer") st.write("This is a Wikipedia search section. You can find detailed information and summaries here.") elif search_type == "Google": st.title("Google Search") query = st.text_input("Enter a search query for Google:", value=st.session_state.query) if query and st.button("Search"): results = google_search("AIzaSyBvnTpjwspsYBMlHN4nMEvybEmZL8mwAQ4", "464947c4e602c4ee8", query) display_google_results(results) st.write("---") st.write("### Footer") st.write("This is a Google search section. Use it to find websites and online resources.") elif search_type == "YouTube": st.title("YouTube Search") query = st.text_input("Enter a topic to search on YouTube:", value=st.session_state.query) if query and st.button("Search"): videos = search_youtube(query) if videos: for video in videos: st.write(f"[{video['title']}]({video['url']})") st.image(video['thumbnail']) st.video(video['url']) st.write("---") st.write("---") st.write("### Footer") st.write("This is a YouTube search section. Watch videos directly from your search results.") elif search_type == "News": st.subheader("Select Date Range") start_date = st.date_input("From", datetime.date.today() - datetime.timedelta(days=7)) end_date = st.date_input("To", datetime.date.today()) st.title("News Search") query = st.text_input("Enter a news topic to search:", value=st.session_state.query) if query and st.button("Search"): articles = search_news(query, start_date, end_date) display_news(articles) st.write("---") st.write("### Footer") st.write("This is a news search section. Find the latest news articles here.") elif search_type == "Chat": st.title(chat_title) for chat in st.session_state.chat_history: with st.chat_message(chat["role"]): st.write(chat["content"]) user_input = st.text_input("Ask AI:") st.session_state.query = user_input # Explicitly store the input if st.button("Generate Response"): if st.session_state.query and st.session_state.query.strip(): with st.spinner("Generating response..."): response = chat_with_mistral_hf(user_input) st.session_state.chat_history.append({"role": "user", "content": user_input}) st.session_state.chat_history.append({"role": "assistant", "content": response}) st.rerun() else: st.warning("Please enter a prompt before clicking Generate Response.") elif search_type == "Image Generation": st.title("AI Image Generator") st.write("Generate AI-powered images using text prompts.") prompt = st.text_area("Enter your image description:") output_type = st.selectbox("Select output format:", ["png", "jpg"]) def generate_image(): url = "https://ai-image-generator14.p.rapidapi.com/" headers = { "x-rapidapi-key": AI_IMAGE_API_KEY, "x-rapidapi-host": "ai-image-generator14.p.rapidapi.com", "Content-Type": "application/json" } payload = { "jsonBody": { "function_name": "image_generator", "type": "image_generation", "query": prompt, "output_type": output_type } } response = requests.post(url, json=payload, headers=headers) return response.json() if st.button("Generate Image"): if prompt: with st.spinner("Generating image..."): result = generate_image() image_url = result.get("message", {}).get("output_png") if image_url: st.image(image_url, caption="Generated Image", use_container_width=True) # Provide download button st.download_button( label="Download Image", data=requests.get(image_url).content, file_name=f"generated_image.{output_type}", mime=f"image/{output_type}" ) else: st.error("Failed to generate image. No image URL found in response.") st.write("Response Data:", result) # Debugging: Show response data else: st.warning("Please enter an image description.") elif search_type == "Logo Generation": st.title("AI Logo Generator 🎨") st.write("Generate a unique logo for your business using AI!") # User Inputs prompt = st.text_input("Enter a description for the logo:", "Make a logo for my gaming company BTZ") style = st.selectbox("Select a Logo Style:", [28, 29, 30], index=0) # Customize styles if needed size = st.radio("Select Image Size:", ["1-1", "2-3", "3-4"], index=0) def generate_logo(prompt, style, size): api_url = "https://ai-logo-generator.p.rapidapi.com/aaaaaaaaaaaaaaaaaiimagegenerator/quick.php" headers = { "x-rapidapi-key": LOGO_API_KEY, "x-rapidapi-host": "ai-logo-generator.p.rapidapi.com", "Content-Type": "application/json" } payload = { "prompt": prompt, "style_id": style, "size": size } response = requests.post(api_url, json=payload, headers=headers) return response.json() # Generate button if st.button("Generate Logo"): with st.spinner("Generating logo... Please wait!"): result = generate_logo(prompt, style, size) # Extracting image URLs from the JSON response image_data = result.get("final_result", []) if image_data: st.subheader("Generated Logo Designs") for index, image in enumerate(image_data): image_url = image.get("origin") # Extracting the logo link if image_url: st.image(image_url, caption=f"Logo Design {index+1}", use_container_width=True) # Download button with a unique key st.download_button( label="Download Logo", data=requests.get(image_url).content, file_name=f"logo_design_{index+1}.webp", mime="image/webp", key=f"download_{index}" # Unique key to prevent duplicate errors ) else: st.error("Failed to generate logo. No image URL found.") st.write("Response Data:", result) # Debugging: Show full response data # Save chat history as PDF if st.button("Save Chat History as PDF"): chat_history = [] if st.session_state.query: chat_history.append((st.session_state.query, "Your response here")) file_name = st.text_input("Enter filename for PDF:", "chat_history.pdf") pdf_file = save_chat_history_as_pdf(chat_history, file_name) st.success(f"Chat history saved as PDF: {pdf_file}") if __name__ == "__main__": main()