_Culture_Bot_ / app.py
RaghavenderReddy's picture
Update app.py
e06d563 verified
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("""
<style>
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 10px;
color: white;
text-align: center;
margin-bottom: 2rem;
}
.sidebar-info {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
padding: 1.5rem;
border-radius: 10px;
color: white;
margin-bottom: 1rem;
}
.chat-message {
padding: 1rem;
border-radius: 10px;
margin: 0.5rem 0;
}
.user-message {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
margin-left: 2rem;
}
.bot-message {
background: #f8f9fa;
color: #333;
border-left: 4px solid #667eea;
margin-right: 2rem;
}
.fact-card {
background: linear-gradient(135deg, #ffd3a5 0%, #fd6585 100%);
color: black;
padding: 1.5rem;
border-radius: 10px;
margin: 1rem 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.festival-card {
background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
color: black;
padding: 1.5rem;
border-radius: 10px;
margin: 1rem 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.location-card {
background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);
color: black;
padding: 1.5rem;
border-radius: 10px;
margin: 1rem 0;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.metric-card {
background: white;
color: black;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
}
</style>
""", unsafe_allow_html=True)
# Sidebar with app information
with st.sidebar:
st.markdown("""
<div class="sidebar-info">
<h1 style="font-size: 2.5rem; font-weight: bold; margin-bottom: 1rem;">CultureBot</h1>
<div style="font-size: 0.9rem; opacity: 0.9;">
<p><strong>Team:</strong> CultureCoders</p>
<p><strong>Version:</strong> 1.0</p>
<p><strong>Created:</strong> June 2025</p>
</div>
</div>
""", 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"""
<div class="fact-card">
<h4>{fact['country']}</h4>
<p>{fact['fact']}</p>
<small>Category: {fact['category']}</small>
</div>
""", unsafe_allow_html=True)
# Main content area
if page == "🏠 Home":
# Home page
st.markdown("""
<div class="main-header">
<h1 style="font-size: 3rem; margin-bottom: 1rem;">Welcome to CultureBot</h1>
<p style="font-size: 1.2rem; opacity: 0.9;">Your comprehensive AI-powered guide to understanding cultures, traditions, festivals, and destinations from around the world</p>
</div>
""", unsafe_allow_html=True)
# Feature cards
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="metric-card">
<h3>🌍 Global Insights</h3>
<p>Discover fascinating cultural facts, festivals, languages, and customs from countries across all continents.</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="metric-card">
<h3>πŸ€– AI-Powered Chat</h3>
<p>Ask questions and get personalized responses about specific countries, festivals, locations, and cultural practices.</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="metric-card">
<h3>πŸ“š Comprehensive Database</h3>
<p>Explore festivals, best locations, languages, food culture, and travel information for each country.</p>
</div>
""", 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("""
<div class="main-header">
<h1>Chat with CultureBot</h1>
<p>Ask me about any culture, country, festival, location, or tradition!</p>
</div>
""", 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"""
<div class="chat-message user-message">
<strong>You:</strong> {message["content"]}
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="chat-message bot-message">
<strong>CultureBot:</strong> {message["content"]}
</div>
""", 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("""
<div class="main-header">
<h1>Cultural Facts Explorer</h1>
<p>Browse our curated collection of cultural insights</p>
</div>
""", 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"""
<div class="fact-card">
<h3>{fact['country']}</h3>
<p>{fact['fact']}</p>
<div style="display: flex; justify-content: space-between; margin-top: 1rem;">
<small><strong>Category:</strong> {fact['category']}</small>
<small><strong>Source:</strong> {fact['source']}</small>
</div>
</div>
""", unsafe_allow_html=True)
else:
st.info("No facts found for the selected filters.")
elif page == "🎭 Festivals":
# Festivals page
st.markdown("""
<div class="main-header">
<h1>Cultural Festivals</h1>
<p>Discover celebrations and traditions from around the world</p>
</div>
""", 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"<p><strong>Traditions:</strong> {', '.join(festival['traditions'])}</p>"
# Build foods text safely
foods_text = ""
if festival.get('foods'):
foods_text = f"<p><strong>Traditional Foods:</strong> {', '.join(festival['foods'])}</p>"
st.markdown(f"""
<div class="festival-card">
<h3>{festival['name']}</h3>
<p><strong>Season:</strong> {festival['season']}</p>
<p><strong>Description:</strong> {festival['description']}</p>
<p><strong>Significance:</strong> {festival['significance']}</p>
{traditions_text}
{foods_text}
</div>
""", 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"""
<div class="festival-card">
<h4>{festival['name']}</h4>
<p><strong>Season:</strong> {festival['season']}</p>
<p>{festival['description']}</p>
</div>
""", unsafe_allow_html=True)
elif page == "πŸ“ Best Locations":
# Best locations page
st.markdown("""
<div class="main-header">
<h1>Best Places to Visit</h1>
<p>Explore must-visit destinations around the world</p>
</div>
""", 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"<p><strong>Highlights:</strong> {', '.join(location['highlights'])}</p>"
# Build best time text safely
best_time_text = ""
if location.get('best_time'):
best_time_text = f"<p><strong>Best Time:</strong> {location['best_time']}</p>"
# Build significance text safely
significance_text = ""
if location.get('significance'):
significance_text = f"<p><strong>Significance:</strong> {location['significance']}</p>"
st.markdown(f"""
<div class="location-card">
<h3>{location['name']}</h3>
<p><strong>Type:</strong> {location['type']}</p>
<p><strong>Description:</strong> {location['description']}</p>
{best_time_text}
{significance_text}
{highlights_text}
</div>
""", 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"""
<div class="location-card">
<h4>{location['name']}</h4>
<p><strong>Type:</strong> {location['type']}</p>
<p>{location['description']}</p>
</div>
""", unsafe_allow_html=True)
else: # About page
st.markdown("""
<div class="main-header">
<h1>About CultureBot</h1>
<p>Bridging cultures through comprehensive AI-powered conversations</p>
</div>
""", 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
""")