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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bdd106
ad2bfab
9c440c0
ad2bfab
 
 
9c440c0
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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()