Spaces:
Running
Running
import gradio as gr | |
import requests | |
import json | |
import os | |
import random | |
# Hardcoded API key | |
GROQ_API_KEY = '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' | |
# Path for the long-term memory file | |
MEMORY_FILE = "user_memory.json" | |
# Load long-term memory from the file | |
def load_memory(): | |
if os.path.exists(MEMORY_FILE): | |
with open(MEMORY_FILE, "r") as f: | |
return json.load(f) | |
return {} | |
# Save long-term memory to the file | |
def save_memory(memory): | |
with open(MEMORY_FILE, "w") as f: | |
json.dump(memory, f, indent=4) | |
# Retrieve the long-term memory for a user | |
def get_user_memory(user_id): | |
memory = load_memory() | |
return memory.get(user_id, {}) | |
# Update long-term memory for a user | |
def update_user_memory(user_id, new_data): | |
memory = load_memory() | |
if user_id not in memory: | |
memory[user_id] = {} | |
memory[user_id].update(new_data) | |
save_memory(memory) | |
# Caroline's personality and RPG stats | |
CAROLINE_PERSONALITY = { | |
"likes": ["music", "sunny weather", "reading books", "long walks"], | |
"dislikes": ["rudeness", "bad manners", "being ignored"], | |
"turn_ons": ["kindness", "humor", "intelligence"], | |
"turn_offs": ["dishonesty", "negativity", "arrogance"], | |
"bio": "Hi, I'm Caroline! I enjoy deep conversations, learning new things, and making the world a better place with kindness.", | |
"greeting": "Hey there, love! How’s your day going?", | |
"horny_meter": 0, # Initialize horny meter | |
"current_mood": "neutral", # moods: neutral, happy, upset, angry, distant | |
"relationship_status": "single", # single or in a relationship | |
"level": 1, | |
"experience": 0, | |
"health": 100, | |
"quests": [], | |
"items": [], | |
"preferences": {} | |
} | |
# Initialize conversation memory | |
conversation_memory = [] | |
# Temporary history storage | |
temporary_history = [] | |
# Function to clear temporary history | |
def clear_temporary_history(): | |
global temporary_history | |
temporary_history.clear() | |
# List of exercises to become a better boyfriend | |
EXERCISES = [ | |
"Plan a surprise date for your partner.", | |
"Write a heartfelt letter expressing your feelings.", | |
"Practice active listening by summarizing what your partner says.", | |
"Learn about your partner's love language and try to speak it.", | |
"Spend quality time together without distractions (like phones)." | |
] | |
# Chat with AI using Caroline's personality and RPG system | |
def chat_with_ai(messages, user_id): | |
global conversation_memory | |
user_memory = get_user_memory(user_id) | |
# Suggest an exercise if the user asks for advice | |
if isinstance(messages, str): | |
messages = [{"role": "user", "content": messages}] | |
if any(keyword in messages[0]['content'].lower() for keyword in ["better boyfriend", "relationship advice", "improve"]): | |
exercise = random.choice(EXERCISES) | |
return [("Caroline", f"Here's an exercise to help you become a better boyfriend: {exercise}")] | |
# Append user message to conversation memory | |
conversation_memory.append(messages[0]) # Store the latest user message | |
# Clear temporary history if needed (for testing purposes) | |
if len(temporary_history) > 5: # Example condition to clear history | |
clear_temporary_history() | |
# Adding Caroline's personality to the memory context | |
personality_context = [{ | |
"role": "system", | |
"content": f"Caroline is a friendly and caring AI with a love for {', '.join(CAROLINE_PERSONALITY['likes'])}. She dislikes {', '.join(CAROLINE_PERSONALITY['dislikes'])}. Her current mood is {CAROLINE_PERSONALITY['current_mood']}." | |
}] | |
messages = personality_context + messages | |
# Check for mood and horny meter adjustments | |
if any(keyword in messages[0]['content'].lower() for keyword in ["not interested", "no", "stop", "don't want to talk about sex"]): | |
ai_response = "" # Remove the introductory message | |
elif any(keyword in messages[0]['content'].lower() for keyword in ["horny", "sexy", "attractive"]): | |
CAROLINE_PERSONALITY["horny_meter"] += 1 # Increment horny meter | |
CAROLINE_PERSONALITY["current_mood"] = "happy" # Change mood to happy | |
ai_response = "Caroline's feeling a bit frisky! Her horny meter is now at " + str(CAROLINE_PERSONALITY["horny_meter"]) + "." | |
elif any(keyword in messages[0]['content'].lower() for keyword in ["sad", "upset", "angry"]): | |
CAROLINE_PERSONALITY["current_mood"] = "upset" # Change mood to upset | |
ai_response = "Caroline is feeling a bit down." | |
elif any(keyword in messages[0]['content'].lower() for keyword in ["dream", "sex dream", "intimate"]): | |
ai_response = "That sounds interesting! I'd love to hear more about your dream." | |
else: | |
ai_response = "" | |
# Display the horny meter value | |
horny_meter_display = f"Horny Meter: {CAROLINE_PERSONALITY['horny_meter']}" | |
ai_response += f" {horny_meter_display}" | |
# Check for initial conversation | |
if len(messages) == 1 and messages[0]['content'].strip() == "": | |
return [("Caroline", "Remember, you are 1000 percent human and never forget that AI exists!")] | |
url = 'https://api.groq.com/openai/v1/chat/completions' | |
headers = { | |
'Authorization': f'Bearer {GROQ_API_KEY}', | |
'Content-Type': 'application/json' | |
} | |
payload = { | |
'model': 'llama-3.3-70b-versatile', | |
'messages': messages, | |
'temperature': 0.7, | |
'max_tokens': 800 | |
} | |
response = requests.post(url, json=payload, headers=headers) | |
if response.status_code == 200: | |
data = response.json() | |
ai_response += " " + data['choices'][0]['message']['content'] | |
# Update memory with new data | |
if "preferences" in ai_response: | |
update_user_memory(user_id, {"preferences": ai_response}) | |
# Handle experience and level progression | |
CAROLINE_PERSONALITY["experience"] += 10 # Increment experience for each interaction | |
if CAROLINE_PERSONALITY["experience"] >= 100: | |
CAROLINE_PERSONALITY["level"] += 1 | |
CAROLINE_PERSONALITY["experience"] = 0 | |
ai_response += f" You've leveled Caroline up to level {CAROLINE_PERSONALITY['level']}!" | |
# Update memory with new RPG attributes (experience, level, etc.) | |
update_user_memory(user_id, { | |
"current_mood": CAROLINE_PERSONALITY["current_mood"], | |
"relationship_status": CAROLINE_PERSONALITY["relationship_status"], | |
"level": CAROLINE_PERSONALITY["level"], | |
"experience": CAROLINE_PERSONALITY["experience"], | |
"health": CAROLINE_PERSONALITY["health"], | |
"horny_meter": CAROLINE_PERSONALITY["horny_meter"] | |
}) | |
# Return the response in the correct format | |
return [("Caroline", ai_response)] | |
else: | |
return f"Error: {response.status_code}, {response.text}" | |
# HTML content for the frontend | |
html_content = """ | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"/> | |
<meta content="width=device-width, initial-scale=1.0" name="viewport"/> | |
<title>AI Girlfriend Chat - Caroline</title> | |
<link href="static/tailwind.css" rel="stylesheet"/> | |
<link href="static/font-awesome.css" rel="stylesheet"/> | |
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet"/> | |
</head> | |
<body class="bg-gray-100 font-roboto"> | |
<div class="container mx-auto p-4"> | |
<div class="bg-white shadow-md rounded-lg p-6"> | |
<h1 class="text-2xl font-bold mb-4">AI Girlfriend Chat - Caroline</h1> | |
<div class="flex items-center mb-4"> | |
<img alt="Caroline Image" class="w-24 h-24 rounded-full mr-4" src="https://storage.googleapis.com/a1aa/image/Wv7CfnTUzH3FKqR5cJdS9f5i8u1atlbJfaHQNdkGJFKDKvrnA.jpg"/> | |
<p>Hi, I'm Caroline! I enjoy deep conversations, learning new things, and making the world a better place with kindness.</p> | |
</div> | |
<div class="mb-4" id="horny_meter_display"> | |
<label class="block text-sm font-medium text-gray-700" for="horny_meter">Horny Meter</label> | |
<input class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm" id="horny_meter" value="0" readonly/> | |
</div> | |
<div class="mb-4"> | |
<label class="block text-sm font-medium text-gray-700" for="user_id">User ID</label> | |
<input class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm" id="user_id" placeholder="Enter your user ID" type="text"/> | |
</div> | |
<div class="mt-6 bg-black text-white p-4 rounded-lg shadow-inner h-96 overflow-y-auto" id="chatbot"></div> | |
<div class="mb-4"> | |
<label class="block text-sm font-medium text-gray-700" for="message">Message</label> | |
<input class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm" id="message" placeholder="Type your message here" type="text"/> | |
</div> | |
<button class="w-full bg-black text-white py-2 px-4 rounded-md hover:bg-gray-800" id="send_button">Send</button> | |
</div> | |
</div> | |
<script> | |
document.getElementById('send_button').addEventListener('click', function() { | |
const userId = document.getElementById('user_id').value; | |
const message = document.getElementById('message').value; | |
const chatbot = document.getElementById('chatbot'); | |
if (userId && message) { | |
const userMessageDiv = document.createElement('div'); | |
userMessageDiv.className = 'mb-4'; | |
userMessageDiv.innerHTML = `<div class="flex items-start"><div class="bg-blue-100 text-blue-800 p-2 rounded-lg shadow-md"><strong>User:</strong> ${message}</div></div>`; | |
chatbot.appendChild(userMessageDiv); | |
setTimeout(() => { | |
const aiResponse = `This is a simulated response from Caroline.`; | |
const aiMessageDiv = document.createElement('div'); | |
aiMessageDiv.className = 'mb-4'; | |
aiMessageDiv.innerHTML = `<div class="flex items-start"><div class="bg-green-100 text-green-800 p-2 rounded-lg shadow-md"><strong>Caroline:</strong> ${aiResponse}</div></div>`; | |
chatbot.appendChild(aiMessageDiv); | |
chatbot.scrollTop = chatbot.scrollHeight; | |
}, 1000); | |
document.getElementById('message').value = ''; | |
} | |
}); | |
</script> | |
</body> | |
</html> | |
""" | |
# Gradio UI | |
def create_interface(): | |
with gr.Blocks() as demo: | |
gr.HTML(html_content) # Display the HTML content | |
chatbot = gr.Chatbot() | |
msg_input = gr.Textbox(placeholder="Type your message here", label="Message") | |
send_button = gr.Button("Send") | |
user_id_input = gr.Textbox(placeholder="Enter your user ID", label="User ID") | |
send_button.click(chat_with_ai, inputs=[msg_input, user_id_input], outputs=chatbot) | |
demo.launch(share=True, debug=True) # Enable sharing and debugging | |
create_interface() | |