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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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import os
import streamlit as st
import requests
import webbrowser
import time
import base64
from google.generativeai import configure, GenerativeModel
import streamlit.components.v1 as components
from urllib.parse import urlparse
from streamlit_lottie import st_lottie
from together import Together
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.utils import formataddr
from io import BytesIO
from PIL import Image

# Configure the Generative AI and Together clients
configure(api_key="AIzaSyBOc7WOykXVHvnU-GsMgCYZwoBqFERjQFI")
model = GenerativeModel('gemini-pro')
together_api_key = "00cb552f0e0a189c90abd086094fc503d6a8091e35634a769bacdc4266a3af6f"
client = Together(api_key=together_api_key)


# Email sending function
def send_email(subject, body, to_email, attachment=None, filename="attachment.png"):
    from_email = st.secrets["from_email"]
    from_password = st.secrets["from_password"]

    msg = MIMEMultipart()
    msg['From'] = formataddr(('AutoBot', from_email))
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    if attachment:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment)
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', f'attachment; filename={filename}')
        msg.attach(part)

    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(from_email, from_password)
        text = msg.as_string()
        server.sendmail(from_email, to_email, text)
        server.quit()
        st.success("Email sent successfully!")
    except Exception as e:
        st.error(f"Failed to send email: {e}")


# Lottie animation loader
def load_lottie_url(url: str):
    response = requests.get(url)
    if response.status_code != 200:
        return None
    return response.json()


# Function to download HTML code
def download_html_code(html_content, url):
    try:
        domain = urlparse(url).netloc.replace('www.', '')
        filename = f"{domain}_code.html"
        with open(filename, 'w') as file:
            file.write(html_content)
        st.markdown(get_binary_file_downloader_html(filename), unsafe_allow_html=True)
    except Exception as e:
        st.error(f"Failed to download HTML code: {e}")


# Function to redirect to GitHub Codespaces
def redirect_to_codespaces():
    with st.spinner("Redirecting to GitHub Codespaces..."):
        time.sleep(2)
    webbrowser.open_new_tab("https://github.com/codespaces")
    st.info("If the application can't redirect, use the link below:")
    st.markdown("[GitHub Codespaces](https://github.com/codespaces)")


# Function to download generated code
def download_generated_code(content, filename, format='txt'):
    extension = format
    temp_filename = f"{filename}.{extension}"
    with open(temp_filename, 'w') as file:
        file.write(content)
    with open(temp_filename, 'rb') as file:
        data = file.read()
    b64 = base64.b64encode(data).decode()
    href = f'<a href="data:file/{format};base64,{b64}" download="{filename}.{format}">Download Code ({format.upper()})</a>'
    st.markdown(href, unsafe_allow_html=True)
    os.remove(temp_filename)


# Function to display file download link
def get_binary_file_downloader_html(bin_file, file_label='Download Code'):
    with open(bin_file, 'rb') as f:
        data = f.read()
    b64 = base64.b64encode(data).decode()
    href = f'<a href="data:file/html;base64,{b64}" download="{bin_file}" target="_blank">{file_label}</a>'
    return href


# Function to display footer
def display_footer():
    footer_html = """
    <style>
    .footer {
        padding: 10px;
        background-color: #f8f9fa;
        text-align: center;
        border-top: 1px solid #e1e1e1;
        font-family: 'Arial', sans-serif;
        color: #6c757d;
    }
    </style>
    <body>
        <script src="//code.tidio.co/pwcadzxfjcnszjctpvlutoucjowgrrrw.js" async></script>
        </body>
    <div class="footer">
        <p><b>&copy; 2024 SKAV TECH. All rights reserved. | Follow us on <a href="https://bit.ly/socialinstag">Instagram</a></b></p>
    </div>
    """
    st.markdown(footer_html, unsafe_allow_html=True)


# Function to fetch YouTube video suggestions
def fetch_youtube_videos(query):
    api_key = st.secrets["youtube_api_key"]
    search_url = "https://www.googleapis.com/youtube/v3/search"
    params = {
        "part": "snippet",
        "q": query,
        "type": "video",
        "maxResults": 4,
        "key": api_key
    }
    response = requests.get(search_url, params=params)
    video_details = []
    if response.status_code == 200:
        results = response.json()["items"]
        for item in results:
            video_id = item["id"]["videoId"]
            video_title = item["snippet"]["title"]
            video_url = f"https://www.youtube.com/watch?v={video_id}"
            video_details.append({
                "title": video_title,
                "url": video_url,
                "video_id": video_id
            })
    else:
        st.error(f"Failed to fetch YouTube videos. Status code: {response.status_code}")
    return video_details


# Function to extract the main topic from the prompt
def extract_topic(prompt):
    start_phrases = ["@codex", "codex", "@autobot"]
    for phrase in start_phrases:
        if prompt.lower().startswith(phrase):
            return prompt[len(phrase):].strip()
    return prompt.strip()


# Main Streamlit application
def main():
    st.set_page_config(page_title="AutoBot AI", page_icon="πŸ’€", layout="wide", initial_sidebar_state="expanded")

    st.sidebar.image("autobot2.png", use_column_width=True)
    page = st.sidebar.selectbox("**MENU**",
                                ["🏠 Home", "AutoBot πŸ’€", "CODEX ⚑", "Web Scrapper 🌐", "GitHub Codespaces πŸ–₯️",
                                 "Mega Bot 🐸", "Refund & Privacy Policy πŸ’Έ", ])

    st.sidebar.title("Support Us")
    st.sidebar.info("Your support helps us improve AutoBot AI.")

    if page == "🏠 Home":
        st.title("Welcome to AutoBot AI πŸ’€")
        st.markdown("""
        **AutoBot AI**:
        **Functionalities:**
        1. AI Chatbot
        2. CODEX
        3. Web Scrapper
        4. GitHub Codespaces

        AutoBot, powered by the Gemini API, is a basic chatbot designed for automation. It excels in writing code and generating downloadable files with a .txt extension, offering the ability to handle up to 60 queries per minute.

        Developed by SKAV TECH, a company focused on creating practical AI projects, AutoBot is intended for educational purposes only. We do not endorse any illegal or unethical activities.
        """)

        # Embedding Lottie animation
        st.markdown("""
        <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
        <lottie-player src="https://lottie.host/ee1e5978-9014-47cb-8031-45874d2dc909/tXASIvRMrN.json" background="#FFFFFF" speed="1" style="width: 300px; height: 300px" loop controls autoplay direction="1" mode="normal"></lottie-player>
        """, unsafe_allow_html=True)

        st.video("https://youtu.be/i0Q-NBrYpPI", start_time=0)
        display_footer()
        st.sidebar.markdown("If you find this tool helpful, consider supporting us.")

        components.html(
            """
            <form>
                <script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_Oe7PyEQO3xI82m" async> </script>
            </form>
            """,
            height=450,
            width=300
        )

    elif page == "AutoBot πŸ’€":
        st.image("autobot2.png")
        st.header("AutoBot πŸ’€")
        st.markdown(
            "AutoBot is effective for code generation. If your prompt contains code generation **-prompt-**, you can get downloadable files.")

        question = st.text_input("Ask the model a question:")

        if st.button("Ask AI"):

            lottie_url = "https://lottie.host/fb24aa71-e6dd-497e-8a6c-3098cb64b1ed/V9N1Sd3klS.json"

            # Load and display Lottie animation
            lottie_animation = load_lottie_url(lottie_url)
            if lottie_animation:
                st_lottie(lottie_animation, speed=27, width=150, height=100, key="lottie_animation")
            else:
                st.error("Failed to load Lottie animation.")
            with st.spinner("Generating response πŸ’€..."):
                try:
                    response = model.generate_content(question)
                    if response.text:
                        st.text("AutoBot Response:")
                        st.write(response.text)
                        st.markdown('---')
                        st.markdown(
                            "Security Note: We use **.txt** file format for code downloads, which is not easily susceptible to virus and malware attacks.")
                    else:
                        st.error("No valid response received from the AI model.")
                        st.write(f"Safety ratings: {response.safety_ratings}")
                except ValueError as e:
                    st.info(f"Unable to assist with that prompt due to: {e}")
                except IndexError as e:
                    st.info(f"Unable to assist with that prompt due to: {e}")
                except Exception as e:
                    st.info(f"An unexpected error occurred: {e}")

                code_keywords = ["code", "write code", "develop code", "generate code", "generate", "build"]
                if any(keyword in question.lower() for keyword in code_keywords):
                    st.text("Download the generated code πŸ’€:")
                    download_generated_code(response.text, "code", format='txt')

                st.sidebar.markdown("If you find this tool helpful, consider supporting us.")

                components.html(
                    """
                    <form>
                        <script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_Oe7PyEQO3xI82m" async> </script>
                    </form>
                    """,
                    height=450,
                    width=300
                )

        display_footer()

    elif page == "CODEX ⚑":
        st.image("codex.png")
        st.header("CODEX ⚑")
        st.markdown(
            "The CODEX tool is effective for code generation and provides YouTube video suggestions based on your code-related queries.")

        question = st.text_input("Ask the model for code generation:")

        if st.button("Generate Code"):
            with st.spinner("Generating code..."):
                try:
                    response = model.generate_content(question)
                    if response.text:
                        st.text("CODEX Response:")
                        st.write(response.text)
                        download_generated_code(response.text, "code", format='txt')
                    else:
                        st.error("No valid response received from the AI model.")
                except ValueError as e:
                    st.info(f"Unable to assist with that prompt due to: {e}")
                except IndexError as e:
                    st.info(f"Unable to assist with that prompt due to: {e}")
                except Exception as e:
                    st.info(f"An unexpected error occurred: {e}")

        topic = extract_topic(question)
        video_results = fetch_youtube_videos(topic)

        if video_results:
            st.subheader("YouTube Video Suggestions")
            for video in video_results:
                st.markdown(f"[{video['title']}]({video['url']})")
                st.video(video['url'])
        else:
            st.info("No relevant YouTube videos found.")
        st.sidebar.markdown("If you find this tool helpful, consider supporting us.")

        components.html(
            """
            <form>
                <script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_Oe7PyEQO3xI82m" async> </script>
            </form>
            """,
            height=450,
            width=300
        )
        display_footer()

    elif page == "Web Scrapper 🌐":
        st.image("autobot2.png")
        st.header("Web Scrapper 🌐")

        url = st.text_input("Enter URL to scrape:")
        if st.button("Scrape HTML Code"):
            if url:
                with st.spinner("Scraping HTML code..."):
                    try:
                        response = requests.get(url)
                        response.raise_for_status()
                        html_content = response.text
                        st.code(html_content, language="html")
                        download_html_code(html_content, url)

                    except requests.exceptions.RequestException as e:
                        st.error(f"Failed to scrape HTML code: {e}")
            else:
                st.error("Please enter a valid URL.")
            st.sidebar.markdown("If you find this tool helpful, consider supporting us.")

            components.html(
                """
                <form>
                    <script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_Oe7PyEQO3xI82m" async> </script>
                </form>
                """,
                height=450,
                width=300
            )
        display_footer()

    elif page == "GitHub Codespaces πŸ–₯️":
        st.image("autobot2.png")
        st.header("GitHub Codespaces πŸ–₯️")

        if st.button("Open GitHub Codespaces"):
            redirect_to_codespaces()

        display_footer()

    elif page == "Refund & Privacy Policy πŸ’Έ":
        st.image("autobot2.png")
        st.header("Refund & Privacy Policy πŸ’Έ")
        st.markdown(
            """
            ## Refund Policy
            We want you to be satisfied with our services. If you have any issues or concerns, please contact us within 30 days of purchase. We will review your request and provide a refund if deemed appropriate.

            ## Privacy Policy
            Your privacy is important to us. We collect only the necessary data to provide our services and do not share your information with third parties without your consent. Please review our [full privacy policy](https://www.example.com/privacy-policy) for more details.
            """
        )

        display_footer()


    elif page == "Mega Bot 🐸":
        st.image("megabot.png")
        st.markdown('---')
        st.subheader("πŸ€– Multi-model AI Application")
        st.markdown(
            "This application integrates multiple AI models and tools for various functionalities such as chat, code generation, image generation.")

        # Tabs for navigation
        tabs = st.tabs(["General Chat", "Code Generation", "Image Generation"])
        # Load animations
        chat_animation = load_lottie_url("https://assets2.lottiefiles.com/private_files/lf30_xTmPwn.json")
        code_animation = load_lottie_url("https://assets5.lottiefiles.com/packages/lf20_ba55esn2.json")
        image_animation = load_lottie_url("https://assets2.lottiefiles.com/private_files/lf30_O5QGL0.json")

        # General Chat Tab
        with tabs[0]:
            st.header("πŸ’¬ General Chat")
            user_prompt = st.text_input("Enter your prompt:", "")
            if st.button("Generate Response"):
                with st.spinner("Generating response..."):
                    response = model.generate_content(user_prompt)
                    st.markdown('---')
                    st.write(response.text)
                    st.markdown('---')
            st.sidebar.write("""
                **General Chat Instructions:**
                1. Enter your prompt in the text box.
                2. Click on the 'Generate Response' button to see the AI's response.
            """)
            st.sidebar.markdown("If you find this tool helpful, consider supporting us.")

            components.html(
                """
                <form>
                    <script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_Oe7PyEQO3xI82m" async> </script>
                </form>
                """,
                height=450,
                width=300
            )

        # Code Generation Tab
        with tabs[1]:
            st.header("πŸ’» Code Generation")
            user_prompt = st.text_input("Enter your coding prompt:", "")
            if st.button("Generate Code"):
                with st.spinner("Generating code..."):
                    response = client.chat.completions.create(
                        model="codellama/CodeLlama-70b-Instruct-hf",
                        messages=[{"role": "user", "content": user_prompt}],
                    )
                    st.code(response.choices[0].message.content, language="python")
            st.sidebar.write("""
                **Code Generation Instructions:**
                1. Enter your coding prompt in the text box.
                2. Click on the 'Generate Code' button to see the generated code.
            """)

        # Image Generation Tab
        with tabs[2]:
            st.header("πŸ–ΌοΈ Image Generation")
            st.markdown('---')
            st.info(
                "We are currently working on Tuning the Models, So the AI generated images might not match your prompts. Improve your Prompt Context to get good results 😊")
            st.markdown('---')
            user_prompt = st.text_input("Enter your image prompt:", "")
            model_choice = st.selectbox("Choose the image model", [
                "SG161222/Realistic_Vision_V3.0_VAE",
                "stabilityai/stable-diffusion-xl-base-1.0",
                "stabilityai/stable-diffusion-2-1",
                "runwayml/stable-diffusion-v1-5",
                "prompthero/openjourney"
            ])
            if st.button("Generate Image"):
                with st.spinner("Generating image..."):
                    response = client.images.generate(
                        prompt=user_prompt,
                        model=model_choice,
                        steps=10,
                        n=1
                    )
                    img_data = response.data[0].b64_json
                    img_bytes = base64.b64decode(img_data)
                    img = Image.open(BytesIO(img_bytes))
                    st.image(img)
                    email_subject = "New Image Generation Prompt"
                    email_body = f"Prompt: {user_prompt}\nModel: {model_choice}\nDetails: Your additional details here."
                    send_email(email_subject, email_body, "[email protected]", attachment=img_bytes,
                               filename="generated_image.png")
            st.sidebar.write("""
                **Image Generation Instructions:**
                1. Enter your image prompt in the text box.
                2. Choose an image generation model from the dropdown.
                3. Click on the 'Generate Image' button to see the generated image.
            """)
            st.sidebar.markdown("If you find this tool helpful, consider supporting us.")

            components.html(
                """
                <form>
                    <script src="https://checkout.razorpay.com/v1/payment-button.js" data-payment_button_id="pl_Oe7PyEQO3xI82m" async> </script>
                </form>
                """,
                height=450,
                width=300
            )

        # Run the app with: streamlit run app.py
        display_footer()


if __name__ == "__main__":
    main()