Download app.py from schennu/elderly: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/schennu/elderly/resolve/main/app.py
- Command line
-
hf download hf://spaces/schennu/elderly/app.py
-
curl -L -o app.py https://huggingface.co/spaces/schennu/elderly/resolve/main/app.py
14.8 kB
| # Create a simple chat | |
| import streamlit as st | |
| from openai import OpenAI | |
| from crewai import Agent, Task, Crew, Process | |
| from crewai_tools import SerperDevTool, WebsiteSearchTool | |
| import os | |
| import time | |
| st.set_page_config( | |
| page_title="SeniorMatch - Elder Engage", | |
| page_icon="π΅π΄", | |
| layout="wide" | |
| ) | |
| st.title("β¨ SeniorMatch: Activities & Resources for Seniors") | |
| st.markdown("*Connecting seniors to social activities, volunteer opportunities, and community engagement*") | |
| def get_result(user_prompt, age_group, zip_code, mobility, serper_api_key): | |
| # Double-check that API keys are set | |
| if "OPENAI_API_KEY" not in os.environ or not os.environ["OPENAI_API_KEY"]: | |
| raise ValueError("OpenAI API key is not set properly") | |
| if "SERPER_API_KEY" not in os.environ or not os.environ["SERPER_API_KEY"]: | |
| # Set the required API key for SerperDevTool if not already set | |
| os.environ["SERPER_API_KEY"] = serper_api_key | |
| researcher = Agent( | |
| name="Senior Activities Researcher", | |
| role="Elderly Support Specialist", | |
| goal=f"Find appropriate activities for a senior (Age: {age_group}, Mobility: {mobility}) in zipcode {zip_code}.", | |
| backstory="You are a compassionate elderly care specialist who understands the unique needs and interests of seniors. You find accessible, engaging activities that promote well-being and social connection.", | |
| tools=[WebsiteSearchTool(), SerperDevTool()], | |
| verbose=False | |
| ) | |
| writer = Agent( | |
| name="Senior Engagement Specialist", | |
| role="Elderly Care Advisor", | |
| goal="Provide clear, accessible activity recommendations that consider the physical capabilities, interests, and social needs of seniors.", | |
| backstory=f"You are a compassionate advisor for seniors who understands the challenges they face. You focus on activities that promote physical health, mental stimulation, and social connection while considering mobility limitations ({mobility}) and age-appropriate options for someone {age_group} years old.", | |
| verbose=False | |
| ) | |
| # Define tasks | |
| research_task = Task( | |
| description=f"Find senior-friendly activities, community resources, and online events related to: {user_prompt} in zipcode {zip_code}. Consider mobility level: {mobility} and age: {age_group}.", | |
| expected_output=f"Provide a mix of in-person and virtual activities suitable for seniors. Include senior centers, community classes, accessible events, and easy-to-follow online videos. For each suggestion, provide clear accessibility information, transportation options if available, and direct links. Ensure all activities are appropriate for someone with {mobility} mobility level.", | |
| agent=researcher | |
| ) | |
| write_task = Task( | |
| description=f"Select the most appropriate activities for a senior (Age: {age_group}, Mobility: {mobility}) interested in {user_prompt}. Include a mix of social, physical, and mental stimulation options.", | |
| expected_output="Provide 3-5 senior-friendly recommendations with detailed information on: \n1. Why this activity is beneficial for seniors \n2. Clear accessibility information \n3. Transportation options if needed \n4. Step-by-step instructions for participating \n5. Direct links to register or participate \n\nFormat the information in large, readable text with clear headings and simple instructions.", | |
| agent=writer, | |
| context=[research_task] | |
| ) | |
| crew = Crew( | |
| agents=[researcher, writer], | |
| tasks=[research_task, write_task], | |
| process=Process.sequential, | |
| verbose=True | |
| ) | |
| result = crew.kickoff() | |
| return result | |
| def open_ai_chat(user_prompt, api_key): | |
| # Set the API key explicitly for OpenAI | |
| os.environ["OPENAI_API_KEY"] = api_key | |
| # Create client with the API key | |
| client = OpenAI(api_key=api_key) | |
| try: | |
| response = client.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=[ | |
| {"role": "system", "content": "You are a helpful assistant."}, | |
| {"role": "user", "content": user_prompt} | |
| ] | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| st.error(f"OpenAI API Error: {str(e)}") | |
| return "Could not generate additional tips. Please check your API key." | |
| # App UI | |
| st.sidebar.header("API Keys") | |
| # Use session state to preserve API keys | |
| if 'user_api_key' not in st.session_state: | |
| st.session_state.user_api_key = '' | |
| if 'serper_api_key' not in st.session_state: | |
| st.session_state.serper_api_key = '' | |
| if 'youtube_api_key' not in st.session_state: | |
| st.session_state.youtube_api_key = '' | |
| user_api_key = st.sidebar.text_input("Enter your OpenAI API key", type="password", | |
| value=st.session_state.user_api_key, | |
| help="Required for both CrewAI agents and additional tips") | |
| serper_api_key = st.sidebar.text_input("Enter your Serper API key", type="password", | |
| value=st.session_state.serper_api_key, | |
| help="Required for web search functionality") | |
| youtube_api_key = st.sidebar.text_input("Enter your YouTube API key", type="password", | |
| value=st.session_state.youtube_api_key, | |
| help="Optional: Enhances video search results") | |
| # Store API keys in session state | |
| st.session_state.user_api_key = user_api_key | |
| st.session_state.serper_api_key = serper_api_key | |
| st.session_state.youtube_api_key = youtube_api_key | |
| # Verify API keys format | |
| if user_api_key: | |
| if not user_api_key.startswith('sk-'): | |
| st.sidebar.warning("OpenAI API key should start with 'sk-'") | |
| # Add API key instructions | |
| with st.sidebar.expander("How to get API keys"): | |
| st.markdown(""" | |
| **OpenAI API Key:** | |
| 1. Go to [OpenAI Platform](https://platform.openai.com/) | |
| 2. Sign up or log in | |
| 3. Navigate to API keys section | |
| 4. Create a new secret key | |
| **Serper API Key:** | |
| 1. Go to [Serper.dev](https://serper.dev/) | |
| 2. Sign up or log in | |
| 3. Find your API key in the dashboard | |
| """) | |
| # Test connection button | |
| if st.sidebar.button("Test API Connections"): | |
| with st.sidebar: | |
| if not user_api_key or not serper_api_key: | |
| st.error("Please enter both required API keys") | |
| else: | |
| with st.spinner("Testing connections..."): | |
| try: | |
| # Test OpenAI connection | |
| os.environ["OPENAI_API_KEY"] = user_api_key | |
| client = OpenAI(api_key=user_api_key) | |
| client.models.list() | |
| st.success("β OpenAI connection successful") | |
| except Exception as e: | |
| st.error(f"β OpenAI connection failed: {str(e)}") | |
| # We can't easily test SerperDevTool without making a real query | |
| # Just set the environment variable to check format | |
| try: | |
| os.environ["SERPER_API_KEY"] = serper_api_key | |
| st.success("β Serper API key set correctly") | |
| except Exception as e: | |
| st.error(f"β Serper API key error: {str(e)}") | |
| st.header("Senior Information") | |
| st.markdown("Tell us about yourself so we can find the most appropriate activities and resources.") | |
| age_group = st.text_input("Enter your age") | |
| zip_code = st.text_input("Enter your zip code") | |
| mobility = st.selectbox("Mobility level:", ["Fully mobile", "Some limitations", "Limited mobility", "Requires assistance"]) | |
| user_prompt = st.text_area("What activities or interests would you like to explore?", height=100) | |
| st.caption("Examples: gardening, book clubs, gentle exercise, music, crafts, technology learning") | |
| st.markdown("---") | |
| # Initialize session state for tracking errors if not already initialized | |
| if 'api_error' not in st.session_state: | |
| st.session_state.api_error = False | |
| if st.button("Find Activities", type="primary"): | |
| if not user_prompt: | |
| st.warning("Please enter your interests.") | |
| elif not user_api_key: | |
| st.warning("Please enter your OpenAI API key.") | |
| elif not serper_api_key: | |
| st.warning("Please enter your Serper API key.") | |
| else: | |
| with st.spinner("Finding activities for you..."): | |
| try: | |
| st.subheader("Results:") | |
| # Set API keys in environment variables | |
| os.environ["OPENAI_API_KEY"] = user_api_key | |
| os.environ["SERPER_API_KEY"] = serper_api_key | |
| if youtube_api_key: | |
| os.environ["YOUTUBE_API_KEY"] = youtube_api_key | |
| # Add a small delay to ensure environment variables are set | |
| time.sleep(0.5) | |
| try: | |
| result = get_result(user_prompt, age_group, zip_code, mobility, serper_api_key) | |
| st.session_state.api_error = False | |
| except Exception as e: | |
| st.error(f"CrewAI Error: {str(e)}") | |
| st.session_state.api_error = True | |
| st.stop() | |
| # Format the result with better styling | |
| st.markdown("## π Recommended Activities") | |
| st.markdown(f""" | |
| <div style="background-color: #f8f9fa; padding: 20px; border-radius: 10px; border-left: 5px solid #4CAF50;"> | |
| <div style="font-size: 18px;"> | |
| {result} | |
| </div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Optional: Get additional senior-specific tips | |
| if st.checkbox("Get additional senior wellness tips"): | |
| openai_prompt = f"Provide 3-5 health and wellness tips for a senior aged {age_group} with {mobility} mobility who enjoys {user_prompt}. Include social connection suggestions, gentle exercise recommendations appropriate for their mobility level, and mental wellness activities." | |
| openai_response = open_ai_chat(openai_prompt, user_api_key) | |
| st.markdown("## πΏ Senior Wellness Tips") | |
| st.markdown(f""" | |
| <div style="background-color: #e8f4f8; padding: 20px; border-radius: 10px; border-left: 5px solid #3498db;"> | |
| <div style="font-size: 18px;"> | |
| {openai_response} | |
| </div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| except Exception as e: | |
| st.error(f"Error: {str(e)}") | |
| st.markdown(""" | |
| ### Troubleshooting API Key Issues: | |
| 1. Ensure you've entered valid API keys | |
| 2. Check that your OpenAI account has available credits | |
| 3. Verify the Serper API key is active | |
| """) | |
| st.session_state.api_error = True | |
| else: | |
| # About SeniorMatch section | |
| st.info("Tell us about yourself, and we'll find the perfect activities for you. Click 'Find Activities' when ready.") | |
| st.markdown("---") | |
| # Vision and features section | |
| st.header("π Welcome to SeniorMatch") | |
| st.markdown(""" | |
| ### **Connect. Contribute. Thrive.** | |
| #### **The Challenge**: | |
| Many seniors remain mentally vibrant but face barriers to meaningful social connection and community engagement. | |
| Despite rich life experiences, logistical hurdles and technology gaps often lead to isolation. | |
| #### **Our Solution:** | |
| SeniorMatch uses AI to bridge these gaps, connecting you with perfect-fit volunteer opportunities, | |
| flexible income options, and social activities that match your schedule and interests. | |
| """) | |
| # Features in columns | |
| st.subheader("What We Offer:") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown(""" | |
| #### π€ **Give Back & Earn** | |
| Discover local volunteer opportunities and flexible gigs that fit your schedule and skills. | |
| #### ποΈ **Meet & Connect** | |
| Join walks, lunches, or hobby groups with like-minded people in your community. | |
| """) | |
| with col2: | |
| st.markdown(""" | |
| #### π± **Simple & Accessible** | |
| Large text, clear navigation, and voice commands make technology work for you, not against you. | |
| #### π§ **Smart Recommendations** | |
| The more you use SeniorMatch, the better it understands your preferences and schedule. | |
| """) | |
| # Impact section | |
| st.subheader("Why It Matters:") | |
| impact_col1, impact_col2, impact_col3 = st.columns(3) | |
| with impact_col1: | |
| st.markdown(""" | |
| #### πͺ **Purpose** | |
| Tap into opportunities that use your skills and wisdom. | |
| """) | |
| with impact_col2: | |
| st.markdown(""" | |
| #### β€οΈ **Health** | |
| Social connection improves mental and physical wellbeing. | |
| """) | |
| with impact_col3: | |
| st.markdown(""" | |
| #### π **Inclusion** | |
| Technology that adapts to you, not the other way around. | |
| """) | |
| # Add testimonials | |
| st.markdown("---") | |
| st.subheader("π£ What Our Community Says") | |
| testimonial_cols = st.columns(3) | |
| with testimonial_cols[0]: | |
| st.markdown(""" | |
| > "SeniorMatch connected me with a local garden club. Now I volunteer twice a week and have made wonderful friends." | |
| > | |
| > **β Margaret, 72** | |
| """) | |
| with testimonial_cols[1]: | |
| st.markdown(""" | |
| > "I found a part-time gig teaching piano to kids. It's perfect for my schedule and keeps me feeling useful." | |
| > | |
| > **β Robert, 68** | |
| """) | |
| with testimonial_cols[2]: | |
| st.markdown(""" | |
| > "The weekly walking group has improved my health and given me something to look forward to every Monday." | |
| > | |
| > **β Eleanor, 77** | |
| """) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown("**Physical Benefits:**") | |
| st.markdown("β’ Maintains strength and mobility") | |
| st.markdown("β’ Reduces fall risks") | |
| st.markdown("β’ Improves heart health") | |
| st.markdown("β’ Manages chronic conditions") | |
| with col2: | |
| st.markdown("**Mental & Social Benefits:**") | |
| st.markdown("β’ Fights isolation") | |
| st.markdown("β’ Sharpens the mind") | |
| st.markdown("β’ Elevates mood") | |
| st.markdown("β’ Creates community connection") |