Spaces:
Runtime error
Runtime error
Download src/streamlit_app.py from macken39/Kid-Planner-4: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/spaces/macken39/Kid-Planner-4/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/macken39/Kid-Planner-4/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/macken39/Kid-Planner-4/resolve/main/src/streamlit_app.py
12.5 kB
| import streamlit as st | |
| import json | |
| import os | |
| from datetime import datetime | |
| # Import OpenAI with error handling | |
| try: | |
| from openai import OpenAI | |
| OPENAI_AVAILABLE = True | |
| except ImportError: | |
| st.error("OpenAI library not installed. Please install it with: pip install openai") | |
| OPENAI_AVAILABLE = False | |
| # Page configuration | |
| st.set_page_config( | |
| page_title="Milwaukee Family Activities", | |
| page_icon="ποΈ", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Initialize session state | |
| if 'activities' not in st.session_state: | |
| st.session_state.activities = [] | |
| if 'search_completed' not in st.session_state: | |
| st.session_state.search_completed = False | |
| def get_openai_key(): | |
| """Get OpenAI API key from environment or secrets""" | |
| try: | |
| return st.secrets["OPENAI_API_KEY"] | |
| except: | |
| key = os.getenv("OPENAI_API_KEY") | |
| if key: | |
| return key | |
| return None | |
| # Cache for 24 hours | |
| def load_milwaukee_activities(): | |
| """Load Milwaukee activities from JSON file""" | |
| json_file = 'milwaukee_activities.json' | |
| try: | |
| if os.path.exists(json_file): | |
| with open(json_file, 'r', encoding='utf-8') as f: | |
| activities = json.load(f) | |
| return activities | |
| else: | |
| st.error(f"β {json_file} not found! Please run the scraper first:") | |
| st.code("python scraper.py") | |
| st.stop() | |
| except Exception as e: | |
| st.error(f"Error loading activities: {str(e)}") | |
| st.stop() | |
| def filter_milwaukee_activities(activities, location, kids_ages, interests, budget, category_filter, season_filter): | |
| """Filter Milwaukee activities based on family criteria""" | |
| if not activities: | |
| return [] | |
| filtered = [] | |
| for activity in activities: | |
| # Location filter (basic Milwaukee area check) | |
| if location and 'milwaukee' not in location.lower(): | |
| # If they're not in Milwaukee area, still show activities but with a note | |
| pass | |
| # Category filter | |
| if category_filter != "All Categories": | |
| activity_category = activity.get('category', '').lower() | |
| if category_filter.lower() not in activity_category: | |
| continue | |
| # Season filter | |
| if season_filter != "All Seasons": | |
| activity_season = activity.get('season', '').lower() | |
| if (season_filter.lower() not in activity_season and | |
| 'year round' not in activity_season): | |
| continue | |
| # Age appropriateness filter | |
| if kids_ages: | |
| age_range = activity.get('age_range', '').lower() | |
| if age_range and 'all ages' not in age_range: | |
| # Check if any kid age fits the range | |
| suitable_for_ages = False | |
| for age in kids_ages: | |
| if (str(age) in age_range or | |
| 'toddler' in age_range and age <= 3 or | |
| 'preschool' in age_range and 3 <= age <= 5 or | |
| 'school' in age_range and 5 <= age <= 12 or | |
| 'teen' in age_range and 13 <= age <= 17): | |
| suitable_for_ages = True | |
| break | |
| if not suitable_for_ages: | |
| continue | |
| # Budget filter | |
| cost = activity.get('cost', '').lower() | |
| if budget == "Free Only": | |
| if not any(term in cost for term in ['free', '$0', 'no cost']): | |
| continue | |
| elif budget == "Low Budget": | |
| if not (any(term in cost for term in ['free', '$0']) or | |
| any(price in cost for price in ['$5', '$6', '$7', '$8', '$9', '$10', '$12', '$15'])): | |
| continue | |
| filtered.append(activity) | |
| return filtered | |
| def search_milwaukee_activities_ai(query, family_profile, activities, api_key): | |
| """Use AI to find and rank Milwaukee activities""" | |
| if not OPENAI_AVAILABLE or not api_key: | |
| return simple_text_search(query, activities) | |
| try: | |
| client = OpenAI(api_key=api_key) | |
| # Find relevant activities | |
| query_lower = query.lower() | |
| relevant_activities = [] | |
| for activity in activities: | |
| activity_text = f"{activity['name']} {activity['description']} {activity.get('category', '')}".lower() | |
| if any(word in activity_text for word in query_lower.split()): | |
| relevant_activities.append(activity) | |
| # Limit for API efficiency | |
| relevant_activities = relevant_activities[:8] | |
| # Format for AI | |
| context = "\n\n".join([ | |
| f"Activity: {act['name']}\nDescription: {act['description']}\nLocation: {act['location']}\nCategory: {act['category']}\nCost: {act['cost']}\nAges: {act['age_range']}\nSeason: {act['season']}" | |
| for act in relevant_activities | |
| ]) | |
| prompt = f""" | |
| Based on these Milwaukee family activities, provide personalized recommendations. | |
| Family Profile: | |
| {family_profile} | |
| User Request: {query} | |
| Available Activities: | |
| {context} | |
| Rank and recommend the best 5 activities for this family. For each, provide: | |
| - name: Exact activity name | |
| - why_perfect: Why it's perfect for this family (2-3 sentences) | |
| - family_tips: Practical tips for families visiting | |
| - timing_advice: Best times to visit | |
| - cost_info: What to expect cost-wise | |
| Only recommend activities from the provided list. Focus on practical advice. | |
| Return as JSON array. | |
| """ | |
| response = client.chat.completions.create( | |
| model="gpt-4", | |
| messages=[ | |
| { | |
| "role": "system", | |
| "content": "You are a Milwaukee family activity expert. Provide practical, helpful recommendations based only on the provided activities." | |
| }, | |
| {"role": "user", "content": prompt} | |
| ], | |
| temperature=0.7, | |
| max_tokens=1500 | |
| ) | |
| content = response.choices[0].message.content | |
| try: | |
| ai_recommendations = json.loads(content) | |
| return ai_recommendations if isinstance(ai_recommendations, list) else [ai_recommendations] | |
| except: | |
| return simple_text_search(query, activities) | |
| except Exception as e: | |
| st.warning(f"AI search failed: {str(e)}") | |
| return simple_text_search(query, activities) | |
| def simple_text_search(query, activities): | |
| """Simple text search through activities""" | |
| query_lower = query.lower() | |
| results = [] | |
| for activity in activities: | |
| activity_text = f"{activity['name']} {activity['description']} {activity.get('category', '')}".lower() | |
| if any(word in activity_text for word in query_lower.split()): | |
| results.append({ | |
| 'name': activity['name'], | |
| 'why_perfect': activity['description'], | |
| 'family_tips': activity.get('practical_tips', 'Check website for current information'), | |
| 'timing_advice': activity.get('best_times', f"Best during {activity.get('season', 'year round')}"), | |
| 'cost_info': activity.get('cost', 'Contact for pricing') | |
| }) | |
| return results[:5] | |
| def display_activity(activity, original_data=None): | |
| """Display a single Milwaukee activity""" | |
| with st.container(): | |
| # Header | |
| col_header1, col_header2 = st.columns([4, 1]) | |
| with col_header1: | |
| st.subheader(activity.get('name', 'Milwaukee Activity')) | |
| with col_header2: | |
| if original_data: | |
| category = original_data.get('category', 'Activity') | |
| st.markdown(f""" | |
| <div style=" | |
| background-color: #e8f4f8; | |
| border-radius: 12px; | |
| padding: 4px 12px; | |
| text-align: center; | |
| font-size: 12px; | |
| color: #1f4e79; | |
| font-weight: 500; | |
| margin-top: 8px; | |
| "> | |
| {category} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Main content | |
| col1, col2 = st.columns([3, 1]) | |
| with col1: | |
| # Description | |
| description = activity.get('why_perfect', activity.get('description', '')) | |
| if description: | |
| st.write(description) | |
| # Location | |
| if original_data: | |
| location = original_data.get('location', '') | |
| if location: | |
| st.write(f"π **Location:** {location}") | |
| # Age and season info | |
| if original_data: | |
| age_range = original_data.get('age_range', '') | |
| season = original_data.get('season', '') | |
| if age_range: | |
| st.write(f"πΆ **Good for:** {age_range}") | |
| if season: | |
| st.write(f"ποΈ **Best time:** {season}") | |
| # Website and contact | |
| if original_data: | |
| website = original_data.get('website', '') | |
| contact = original_data.get('contact_info', '') | |
| if website: | |
| st.write(f"π **Website:** https://{website}") | |
| if contact: | |
| st.write(f"π **Contact:** {contact}") | |
| with col2: | |
| # Cost | |
| cost = activity.get('cost_info', '') | |
| if original_data: | |
| cost = original_data.get('cost', cost) | |
| if cost: | |
| if 'free' in cost.lower(): | |
| st.success(f"π° {cost}") | |
| else: | |
| st.metric("π° Cost", cost) | |
| # Duration | |
| if original_data: | |
| duration = original_data.get('duration', '') | |
| if duration: | |
| st.info(f"β±οΈ {duration}") | |
| # Indoor/Outdoor | |
| if original_data: | |
| activity_type = original_data.get('indoor_outdoor', '') | |
| if activity_type: | |
| if 'outdoor' in activity_type.lower(): | |
| st.success("π Outdoor") | |
| elif 'indoor' in activity_type.lower(): | |
| st.info("π Indoor") | |
| # Expandable details | |
| col_expand1, col_expand2 = st.columns(2) | |
| with col_expand1: | |
| family_tips = activity.get('family_tips', '') | |
| if not family_tips and original_data: | |
| family_tips = original_data.get('practical_tips', '') | |
| if family_tips: | |
| with st.expander("π‘ Family Tips"): | |
| st.write(family_tips) | |
| with col_expand2: | |
| timing_advice = activity.get('timing_advice', '') | |
| if not timing_advice and original_data: | |
| timing_advice = original_data.get('best_times', '') | |
| if timing_advice: | |
| with st.expander("β° Best Times to Visit"): | |
| st.write(timing_advice) | |
| # Insider info | |
| if original_data and original_data.get('insider_info'): | |
| with st.expander("π Insider Tips"): | |
| st.write(original_data['insider_info']) | |
| st.divider() | |
| def main(): | |
| # Header | |
| st.title("ποΈ Milwaukee Family Activities") | |
| st.markdown("Discover amazing family-friendly activities in Milwaukee! π") | |
| # Load activities | |
| with st.spinner("Loading Milwaukee activities..."): | |
| all_activities = load_milwaukee_activities() | |
| st.success(f"β Loaded {len(all_activities)} Milwaukee family activities!") | |
| # Get API key | |
| api_key = get_openai_key() | |
| # Family info inputs | |
| with st.sidebar: | |
| st.header("π¨βπ©βπ§βπ¦ About Your Family") | |
| # Location | |
| location = st.text_input("π Your Location", placeholder="Milwaukee, Wauwatosa, etc.", help="Where are you visiting from?") | |
| # Kids ages | |
| st.subheader("πΆ Kids Ages") | |
| age_inputs = st.columns(2) |