import streamlit as st import os import json import random from typing import Dict, List, Any from datetime import datetime # Import cultural data from cultural_data import ( CULTURAL_DATA, get_all_countries, get_country_data, search_by_category, get_all_cultural_facts, get_festivals_by_season, search_locations_by_type ) # Page configuration st.set_page_config( page_title="CultureBot - Your AI Cultural Guide", page_icon="🌍", layout="wide", initial_sidebar_state="expanded" ) # Enhanced Cultural Database Class class CulturalDatabase: def __init__(self): self.cultural_data = CULTURAL_DATA self.cultural_facts = get_all_cultural_facts() def search_facts(self, query: str) -> List[Dict[str, Any]]: """Search for relevant cultural facts based on query""" query_lower = query.lower() relevant_facts = [] # Search by country for country in self.cultural_data.keys(): if country.lower() in query_lower: country_data = get_country_data(country) if 'cultural_facts' in country_data: for fact in country_data['cultural_facts']: fact_with_country = fact.copy() fact_with_country['country'] = country relevant_facts.append(fact_with_country) # Search by category if not relevant_facts: for fact in self.cultural_facts: if fact['category'].lower() in query_lower: relevant_facts.append(fact) # Search by keywords in fact content if not relevant_facts: keywords = query_lower.split() for fact in self.cultural_facts: fact_text = fact['fact'].lower() if any(keyword in fact_text for keyword in keywords): relevant_facts.append(fact) # Search in festivals if not relevant_facts and ('festival' in query_lower or 'celebration' in query_lower): for country, data in self.cultural_data.items(): if 'festivals' in data: for festival in data['festivals']: if any(keyword in festival['name'].lower() or keyword in festival['description'].lower() for keyword in query_lower.split()): festival_fact = { 'country': country, 'fact': f"{festival['name']} is celebrated in {festival['season']}. {festival['description']}", 'category': 'festival', 'source': 'Cultural Festival Database' } relevant_facts.append(festival_fact) # Search in locations if not relevant_facts and ('place' in query_lower or 'visit' in query_lower or 'location' in query_lower): for country, data in self.cultural_data.items(): if 'best_locations' in data: for location in data['best_locations']: if any(keyword in location['name'].lower() or keyword in location['description'].lower() for keyword in query_lower.split()): location_fact = { 'country': country, 'fact': f"{location['name']} is a {location['type']} in {country}. {location['description']}", 'category': 'location', 'source': 'Cultural Location Database' } relevant_facts.append(location_fact) return relevant_facts[:5] def get_random_fact(self) -> Dict[str, Any]: """Get a random cultural fact""" return random.choice(self.cultural_facts) def get_facts_by_country(self, country: str) -> List[Dict[str, Any]]: """Get all facts for a specific country""" return [fact for fact in self.cultural_facts if fact['country'].lower() == country.lower()] def get_facts_by_category(self, category: str) -> List[Dict[str, Any]]: """Get all facts for a specific category""" return [fact for fact in self.cultural_facts if fact['category'].lower() == category.lower()] def get_all_countries(self) -> List[str]: """Get list of all countries in the database""" return get_all_countries() def get_all_categories(self) -> List[str]: """Get list of all categories in the database""" return list(set(fact['category'] for fact in self.cultural_facts)) def get_country_festivals(self, country: str) -> List[Dict[str, Any]]: """Get festivals for a specific country""" country_data = get_country_data(country) return country_data.get('festivals', []) def get_country_locations(self, country: str) -> List[Dict[str, Any]]: """Get best locations for a specific country""" country_data = get_country_data(country) return country_data.get('best_locations', []) def get_country_languages(self, country: str) -> Dict[str, Any]: """Get language information for a specific country""" country_data = get_country_data(country) return country_data.get('languages', {}) # Enhanced AI Response Generator class CultureAI: def __init__(self): self.cultural_db = CulturalDatabase() def generate_response(self, user_message: str) -> Dict[str, Any]: """Generate response based on cultural database""" query_lower = user_message.lower() # Check for specific country mentions mentioned_country = None for country in self.cultural_db.get_all_countries(): if country.lower() in query_lower: mentioned_country = country break # Handle different types of queries if mentioned_country: country_data = get_country_data(mentioned_country) if 'festival' in query_lower or 'celebration' in query_lower: festivals = country_data.get('festivals', []) if festivals: festival = festivals[0] response = f"Here's information about festivals in {mentioned_country}: {festival['name']} is celebrated during {festival['season']}. {festival['description']} {festival['significance']}" if len(festivals) > 1: response += f"\n\nOther notable festivals include: {', '.join([f['name'] for f in festivals[1:3]])}" else: response = f"I don't have specific festival information for {mentioned_country} in my current database." elif 'language' in query_lower: languages = country_data.get('languages', {}) if languages: official = ', '.join(languages.get('official', [])) response = f"Language information for {mentioned_country}: The official language(s) are {official}. " if languages.get('facts'): response += f"Interesting fact: {languages['facts'][0]}" else: response = f"I don't have specific language information for {mentioned_country} in my current database." elif 'visit' in query_lower or 'place' in query_lower or 'location' in query_lower: locations = country_data.get('best_locations', []) if locations: location = locations[0] response = f"Best places to visit in {mentioned_country}: {location['name']} is a {location['type']}. {location['description']}" if len(locations) > 1: response += f"\n\nOther must-visit places include: {', '.join([l['name'] for l in locations[1:3]])}" else: response = f"I don't have specific location information for {mentioned_country} in my current database." elif 'food' in query_lower or 'cuisine' in query_lower: food_culture = country_data.get('food_culture', {}) if food_culture: staples = ', '.join(food_culture.get('staples', [])) dishes = ', '.join(food_culture.get('popular_dishes', [])[:3]) response = f"Food culture in {mentioned_country}: Main staples include {staples}. Popular dishes are {dishes}." if food_culture.get('dining_etiquette'): response += f" Dining etiquette: {food_culture['dining_etiquette'][0]}" else: response = f"I don't have specific food culture information for {mentioned_country} in my current database." else: # Default to cultural facts search relevant_facts = self.cultural_db.search_facts(user_message) if relevant_facts: fact = relevant_facts[0] response = f"Here's cultural information about {mentioned_country}: {fact['fact']}" else: response = f"Here's general information about {mentioned_country}: {mentioned_country} is located in {country_data.get('basic_info', {}).get('continent', 'N/A')} with a population of approximately {country_data.get('basic_info', {}).get('population', 'N/A')}." else: # Generic search across all data relevant_facts = self.cultural_db.search_facts(user_message) if relevant_facts: fact = relevant_facts[0] if "greeting" in query_lower: response = f"Regarding greetings in {fact['country']}: {fact['fact']} This reflects the cultural values of respect and social harmony that are important in {fact['country']}." elif "business" in query_lower: response = f"For business practices in {fact['country']}: {fact['fact']} Understanding these customs is crucial for successful professional relationships." elif "food" in query_lower or "dining" in query_lower: response = f"About dining culture in {fact['country']}: {fact['fact']} Food customs often reflect deeper cultural values and social structures." else: response = f"Here's an important cultural insight about {fact['country']}: {fact['fact']} This practice is rooted in the cultural values and traditions of the region." if len(relevant_facts) > 1: response += f"\n\nAdditionally, it's worth noting that cultural practices can vary within {fact['country']}, and these customs may differ between regions or generations." else: # Fallback response random_fact = self.cultural_db.get_random_fact() response = f"While I don't have specific information about that topic, here's an interesting cultural fact about {random_fact['country']}: {random_fact['fact']} Feel free to ask about specific countries or cultural practices!" return { "response": response, "confidence": 0.8 if 'relevant_facts' in locals() and relevant_facts else 0.6, "sources": ["Enhanced Cultural Database"], "category": "cultural_information" } # Initialize components @st.cache_resource def initialize_components(): return CultureAI(), CulturalDatabase() culture_ai, cultural_db = initialize_components() # Custom CSS for beautiful styling st.markdown(""" """, unsafe_allow_html=True) # Sidebar with app information with st.sidebar: st.markdown(""" """, unsafe_allow_html=True) st.markdown("---") # Navigation st.markdown("### 🧭 Navigation") page = st.selectbox( "Choose a page:", ["🏠 Home", "đŸ’Ŧ Chat with CultureBot", "📚 Cultural Facts", "🎭 Festivals", "📍 Best Locations", "â„šī¸ About"], key="navigation" ) st.markdown("---") # Quick stats st.markdown("### 📊 Quick Stats") st.success("đŸŸĸ System Online") st.info(f"📈 {len(cultural_db.cultural_facts)} Cultural Facts") st.info(f"🌍 {len(cultural_db.get_all_countries())} Countries") # Random fact st.markdown("### 🎲 Random Fact") if st.button("Get Random Fact"): fact = cultural_db.get_random_fact() st.markdown(f"""

{fact['country']}

{fact['fact']}

Category: {fact['category']}
""", unsafe_allow_html=True) # Main content area if page == "🏠 Home": # Home page st.markdown("""

Welcome to CultureBot

Your comprehensive AI-powered guide to understanding cultures, traditions, festivals, and destinations from around the world

""", unsafe_allow_html=True) # Feature cards col1, col2, col3 = st.columns(3) with col1: st.markdown("""

🌍 Global Insights

Discover fascinating cultural facts, festivals, languages, and customs from countries across all continents.

""", unsafe_allow_html=True) with col2: st.markdown("""

🤖 AI-Powered Chat

Ask questions and get personalized responses about specific countries, festivals, locations, and cultural practices.

""", unsafe_allow_html=True) with col3: st.markdown("""

📚 Comprehensive Database

Explore festivals, best locations, languages, food culture, and travel information for each country.

""", unsafe_allow_html=True) st.markdown("---") # Getting started st.markdown("## 🚀 Getting Started") st.markdown(""" 1. **Chat with CultureBot**: Ask questions about any culture, country, festival, or location 2. **Explore Facts**: Browse our curated collection of cultural insights 3. **Discover Festivals**: Learn about celebrations and traditions worldwide 4. **Find Destinations**: Explore the best places to visit in each country 5. **Learn Languages**: Understand linguistic diversity and communication styles """) elif page == "đŸ’Ŧ Chat with CultureBot": # Chat page st.markdown("""

Chat with CultureBot

Ask me about any culture, country, festival, location, or tradition!

""", unsafe_allow_html=True) # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat messages for message in st.session_state.messages: if message["role"] == "user": st.markdown(f"""
You: {message["content"]}
""", unsafe_allow_html=True) else: st.markdown(f"""
CultureBot: {message["content"]}
""", unsafe_allow_html=True) # Chat input user_input = st.chat_input("Ask about any culture, country, festival, or location...") if user_input: # Add user message to chat history st.session_state.messages.append({"role": "user", "content": user_input}) # Get bot response with st.spinner("CultureBot is thinking..."): bot_response = culture_ai.generate_response(user_input) st.session_state.messages.append({ "role": "assistant", "content": bot_response["response"] }) st.rerun() # Suggested questions st.markdown("### 💡 Try asking about:") suggestions = [ "Tell me about Japanese festivals", "What are the best places to visit in India?", "What languages are spoken in Brazil?", "Tell me about German food culture", "What festivals does China celebrate?", "Best locations in France" ] cols = st.columns(2) for i, suggestion in enumerate(suggestions): with cols[i % 2]: if st.button(suggestion, key=f"suggestion_{i}", use_container_width=True): st.session_state.messages.append({"role": "user", "content": suggestion}) with st.spinner("CultureBot is thinking..."): bot_response = culture_ai.generate_response(suggestion) st.session_state.messages.append({ "role": "assistant", "content": bot_response["response"] }) st.rerun() elif page == "📚 Cultural Facts": # Cultural facts page st.markdown("""

Cultural Facts Explorer

Browse our curated collection of cultural insights

""", unsafe_allow_html=True) # Filters col1, col2 = st.columns(2) with col1: countries = ["All Countries"] + sorted(cultural_db.get_all_countries()) country_filter = st.selectbox("Filter by Country:", countries) with col2: categories = ["All Categories"] + sorted(cultural_db.get_all_categories()) category_filter = st.selectbox("Filter by Category:", categories) # Display facts if country_filter != "All Countries": facts = cultural_db.get_facts_by_country(country_filter) elif category_filter != "All Categories": facts = cultural_db.get_facts_by_category(category_filter) else: facts = cultural_db.cultural_facts if facts: for fact in facts: st.markdown(f"""

{fact['country']}

{fact['fact']}

Category: {fact['category']} Source: {fact['source']}
""", unsafe_allow_html=True) else: st.info("No facts found for the selected filters.") elif page == "🎭 Festivals": # Festivals page st.markdown("""

Cultural Festivals

Discover celebrations and traditions from around the world

""", unsafe_allow_html=True) # Country selector countries = ["All Countries"] + sorted(cultural_db.get_all_countries()) country_filter = st.selectbox("Select Country:", countries, key="festival_country") # Display festivals if country_filter != "All Countries": festivals = cultural_db.get_country_festivals(country_filter) if festivals: st.markdown(f"### Festivals in {country_filter}") for festival in festivals: # Build traditions text safely traditions_text = "" if festival.get('traditions'): traditions_text = f"

Traditions: {', '.join(festival['traditions'])}

" # Build foods text safely foods_text = "" if festival.get('foods'): foods_text = f"

Traditional Foods: {', '.join(festival['foods'])}

" st.markdown(f"""

{festival['name']}

Season: {festival['season']}

Description: {festival['description']}

Significance: {festival['significance']}

{traditions_text} {foods_text}
""", unsafe_allow_html=True) else: st.info(f"No festival information available for {country_filter}.") else: # Show all festivals for country in cultural_db.get_all_countries(): festivals = cultural_db.get_country_festivals(country) if festivals: st.markdown(f"### {country}") for festival in festivals[:2]: # Show first 2 festivals per country st.markdown(f"""

{festival['name']}

Season: {festival['season']}

{festival['description']}

""", unsafe_allow_html=True) elif page == "📍 Best Locations": # Best locations page st.markdown("""

Best Places to Visit

Explore must-visit destinations around the world

""", unsafe_allow_html=True) # Country selector countries = ["All Countries"] + sorted(cultural_db.get_all_countries()) country_filter = st.selectbox("Select Country:", countries, key="location_country") # Display locations if country_filter != "All Countries": locations = cultural_db.get_country_locations(country_filter) if locations: st.markdown(f"### Best Places in {country_filter}") for location in locations: # Build highlights text safely highlights_text = "" if location.get('highlights'): highlights_text = f"

Highlights: {', '.join(location['highlights'])}

" # Build best time text safely best_time_text = "" if location.get('best_time'): best_time_text = f"

Best Time: {location['best_time']}

" # Build significance text safely significance_text = "" if location.get('significance'): significance_text = f"

Significance: {location['significance']}

" st.markdown(f"""

{location['name']}

Type: {location['type']}

Description: {location['description']}

{best_time_text} {significance_text} {highlights_text}
""", unsafe_allow_html=True) else: st.info(f"No location information available for {country_filter}.") else: # Show all locations for country in cultural_db.get_all_countries(): locations = cultural_db.get_country_locations(country) if locations: st.markdown(f"### {country}") for location in locations[:2]: # Show first 2 locations per country st.markdown(f"""

{location['name']}

Type: {location['type']}

{location['description']}

""", unsafe_allow_html=True) else: # About page st.markdown("""

About CultureBot

Bridging cultures through comprehensive AI-powered conversations

""", unsafe_allow_html=True) # Mission and features col1, col2 = st.columns(2) with col1: st.markdown(""" ### đŸŽ¯ Our Mission CultureBot was created to help people understand and appreciate the rich diversity of cultures around the world. In our increasingly connected world, cultural awareness is more important than ever. ### 🔧 Technology Stack - **Frontend**: Streamlit (Python) - **AI Engine**: Enhanced rule-based cultural knowledge system - **Database**: Comprehensive cultural data repository - **Deployment**: Hugging Face Spaces """) with col2: st.markdown(""" ### ✨ Enhanced Features - **Global Coverage**: Cultural insights from countries across all continents - **Festival Information**: Detailed celebration and tradition data - **Best Locations**: Must-visit destinations and attractions - **Language Information**: Linguistic diversity and communication styles - **Food Culture**: Culinary traditions and dining etiquette - **Smart Chat**: Context-aware responses about cultural practices - **Interactive Interface**: Beautiful, responsive design """) st.markdown("---") # Technical details st.markdown("### đŸ—ī¸ Enhanced Architecture") st.markdown(""" CultureBot 3.0 features a modular architecture with separated data management: 1. **Streamlit Frontend**: Beautiful, interactive user interface with multiple pages 2. **Cultural Data Repository**: Comprehensive, structured cultural database 3. **Enhanced AI Engine**: Smart response generation with contextual understanding 4. **Modular Design**: Separated data layer for easy maintenance and expansion 5. **Multi-category Support**: Facts, festivals, locations, languages, and more """) # Data statistics st.markdown("### 📊 Database Statistics") col1, col2, col3 = st.columns(3) with col1: st.metric("Countries", len(cultural_db.get_all_countries())) with col2: st.metric("Cultural Facts", len(cultural_db.cultural_facts)) with col3: total_festivals = sum(len(get_country_data(country).get('festivals', [])) for country in cultural_db.get_all_countries()) st.metric("Festivals", total_festivals) # Contact and support st.markdown("### 📞 Support") st.markdown(""" For technical support or cultural content suggestions: - **Team**: CultureCoders - **Team Lead**: Raghavender Reddy - **Version**: 1.0 - **Platform**: Hugging Face Spaces - **Last Updated**: June 2025 - **Contact Info**: culturecoders@gmail.com """)