import os import requests import streamlit as st from dotenv import load_dotenv # Load environment variables from the .env file load_dotenv() # Get the API key from the .env file API_KEY = os.getenv("GEMINI_API_KEY") if API_KEY is None: st.error("API key not found! Please set the GEMINI_API_KEY in your .env file.") st.stop() # Define the 3 questions for mood analysis questions = [ "How are you feeling today in one word?", "What's currently on your mind?", "Do you feel calm or overwhelmed right now?", ] # Function to query the Gemini API def query_gemini_api(user_answers): # Correct API URL url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key={API_KEY}" headers = {'Content-Type': 'application/json'} # Combine user responses into a single input input_text = " ".join(user_answers) # Payload for the API request payload = { "contents": [ { "parts": [ {"text": f"Analyze the mood based on these inputs: {input_text}. Provide recommendations."} ] } ] } try: # Send POST request response = requests.post(url, headers=headers, json=payload) if response.status_code == 200: result = response.json() # Extract recommendations from the response recommendations = result.get("contents", [{}])[0].get("parts", [{}])[0].get("text", "") return recommendations else: # Handle API error st.error(f"API Error {response.status_code}: {response.text}") return None except requests.exceptions.RequestException as e: st.error(f"An error occurred: {e}") return None # Streamlit app def main(): st.title("Mood Analysis and Suggestions") st.write("Answer the following 3 questions to help us understand your mood:") # Collect user responses responses = [] for i, question in enumerate(questions): response = st.text_input(f"{i+1}. {question}") if response: responses.append(response) # Query the API if all questions are answered if len(responses) == len(questions): st.write("Processing your answers...") # Query the Gemini API recommendations = query_gemini_api(responses) if recommendations: st.write("### Recommendations to Improve Your Mood:") st.write(recommendations) else: st.warning("Could not generate mood analysis. Please try again later.") else: st.info("Please answer all 3 questions to receive suggestions.") if __name__ == "__main__": main()