import gradio as gr from transformers import pipeline import openai import random import os from datetime import datetime # Initialize sentiment analysis pipeline sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english") # Retrieve OpenAI API key from Hugging Face secret openai.api_key = os.getenv("open_AI_API_key") class JournalCompanion: def __init__(self): self.entries = [] def analyze_entry(self, entry_text): if not entry_text.strip(): return ("Please write something in your journal entry.", "", "", "") try: # Perform sentiment analysis sentiment_result = sentiment_analyzer(entry_text)[0] sentiment = sentiment_result["label"].upper() sentiment_score = sentiment_result["score"] except Exception as e: print("Error during sentiment analysis:", e) return ( "An error occurred during analysis. Please try again.", "Error", "Could not generate prompts due to an error.", "Could not generate affirmation due to an error." ) entry_data = { "text": entry_text, "timestamp": datetime.now().isoformat(), "sentiment": sentiment, "sentiment_score": sentiment_score } self.entries.append(entry_data) # Generate dynamic responses using a language model prompts = self.generate_dynamic_prompts(sentiment) affirmation = self.generate_dynamic_affirmation(sentiment) sentiment_percentage = f"{sentiment_score * 100:.1f}%" message = f"Entry analyzed! Sentiment: {sentiment} ({sentiment_percentage} confidence)" return message, sentiment, prompts, affirmation def generate_dynamic_prompts(self, sentiment): prompt_request = f"Generate three reflective journal prompts for a person feeling {sentiment.lower()}." try: response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt_request} ], max_tokens=60, n=1 ) prompts = response.choices[0].message["content"].strip() except Exception as e: print("Error generating prompts:", e) prompts = "Could not generate prompts at this time." return prompts def generate_dynamic_affirmation(self, sentiment): affirmation_request = f"Generate an affirmation for someone who is feeling {sentiment.lower()}." try: response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": affirmation_request} ], max_tokens=20, n=1 ) affirmation = response.choices[0].message["content"].strip() except Exception as e: print("Error generating affirmation:", e) affirmation = "Could not generate an affirmation at this time." return affirmation def get_monthly_insights(self): if not self.entries: return "No entries yet to analyze." total_entries = len(self.entries) positive_entries = sum(1 for entry in self.entries if entry["sentiment"] == "POSITIVE") insights = f"""Monthly Insights: Total Entries: {total_entries} Positive Entries: {positive_entries} ({(positive_entries / total_entries * 100):.1f}%) Negative Entries: {total_entries - positive_entries} ({((total_entries - positive_entries) / total_entries * 100):.1f}%) """ return insights def create_journal_interface(): journal = JournalCompanion() with gr.Blocks(title="AI Journal Companion") as interface: gr.Markdown("# 📔 AI Journal Companion") gr.Markdown("Write your thoughts and receive AI-powered insights, prompts, and affirmations.") with gr.Row(): with gr.Column(): entry_input = gr.Textbox( label="Journal Entry", placeholder="Write your journal entry here...", lines=5 ) submit_btn = gr.Button("Submit Entry", variant="primary") with gr.Column(): result_message = gr.Markdown(label="Analysis Result") sentiment_output = gr.Textbox(label="Detected Sentiment") prompt_output = gr.Markdown(label="Reflective Prompts") affirmation_output = gr.Textbox(label="Daily Affirmation") with gr.Row(): insights_btn = gr.Button("Show Monthly Insights") insights_output = gr.Markdown(label="Monthly Insights") submit_btn.click( fn=journal.analyze_entry, inputs=[entry_input], outputs=[ result_message, sentiment_output, prompt_output, affirmation_output ] ) insights_btn.click( fn=journal.get_monthly_insights, inputs=[], outputs=[insights_output] ) return interface if __name__ == "__main__": interface = create_journal_interface() interface.launch()