TeaTimeLogic / app.py
Iammcqwory's picture
Update app.py
d73224e verified
import streamlit as st
import requests
import os
# Access the Hugging Face token from the environment variable
HF_TOKEN = os.environ.get("HF_TOKEN")
if not HF_TOKEN:
st.error("Hugging Face token not found. Please check your Secrets configuration.")
st.stop()
# Hugging Face Inference API endpoints
SENTIMENT_API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
TEXT_GENERATION_API_URL = "https://api-inference.huggingface.co/models/gpt2"
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
# Tea recommendations based on mood
tea_recommendations = {
"POSITIVE": {
"description": "Perfect for celebrating your joy!",
"teas": ["Fruit Infusion Tea", "Hibiscus Tea", "Earl Grey Tea"],
"health_benefits": "Boosts mood, rich in vitamins, and supports heart health.",
"recipe": "Steep for 6 minutes in hot water (95Β°C). Add sugar or fruit slices for extra flavor."
},
"NEGATIVE": {
"description": "Calm your mind and reduce stress.",
"teas": ["Peppermint Tea", "Lemon Balm Tea", "Rooibos Tea"],
"health_benefits": "Relieves anxiety, soothes digestion, and reduces tension.",
"recipe": "Steep for 4 minutes in boiling water. Add lemon for a refreshing twist."
}
}
# Function to detect mood using Hugging Face Inference API
def detect_mood(user_input):
try:
payload = {"inputs": user_input}
response = requests.post(SENTIMENT_API_URL, headers=HEADERS, json=payload)
if response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0:
return result[0][0]["label"] # Returns "POSITIVE" or "NEGATIVE"
return "POSITIVE" # Default to positive if API fails
except Exception as e:
st.error(f"Error detecting mood: {e}")
return "POSITIVE" # Fallback to positive mood
# Function to generate personalized tea recommendations using Hugging Face Inference API
def personalized_recommendation(user_input):
try:
prompt = f"Based on the following preferences: '{user_input}', suggest a type of tea and explain why it's a good fit."
payload = {"inputs": prompt, "max_length": 100, "num_return_sequences": 1}
response = requests.post(TEXT_GENERATION_API_URL, headers=HEADERS, json=payload)
if response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0:
return result[0]["generated_text"]
return "I recommend trying Chamomile Tea for its calming properties." # Default recommendation if API fails
except Exception as e:
st.error(f"Error generating recommendation: {e}")
return "I recommend trying Chamomile Tea for its calming properties." # Fallback recommendation
# Streamlit app
def main():
st.title("🍡 Tea Time Logic")
st.write("Welcome to your AI-powered tea recommendation app! Describe how you're feeling, and we'll suggest the perfect tea for you.")
# User input for mood detection
user_input = st.text_input("Describe how you're feeling today:")
if user_input:
mood = detect_mood(user_input)
st.write(f"**Detected Mood:** {mood}")
st.subheader(f"Tea Recommendations for Feeling {mood}:")
st.write(tea_recommendations[mood]["description"])
st.write("**Recommended Teas:**")
for tea in tea_recommendations[mood]["teas"]:
st.write(f"- {tea}")
st.write("**Health Benefits:**")
st.write(tea_recommendations[mood]["health_benefits"])
st.write("**Brewing Recipe:**")
st.write(tea_recommendations[mood]["recipe"])
# Personalized recommendations
st.subheader("Personalized Tea Recommendations")
preference_input = st.text_input("Describe your preferences (e.g., 'I like sweet and floral teas'):")
if preference_input:
recommendation = personalized_recommendation(preference_input)
st.write("**Your Personalized Recommendation:**")
st.write(recommendation)
# Footer
st.write("---")
st.write("Enjoy your tea and have a wonderful day! 😊")
if __name__ == "__main__":
main()