|
import gradio as gr |
|
import openai |
|
import os |
|
import json |
|
from gtts import gTTS |
|
|
|
|
|
|
|
openai.api_key = os.getenv("GROQ_API_KEY") |
|
openai.api_base = "https://api.groq.com/openai/v1" |
|
|
|
|
|
CONVERSATION_FILE = "conversation_history.json" |
|
|
|
|
|
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)" |
|
] |
|
} |
|
|
|
|
|
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 [] |
|
|
|
|
|
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}") |
|
|
|
|
|
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() |
|
|
|
|
|
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: |
|
return None |
|
tts = gTTS(latest_response, lang="en") |
|
audio_file = "response_audio.mp3" |
|
tts.save(audio_file) |
|
return audio_file |
|
except Exception as e: |
|
print(f"Error generating audio: {e}") |
|
return None |
|
|
|
|
|
|
|
def chatbot(user_input, sub_category, history): |
|
|
|
conversation_history = history or load_history() |
|
|
|
|
|
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}) |
|
|
|
|
|
user_message = {"role": "user", "content": user_input} |
|
formatted_history.append(user_message) |
|
|
|
|
|
bot_response = get_groq_response(user_input, sub_category, formatted_history) |
|
|
|
|
|
conversation_history.append((user_input, bot_response)) |
|
save_history(conversation_history) |
|
|
|
|
|
formatted_history.append({"role": "assistant", "content": bot_response}) |
|
|
|
|
|
return formatted_history, conversation_history, "" |
|
|
|
|
|
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") |
|
|
|
|
|
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) |
|
|
|
|
|
main_category.change(update_subcategories, inputs=main_category, outputs=sub_category) |
|
|
|
|
|
|
|
chatbot_ui = gr.Chatbot(type="messages") |
|
|
|
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()) |
|
|
|
|
|
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."), |
|
inputs=[history_state], |
|
outputs=audio_output |
|
) |
|
|
|
|
|
|
|
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_button.click(clear_conversation_history, inputs=None, outputs=[chatbot_ui, history_state]) |
|
clear_button.click(lambda: [], outputs=history_state) |
|
|
|
|
|
demo.launch() |