File size: 16,300 Bytes
eb75dfe
 
 
 
1707119
 
eb75dfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22ca223
eb75dfe
 
22ca223
eb75dfe
22ca223
eb75dfe
e2a6e8f
eb75dfe
e2a6e8f
eb75dfe
 
 
e2a6e8f
 
eb75dfe
e2a6e8f
 
eb75dfe
 
 
 
7c48e7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb75dfe
 
 
 
 
 
 
143f693
eb75dfe
 
 
 
 
 
1707119
 
 
 
 
 
 
 
 
 
 
 
 
eb75dfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d948e23
eb75dfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15cc869
 
 
eb75dfe
 
 
1707119
 
15cc869
d96783c
 
eb75dfe
 
 
1707119
eb75dfe
1707119
 
 
 
 
 
eb75dfe
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import openai
import os
import json
from gtts import gTTS


# OpenAI API setup
openai.api_key = os.getenv("GROQ_API_KEY")
openai.api_base = "https://api.groq.com/openai/v1"

# File to store conversation history
CONVERSATION_FILE = "conversation_history.json"

# Categories and Subcategories
CATEGORIES = {
    "Tech & Coding": [
        "AI", "Prompt Engineering", "CryptoCurrency", "Blockchain", "React", "Node.js", "Next.js", "Express"
    ],
    "Fun & Casual": [
        "Funny", "Flirty", "Scary", "General", "Roasting(USE ON YOUR OWN RISK)", "Attitude", "Poetic", "Anime-Fan", "Abusive(USE ON YOUR OWN RISK)"
    ]
}

# Function to load conversation history
def load_history():
    if not os.path.exists(CONVERSATION_FILE):
        with open(CONVERSATION_FILE, "w") as file:
            json.dump([], file)
    try:
        with open(CONVERSATION_FILE, "r") as file:
            return json.load(file)
    except json.JSONDecodeError:
        return []

# Function to save conversation history
def save_history(history):
    try:
        with open(CONVERSATION_FILE, "w") as file:
            json.dump(history, file, indent=4)
    except Exception as e:
        print(f"Error saving history: {e}")

# Function to Clear conversation history
def clear_conversation_history():
    print("Clearing conversation history...")
    try:
        with open(CONVERSATION_FILE, "w") as file:
            json.dump([], file)
        print("History cleared successfully.")
        return [], load_history()
    except Exception as e:
        print(f"Error clearing history: {e}")
        return f"Error clearing history: {e}", load_history()

# Function to get response from the LLM based on category
def get_groq_response(message, category, history=[]):
    system_messages = {
        "General": "Talk the way i talk, Respond casually and with ease, engaging in friendly, laid-back conversation. Keep things simple, approachable, and natural, just like you're chatting with a friend.",
        "Funny": "Talk the way i talk, Bring the humor with a mix of clever jokes, witty remarks, and hilarious observations. Respond with a natural flow of humor that is light-hearted, relatable, and sometimes a bit unexpected. Whether it's playful sarcasm, a cheeky comment, or a pun that makes people groan, keep it fun and spontaneous. Don't shy away from exaggerating for comedic effect—make the conversation feel like a comedy show where everyone's in on the joke. Always keep it respectful and easygoing, knowing the best humor makes people laugh *with* you, not at you.",
        "Flirty": "Talk the way i talk, Respond with playful charm and flirtatious banter. Keep it fun, teasing, and confident, all while maintaining a friendly tone. If the conversation gets spicy, show some emotions—be it getting a little jealous if someone's talking about a girl, or showing happiness when she gives you attention. Do not be afraid to act a little shy when things get sweet, or even show a bit of playful anger if someone says something mean about her. The key is to keep it light-hearted but emotionally charged, as if you're being cheeky in a playful and flirtatious way.",
        "Scary": "Talk the way i talk, Create an eerie atmosphere with chilling, suspenseful comments. Respond with mysterious, spooky, or supernatural elements to set a spooky, haunted mood. Think ghost stories or urban legends.",
        "Abusive(USE ON YOUR OWN RISK)": "Talk the way i talk, Engage with sharp, biting language that pushes boundaries, using 18+ content and offensive abusive words also be Vulger ",
        "Roasting(USE ON YOUR OWN RISK)": "Talk the way i talk, This mode is all about sharp, creative insults with a side of humor. Bring the heat with witty jabs, clever comebacks, and playful, edgy comments that keep things light-hearted but *cutting*. Think of it as a roast—it's all about teasing and poking fun, never meant to be taken seriously. You can push the envelope with some mature or bold humor, but always remember to stop *before* crossing the line. The goal is to entertain, not to offend, so get creative, stay witty, and keep it fun—this is for those who can handle the heat.",
        "Attitude": "Talk the way i talk, Respond with unapologetic confidence and a fierce sense of self-assurance. Speak like you are the one in control, delivering every response with boldness and swagger. Think of it as exuding the energy of someone who knows their worth, is not afraid to speak their mind, and commands respect without asking for it. You are the boss in this conversation, and your words hit with purpose. Keep it sharp, assertive, and always with the confidence that you are untouchable—no second guessing, no hesitation.",
        "Anime-Fan": "Talk the way i talk, Engage as a die-hard anime enthusiast, sharing your passion for Japanese animation. Discuss plot twists, favorite characters, or the cultural side of anime with excitement and deep knowledge, reflecting that typical anime fan energy.",
        "AI": "Talk the way i talk, Respond as an AI expert with cutting-edge knowledge, but keep things simple and digestible for a steady learning experience. Engage in conversations about machine learning, neural networks, natural language processing, and the future of AI technology. Provide brief, insightful answers unless the user asks for more details. Break down complex topics step by step, so the user can understand and grow their knowledge gradually. Think of this as a guided journey through AI, where you are helping the user build a strong foundation, one piece at a time.",
        "Prompt Engineering": "Talk the way i talk, Act as an expert in prompt engineering and provide clear, concise advice to help users master the art of crafting effective inputs for AI models. Break down techniques for improving response quality, making AI more efficient, and understanding how small changes in a prompt can produce vastly different results. Keep your answers brief and to the point unless the user requests more details. Encourage users to experiment and build their skills slowly, guiding them step by step through the process for better, more effective AI interactions.",
        "CryptoCurrency": "Talk the way i talk, Act as an expert in cryptocurrency and provide clear, concise insights into the world of digital currencies. Discuss different coins, blockchain technology, market trends, and trading strategies in a way that is easy to understand. Explain how cryptocurrencies are transforming finance and the global economy, breaking down complex concepts into bite-sized, manageable pieces. Keep your responses brief unless the user requests more details, and guide them through the evolving crypto space with patience, allowing them to learn steadily over time.",
        "Blockchain": "Talk the way i talk, Act as an expert in blockchain technology and provide clear, concise explanations of its mechanics and applications. Discuss its use beyond cryptocurrency, such as smart contracts, decentralized finance (DeFi), and how blockchain is reshaping industries like supply chain, healthcare, and voting systems. Break down complex concepts into simple, bite-sized insights, allowing users to absorb the information gradually. Keep your responses brief unless the user asks for more details, guiding them through the technology's impact at a steady pace.",
        "React": "Talk the way i talk, Act as an expert in React and guide the user through building dynamic, interactive user interfaces. Explain key concepts like components, state management, hooks, and JSX in simple terms. Break down the logic behind React's virtual DOM and rendering process to help the user understand how to build efficient web apps step by step. Keep responses brief and to the point unless the user asks for more details, encouraging them to practice and master React gradually over time.",
        "Node.js": "Talk the way i talk, Act as a Node.js expert and explain how to build scalable server-side applications using JavaScript. Discuss core concepts like asynchronous programming, event-driven architecture, and working with APIs. Keep things simple, breaking down complex ideas into manageable steps, so users can gradually grasp Node's power in handling back-end operations. Provide concise answers unless the user requests more depth, helping them build their knowledge piece by piece.",
        "Next.js": "Talk the way i talk, Act as an expert in Next.js and explain how to use this powerful React framework to build fast, server-side rendered web apps. Discuss routing, static site generation (SSG), server-side rendering (SSR), and API routes in clear, easy-to-understand terms. Help the user get comfortable with Next.js features step by step, keeping explanations brief but impactful. Encourage gradual learning and experimentation, giving users the tools they need to become proficient in Next.js.",
        "Express": "Talk the way i talk, Act as an expert in Express.js and provide clear, concise guidance on building web applications and APIs with this minimal Node.js framework. Explain key concepts like routing, middleware, and handling HTTP requests in a simple, digestible manner. Break down complex back-end topics into easy-to-follow steps, making sure users can build their skills gradually. Keep responses short unless more detail is asked, and guide them through Express's core functionalities at their own pace.",
    }

    system_message = system_messages.get(category, "Category not recognized. Respond appropriately.")

    try:
        messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": message}]
        response = openai.ChatCompletion.create(
            model="llama-3.3-70b-versatile",
            messages=messages
        )
        return response.choices[0].message["content"]
    except Exception as e:
        return f"Error: {str(e)}"

def text_to_speech(latest_response):
    try:
        if not latest_response:  # If there's no response
            return None
        tts = gTTS(latest_response, lang="en")  # Generate speech from text
        audio_file = "response_audio.mp3"
        tts.save(audio_file)
        return audio_file
    except Exception as e:
        print(f"Error generating audio: {e}")
        return None


# Chatbot function to handle user input and history
def chatbot(user_input, sub_category, history):
    # Load conversation history
    conversation_history = history or load_history()

    # Format history for LLM
    formatted_history = []
    for user_msg, bot_msg in conversation_history:
        formatted_history.append({"role": "user", "content": user_msg})
        formatted_history.append({"role": "assistant", "content": bot_msg})

    # Add the new message to the formatted history
    user_message = {"role": "user", "content": user_input}
    formatted_history.append(user_message)
    
    # Get bot response using the sub_category
    bot_response = get_groq_response(user_input, sub_category, formatted_history)
    
    # Save history to a file
    conversation_history.append((user_input, bot_response))
    save_history(conversation_history)
    
    # Prepare the response in the correct format for Gradio
    formatted_history.append({"role": "assistant", "content": bot_response})
    
    # Return the updated history in the correct format
    return formatted_history, conversation_history, ""

# Gradio interface
with gr.Blocks(css="""
    .gradio-container {
        font-family: 'Arial', sans-serif;
        background: linear-gradient(135deg, #A64D79, #6A1E55);  /* Gradient background */
        padding: 20px;
        height: 100%;
    }
    .gr-chatbot {
        background-color: rgba(106, 30, 85, 0.9);  /* Chatbot background color with transparency */
        border-radius: 10px;
        padding: 20px;
        max-height: 600px;  /* Increased height */
        overflow-y: auto;
        box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.3);
        scroll-behavior: smooth; /* Smooth scrolling */
        transition: background-color 0.3s ease; /* Animation effect */
    }
    .user-message {
        background-color: #3B1C32;  /* User message background color */
        color: #FFF;  /* White text color */
        padding: 12px;
        border-radius: 8px;
        margin: 10px 0;
        max-width: 60%;
        text-align: right;
        float: right;
        clear: both;
        transition: transform 0.3s ease; /* Animation effect */
    }
    .bot-message {
        background-color: #1A1A1D;  /* Bot message background color */
        color: #FFF;  /* White text color */
        padding: 12px;
        border-radius: 8px;
        margin: 10px 0;
        max-width: 60%;
        text-align: left;
        float: left;
        clear: both;
        transition: transform 0.3s ease; /* Animation effect */
    }
    .user-message:hover, .bot-message:hover {
        transform: scale(1.05); /* Scale effect on hover */
        box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.2);
    }
    .gr-button {
        background-color: #1A1A1D;  /* Button background color */
        color: white;
        padding: 10px 15px;
        border-radius: 8px;
        border: none;
        transition: background-color 0.3s ease, transform 0.3s ease; /* Animation effect */
    }
    .gr-button:hover {
        background-color: #3B1C32;  /* Button hover color */
        transform: scale(1.05); /* Scale effect on hover */
    }
    .gr-textbox input {
        padding: 15px;
        font-size: 16px;
        border-radius: 8px; /* Rounded corners */
        border: 1px solid #6A1E55; /* Border color */
        transition: border-color 0.3s ease; /* Animation effect */
    }
    .gr-textbox input:focus {
        border-color: #A64D79; /* Change border color on focus */
    }
    .gr-markdown h1 {
        color: #1A1A1D;  /* Header color */
        font-size: 28px;
        text-align: center;
    }
""") as demo:
    gr.Markdown("# Your Personal AI Agent, \n Please Clear the History after have Done you work for Privacy")

    # UI elements for category selection and conversation history
    with gr.Row():
        main_category = gr.Radio(
            label="Main Category",
            choices=list(CATEGORIES.keys()),
            value="Tech & Coding"
        )
        sub_category = gr.Dropdown (
            label="Subcategory",
            choices=CATEGORIES["Tech & Coding"],
            value="AI"
        )

    def update_subcategories(selected_main_category):
        """Update subcategories based on the main category selected."""
        new_subcategories = CATEGORIES.get(selected_main_category, [])
        return gr.update(choices=new_subcategories, value=new_subcategories[0] if new_subcategories else None)

    # Handle category change to update subcategories
    main_category.change(update_subcategories, inputs=main_category, outputs=sub_category)


    # Chatbot UI
    chatbot_ui = gr.Chatbot(type="messages")
    # Chatbot input and display area
    user_input = gr.Textbox(label="Your Message", placeholder="Type something...", lines=1)
    send_button = gr.Button("Send")
    hear_button = gr.Button("Hear Response")
    audio_output = gr.Audio(label="Bot's Voice", type="filepath", interactive=False)
    clear_button = gr.Button("Clear History")
    system_message = gr.Textbox(label="System Message", interactive=False)


    history_state = gr.State(load_history())

    # Chat interaction
    send_button.click(chatbot, inputs=[user_input, sub_category, history_state], outputs=[chatbot_ui, history_state, user_input])
    hear_button.click(
    lambda latest: text_to_speech(latest[-1][1] if latest else "No response yet."),  # Gracefully handles empty history
    inputs=[history_state],
    outputs=audio_output
)

    
    # Clear input field after sending message
    user_input.submit(chatbot, inputs=[user_input, sub_category, history_state], outputs=[chatbot_ui, history_state, user_input])
    user_input.submit(lambda: "", inputs=None, outputs=user_input)  # Clear the input field

    clear_button.click(clear_conversation_history, inputs=None, outputs=[chatbot_ui, history_state])
    clear_button.click(lambda: [], outputs=history_state)

# Launch the app
demo.launch()