Car-info / src /Pages /3_chatbot.py
Rajesh0279's picture
Upload 3 files
5ea1211 verified
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import StandardScaler
import wikipedia
import re
import json
class CarRecommendationAI:
def __init__(self):
self.car_database = self.create_car_database()
self.vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
self.scaler = StandardScaler()
self.setup_recommendation_system()
def create_car_database(self):
"""Create a comprehensive car database with features"""
cars = [
{
'name': 'Toyota Camry',
'brand': 'Toyota',
'type': 'Sedan',
'fuel_type': 'Hybrid',
'price_range': 'Mid-range',
'size': 'Mid-size',
'mpg': 32,
'reliability_score': 9,
'safety_score': 8,
'features': 'fuel efficient reliable comfortable family sedan hybrid technology',
'year': 2024
},
{
'name': 'Honda Civic',
'brand': 'Honda',
'type': 'Sedan',
'fuel_type': 'Gasoline',
'price_range': 'Budget',
'size': 'Compact',
'mpg': 31,
'reliability_score': 8,
'safety_score': 9,
'features': 'compact affordable reliable good gas mileage sporty',
'year': 2024
},
{
'name': 'BMW X5',
'brand': 'BMW',
'type': 'SUV',
'fuel_type': 'Gasoline',
'price_range': 'Luxury',
'size': 'Large',
'mpg': 23,
'reliability_score': 7,
'safety_score': 9,
'features': 'luxury SUV powerful performance premium interior technology',
'year': 2024
},
{
'name': 'Tesla Model 3',
'brand': 'Tesla',
'type': 'Sedan',
'fuel_type': 'Electric',
'price_range': 'Premium',
'size': 'Mid-size',
'mpg': 120, # MPGe for electric
'reliability_score': 7,
'safety_score': 10,
'features': 'electric autonomous driving technology innovative sustainable',
'year': 2024
},
{
'name': 'Ford F-150',
'brand': 'Ford',
'type': 'Truck',
'fuel_type': 'Gasoline',
'price_range': 'Mid-range',
'size': 'Large',
'mpg': 20,
'reliability_score': 8,
'safety_score': 8,
'features': 'pickup truck powerful towing capacity work vehicle durable',
'year': 2024
},
{
'name': 'Porsche 911',
'brand': 'Porsche',
'type': 'Sports Car',
'fuel_type': 'Gasoline',
'price_range': 'Luxury',
'size': 'Compact',
'mpg': 22,
'reliability_score': 8,
'safety_score': 7,
'features': 'sports car high performance luxury speed racing heritage',
'year': 2024
},
{
'name': 'Subaru Outback',
'brand': 'Subaru',
'type': 'SUV',
'fuel_type': 'Gasoline',
'price_range': 'Mid-range',
'size': 'Mid-size',
'mpg': 26,
'reliability_score': 9,
'safety_score': 9,
'features': 'all wheel drive outdoor adventure reliable safe family',
'year': 2024
},
{
'name': 'Hyundai Elantra',
'brand': 'Hyundai',
'type': 'Sedan',
'fuel_type': 'Gasoline',
'price_range': 'Budget',
'size': 'Compact',
'mpg': 33,
'reliability_score': 8,
'safety_score': 8,
'features': 'affordable fuel efficient warranty reliable compact',
'year': 2024
}
]
return pd.DataFrame(cars)
def setup_recommendation_system(self):
"""Setup the AI recommendation system"""
# Create feature matrix for text-based similarity
feature_matrix = self.vectorizer.fit_transform(self.car_database['features'])
self.feature_similarity = cosine_similarity(feature_matrix)
# Create numerical feature matrix
numerical_features = self.car_database[['mpg', 'reliability_score', 'safety_score', 'year']].values
self.numerical_features_scaled = self.scaler.fit_transform(numerical_features)
def get_user_preferences(self):
"""Create UI for user preferences"""
st.subheader("πŸ€– AI Car Recommendation System")
st.write("Tell us your preferences and our AI will recommend the perfect car for you!")
col1, col2 = st.columns(2)
with col1:
budget = st.selectbox(
"πŸ’° Budget Range:",
["Budget", "Mid-range", "Premium", "Luxury", "Any"]
)
car_type = st.selectbox(
"πŸš— Car Type:",
["Sedan", "SUV", "Truck", "Sports Car", "Any"]
)
fuel_preference = st.selectbox(
"β›½ Fuel Type:",
["Gasoline", "Hybrid", "Electric", "Any"]
)
with col2:
size_preference = st.selectbox(
"πŸ“ Size Preference:",
["Compact", "Mid-size", "Large", "Any"]
)
priority = st.selectbox(
"🎯 What's Most Important:",
["Fuel Efficiency", "Reliability", "Safety", "Performance", "Technology", "Balanced"]
)
usage = st.selectbox(
"πŸ›£οΈ Primary Usage:",
["Daily Commuting", "Family Travel", "Work/Business", "Recreation", "Sports/Performance"]
)
return {
'budget': budget,
'car_type': car_type,
'fuel_preference': fuel_preference,
'size_preference': size_preference,
'priority': priority,
'usage': usage
}
def calculate_preference_score(self, car, preferences):
"""Calculate how well a car matches user preferences"""
score = 0
max_score = 100
# Budget matching (25 points)
if preferences['budget'] == 'Any' or car['price_range'] == preferences['budget']:
score += 25
elif (preferences['budget'] == 'Budget' and car['price_range'] == 'Mid-range') or \
(preferences['budget'] == 'Mid-range' and car['price_range'] in ['Budget', 'Premium']) or \
(preferences['budget'] == 'Premium' and car['price_range'] in ['Mid-range', 'Luxury']):
score += 15
# Car type matching (20 points)
if preferences['car_type'] == 'Any' or car['type'] == preferences['car_type']:
score += 20
# Fuel type matching (15 points)
if preferences['fuel_preference'] == 'Any' or car['fuel_type'] == preferences['fuel_preference']:
score += 15
# Size matching (10 points)
if preferences['size_preference'] == 'Any' or car['size'] == preferences['size_preference']:
score += 10
# Priority-based scoring (20 points)
priority_scores = {
'Fuel Efficiency': car['mpg'] / 50 * 20, # Normalize MPG
'Reliability': car['reliability_score'] / 10 * 20,
'Safety': car['safety_score'] / 10 * 20,
'Performance': (10 - car['reliability_score']) / 10 * 20 if car['type'] == 'Sports Car' else 10,
'Technology': 20 if car['brand'] in ['Tesla', 'BMW'] else 10,
'Balanced': (car['reliability_score'] + car['safety_score']) / 20 * 20
}
score += priority_scores.get(preferences['priority'], 10)
# Usage-based scoring (10 points)
usage_scores = {
'Daily Commuting': 10 if car['mpg'] > 25 else 5,
'Family Travel': 10 if car['type'] in ['SUV', 'Sedan'] and car['size'] in ['Mid-size', 'Large'] else 5,
'Work/Business': 10 if car['type'] in ['Truck', 'SUV'] else 5,
'Recreation': 10 if car['type'] in ['SUV', 'Truck'] else 5,
'Sports/Performance': 10 if car['type'] == 'Sports Car' else 5
}
score += usage_scores.get(preferences['usage'], 5)
return min(score, max_score)
def get_recommendations(self, preferences, num_recommendations=3):
"""Get AI-powered car recommendations"""
scored_cars = []
for idx, car in self.car_database.iterrows():
preference_score = self.calculate_preference_score(car, preferences)
# Add some AI-based similarity scoring
similarity_bonus = np.mean(self.feature_similarity[idx]) * 10
total_score = preference_score + similarity_bonus
scored_cars.append({
'car': car,
'score': total_score,
'preference_match': preference_score,
'index': idx
})
# Sort by total score
scored_cars.sort(key=lambda x: x['score'], reverse=True)
return scored_cars[:num_recommendations]
def get_wikipedia_info(self, car_name):
"""Get Wikipedia information for a car"""
try:
# Search for the car on Wikipedia
search_results = wikipedia.search(car_name, results=3)
if search_results:
page = wikipedia.page(search_results[0])
summary = wikipedia.summary(car_name, sentences=3)
return {
'summary': summary,
'url': page.url,
'title': page.title
}
except:
return {
'summary': f"Wikipedia information for {car_name} is not available at the moment.",
'url': "",
'title': car_name
}
def explain_recommendation(self, car, preferences, score):
"""Generate AI explanation for why this car was recommended"""
explanations = []
if preferences['budget'] == 'Any' or car['price_range'] == preferences['budget']:
explanations.append(f"βœ… Matches your {preferences['budget'].lower()} budget preference")
if preferences['car_type'] == 'Any' or car['type'] == preferences['car_type']:
explanations.append(f"βœ… Perfect {car['type'].lower()} match for your needs")
if car['mpg'] > 30:
explanations.append("β›½ Excellent fuel efficiency")
if car['reliability_score'] >= 8:
explanations.append("πŸ”§ High reliability rating")
if car['safety_score'] >= 8:
explanations.append("πŸ›‘οΈ Outstanding safety features")
# Priority-based explanations
priority_explanations = {
'Fuel Efficiency': f"πŸ’‘ Great choice for fuel efficiency with {car['mpg']} MPG",
'Reliability': f"πŸ’‘ Highly reliable with {car['reliability_score']}/10 rating",
'Safety': f"πŸ’‘ Excellent safety with {car['safety_score']}/10 rating",
'Performance': "πŸ’‘ Built for performance and driving excitement",
'Technology': "πŸ’‘ Features cutting-edge automotive technology"
}
if preferences['priority'] in priority_explanations:
explanations.append(priority_explanations[preferences['priority']])
return explanations
def integrate_ai_recommendations():
"""Main function to integrate AI recommendations into Streamlit app"""
# Initialize the AI system
if 'ai_system' not in st.session_state:
st.session_state.ai_system = CarRecommendationAI()
ai_system = st.session_state.ai_system
# Create tabs for different functionalities
tab1, tab3 = st.tabs(["πŸ€– AI Recommendations", "πŸ“Š Compare Cars"])
with tab1:
st.title("πŸš— AI-Powered Car Recommendations")
# Get user preferences
preferences = ai_system.get_user_preferences()
if st.button("🎯 Get My AI Recommendations", type="primary"):
with st.spinner("πŸ€– AI is analyzing your preferences..."):
recommendations = ai_system.get_recommendations(preferences)
st.success("✨ Here are your personalized recommendations!")
for i, rec in enumerate(recommendations, 1):
car = rec['car']
score = rec['preference_match']
with st.expander(f"#{i} {car['name']} - Match Score: {score:.1f}%", expanded=i==1):
col1, col2 = st.columns([2, 1])
with col1:
st.subheader(f"{car['brand']} {car['name']}")
# Car details
st.write(f"**Type:** {car['type']} | **Size:** {car['size']}")
st.write(f"**Price Range:** {car['price_range']} | **Fuel:** {car['fuel_type']}")
st.write(f"**MPG:** {car['mpg']} | **Year:** {car['year']}")
# Ratings
st.write("**Ratings:**")
st.write(f"πŸ”§ Reliability: {car['reliability_score']}/10")
st.write(f"πŸ›‘οΈ Safety: {car['safety_score']}/10")
# AI Explanation
st.write("**πŸ€– Why we recommend this:**")
explanations = ai_system.explain_recommendation(car, preferences, score)
for explanation in explanations:
st.write(f"β€’ {explanation}")
with col2:
# Progress bars for ratings
st.metric("Match Score", f"{score:.1f}%")
st.progress(score/100)
st.metric("Reliability", f"{car['reliability_score']}/10")
st.progress(car['reliability_score']/10)
st.metric("Safety", f"{car['safety_score']}/10")
st.progress(car['safety_score']/10)
# Wikipedia integration
if st.button(f"πŸ“– Learn more about {car['name']}", key=f"wiki_{i}"):
with st.spinner("Fetching Wikipedia information..."):
wiki_info = ai_system.get_wikipedia_info(car['name'])
st.write("**Wikipedia Summary:**")
st.write(wiki_info['summary'])
if wiki_info['url']:
st.write(f"[Read more on Wikipedia]({wiki_info['url']})")
# with tab2:
# st.title("πŸ” Enhanced Car Search")
# search_term = st.text_input("Search for a specific car model:")
# if search_term:
# # Filter cars based on search
# filtered_cars = ai_system.car_database[
# ai_system.car_database['name'].str.contains(search_term, case=False) |
# ai_system.car_database['brand'].str.contains(search_term, case=False)
# ]
# if not filtered_cars.empty:
# for _, car in filtered_cars.iterrows():
# with st.expander(f"{car['name']}"):
# col1, col2 = st.columns(2)
# with col1:
# st.write(f"**Brand:** {car['brand']}")
# st.write(f"**Type:** {car['type']}")
# st.write(f"**Price Range:** {car['price_range']}")
# with col2:
# st.write(f"**MPG:** {car['mpg']}")
# st.write(f"**Reliability:** {car['reliability_score']}/10")
# st.write(f"**Safety:** {car['safety_score']}/10")
# if st.button(f"Get Wikipedia info for {car['name']}", key=f"search_wiki_{car['name']}"):
# wiki_info = ai_system.get_wikipedia_info(car['name'])
# st.write(wiki_info['summary'])
# if wiki_info['url']:
# st.write(f"[Read more]({wiki_info['url']})")
# else:
# st.warning("No cars found matching your search.")
with tab3:
st.title("πŸ“Š Car Comparison Tool")
car_names = ai_system.car_database['name'].tolist()
col1, col2 = st.columns(2)
with col1:
car1 = st.selectbox("Select first car:", car_names)
with col2:
car2 = st.selectbox("Select second car:", car_names, index=1)
if st.button("Compare Cars"):
car1_data = ai_system.car_database[ai_system.car_database['name'] == car1].iloc[0]
car2_data = ai_system.car_database[ai_system.car_database['name'] == car2].iloc[0]
comparison_df = pd.DataFrame({
car1: [car1_data['brand'], car1_data['type'], car1_data['price_range'],
car1_data['mpg'], car1_data['reliability_score'], car1_data['safety_score']],
car2: [car2_data['brand'], car2_data['type'], car2_data['price_range'],
car2_data['mpg'], car2_data['reliability_score'], car2_data['safety_score']]
}, index=['Brand', 'Type', 'Price Range', 'MPG', 'Reliability', 'Safety'])
st.table(comparison_df)
# AI-powered comparison insights
st.subheader("πŸ€– AI Comparison Insights")
if car1_data['mpg'] > car2_data['mpg']:
st.write(f"βœ… {car1} has better fuel efficiency ({car1_data['mpg']} vs {car2_data['mpg']} MPG)")
else:
st.write(f"βœ… {car2} has better fuel efficiency ({car2_data['mpg']} vs {car1_data['mpg']} MPG)")
if car1_data['reliability_score'] > car2_data['reliability_score']:
st.write(f"πŸ”§ {car1} has higher reliability rating")
elif car2_data['reliability_score'] > car1_data['reliability_score']:
st.write(f"πŸ”§ {car2} has higher reliability rating")
else:
st.write("πŸ”§ Both cars have equal reliability ratings")
# Usage example - Add this to your existing Streamlit app
if __name__ == "__main__":
integrate_ai_recommendations()