Spaces:
Sleeping
Sleeping
import os | |
import requests | |
import streamlit as st | |
from dotenv import load_dotenv | |
# Load environment variables from the .env file | |
load_dotenv() | |
# Get the Gemini API key from the .env file | |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") | |
if GEMINI_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 Gemini API endpoint | |
url = f"https://generativelanguage.googleapis.com/v1beta/models/text-bison-001:generateText?key={GEMINI_API_KEY}" | |
headers = {'Content-Type': 'application/json'} | |
# Combine the user answers into a single input text | |
input_text = " ".join(user_answers) | |
# Payload for the API | |
payload = { | |
"prompt": { | |
"text": f"Analyze the following mood based on these inputs: {input_text}. Provide suggestions to improve the mood." | |
}, | |
"temperature": 0.7, | |
"maxOutputTokens": 256, | |
"topP": 0.8, | |
"topK": 40 | |
} | |
try: | |
# Send the POST request | |
response = requests.post(url, headers=headers, json=payload) | |
# Check if the response is successful | |
if response.status_code == 200: | |
result = response.json() | |
# Extract the generated text from the response | |
generated_text = result.get("candidates", [{}])[0].get("output", "") | |
return generated_text | |
else: | |
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 for collecting answers | |
def main(): | |
st.title("Mood Analysis and Suggestions") | |
st.write("Answer the following 3 questions to help us understand your mood:") | |
# Collect responses from the user | |
responses = [] | |
for i, question in enumerate(questions): | |
response = st.text_input(f"{i+1}. {question}") | |
if response: | |
responses.append(response) | |
# If all 3 responses are collected, send them to Gemini for analysis | |
if len(responses) == len(questions): | |
st.write("Processing your answers...") | |
# Query the Gemini API | |
generated_text = query_gemini_api(responses) | |
if generated_text: | |
# Display the generated mood analysis and recommendations | |
st.write("### Mood Analysis and Suggestions:") | |
st.write(generated_text) | |
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() | |