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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import wikipedia
|
| 3 |
+
import re
|
| 4 |
+
import requests
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
# Page configuration
|
| 9 |
+
st.set_page_config(page_title="π Search Car Info", layout="centered")
|
| 10 |
+
st.title("π Search Car Info")
|
| 11 |
+
|
| 12 |
+
# Enhanced Wikipedia Functions
|
| 13 |
+
def fetch_single_car_info(car_name):
|
| 14 |
+
"""Enhanced function to fetch car info with better error handling and data extraction"""
|
| 15 |
+
try:
|
| 16 |
+
# Try different search variations for better results
|
| 17 |
+
search_variations = [
|
| 18 |
+
car_name,
|
| 19 |
+
f"{car_name} car",
|
| 20 |
+
f"{car_name} automobile",
|
| 21 |
+
f"{car_name} vehicle",
|
| 22 |
+
car_name.replace(" ", "_")
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
for variation in search_variations:
|
| 26 |
+
try:
|
| 27 |
+
# Get Wikipedia page
|
| 28 |
+
page = wikipedia.page(variation)
|
| 29 |
+
|
| 30 |
+
# Get enhanced summary with more sentences
|
| 31 |
+
summary = wikipedia.summary(variation, sentences=12)
|
| 32 |
+
|
| 33 |
+
# Clean summary from references
|
| 34 |
+
clean_summary = re.sub(r'\[\d+\]', '', summary)
|
| 35 |
+
clean_summary = re.sub(r'\([^)]*\)', '', clean_summary) # Remove parenthetical references
|
| 36 |
+
|
| 37 |
+
# Get the best quality image
|
| 38 |
+
image_url = None
|
| 39 |
+
if page.images:
|
| 40 |
+
# Filter for car-related images and common formats
|
| 41 |
+
for img in page.images[:5]: # Check first 5 images
|
| 42 |
+
if any(ext in img.lower() for ext in ['.jpg', '.jpeg', '.png', '.webp']):
|
| 43 |
+
# Avoid common non-car images
|
| 44 |
+
if not any(avoid in img.lower() for avoid in ['commons-logo', 'wiki', 'edit-icon', 'flag']):
|
| 45 |
+
image_url = img
|
| 46 |
+
break
|
| 47 |
+
|
| 48 |
+
# Extract additional info from content
|
| 49 |
+
content = page.content
|
| 50 |
+
|
| 51 |
+
# Extract specifications if available
|
| 52 |
+
specs = extract_specifications(content)
|
| 53 |
+
|
| 54 |
+
# Extract infobox data if available
|
| 55 |
+
infobox_data = extract_infobox_data(content)
|
| 56 |
+
|
| 57 |
+
return {
|
| 58 |
+
'summary': clean_summary,
|
| 59 |
+
'image_url': image_url,
|
| 60 |
+
'page_url': page.url,
|
| 61 |
+
'title': page.title,
|
| 62 |
+
'specifications': specs,
|
| 63 |
+
'infobox': infobox_data,
|
| 64 |
+
'full_content': content[:2000] # First 2000 chars for additional info
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
except wikipedia.exceptions.DisambiguationError as e:
|
| 68 |
+
# Handle disambiguation by trying the most relevant option
|
| 69 |
+
for option in e.options[:3]: # Try first 3 options
|
| 70 |
+
if any(keyword in option.lower() for keyword in ['car', 'automobile', 'vehicle', car_name.lower()]):
|
| 71 |
+
try:
|
| 72 |
+
page = wikipedia.page(option)
|
| 73 |
+
summary = wikipedia.summary(option, sentences=10)
|
| 74 |
+
clean_summary = re.sub(r'\[\d+\]', '', summary)
|
| 75 |
+
image_url = page.images[0] if page.images else None
|
| 76 |
+
|
| 77 |
+
specs = extract_specifications(page.content)
|
| 78 |
+
infobox_data = extract_infobox_data(page.content)
|
| 79 |
+
|
| 80 |
+
return {
|
| 81 |
+
'summary': clean_summary,
|
| 82 |
+
'image_url': image_url,
|
| 83 |
+
'page_url': page.url,
|
| 84 |
+
'title': page.title,
|
| 85 |
+
'specifications': specs,
|
| 86 |
+
'infobox': infobox_data,
|
| 87 |
+
'full_content': page.content[:2000]
|
| 88 |
+
}
|
| 89 |
+
except:
|
| 90 |
+
continue
|
| 91 |
+
except wikipedia.exceptions.PageError:
|
| 92 |
+
continue
|
| 93 |
+
except Exception as e:
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
return None
|
| 97 |
+
except Exception as e:
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
def extract_specifications(content):
|
| 101 |
+
"""Extract car specifications from Wikipedia content"""
|
| 102 |
+
specs = {}
|
| 103 |
+
|
| 104 |
+
# Common specification patterns
|
| 105 |
+
spec_patterns = {
|
| 106 |
+
'Engine': r'[Ee]ngine[:\s]*([^\n.]+)',
|
| 107 |
+
'Power': r'[Pp]ower[:\s]*([^\n.]+)',
|
| 108 |
+
'Torque': r'[Tt]orque[:\s]*([^\n.]+)',
|
| 109 |
+
'Top Speed': r'[Tt]op [Ss]peed[:\s]*([^\n.]+)',
|
| 110 |
+
'Acceleration': r'0[-β]60[:\s]*([^\n.]+)|0[-β]100[:\s]*([^\n.]+)',
|
| 111 |
+
'Fuel Economy': r'[Ff]uel [Ee]conomy[:\s]*([^\n.]+)|[Mm]ileage[:\s]*([^\n.]+)',
|
| 112 |
+
'Length': r'[Ll]ength[:\s]*([^\n.]+)',
|
| 113 |
+
'Width': r'[Ww]idth[:\s]*([^\n.]+)',
|
| 114 |
+
'Height': r'[Hh]eight[:\s]*([^\n.]+)',
|
| 115 |
+
'Wheelbase': r'[Ww]heelbase[:\s]*([^\n.]+)',
|
| 116 |
+
'Weight': r'[Ww]eight[:\s]*([^\n.]+)|[Cc]urb [Ww]eight[:\s]*([^\n.]+)'
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
for spec_name, pattern in spec_patterns.items():
|
| 120 |
+
matches = re.findall(pattern, content, re.IGNORECASE)
|
| 121 |
+
if matches:
|
| 122 |
+
# Get the first non-empty match
|
| 123 |
+
for match in matches:
|
| 124 |
+
if isinstance(match, tuple):
|
| 125 |
+
match = next((m for m in match if m), '')
|
| 126 |
+
if match and len(match.strip()) > 0:
|
| 127 |
+
specs[spec_name] = match.strip()[:100] # Limit length
|
| 128 |
+
break
|
| 129 |
+
|
| 130 |
+
return specs
|
| 131 |
+
|
| 132 |
+
def extract_infobox_data(content):
|
| 133 |
+
"""Extract infobox-style data from Wikipedia content"""
|
| 134 |
+
infobox = {}
|
| 135 |
+
|
| 136 |
+
# Look for common car infobox patterns
|
| 137 |
+
infobox_patterns = {
|
| 138 |
+
'Manufacturer': r'[Mm]anufacturer[:\s]*([^\n.]+)',
|
| 139 |
+
'Production': r'[Pp]roduction[:\s]*([^\n.]+)',
|
| 140 |
+
'Assembly': r'[Aa]ssembly[:\s]*([^\n.]+)',
|
| 141 |
+
'Designer': r'[Dd]esigner[:\s]*([^\n.]+)',
|
| 142 |
+
'Body Style': r'[Bb]ody [Ss]tyle[:\s]*([^\n.]+)',
|
| 143 |
+
'Layout': r'[Ll]ayout[:\s]*([^\n.]+)',
|
| 144 |
+
'Platform': r'[Pp]latform[:\s]*([^\n.]+)',
|
| 145 |
+
'Related': r'[Rr]elated[:\s]*([^\n.]+)',
|
| 146 |
+
'Predecessor': r'[Pp]redecessor[:\s]*([^\n.]+)',
|
| 147 |
+
'Successor': r'[Ss]uccessor[:\s]*([^\n.]+)'
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
for key, pattern in infobox_patterns.items():
|
| 151 |
+
matches = re.findall(pattern, content, re.IGNORECASE)
|
| 152 |
+
if matches:
|
| 153 |
+
infobox[key] = matches[0].strip()[:150] # Limit length
|
| 154 |
+
|
| 155 |
+
return infobox
|
| 156 |
+
|
| 157 |
+
def fetch_versions(query):
|
| 158 |
+
"""Enhanced function to fetch car versions with better filtering"""
|
| 159 |
+
try:
|
| 160 |
+
# Get more search results
|
| 161 |
+
results = wikipedia.search(query, results=15)
|
| 162 |
+
|
| 163 |
+
# Enhanced filtering for car-related results
|
| 164 |
+
car_keywords = ['car', 'automobile', 'vehicle', 'motor', 'auto', 'sedan', 'suv', 'hatchback', 'coupe', 'convertible']
|
| 165 |
+
brand_keywords = ['toyota', 'honda', 'ford', 'bmw', 'mercedes', 'audi', 'volkswagen', 'nissan', 'hyundai', 'kia', 'mazda', 'subaru', 'lexus', 'acura', 'infiniti', 'tata', 'maruti', 'mahindra', 'bajaj']
|
| 166 |
+
|
| 167 |
+
filtered_results = []
|
| 168 |
+
query_lower = query.lower()
|
| 169 |
+
|
| 170 |
+
for result in results:
|
| 171 |
+
result_lower = result.lower()
|
| 172 |
+
|
| 173 |
+
# Include if it contains the query or car-related keywords
|
| 174 |
+
if (query_lower in result_lower or
|
| 175 |
+
any(keyword in result_lower for keyword in car_keywords) or
|
| 176 |
+
any(brand in result_lower for brand in brand_keywords)):
|
| 177 |
+
|
| 178 |
+
# Exclude irrelevant results
|
| 179 |
+
if not any(exclude in result_lower for exclude in ['biography', 'politician', 'actor', 'singer', 'company', 'corporation']):
|
| 180 |
+
filtered_results.append(result)
|
| 181 |
+
|
| 182 |
+
# Sort by relevance (prefer results with years, exact matches first)
|
| 183 |
+
def sort_key(x):
|
| 184 |
+
score = 0
|
| 185 |
+
x_lower = x.lower()
|
| 186 |
+
|
| 187 |
+
# Exact query match gets highest score
|
| 188 |
+
if query_lower == x_lower:
|
| 189 |
+
score += 1000
|
| 190 |
+
elif query_lower in x_lower:
|
| 191 |
+
score += 500
|
| 192 |
+
|
| 193 |
+
# Results with years get higher score
|
| 194 |
+
if re.search(r'\d{4}', x):
|
| 195 |
+
score += 100
|
| 196 |
+
|
| 197 |
+
# Car-specific terms get higher score
|
| 198 |
+
for keyword in car_keywords:
|
| 199 |
+
if keyword in x_lower:
|
| 200 |
+
score += 50
|
| 201 |
+
|
| 202 |
+
return score
|
| 203 |
+
|
| 204 |
+
sorted_versions = sorted(filtered_results, key=sort_key, reverse=True)
|
| 205 |
+
return sorted_versions[:8] # Return top 8 results
|
| 206 |
+
|
| 207 |
+
except Exception as e:
|
| 208 |
+
return []
|
| 209 |
+
|
| 210 |
+
def validate_image_url(url):
|
| 211 |
+
"""Validate if image URL is accessible"""
|
| 212 |
+
try:
|
| 213 |
+
response = requests.head(url, timeout=5)
|
| 214 |
+
return response.status_code == 200
|
| 215 |
+
except:
|
| 216 |
+
return False
|
| 217 |
+
|
| 218 |
+
def display_car_info(car_data, car_name):
|
| 219 |
+
"""Display car information in an organized way"""
|
| 220 |
+
if not car_data:
|
| 221 |
+
return False
|
| 222 |
+
|
| 223 |
+
st.success(f"β
Found information about **{car_data['title']}**")
|
| 224 |
+
|
| 225 |
+
# Main content layout
|
| 226 |
+
if car_data['image_url']:
|
| 227 |
+
col1, col2 = st.columns([2, 1])
|
| 228 |
+
else:
|
| 229 |
+
col1, col2 = st.columns([1, 1])
|
| 230 |
+
|
| 231 |
+
with col1:
|
| 232 |
+
# Summary section
|
| 233 |
+
st.markdown("### π Summary")
|
| 234 |
+
st.write(car_data['summary'])
|
| 235 |
+
|
| 236 |
+
# Specifications section
|
| 237 |
+
if car_data['specifications']:
|
| 238 |
+
st.markdown("### π§ Specifications")
|
| 239 |
+
spec_cols = st.columns(2)
|
| 240 |
+
spec_items = list(car_data['specifications'].items())
|
| 241 |
+
|
| 242 |
+
for i, (key, value) in enumerate(spec_items):
|
| 243 |
+
with spec_cols[i % 2]:
|
| 244 |
+
st.write(f"**{key}:** {value}")
|
| 245 |
+
|
| 246 |
+
# Wikipedia link
|
| 247 |
+
if car_data['page_url']:
|
| 248 |
+
st.markdown(f"[π Read full article on Wikipedia]({car_data['page_url']})")
|
| 249 |
+
|
| 250 |
+
with col2:
|
| 251 |
+
# Image section
|
| 252 |
+
if car_data['image_url']:
|
| 253 |
+
st.markdown("### πΌοΈ Image")
|
| 254 |
+
try:
|
| 255 |
+
st.image(car_data['image_url'], caption=car_data['title'], use_column_width=True)
|
| 256 |
+
except:
|
| 257 |
+
st.info("Image could not be loaded")
|
| 258 |
+
|
| 259 |
+
# Infobox data
|
| 260 |
+
if car_data['infobox']:
|
| 261 |
+
st.markdown("### βΉοΈ Quick Facts")
|
| 262 |
+
for key, value in list(car_data['infobox'].items())[:6]: # Show max 6 items
|
| 263 |
+
st.write(f"**{key}:** {value}")
|
| 264 |
+
|
| 265 |
+
return True
|
| 266 |
+
|
| 267 |
+
# Main Interface
|
| 268 |
+
st.markdown("*Search for detailed car information from Wikipedia*")
|
| 269 |
+
|
| 270 |
+
# Pre-fill search box from other pages (if exists)
|
| 271 |
+
default_car = st.session_state.get("selected_car_name", "")
|
| 272 |
+
car_name = st.text_input("Enter Car Name",
|
| 273 |
+
value=default_car,
|
| 274 |
+
placeholder="e.g., Tata Nano, Toyota Camry, BMW X5, Maruti Swift")
|
| 275 |
+
|
| 276 |
+
# Search options
|
| 277 |
+
col1, col2 = st.columns([2, 1])
|
| 278 |
+
with col1:
|
| 279 |
+
search_btn = st.button("π Search Car Info", type="primary")
|
| 280 |
+
with col2:
|
| 281 |
+
detailed_search = st.checkbox("Include similar models", value=True)
|
| 282 |
+
|
| 283 |
+
# Handle Search
|
| 284 |
+
if search_btn and car_name:
|
| 285 |
+
st.markdown("---")
|
| 286 |
+
st.subheader(f"π Search Results for '{car_name}'")
|
| 287 |
+
|
| 288 |
+
with st.spinner("π Searching Wikipedia database..."):
|
| 289 |
+
# Try exact match first
|
| 290 |
+
car_data = fetch_single_car_info(car_name)
|
| 291 |
+
|
| 292 |
+
if car_data:
|
| 293 |
+
# Display main result
|
| 294 |
+
display_car_info(car_data, car_name)
|
| 295 |
+
|
| 296 |
+
# Show additional versions if detailed search is enabled
|
| 297 |
+
if detailed_search:
|
| 298 |
+
st.markdown("---")
|
| 299 |
+
st.subheader("π Related Models & Versions")
|
| 300 |
+
|
| 301 |
+
versions = fetch_versions(car_name)
|
| 302 |
+
additional_results = 0
|
| 303 |
+
|
| 304 |
+
for version in versions:
|
| 305 |
+
# Skip if it's the same as main result
|
| 306 |
+
if version.lower() == car_data['title'].lower():
|
| 307 |
+
continue
|
| 308 |
+
|
| 309 |
+
version_data = fetch_single_car_info(version)
|
| 310 |
+
if version_data and additional_results < 3: # Limit to 3 additional results
|
| 311 |
+
additional_results += 1
|
| 312 |
+
|
| 313 |
+
with st.expander(f"π {version_data['title']}", expanded=False):
|
| 314 |
+
# Compact display for additional results
|
| 315 |
+
st.write(version_data['summary'][:500] + "..." if len(version_data['summary']) > 500 else version_data['summary'])
|
| 316 |
+
|
| 317 |
+
if version_data['specifications']:
|
| 318 |
+
st.markdown("**Key Specs:**")
|
| 319 |
+
spec_items = list(version_data['specifications'].items())[:4] # Show top 4 specs
|
| 320 |
+
for key, value in spec_items:
|
| 321 |
+
st.write(f"β’ **{key}:** {value}")
|
| 322 |
+
|
| 323 |
+
if version_data['image_url']:
|
| 324 |
+
try:
|
| 325 |
+
st.image(version_data['image_url'], caption=version_data['title'], width=200)
|
| 326 |
+
except:
|
| 327 |
+
pass
|
| 328 |
+
|
| 329 |
+
if version_data['page_url']:
|
| 330 |
+
st.markdown(f"[π Read more]({version_data['page_url']})")
|
| 331 |
+
|
| 332 |
+
if additional_results == 0:
|
| 333 |
+
st.info("No additional related models found.")
|
| 334 |
+
|
| 335 |
+
else:
|
| 336 |
+
# No exact match found, try broader search
|
| 337 |
+
st.warning(f"No exact match found for '{car_name}'. Searching for related results...")
|
| 338 |
+
|
| 339 |
+
versions = fetch_versions(car_name)
|
| 340 |
+
results_found = 0
|
| 341 |
+
|
| 342 |
+
if versions:
|
| 343 |
+
for version in versions:
|
| 344 |
+
version_data = fetch_single_car_info(version)
|
| 345 |
+
if version_data:
|
| 346 |
+
results_found += 1
|
| 347 |
+
|
| 348 |
+
with st.expander(f"π {version_data['title']}", expanded=results_found==1):
|
| 349 |
+
display_success = display_car_info(version_data, version)
|
| 350 |
+
|
| 351 |
+
if results_found >= 5: # Limit results
|
| 352 |
+
break
|
| 353 |
+
|
| 354 |
+
if results_found == 0:
|
| 355 |
+
st.error("β No matching Wikipedia pages found.")
|
| 356 |
+
st.info("π‘ **Search Tips:**")
|
| 357 |
+
st.write("β’ Try using the full car name (e.g., 'Toyota Camry' instead of 'Camry')")
|
| 358 |
+
st.write("β’ Include the model year (e.g., 'Honda Civic 2020')")
|
| 359 |
+
st.write("β’ Use alternative names or spellings")
|
| 360 |
+
st.write("β’ Search for the car manufacturer first")
|
| 361 |
+
|
| 362 |
+
# Quick search suggestions
|
| 363 |
+
if not car_name:
|
| 364 |
+
st.markdown("---")
|
| 365 |
+
st.markdown("### π‘ Popular Car Searches")
|
| 366 |
+
|
| 367 |
+
col1, col2, col3 = st.columns(3)
|
| 368 |
+
|
| 369 |
+
suggestions = [
|
| 370 |
+
"Tata Nano", "Maruti Swift", "Hyundai Creta",
|
| 371 |
+
"Toyota Camry", "Honda Civic", "BMW X5",
|
| 372 |
+
"Tesla Model 3", "Ford Mustang", "Audi A4"
|
| 373 |
+
]
|
| 374 |
+
|
| 375 |
+
for i, suggestion in enumerate(suggestions):
|
| 376 |
+
with [col1, col2, col3][i % 3]:
|
| 377 |
+
if st.button(f"π {suggestion}", key=f"suggest_{i}"):
|
| 378 |
+
st.session_state.selected_car_name = suggestion
|
| 379 |
+
st.rerun()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
# Footer
|
| 383 |
+
st.markdown("---")
|
| 384 |
+
st.markdown("*π Enhanced Wikipedia search with detailed car specifications and images*")
|
src/Pages/2_Catogeries.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import wikipedia
|
| 3 |
+
import re
|
| 4 |
+
from functools import lru_cache
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
# Configure page
|
| 8 |
+
st.set_page_config(
|
| 9 |
+
page_title="Car Categories Explorer",
|
| 10 |
+
layout="centered",
|
| 11 |
+
page_icon="π"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
# Custom CSS for better styling
|
| 15 |
+
st.markdown("""
|
| 16 |
+
<style>
|
| 17 |
+
.main-header {
|
| 18 |
+
text-align: center;
|
| 19 |
+
color: #2E86AB;
|
| 20 |
+
margin-bottom: 2rem;
|
| 21 |
+
}
|
| 22 |
+
.car-card {
|
| 23 |
+
border: 1px solid #ddd;
|
| 24 |
+
border-radius: 10px;
|
| 25 |
+
padding: 1rem;
|
| 26 |
+
margin: 1rem 0;
|
| 27 |
+
background-color: #f9f9f9;
|
| 28 |
+
}
|
| 29 |
+
.error-message {
|
| 30 |
+
color: #d32f2f;
|
| 31 |
+
font-weight: bold;
|
| 32 |
+
}
|
| 33 |
+
</style>
|
| 34 |
+
""", unsafe_allow_html=True)
|
| 35 |
+
|
| 36 |
+
st.markdown('<h1 class="main-header">π Car Categories Explorer</h1>', unsafe_allow_html=True)
|
| 37 |
+
|
| 38 |
+
# --- Initialize session state ---
|
| 39 |
+
if 'search_history' not in st.session_state:
|
| 40 |
+
st.session_state.search_history = []
|
| 41 |
+
if 'favorites' not in st.session_state:
|
| 42 |
+
st.session_state.favorites = []
|
| 43 |
+
|
| 44 |
+
# --- Sidebar Configuration ---
|
| 45 |
+
st.sidebar.header("π Car Categories")
|
| 46 |
+
|
| 47 |
+
# Category selection with descriptions
|
| 48 |
+
categories = {
|
| 49 |
+
"Vintage Cars": {
|
| 50 |
+
"description": "Classic automobiles from bygone eras",
|
| 51 |
+
"examples": ["Ford Model T", "Jaguar E-Type", "Rolls-Royce Silver Ghost", "Chevrolet Bel Air"]
|
| 52 |
+
},
|
| 53 |
+
"Trending Cars": {
|
| 54 |
+
"description": "Popular modern vehicles",
|
| 55 |
+
"examples": ["Tesla Model S", "Hyundai Exter", "Mahindra Thar", "Toyota Camry"]
|
| 56 |
+
},
|
| 57 |
+
"SUVs": {
|
| 58 |
+
"description": "Sport Utility Vehicles",
|
| 59 |
+
"examples": ["Tata Harrier", "Jeep Compass", "Hyundai Creta", "Ford EcoSport"]
|
| 60 |
+
},
|
| 61 |
+
"Electric Cars": {
|
| 62 |
+
"description": "Eco-friendly electric vehicles",
|
| 63 |
+
"examples": ["Tesla Model 3", "Nissan Leaf", "Tata Nexon EV", "BMW i3"]
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
category = st.sidebar.selectbox("Choose a Category", list(categories.keys()))
|
| 68 |
+
|
| 69 |
+
# Display category info
|
| 70 |
+
st.sidebar.markdown(f"**{categories[category]['description']}**")
|
| 71 |
+
st.sidebar.markdown("#### π‘ Example Cars:")
|
| 72 |
+
for example in categories[category]['examples']:
|
| 73 |
+
st.sidebar.markdown(f"- {example}")
|
| 74 |
+
|
| 75 |
+
# Search history in sidebar
|
| 76 |
+
if st.session_state.search_history:
|
| 77 |
+
st.sidebar.markdown("#### π Recent Searches:")
|
| 78 |
+
for item in st.session_state.search_history[-5:]: # Show last 5 searches
|
| 79 |
+
if st.sidebar.button(f"π {item}", key=f"history_{item}"):
|
| 80 |
+
st.session_state.current_search = item
|
| 81 |
+
|
| 82 |
+
# --- Caching Functions ---
|
| 83 |
+
@lru_cache(maxsize=100)
|
| 84 |
+
def cached_wikipedia_search(query):
|
| 85 |
+
"""Cache Wikipedia search results to avoid repeated API calls"""
|
| 86 |
+
try:
|
| 87 |
+
if len(query.strip()) < 3:
|
| 88 |
+
return []
|
| 89 |
+
return wikipedia.search(query, results=10)
|
| 90 |
+
except Exception as e:
|
| 91 |
+
st.error(f"Search error: {str(e)}")
|
| 92 |
+
return []
|
| 93 |
+
|
| 94 |
+
@lru_cache(maxsize=50)
|
| 95 |
+
def cached_wikipedia_page(car_name):
|
| 96 |
+
"""Cache Wikipedia page content"""
|
| 97 |
+
try:
|
| 98 |
+
# Set language to English for better car results
|
| 99 |
+
wikipedia.set_lang("en")
|
| 100 |
+
page = wikipedia.page(car_name)
|
| 101 |
+
summary = wikipedia.summary(car_name, sentences=8)
|
| 102 |
+
|
| 103 |
+
# Clean summary
|
| 104 |
+
clean_summary = re.sub(r'\[\d+\]', '', summary)
|
| 105 |
+
clean_summary = re.sub(r'\s+', ' ', clean_summary).strip()
|
| 106 |
+
|
| 107 |
+
# Get first valid image
|
| 108 |
+
image_url = None
|
| 109 |
+
if page.images:
|
| 110 |
+
for img in page.images[:3]: # Try first 3 images
|
| 111 |
+
if any(ext in img.lower() for ext in ['.jpg', '.jpeg', '.png', '.gif']):
|
| 112 |
+
image_url = img
|
| 113 |
+
break
|
| 114 |
+
|
| 115 |
+
return clean_summary, image_url, page.url, page.title
|
| 116 |
+
except wikipedia.exceptions.DisambiguationError as e:
|
| 117 |
+
# Handle disambiguation by trying the first option
|
| 118 |
+
try:
|
| 119 |
+
return cached_wikipedia_page(e.options[0])
|
| 120 |
+
except:
|
| 121 |
+
return None, None, None, None
|
| 122 |
+
except wikipedia.exceptions.PageError:
|
| 123 |
+
return None, None, None, None
|
| 124 |
+
except Exception as e:
|
| 125 |
+
st.error(f"Error fetching page: {str(e)}")
|
| 126 |
+
return None, None, None, None
|
| 127 |
+
|
| 128 |
+
def smart_search_cars(query, category):
|
| 129 |
+
"""Enhanced search with category-specific terms"""
|
| 130 |
+
if not query.strip():
|
| 131 |
+
return []
|
| 132 |
+
|
| 133 |
+
# Add category context to search
|
| 134 |
+
category_terms = {
|
| 135 |
+
"Vintage Cars": ["vintage", "classic", "antique"],
|
| 136 |
+
"Trending Cars": ["2023", "2024", "new", "latest"],
|
| 137 |
+
"SUVs": ["SUV", "crossover"],
|
| 138 |
+
"Electric Cars": ["electric", "EV", "hybrid"]
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
# Try exact search first
|
| 142 |
+
results = cached_wikipedia_search(query)
|
| 143 |
+
|
| 144 |
+
# If few results, try with category context
|
| 145 |
+
if len(results) < 3:
|
| 146 |
+
enhanced_query = f"{query} {category_terms.get(category, [''])[0]}"
|
| 147 |
+
enhanced_results = cached_wikipedia_search(enhanced_query)
|
| 148 |
+
results.extend([r for r in enhanced_results if r not in results])
|
| 149 |
+
|
| 150 |
+
return results[:10] # Limit to 10 results
|
| 151 |
+
|
| 152 |
+
# --- Main Search Interface ---
|
| 153 |
+
st.markdown(f"### π Search Cars in {category}")
|
| 154 |
+
|
| 155 |
+
# Search input with debouncing
|
| 156 |
+
search_container = st.container()
|
| 157 |
+
with search_container:
|
| 158 |
+
col1, col2 = st.columns([3, 1])
|
| 159 |
+
|
| 160 |
+
with col1:
|
| 161 |
+
query = st.text_input(
|
| 162 |
+
"Type a Car Name",
|
| 163 |
+
placeholder="e.g., Tesla Model S, Ford Mustang",
|
| 164 |
+
key="search_input"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
with col2:
|
| 168 |
+
st.markdown("<br>", unsafe_allow_html=True) # Add spacing
|
| 169 |
+
clear_btn = st.button("ποΈ Clear", help="Clear search")
|
| 170 |
+
|
| 171 |
+
if clear_btn:
|
| 172 |
+
st.rerun()
|
| 173 |
+
|
| 174 |
+
# Live suggestions with improved logic
|
| 175 |
+
suggestions = []
|
| 176 |
+
if query and len(query.strip()) >= 3:
|
| 177 |
+
with st.spinner("Searching..."):
|
| 178 |
+
suggestions = smart_search_cars(query, category)
|
| 179 |
+
|
| 180 |
+
# Display suggestions
|
| 181 |
+
if suggestions:
|
| 182 |
+
selected_car = st.selectbox("π Select from suggestions:", [""] + suggestions)
|
| 183 |
+
else:
|
| 184 |
+
selected_car = None
|
| 185 |
+
|
| 186 |
+
# Search button
|
| 187 |
+
submit_btn = st.button("π Get Car Information", type="primary")
|
| 188 |
+
|
| 189 |
+
# --- Display Results ---
|
| 190 |
+
if submit_btn and selected_car:
|
| 191 |
+
# Add to search history
|
| 192 |
+
if selected_car not in st.session_state.search_history:
|
| 193 |
+
st.session_state.search_history.append(selected_car)
|
| 194 |
+
|
| 195 |
+
st.markdown("---")
|
| 196 |
+
|
| 197 |
+
# Progress bar for better UX
|
| 198 |
+
progress_bar = st.progress(0)
|
| 199 |
+
status_text = st.empty()
|
| 200 |
+
|
| 201 |
+
status_text.text("Fetching car information...")
|
| 202 |
+
progress_bar.progress(25)
|
| 203 |
+
|
| 204 |
+
# Fetch car information
|
| 205 |
+
summary, image_url, page_url, page_title = cached_wikipedia_page(selected_car)
|
| 206 |
+
progress_bar.progress(75)
|
| 207 |
+
|
| 208 |
+
if summary:
|
| 209 |
+
# Display main car info
|
| 210 |
+
st.markdown(f'<div class="car-card">', unsafe_allow_html=True)
|
| 211 |
+
|
| 212 |
+
# Title with favorite button
|
| 213 |
+
col1, col2 = st.columns([4, 1])
|
| 214 |
+
with col1:
|
| 215 |
+
st.subheader(f"π {page_title or selected_car}")
|
| 216 |
+
with col2:
|
| 217 |
+
if st.button("β Favorite", key=f"fav_{selected_car}"):
|
| 218 |
+
if selected_car not in st.session_state.favorites:
|
| 219 |
+
st.session_state.favorites.append(selected_car)
|
| 220 |
+
st.success("Added to favorites!")
|
| 221 |
+
|
| 222 |
+
# Display image and summary
|
| 223 |
+
if image_url:
|
| 224 |
+
try:
|
| 225 |
+
st.image(image_url, caption=page_title or selected_car, use_column_width=True)
|
| 226 |
+
except:
|
| 227 |
+
st.info("π· Image could not be loaded")
|
| 228 |
+
|
| 229 |
+
st.write(summary)
|
| 230 |
+
|
| 231 |
+
# Links and actions
|
| 232 |
+
col1, col2, col3 = st.columns(3)
|
| 233 |
+
with col1:
|
| 234 |
+
if page_url:
|
| 235 |
+
st.markdown(f"[π Wikipedia Page]({page_url})")
|
| 236 |
+
with col2:
|
| 237 |
+
if st.button("π Search Similar", key=f"similar_{selected_car}"):
|
| 238 |
+
# Extract brand name for similar search
|
| 239 |
+
brand = selected_car.split()[0]
|
| 240 |
+
similar_results = cached_wikipedia_search(f"{brand} cars")
|
| 241 |
+
if similar_results:
|
| 242 |
+
st.info(f"Similar cars: {', '.join(similar_results[:3])}")
|
| 243 |
+
with col3:
|
| 244 |
+
if st.button("π€ Share", key=f"share_{selected_car}"):
|
| 245 |
+
st.code(f"Check out this car: {selected_car}\n{page_url}")
|
| 246 |
+
|
| 247 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 248 |
+
|
| 249 |
+
progress_bar.progress(100)
|
| 250 |
+
status_text.text("β
Information loaded successfully!")
|
| 251 |
+
|
| 252 |
+
# Clear progress indicators after 2 seconds
|
| 253 |
+
time.sleep(1)
|
| 254 |
+
progress_bar.empty()
|
| 255 |
+
status_text.empty()
|
| 256 |
+
|
| 257 |
+
else:
|
| 258 |
+
progress_bar.progress(100)
|
| 259 |
+
status_text.empty()
|
| 260 |
+
progress_bar.empty()
|
| 261 |
+
|
| 262 |
+
st.markdown('<div class="error-message">β No information found for this car.</div>', unsafe_allow_html=True)
|
| 263 |
+
st.info("π‘ Try searching with a different spelling or check the suggestions above.")
|
| 264 |
+
|
| 265 |
+
# --- Favorites Section ---
|
| 266 |
+
if st.session_state.favorites:
|
| 267 |
+
st.markdown("---")
|
| 268 |
+
st.subheader("β Your Favorite Cars")
|
| 269 |
+
|
| 270 |
+
for i, fav in enumerate(st.session_state.favorites):
|
| 271 |
+
col1, col2 = st.columns([4, 1])
|
| 272 |
+
with col1:
|
| 273 |
+
st.write(f"π {fav}")
|
| 274 |
+
with col2:
|
| 275 |
+
if st.button("ποΈ", key=f"remove_{i}", help="Remove from favorites"):
|
| 276 |
+
st.session_state.favorites.remove(fav)
|
| 277 |
+
st.rerun()
|
| 278 |
+
|
| 279 |
+
# --- Footer ---
|
| 280 |
+
st.markdown("---")
|
| 281 |
+
st.markdown("""
|
| 282 |
+
<div style='text-align: center; color: #666;'>
|
| 283 |
+
<p>π Car Categories Explorer | Powered by Wikipedia API</p>
|
| 284 |
+
<p><small>Data provided by Wikipedia. Images and content are subject to their respective licenses.</small></p>
|
| 285 |
+
</div>
|
| 286 |
+
""", unsafe_allow_html=True)
|
src/Pages/3_chatbot.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 5 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 6 |
+
from sklearn.preprocessing import StandardScaler
|
| 7 |
+
import wikipedia
|
| 8 |
+
import re
|
| 9 |
+
import json
|
| 10 |
+
|
| 11 |
+
class CarRecommendationAI:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.car_database = self.create_car_database()
|
| 14 |
+
self.vectorizer = TfidfVectorizer(stop_words='english', max_features=1000)
|
| 15 |
+
self.scaler = StandardScaler()
|
| 16 |
+
self.setup_recommendation_system()
|
| 17 |
+
|
| 18 |
+
def create_car_database(self):
|
| 19 |
+
"""Create a comprehensive car database with features"""
|
| 20 |
+
cars = [
|
| 21 |
+
{
|
| 22 |
+
'name': 'Toyota Camry',
|
| 23 |
+
'brand': 'Toyota',
|
| 24 |
+
'type': 'Sedan',
|
| 25 |
+
'fuel_type': 'Hybrid',
|
| 26 |
+
'price_range': 'Mid-range',
|
| 27 |
+
'size': 'Mid-size',
|
| 28 |
+
'mpg': 32,
|
| 29 |
+
'reliability_score': 9,
|
| 30 |
+
'safety_score': 8,
|
| 31 |
+
'features': 'fuel efficient reliable comfortable family sedan hybrid technology',
|
| 32 |
+
'year': 2024
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
'name': 'Honda Civic',
|
| 36 |
+
'brand': 'Honda',
|
| 37 |
+
'type': 'Sedan',
|
| 38 |
+
'fuel_type': 'Gasoline',
|
| 39 |
+
'price_range': 'Budget',
|
| 40 |
+
'size': 'Compact',
|
| 41 |
+
'mpg': 31,
|
| 42 |
+
'reliability_score': 8,
|
| 43 |
+
'safety_score': 9,
|
| 44 |
+
'features': 'compact affordable reliable good gas mileage sporty',
|
| 45 |
+
'year': 2024
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
'name': 'BMW X5',
|
| 49 |
+
'brand': 'BMW',
|
| 50 |
+
'type': 'SUV',
|
| 51 |
+
'fuel_type': 'Gasoline',
|
| 52 |
+
'price_range': 'Luxury',
|
| 53 |
+
'size': 'Large',
|
| 54 |
+
'mpg': 23,
|
| 55 |
+
'reliability_score': 7,
|
| 56 |
+
'safety_score': 9,
|
| 57 |
+
'features': 'luxury SUV powerful performance premium interior technology',
|
| 58 |
+
'year': 2024
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
'name': 'Tesla Model 3',
|
| 62 |
+
'brand': 'Tesla',
|
| 63 |
+
'type': 'Sedan',
|
| 64 |
+
'fuel_type': 'Electric',
|
| 65 |
+
'price_range': 'Premium',
|
| 66 |
+
'size': 'Mid-size',
|
| 67 |
+
'mpg': 120, # MPGe for electric
|
| 68 |
+
'reliability_score': 7,
|
| 69 |
+
'safety_score': 10,
|
| 70 |
+
'features': 'electric autonomous driving technology innovative sustainable',
|
| 71 |
+
'year': 2024
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
'name': 'Ford F-150',
|
| 75 |
+
'brand': 'Ford',
|
| 76 |
+
'type': 'Truck',
|
| 77 |
+
'fuel_type': 'Gasoline',
|
| 78 |
+
'price_range': 'Mid-range',
|
| 79 |
+
'size': 'Large',
|
| 80 |
+
'mpg': 20,
|
| 81 |
+
'reliability_score': 8,
|
| 82 |
+
'safety_score': 8,
|
| 83 |
+
'features': 'pickup truck powerful towing capacity work vehicle durable',
|
| 84 |
+
'year': 2024
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
'name': 'Porsche 911',
|
| 88 |
+
'brand': 'Porsche',
|
| 89 |
+
'type': 'Sports Car',
|
| 90 |
+
'fuel_type': 'Gasoline',
|
| 91 |
+
'price_range': 'Luxury',
|
| 92 |
+
'size': 'Compact',
|
| 93 |
+
'mpg': 22,
|
| 94 |
+
'reliability_score': 8,
|
| 95 |
+
'safety_score': 7,
|
| 96 |
+
'features': 'sports car high performance luxury speed racing heritage',
|
| 97 |
+
'year': 2024
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
'name': 'Subaru Outback',
|
| 101 |
+
'brand': 'Subaru',
|
| 102 |
+
'type': 'SUV',
|
| 103 |
+
'fuel_type': 'Gasoline',
|
| 104 |
+
'price_range': 'Mid-range',
|
| 105 |
+
'size': 'Mid-size',
|
| 106 |
+
'mpg': 26,
|
| 107 |
+
'reliability_score': 9,
|
| 108 |
+
'safety_score': 9,
|
| 109 |
+
'features': 'all wheel drive outdoor adventure reliable safe family',
|
| 110 |
+
'year': 2024
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
'name': 'Hyundai Elantra',
|
| 114 |
+
'brand': 'Hyundai',
|
| 115 |
+
'type': 'Sedan',
|
| 116 |
+
'fuel_type': 'Gasoline',
|
| 117 |
+
'price_range': 'Budget',
|
| 118 |
+
'size': 'Compact',
|
| 119 |
+
'mpg': 33,
|
| 120 |
+
'reliability_score': 8,
|
| 121 |
+
'safety_score': 8,
|
| 122 |
+
'features': 'affordable fuel efficient warranty reliable compact',
|
| 123 |
+
'year': 2024
|
| 124 |
+
}
|
| 125 |
+
]
|
| 126 |
+
return pd.DataFrame(cars)
|
| 127 |
+
|
| 128 |
+
def setup_recommendation_system(self):
|
| 129 |
+
"""Setup the AI recommendation system"""
|
| 130 |
+
# Create feature matrix for text-based similarity
|
| 131 |
+
feature_matrix = self.vectorizer.fit_transform(self.car_database['features'])
|
| 132 |
+
self.feature_similarity = cosine_similarity(feature_matrix)
|
| 133 |
+
|
| 134 |
+
# Create numerical feature matrix
|
| 135 |
+
numerical_features = self.car_database[['mpg', 'reliability_score', 'safety_score', 'year']].values
|
| 136 |
+
self.numerical_features_scaled = self.scaler.fit_transform(numerical_features)
|
| 137 |
+
|
| 138 |
+
def get_user_preferences(self):
|
| 139 |
+
"""Create UI for user preferences"""
|
| 140 |
+
st.subheader("π€ AI Car Recommendation System")
|
| 141 |
+
st.write("Tell us your preferences and our AI will recommend the perfect car for you!")
|
| 142 |
+
|
| 143 |
+
col1, col2 = st.columns(2)
|
| 144 |
+
|
| 145 |
+
with col1:
|
| 146 |
+
budget = st.selectbox(
|
| 147 |
+
"π° Budget Range:",
|
| 148 |
+
["Budget", "Mid-range", "Premium", "Luxury", "Any"]
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
car_type = st.selectbox(
|
| 152 |
+
"π Car Type:",
|
| 153 |
+
["Sedan", "SUV", "Truck", "Sports Car", "Any"]
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
fuel_preference = st.selectbox(
|
| 157 |
+
"β½ Fuel Type:",
|
| 158 |
+
["Gasoline", "Hybrid", "Electric", "Any"]
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
with col2:
|
| 162 |
+
size_preference = st.selectbox(
|
| 163 |
+
"π Size Preference:",
|
| 164 |
+
["Compact", "Mid-size", "Large", "Any"]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
priority = st.selectbox(
|
| 168 |
+
"π― What's Most Important:",
|
| 169 |
+
["Fuel Efficiency", "Reliability", "Safety", "Performance", "Technology", "Balanced"]
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
usage = st.selectbox(
|
| 173 |
+
"π£οΈ Primary Usage:",
|
| 174 |
+
["Daily Commuting", "Family Travel", "Work/Business", "Recreation", "Sports/Performance"]
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
return {
|
| 178 |
+
'budget': budget,
|
| 179 |
+
'car_type': car_type,
|
| 180 |
+
'fuel_preference': fuel_preference,
|
| 181 |
+
'size_preference': size_preference,
|
| 182 |
+
'priority': priority,
|
| 183 |
+
'usage': usage
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
def calculate_preference_score(self, car, preferences):
|
| 187 |
+
"""Calculate how well a car matches user preferences"""
|
| 188 |
+
score = 0
|
| 189 |
+
max_score = 100
|
| 190 |
+
|
| 191 |
+
# Budget matching (25 points)
|
| 192 |
+
if preferences['budget'] == 'Any' or car['price_range'] == preferences['budget']:
|
| 193 |
+
score += 25
|
| 194 |
+
elif (preferences['budget'] == 'Budget' and car['price_range'] == 'Mid-range') or \
|
| 195 |
+
(preferences['budget'] == 'Mid-range' and car['price_range'] in ['Budget', 'Premium']) or \
|
| 196 |
+
(preferences['budget'] == 'Premium' and car['price_range'] in ['Mid-range', 'Luxury']):
|
| 197 |
+
score += 15
|
| 198 |
+
|
| 199 |
+
# Car type matching (20 points)
|
| 200 |
+
if preferences['car_type'] == 'Any' or car['type'] == preferences['car_type']:
|
| 201 |
+
score += 20
|
| 202 |
+
|
| 203 |
+
# Fuel type matching (15 points)
|
| 204 |
+
if preferences['fuel_preference'] == 'Any' or car['fuel_type'] == preferences['fuel_preference']:
|
| 205 |
+
score += 15
|
| 206 |
+
|
| 207 |
+
# Size matching (10 points)
|
| 208 |
+
if preferences['size_preference'] == 'Any' or car['size'] == preferences['size_preference']:
|
| 209 |
+
score += 10
|
| 210 |
+
|
| 211 |
+
# Priority-based scoring (20 points)
|
| 212 |
+
priority_scores = {
|
| 213 |
+
'Fuel Efficiency': car['mpg'] / 50 * 20, # Normalize MPG
|
| 214 |
+
'Reliability': car['reliability_score'] / 10 * 20,
|
| 215 |
+
'Safety': car['safety_score'] / 10 * 20,
|
| 216 |
+
'Performance': (10 - car['reliability_score']) / 10 * 20 if car['type'] == 'Sports Car' else 10,
|
| 217 |
+
'Technology': 20 if car['brand'] in ['Tesla', 'BMW'] else 10,
|
| 218 |
+
'Balanced': (car['reliability_score'] + car['safety_score']) / 20 * 20
|
| 219 |
+
}
|
| 220 |
+
score += priority_scores.get(preferences['priority'], 10)
|
| 221 |
+
|
| 222 |
+
# Usage-based scoring (10 points)
|
| 223 |
+
usage_scores = {
|
| 224 |
+
'Daily Commuting': 10 if car['mpg'] > 25 else 5,
|
| 225 |
+
'Family Travel': 10 if car['type'] in ['SUV', 'Sedan'] and car['size'] in ['Mid-size', 'Large'] else 5,
|
| 226 |
+
'Work/Business': 10 if car['type'] in ['Truck', 'SUV'] else 5,
|
| 227 |
+
'Recreation': 10 if car['type'] in ['SUV', 'Truck'] else 5,
|
| 228 |
+
'Sports/Performance': 10 if car['type'] == 'Sports Car' else 5
|
| 229 |
+
}
|
| 230 |
+
score += usage_scores.get(preferences['usage'], 5)
|
| 231 |
+
|
| 232 |
+
return min(score, max_score)
|
| 233 |
+
|
| 234 |
+
def get_recommendations(self, preferences, num_recommendations=3):
|
| 235 |
+
"""Get AI-powered car recommendations"""
|
| 236 |
+
scored_cars = []
|
| 237 |
+
|
| 238 |
+
for idx, car in self.car_database.iterrows():
|
| 239 |
+
preference_score = self.calculate_preference_score(car, preferences)
|
| 240 |
+
|
| 241 |
+
# Add some AI-based similarity scoring
|
| 242 |
+
similarity_bonus = np.mean(self.feature_similarity[idx]) * 10
|
| 243 |
+
|
| 244 |
+
total_score = preference_score + similarity_bonus
|
| 245 |
+
|
| 246 |
+
scored_cars.append({
|
| 247 |
+
'car': car,
|
| 248 |
+
'score': total_score,
|
| 249 |
+
'preference_match': preference_score,
|
| 250 |
+
'index': idx
|
| 251 |
+
})
|
| 252 |
+
|
| 253 |
+
# Sort by total score
|
| 254 |
+
scored_cars.sort(key=lambda x: x['score'], reverse=True)
|
| 255 |
+
|
| 256 |
+
return scored_cars[:num_recommendations]
|
| 257 |
+
|
| 258 |
+
def get_wikipedia_info(self, car_name):
|
| 259 |
+
"""Get Wikipedia information for a car"""
|
| 260 |
+
try:
|
| 261 |
+
# Search for the car on Wikipedia
|
| 262 |
+
search_results = wikipedia.search(car_name, results=3)
|
| 263 |
+
if search_results:
|
| 264 |
+
page = wikipedia.page(search_results[0])
|
| 265 |
+
summary = wikipedia.summary(car_name, sentences=3)
|
| 266 |
+
return {
|
| 267 |
+
'summary': summary,
|
| 268 |
+
'url': page.url,
|
| 269 |
+
'title': page.title
|
| 270 |
+
}
|
| 271 |
+
except:
|
| 272 |
+
return {
|
| 273 |
+
'summary': f"Wikipedia information for {car_name} is not available at the moment.",
|
| 274 |
+
'url': "",
|
| 275 |
+
'title': car_name
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
def explain_recommendation(self, car, preferences, score):
|
| 279 |
+
"""Generate AI explanation for why this car was recommended"""
|
| 280 |
+
explanations = []
|
| 281 |
+
|
| 282 |
+
if preferences['budget'] == 'Any' or car['price_range'] == preferences['budget']:
|
| 283 |
+
explanations.append(f"β
Matches your {preferences['budget'].lower()} budget preference")
|
| 284 |
+
|
| 285 |
+
if preferences['car_type'] == 'Any' or car['type'] == preferences['car_type']:
|
| 286 |
+
explanations.append(f"β
Perfect {car['type'].lower()} match for your needs")
|
| 287 |
+
|
| 288 |
+
if car['mpg'] > 30:
|
| 289 |
+
explanations.append("β½ Excellent fuel efficiency")
|
| 290 |
+
|
| 291 |
+
if car['reliability_score'] >= 8:
|
| 292 |
+
explanations.append("π§ High reliability rating")
|
| 293 |
+
|
| 294 |
+
if car['safety_score'] >= 8:
|
| 295 |
+
explanations.append("π‘οΈ Outstanding safety features")
|
| 296 |
+
|
| 297 |
+
# Priority-based explanations
|
| 298 |
+
priority_explanations = {
|
| 299 |
+
'Fuel Efficiency': f"π‘ Great choice for fuel efficiency with {car['mpg']} MPG",
|
| 300 |
+
'Reliability': f"π‘ Highly reliable with {car['reliability_score']}/10 rating",
|
| 301 |
+
'Safety': f"π‘ Excellent safety with {car['safety_score']}/10 rating",
|
| 302 |
+
'Performance': "π‘ Built for performance and driving excitement",
|
| 303 |
+
'Technology': "π‘ Features cutting-edge automotive technology"
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
if preferences['priority'] in priority_explanations:
|
| 307 |
+
explanations.append(priority_explanations[preferences['priority']])
|
| 308 |
+
|
| 309 |
+
return explanations
|
| 310 |
+
|
| 311 |
+
def integrate_ai_recommendations():
|
| 312 |
+
"""Main function to integrate AI recommendations into Streamlit app"""
|
| 313 |
+
|
| 314 |
+
# Initialize the AI system
|
| 315 |
+
if 'ai_system' not in st.session_state:
|
| 316 |
+
st.session_state.ai_system = CarRecommendationAI()
|
| 317 |
+
|
| 318 |
+
ai_system = st.session_state.ai_system
|
| 319 |
+
|
| 320 |
+
# Create tabs for different functionalities
|
| 321 |
+
tab1, tab3 = st.tabs(["π€ AI Recommendations", "π Compare Cars"])
|
| 322 |
+
|
| 323 |
+
with tab1:
|
| 324 |
+
st.title("π AI-Powered Car Recommendations")
|
| 325 |
+
|
| 326 |
+
# Get user preferences
|
| 327 |
+
preferences = ai_system.get_user_preferences()
|
| 328 |
+
|
| 329 |
+
if st.button("π― Get My AI Recommendations", type="primary"):
|
| 330 |
+
with st.spinner("π€ AI is analyzing your preferences..."):
|
| 331 |
+
recommendations = ai_system.get_recommendations(preferences)
|
| 332 |
+
|
| 333 |
+
st.success("β¨ Here are your personalized recommendations!")
|
| 334 |
+
|
| 335 |
+
for i, rec in enumerate(recommendations, 1):
|
| 336 |
+
car = rec['car']
|
| 337 |
+
score = rec['preference_match']
|
| 338 |
+
|
| 339 |
+
with st.expander(f"#{i} {car['name']} - Match Score: {score:.1f}%", expanded=i==1):
|
| 340 |
+
col1, col2 = st.columns([2, 1])
|
| 341 |
+
|
| 342 |
+
with col1:
|
| 343 |
+
st.subheader(f"{car['brand']} {car['name']}")
|
| 344 |
+
|
| 345 |
+
# Car details
|
| 346 |
+
st.write(f"**Type:** {car['type']} | **Size:** {car['size']}")
|
| 347 |
+
st.write(f"**Price Range:** {car['price_range']} | **Fuel:** {car['fuel_type']}")
|
| 348 |
+
st.write(f"**MPG:** {car['mpg']} | **Year:** {car['year']}")
|
| 349 |
+
|
| 350 |
+
# Ratings
|
| 351 |
+
st.write("**Ratings:**")
|
| 352 |
+
st.write(f"π§ Reliability: {car['reliability_score']}/10")
|
| 353 |
+
st.write(f"π‘οΈ Safety: {car['safety_score']}/10")
|
| 354 |
+
|
| 355 |
+
# AI Explanation
|
| 356 |
+
st.write("**π€ Why we recommend this:**")
|
| 357 |
+
explanations = ai_system.explain_recommendation(car, preferences, score)
|
| 358 |
+
for explanation in explanations:
|
| 359 |
+
st.write(f"β’ {explanation}")
|
| 360 |
+
|
| 361 |
+
with col2:
|
| 362 |
+
# Progress bars for ratings
|
| 363 |
+
st.metric("Match Score", f"{score:.1f}%")
|
| 364 |
+
st.progress(score/100)
|
| 365 |
+
|
| 366 |
+
st.metric("Reliability", f"{car['reliability_score']}/10")
|
| 367 |
+
st.progress(car['reliability_score']/10)
|
| 368 |
+
|
| 369 |
+
st.metric("Safety", f"{car['safety_score']}/10")
|
| 370 |
+
st.progress(car['safety_score']/10)
|
| 371 |
+
|
| 372 |
+
# Wikipedia integration
|
| 373 |
+
if st.button(f"π Learn more about {car['name']}", key=f"wiki_{i}"):
|
| 374 |
+
with st.spinner("Fetching Wikipedia information..."):
|
| 375 |
+
wiki_info = ai_system.get_wikipedia_info(car['name'])
|
| 376 |
+
st.write("**Wikipedia Summary:**")
|
| 377 |
+
st.write(wiki_info['summary'])
|
| 378 |
+
if wiki_info['url']:
|
| 379 |
+
st.write(f"[Read more on Wikipedia]({wiki_info['url']})")
|
| 380 |
+
|
| 381 |
+
# with tab2:
|
| 382 |
+
# st.title("π Enhanced Car Search")
|
| 383 |
+
# search_term = st.text_input("Search for a specific car model:")
|
| 384 |
+
|
| 385 |
+
# if search_term:
|
| 386 |
+
# # Filter cars based on search
|
| 387 |
+
# filtered_cars = ai_system.car_database[
|
| 388 |
+
# ai_system.car_database['name'].str.contains(search_term, case=False) |
|
| 389 |
+
# ai_system.car_database['brand'].str.contains(search_term, case=False)
|
| 390 |
+
# ]
|
| 391 |
+
|
| 392 |
+
# if not filtered_cars.empty:
|
| 393 |
+
# for _, car in filtered_cars.iterrows():
|
| 394 |
+
# with st.expander(f"{car['name']}"):
|
| 395 |
+
# col1, col2 = st.columns(2)
|
| 396 |
+
# with col1:
|
| 397 |
+
# st.write(f"**Brand:** {car['brand']}")
|
| 398 |
+
# st.write(f"**Type:** {car['type']}")
|
| 399 |
+
# st.write(f"**Price Range:** {car['price_range']}")
|
| 400 |
+
# with col2:
|
| 401 |
+
# st.write(f"**MPG:** {car['mpg']}")
|
| 402 |
+
# st.write(f"**Reliability:** {car['reliability_score']}/10")
|
| 403 |
+
# st.write(f"**Safety:** {car['safety_score']}/10")
|
| 404 |
+
|
| 405 |
+
# if st.button(f"Get Wikipedia info for {car['name']}", key=f"search_wiki_{car['name']}"):
|
| 406 |
+
# wiki_info = ai_system.get_wikipedia_info(car['name'])
|
| 407 |
+
# st.write(wiki_info['summary'])
|
| 408 |
+
# if wiki_info['url']:
|
| 409 |
+
# st.write(f"[Read more]({wiki_info['url']})")
|
| 410 |
+
# else:
|
| 411 |
+
# st.warning("No cars found matching your search.")
|
| 412 |
+
|
| 413 |
+
with tab3:
|
| 414 |
+
st.title("π Car Comparison Tool")
|
| 415 |
+
|
| 416 |
+
car_names = ai_system.car_database['name'].tolist()
|
| 417 |
+
|
| 418 |
+
col1, col2 = st.columns(2)
|
| 419 |
+
with col1:
|
| 420 |
+
car1 = st.selectbox("Select first car:", car_names)
|
| 421 |
+
with col2:
|
| 422 |
+
car2 = st.selectbox("Select second car:", car_names, index=1)
|
| 423 |
+
|
| 424 |
+
if st.button("Compare Cars"):
|
| 425 |
+
car1_data = ai_system.car_database[ai_system.car_database['name'] == car1].iloc[0]
|
| 426 |
+
car2_data = ai_system.car_database[ai_system.car_database['name'] == car2].iloc[0]
|
| 427 |
+
|
| 428 |
+
comparison_df = pd.DataFrame({
|
| 429 |
+
car1: [car1_data['brand'], car1_data['type'], car1_data['price_range'],
|
| 430 |
+
car1_data['mpg'], car1_data['reliability_score'], car1_data['safety_score']],
|
| 431 |
+
car2: [car2_data['brand'], car2_data['type'], car2_data['price_range'],
|
| 432 |
+
car2_data['mpg'], car2_data['reliability_score'], car2_data['safety_score']]
|
| 433 |
+
}, index=['Brand', 'Type', 'Price Range', 'MPG', 'Reliability', 'Safety'])
|
| 434 |
+
|
| 435 |
+
st.table(comparison_df)
|
| 436 |
+
|
| 437 |
+
# AI-powered comparison insights
|
| 438 |
+
st.subheader("π€ AI Comparison Insights")
|
| 439 |
+
|
| 440 |
+
if car1_data['mpg'] > car2_data['mpg']:
|
| 441 |
+
st.write(f"β
{car1} has better fuel efficiency ({car1_data['mpg']} vs {car2_data['mpg']} MPG)")
|
| 442 |
+
else:
|
| 443 |
+
st.write(f"β
{car2} has better fuel efficiency ({car2_data['mpg']} vs {car1_data['mpg']} MPG)")
|
| 444 |
+
|
| 445 |
+
if car1_data['reliability_score'] > car2_data['reliability_score']:
|
| 446 |
+
st.write(f"π§ {car1} has higher reliability rating")
|
| 447 |
+
elif car2_data['reliability_score'] > car1_data['reliability_score']:
|
| 448 |
+
st.write(f"π§ {car2} has higher reliability rating")
|
| 449 |
+
else:
|
| 450 |
+
st.write("π§ Both cars have equal reliability ratings")
|
| 451 |
+
|
| 452 |
+
# Usage example - Add this to your existing Streamlit app
|
| 453 |
+
if __name__ == "__main__":
|
| 454 |
+
integrate_ai_recommendations()
|