import streamlit as st from textblob import TextBlob import json import os import matplotlib.pyplot as plt # === UI/UX Modifications === def set_background_and_styles(): st.markdown( """ """, unsafe_allow_html=True ) # === Load Quotes === QUOTES_PATH = os.path.join(os.path.dirname(__file__), "quotes.json") # Create a dummy quotes.json if it doesn't exist for the script to run locally without error if not os.path.exists(QUOTES_PATH): dummy_quotes = { "positive": ["You are doing great!", "Keep shining!", "Believe in yourself!"], "negative": ["It's okay to feel down, brighter days are ahead.", "Take a deep breath.", "This too shall pass."], "neutral": ["Observe your thoughts.", "Find your center.", "Acknowledge your feelings."] } with open(QUOTES_PATH, "w") as f: json.dump(dummy_quotes, f, indent=4) with open(QUOTES_PATH, "r") as f: quotes_data = json.load(f) # === Emotion Detection via TextBlob === def detect_emotion(text): blob = TextBlob(text) polarity = blob.sentiment.polarity if polarity > 0.2: return "positive", polarity elif polarity < -0.2: return "negative", polarity else: return "neutral", polarity # === Quotes Retrieval === def get_quote(emotion): if isinstance(quotes_data, dict): # Return a random quote from the list for the given emotion import random return [random.choice(quotes_data.get(emotion, ["Stay strong, you're doing great!"]))] else: return ["Stay strong, you're doing great!"] # === Page Layout === st.set_page_config(page_title="DilBot - Emotionally Intelligent AI Companion", layout="centered") set_background_and_styles() # This div will act as the centered container st.markdown('
', unsafe_allow_html=True) # Motivational quote above title st.markdown("

\"The only way to do great work is to love what you do.\"

", unsafe_allow_html=True) st.title("DilBot: Your Emotional Companion") st.markdown("---") # === Input Section === # Label color is now white via CSS user_input = st.text_area("How are you feeling today?", height=150, placeholder="Type your thoughts here...") if st.button("Analyze"): if user_input.strip(): # Detect Emotion emotion, polarity = detect_emotion(user_input) confidence = abs(polarity) * 100 # Display Emotion - now white text on transparent black background st.subheader("Detected Emotion:") st.success(f"**{emotion.capitalize()}** with a confidence of **{confidence:.2f}%**") # Show a personal quote - now white text on transparent black background st.markdown("### DilBot's Message:") quote = get_quote(emotion)[0] st.info(f"_{quote}_") # === Personal Dashboard === st.markdown("### Personal Dashboard") # Bar & Doughnut Chart fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3), dpi=100) labels = ['Positive', 'Neutral', 'Negative'] display_values = [0, 0, 0] if emotion == 'positive': display_values[0] = confidence remaining = 100 - confidence display_values[1] = remaining / 2 display_values[2] = remaining / 2 elif emotion == 'negative': display_values[2] = confidence remaining = 100 - confidence display_values[0] = remaining / 2 display_values[1] = remaining / 2 else: # neutral display_values[1] = confidence remaining = 100 - confidence display_values[0] = remaining / 2 display_values[2] = remaining / 2 # Ensure values sum to 100 for the pie chart total_sum = sum(display_values) if total_sum != 0: display_values = [v * 100 / total_sum for v in display_values] colors = ['#00cc99', '#b0bec5', '#ff6f61'] # Set chart backgrounds to white ax1.set_facecolor('white') ax2.set_facecolor('white') fig.patch.set_facecolor('white') # Entire figure background white # Bar Chart ax1.bar(labels, display_values, color=colors) ax1.set_title("Confidence by Emotion", color='black') ax1.set_ylabel("Percentage", color='black') ax1.tick_params(axis='x', colors='black') ax1.tick_params(axis='y', colors='black') ax1.spines['bottom'].set_color('black') ax1.spines['left'].set_color('black') ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) # Doughnut Chart if sum(display_values) > 0: wedges, texts, autotexts = ax2.pie( display_values, labels=labels, autopct='%1.1f%%', colors=colors, startangle=90, wedgeprops=dict(width=0.4) ) ax2.set_title("Emotion Distribution", color='black') for text_obj in texts: text_obj.set_color('black') for autotext_obj in autotexts: autotext_obj.set_color('black') else: ax2.text(0.5, 0.5, 'No data', horizontalalignment='center', verticalalignment='center', transform=ax2.transAxes, color='black') # Use st.columns to center the plot col_left, col_center, col_right = st.columns([0.5, 6, 0.5]) with col_center: st.pyplot(fig) plt.close(fig) else: st.warning("Please write something to analyze.") st.markdown('
', unsafe_allow_html=True) # Close main-content-container