import streamlit as st from transformers import pipeline import google.generativeai as genai import json import random # Load the JSON data with open('emotion_templates.json', 'r') as f: data = json.load(f) # Configure Gemini (replace with your API key) genai.configure(api_key="AIzaSyCYRYNwCU1f9cgJYn8pd86Xcf6hiSMwJr0") model = genai.GenerativeModel('gemini-2.0-flash') def generate_text(prompt, context=""): """ Generates text using the Gemini model. """ try: response = model.generate_content(prompt) return response.text except Exception as e: print(f"Error generating text: {e}") return "I am sorry, I encountered an error while generating the text." def create_prompt(emotion, topic = None): """ Chooses a random prompt from the template list. """ templates = data["emotion_templates"][emotion] prompt = random.choice(templates) if topic: prompt = prompt.replace("[topic/person]",topic) prompt = prompt.replace("[topic]",topic) prompt = prompt.replace("[person]",topic) prompt = prompt.replace("[object]",topic) # added object replace prompt = prompt.replace("[outcome]",topic) # added outcome replace subfix_prompt = "Make the generated text in the same language as the topic.\n" prefix_prompt = "## topic language and contant\n"+topic prompt = prefix_prompt + prompt + subfix_prompt return prompt # 1. Emotion Detection Model (Using Hugging Face's transformer) # Choose a suitable model - 'emotion-classification' is the task, you can specify a model from Hugging Face Model Hub. emotion_classifier = pipeline("text-classification", model="AnasAlokla/multilingual_go_emotions") # Or choose another model # 2. Conversational Agent Logic def get_ai_response(user_input, emotion_predictions): """Generates AI response based on user input and detected emotions.""" dominant_emotion = None max_score = 0 responses = None for prediction in emotion_predictions: if prediction['score'] > max_score: max_score = prediction['score'] dominant_emotion = prediction['label'] prompt_text = create_prompt(dominant_emotion,user_input) responses = generate_text(prompt_text) # Handle cases where no specific emotion is clear if dominant_emotion is None: return "Error for response" else: return responses # 3. Streamlit Frontend st.title("Emotionally Aware Chatbot") # Input Text Box user_input = st.text_input("Enter your message:", "") if user_input: # Emotion Detection emotion_predictions = emotion_classifier(user_input) # Display Emotions st.subheader("Detected Emotions:") for prediction in emotion_predictions: st.write(f"- {prediction['label']}: {prediction['score']:.2f}") # Show emotion score. # Get AI Response ai_response = get_ai_response(user_input, emotion_predictions) # Display AI Response st.subheader("AI Response:") st.write(ai_response)