File size: 28,572 Bytes
06f8fec
 
 
 
 
 
 
 
610350a
06f8fec
 
3f605a7
 
 
 
 
06f8fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed92fc5
06f8fec
 
 
ed92fc5
06f8fec
 
 
 
 
 
 
 
 
 
ed92fc5
06f8fec
 
 
 
81334ca
06f8fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81334ca
06f8fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f605a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77e8922
 
3f605a7
 
 
 
 
 
 
 
 
 
 
 
f3327eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f8fec
f3327eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77e8922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f8fec
77e8922
 
 
 
06f8fec
f3327eb
 
06f8fec
 
 
 
 
 
 
 
 
 
f3327eb
06f8fec
 
 
 
f3327eb
06f8fec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f605a7
 
 
 
 
 
 
06f8fec
3f605a7
 
 
 
 
06f8fec
556c3e3
 
 
 
 
 
06f8fec
556c3e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f605a7
 
 
 
 
 
 
 
 
 
 
 
 
06f8fec
3f605a7
06f8fec
3f605a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06f8fec
 
3f605a7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import matplotlib.pyplot as plt
import os
import openai
from sklearn.preprocessing import LabelEncoder
import requests 
from io import BytesIO
import gdown
from PIL import Image
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
import torch
from datetime import datetime

# --- Set page configuration ---
st.set_page_config(
    page_title="The Guide",
    page_icon="πŸš—",
    layout="wide",
    initial_sidebar_state="expanded"
)

# --- Custom CSS for better styling ---

st.markdown("""
    <style>
    /* Base styles */
    * {
        color: black !important;
    }
    
    /* Streamlit specific input elements */
    .stSelectbox, 
    .stNumberInput, 
    .stTextInput {
        color: black !important;
    }
    
    /* Dropdown and select elements */
    select option,
    .streamlit-selectbox option,
    .stSelectbox > div[data-baseweb="select"] > div,
    .stSelectbox > div > div > div {
        color: black !important;
        background-color: white !important;
    }
    
    /* Input fields */
    input, 
    .stNumberInput > div > div > input {
        color: black !important;
    }
    
    /* Text elements */
    div.row-widget.stSelectbox > div,
    div.row-widget.stSelectbox > div > div > div,
    .streamlit-expanderContent,
    .stMarkdown,
    p, span, label {
        color: black !important;
    }
    
    /* Keep button text white */
    .stButton > button {
        color: white !important;
        background-color: #FF4B4B;
    }
    
    /* Specific styling for select boxes */
    div[data-baseweb="select"] {
        color: black !important;
        background-color: white !important;
    }
    
    div[data-baseweb="select"] * {
        color: black !important;
    }
    
    /* Style for the selected option */
    div[data-baseweb="select"] > div:first-child {
        color: black !important;
        background-color: white !important;
    }
    
    /* Dropdown menu items */
    [role="listbox"] {
        background-color: white !important;
    }
    
    [role="listbox"] [role="option"] {
        color: black !important;
    }
    
    /* Number input specific styling */
    input[type="number"] {
        color: black !important;
        background-color: white !important;
    }
    
    .stNumberInput div[data-baseweb="input"] {
        background-color: white !important;
    }
    
    /* Headers */
    h1, h2, h3, h4, h5, h6 {
        color: black !important;
    }
    </style>
""", unsafe_allow_html=True)

# --- Cache functions ---
def create_brand_categories():
    return {
        'luxury_brands': {
            'rolls-royce': (300000, 600000),
            'bentley': (200000, 500000),
            'lamborghini': (250000, 550000),
            'ferrari': (250000, 600000),
            'mclaren': (200000, 500000),
            'aston-martin': (150000, 400000),
            'maserati': (100000, 300000)
        },
        'premium_brands': {
            'porsche': (60000, 150000),
            'bmw': (40000, 90000),
            'mercedes-benz': (45000, 95000),
            'audi': (35000, 85000),
            'lexus': (40000, 80000),
            'jaguar': (45000, 90000),
            'land-rover': (40000, 90000),
            'volvo': (35000, 75000),
            'infiniti': (35000, 70000),
            'cadillac': (40000, 85000),
            'tesla': (40000, 100000)
        },
        'mid_tier_brands': {
            'acura': (30000, 50000),
            'lincoln': (35000, 65000),
            'buick': (25000, 45000),
            'chrysler': (25000, 45000),
            'alfa-romeo': (35000, 60000),
            'genesis': (35000, 60000)
        },
        'standard_brands': {
            'toyota': (20000, 35000),
            'honda': (20000, 35000),
            'volkswagen': (20000, 35000),
            'mazda': (20000, 32000),
            'subaru': (22000, 35000),
            'hyundai': (18000, 32000),
            'kia': (17000, 30000),
            'ford': (20000, 40000),
            'chevrolet': (20000, 38000),
            'gmc': (25000, 45000),
            'jeep': (25000, 45000),
            'dodge': (22000, 40000),
            'ram': (25000, 45000),
            'nissan': (18000, 32000)
        },
        'economy_brands': {
            'mitsubishi': (15000, 25000),
            'suzuki': (12000, 22000),
            'fiat': (15000, 25000),
            'mini': (20000, 35000),
            'smart': (15000, 25000)
        },
        'discontinued_brands': {
            'pontiac': (5000, 15000),
            'saturn': (4000, 12000),
            'mercury': (4000, 12000),
            'oldsmobile': (3000, 10000),
            'plymouth': (3000, 10000),
            'saab': (5000, 15000)
        }
    }

@st.cache_resource
def download_file_from_google_drive(file_id):
    """Downloads a file from Google Drive using gdown."""
    url = f"https://drive.google.com/uc?id={file_id}"
    try:
        with st.spinner('Downloading from Google Drive...'):
            output = f"temp_{file_id}.pkl"
            gdown.download(url, output, quiet=False)
            
            with open(output, 'rb') as f:
                content = f.read()
            
            # Clean up the temporary file
            os.remove(output)
            return content
            
    except Exception as e:
        st.error(f"Error downloading from Google Drive: {str(e)}")
        raise e

@st.cache_data
def load_datasets():
    """Load the dataset from Google Drive."""
    dataset_file_id = "17dj7yW22YsIfp-tvXQFCitKmLFw5IuAv"
    
    try:
        with st.spinner('Loading dataset...'):
            content = download_file_from_google_drive(dataset_file_id)
            # Use BytesIO to read the CSV content
            original_data = pd.read_csv(BytesIO(content), low_memory=False)
            
            # Ensure column names match the model's expectations
            original_data.columns = original_data.columns.str.strip().str.capitalize()
            return original_data
    except Exception as e:
        st.error(f"Error loading dataset: {str(e)}")
        raise e

@st.cache_resource
def load_model_and_encodings():
    """Load model from Google Drive and create encodings."""
    model_file_id = "1ynnVEH7rmAjfe-jH8GOEmTJc6ml8dTi_"
    
    try:
        # Show loading message
        with st.spinner('Loading model...'):
            model_content = download_file_from_google_drive(model_file_id)
            model = joblib.load(BytesIO(model_content))
        
        # Load data for encodings
        original_data = load_datasets()
        
        # Create fresh encoders from data
        label_encoders = {}
        categorical_features = ['Make', 'model', 'condition', 'fuel', 'title_status', 
                              'transmission', 'drive', 'size', 'type', 'paint_color']
        
        for feature in categorical_features:
            if feature in original_data.columns:
                le = LabelEncoder()
                unique_values = original_data[feature].fillna('unknown').str.strip().unique()
                le.fit(unique_values)
                label_encoders[feature.lower()] = le
        
        return model, label_encoders
    except Exception as e:
        st.error(f"Error loading model: {str(e)}")
        raise e


# --- Load data and models ---
try:
    original_data = load_datasets()
    model, label_encoders = load_model_and_encodings()  # Using the new function
except Exception as e:
    st.error(f"Error loading data or models: {str(e)}")
    st.stop()

# --- Define categorical and numeric features ---
# From model.py
# --- Define features ---
numeric_features = ['year', 'odometer', 'age', 'age_squared', 'mileage_per_year']
# Update the categorical features list to use lowercase
categorical_features = ['make', 'model', 'condition', 'fuel', 'title_status', 
                       'transmission', 'drive', 'size', 'type', 'paint_color']
required_features = numeric_features + categorical_features

# --- Feature engineering functions ---
def create_features(df):
    df = df.copy()
    current_year = 2024
    df['age'] = current_year - df['year']
    df['age_squared'] = df['age'] ** 2
    df['mileage_per_year'] = np.clip(df['odometer'] / (df['age'] + 1), 0, 200000)
    return df

def prepare_input(input_dict, label_encoders):
    # Convert None values to 'unknown' for safe handling
    input_dict = {k: v if v is not None else 'unknown' for k, v in input_dict.items()}
    
    # Convert input dictionary to DataFrame
    input_df = pd.DataFrame([input_dict])
    
    # Ensure columns match the model's expected casing
    feature_name_mapping = {
        "make": "Make",  # Match casing for 'Make'
        "model": "Model",  # Match casing for 'Model'
        "condition": "Condition",
        "fuel": "Fuel",
        "title_status": "Title_status",
        "transmission": "Transmission",
        "drive": "Drive",
        "size": "Size",
        "type": "Type",
        "paint_color": "Paint_color",
        "year": "Year",
        "odometer": "Odometer",
        "age": "Age",
        "age_squared": "Age_squared",
        "mileage_per_year": "Mileage_per_year"
    }
    input_df.rename(columns=feature_name_mapping, inplace=True)

    # Numeric feature conversions
    input_df["Year"] = pd.to_numeric(input_df.get("Year", 0), errors="coerce")
    input_df["Odometer"] = pd.to_numeric(input_df.get("Odometer", 0), errors="coerce")
    
    # Feature engineering
    current_year = 2024
    input_df["Age"] = current_year - input_df["Year"]
    input_df["Age_squared"] = input_df["Age"] ** 2
    input_df["Mileage_per_year"] = input_df["Odometer"] / (input_df["Age"] + 1)
    input_df["Mileage_per_year"] = input_df["Mileage_per_year"].clip(0, 200000)

    # Encode categorical features
    for feature, encoded_feature in feature_name_mapping.items():
        if feature in label_encoders:
            input_df[encoded_feature] = input_df[encoded_feature].fillna("unknown").astype(str).str.strip()
            try:
                input_df[encoded_feature] = label_encoders[feature].transform(input_df[encoded_feature])
            except ValueError:
                input_df[encoded_feature] = 0  # Assign default for unseen values

    # Ensure all required features are present
    for feature in model.feature_names_in_:
        if feature not in input_df:
            input_df[feature] = 0  # Default value for missing features

    # Reorder columns
    input_df = input_df[model.feature_names_in_]

    return input_df



# --- Styling functions ---
st.markdown("""
    <style>
    /* Force black text globally */
    .stApp, .stApp * {
        color: black !important;
    }
    
    /* Specific overrides for different elements */
    .main {
        padding: 0rem 1rem;
    }
    
    .stButton>button {
        width: 100%;
        background-color: #FF4B4B;
        color: white !important;  /* Keep button text white */
        border-radius: 5px;
        padding: 0.5rem 1rem;
        border: none;
    }
    
    .stButton>button:hover {
        background-color: #FF6B6B;
    }
    
    .sidebar .sidebar-content {
        background-color: #f5f5f5;
    }
    
    /* Input fields and selectboxes */
    .stSelectbox select, 
    .stSelectbox option,
    .stSelectbox div,
    .stNumberInput input,
    .stTextInput input {
        color: black !important;
    }
    
    /* Headers */
    h1, h2, h3, h4, h5, h6 {
        color: black !important;
    }
    
    /* Labels and text */
    label, .stText, p, span {
        color: black !important;
    }
    
    /* Selectbox options */
    option {
        color: black !important;
        background-color: white !important;
    }
    
    /* Override for any Streamlit specific classes */
    .st-emotion-cache-16idsys p,
    .st-emotion-cache-1wmy9hl p,
    .st-emotion-cache-16idsys span,
    .st-emotion-cache-1wmy9hl span {
        color: black !important;
    }
    
    /* Force white text only for the prediction button */
    .stButton>button[data-testid="stButton"] {
        color: white !important;
    }
    </style>
""", unsafe_allow_html=True)

def style_metric_container(label, value):
    st.markdown(f"""
        <div style="
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 5px;
            margin: 0.5rem 0;
            border-left: 5px solid #FF4B4B;
        ">
            <p style="color: #666; margin-bottom: 0.2rem; font-size: 0.9rem;">{label}</p>
            <p style="color: #1E1E1E; font-size: 1.5rem; font-weight: 600; margin: 0;">{value}</p>
        </div>
    """, unsafe_allow_html=True)

def classify_image(image):
    try:
        model_name = "dima806/car_models_image_detection"
        feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
        model = AutoModelForImageClassification.from_pretrained(model_name)

        inputs = feature_extractor(images=image, return_tensors="pt")
        
        with torch.no_grad():
            outputs = model(**inputs)

        logits = outputs.logits
        predicted_class_idx = logits.argmax(-1).item()
        predicted_class_label = model.config.id2label[predicted_class_idx]
        score = torch.nn.functional.softmax(logits, dim=-1)[0, predicted_class_idx].item()

        return [{'label': predicted_class_label, 'score': score}]
    except Exception as e:
        st.error(f"Classification error: {e}")
        return None



def get_car_overview(brand, model, year):
    try:
        prompt = f"Provide an overview of the following car:\nYear: {year}\nMake: {brand}\nModel: {model}\n"
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message['content']
    except Exception as e:
        st.error(f"Error getting car overview: {str(e)}")
        return None

def search_dataset(dataset, make, model=None):
    """
    Search the dataset for the specified make and model. If no model is provided,
    search by make only. Return relevant information if found.
    """
    # Filter by make and model
    query = dataset[dataset['Make'].str.lower() == make.lower()]
    if model:
        query = query[query['Model'].str.lower() == model.lower()]
    
    if not query.empty:
        # If matching rows exist, return a formatted response
        results = query[['Year', 'Make', 'Model', 'Price']].head(5)  # Adjust columns as needed
        return results
    else:
        # No relevant data found in the dataset
        return None

# --- Updated GPT Functionality ---
def generate_gpt_response(prompt, dataset):
    """
    First look up the dataset for relevant information. If no matches are found,
    generate a GPT response.
    """
    # Extract make and model from the prompt (simplified NLP parsing)
    prompt_lower = prompt.lower()
    make = None
    model = None
    
    # Example: Parse make and model from user query
    for word in prompt_lower.split():
        if word in dataset['Make'].str.lower().unique():
            make = word
        elif word in dataset['Model'].str.lower().unique():
            model = word
    
    # If we find relevant data, use it to respond
    if make:
        dataset_response = search_dataset(dataset, make, model)
        if dataset_response is not None:
            st.write("### Dataset Match Found")
            st.dataframe(dataset_response)  # Show results to the user
            return f"I found some information in our dataset about {make.title()} {model.title() if model else ''}. Please see the details above."
    
    try:
        openai.api_key = "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"  # Replace with your API key
        system_message = {
            "role": "system",
            "content": "You are a helpful car shopping assistant. Provide concise car recommendations or pricing estimates. Keep responses focused and brief."
        }
        messages = [
            system_message,
            {"role": "user", "content": f"Provide a brief response about: {prompt}"}
        ]
        
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo", 
            messages=messages,
            max_tokens=300,  # Reduced from 500
            temperature=0.7,
        )
        
        return response['choices'][0]['message']['content']
    except Exception as e:
        return f"I apologize, but I encountered an error: {str(e)}. Could you please rephrase your question or make it more specific?"

# --- Assistant Section ---
def create_assistant_section(dataset):
    st.markdown("""
        <div style='background-color: #f8f9fa; padding: 1.5rem; border-radius: 10px; margin-bottom: 1rem;'>
            <h2 style='color: #1E1E1E; margin-top: 0;'>πŸ€– Car Shopping Assistant</h2>
            <p style='color: #666;'>Ask me anything about cars! For example: 'What's a good car under $30,000 with low mileage?'</p>
        </div>
    """, unsafe_allow_html=True)

    if "assistant_responses" not in st.session_state:
        st.session_state.assistant_responses = []

    prompt = st.text_input("Ask about car recommendations or pricing...", 
                           placeholder="Type your question here...")

    if prompt:
        try:
            response = generate_gpt_response(prompt, dataset)
            st.session_state.assistant_responses.append(response)
        except Exception as e:
            response = f"Sorry, I encountered an error: {str(e)}"
            st.session_state.assistant_responses.append(response)

        # Display the latest response
        st.write(response)

        # Optionally display previous responses
        if len(st.session_state.assistant_responses) > 1:
            st.markdown("### Previous Responses")
            for prev_response in st.session_state.assistant_responses[:-1]:
                st.markdown("---")
                st.write(prev_response)

    if st.button("Clear Chat"):
        st.session_state.assistant_responses = []
        st.experimental_rerun()
# --- Prediction Interface ---
def create_prediction_interface():
    with st.sidebar:
        st.markdown("""
            <div style='background-color: #FF4B4B; padding: 1rem; border-radius: 5px; margin-bottom: 2rem;'>
                <h2 style='color: white; margin: 0;'>Car Details</h2>
            </div>
        """, unsafe_allow_html=True)
        
        # Year slider
        year = st.slider("Year", min_value=1980, max_value=2024, value=2022)
        
        # Make selection
        make_options = sorted(original_data['Make'].dropna().unique())  # Correct casing for 'Make'
        make = st.selectbox("Make", options=make_options)  
        
        # Filter models based on selected make
        filtered_models = sorted(original_data[original_data['Make'] == make]['Model'].dropna().unique())  # Match 'Model' casing
        model_name = st.selectbox("Model", options=filtered_models if len(filtered_models) > 0 else ["No models available"])
        
        if model_name == "No models available":
            st.warning("No models are available for the selected make.")

        # Additional inputs
        condition = st.selectbox("Condition", ['new', 'like new', 'excellent', 'good', 'fair', 'salvage', 'parts only'])
        fuel = st.selectbox("Fuel Type", sorted(original_data['Fuel'].fillna('Unknown').unique()))  # Match casing for 'Fuel'
        odometer = st.number_input("Odometer (miles)", min_value=0, value=20000, format="%d", step=1000)
        title_status = st.selectbox("Title Status", sorted(original_data['Title_status'].fillna('Unknown').unique()))  # Match casing
        transmission = st.selectbox("Transmission", sorted(original_data['Transmission'].fillna('Unknown').unique()))
        drive = st.selectbox("Drive Type", sorted(original_data['Drive'].fillna('Unknown').unique()))
        size = st.selectbox("Size", sorted(original_data['Size'].fillna('Unknown').unique()))
        paint_color = st.selectbox("Paint Color", sorted(original_data['Paint_color'].fillna('Unknown').unique()))
        
        car_type = 'sedan'  # Default type
        
        # Prediction button
        predict_button = st.button("πŸ“Š Predict Price", use_container_width=True)

    return {
        'year': year,
        'make': make.strip(),  # Use correctly cased `make`
        'model': model_name if model_name != "No models available" else 'unknown',
        'condition': condition.lower().strip(),
        'fuel': fuel.lower().strip(),
        'odometer': odometer,
        'title_status': title_status.lower().strip(),
        'transmission': transmission.lower().strip(),
        'drive': drive.lower().strip(),
        'size': size.lower().strip(),
        'type': car_type.lower().strip(),
        'paint_color': paint_color.lower().strip()
    }, predict_button



def create_market_trends_plot_with_model(model, make, base_inputs, label_encoders, years_range=range(1980, 2025)):
    predictions = []
    
    for year in years_range:
        try:
            current_inputs = base_inputs.copy()
            current_inputs['year'] = float(year)
            age = 2024 - year
            
            # Base value calculation
            base_price = 30000  # Average new car price
            
            # Depreciation curve
            if age <= 1:
                value_factor = 0.85  # 15% first year depreciation
            elif age <= 5:
                value_factor = 0.85 * (0.90 ** (age - 1))  # 10% years 2-5
            else:
                value_factor = 0.85 * (0.90 ** 4) * (0.95 ** (age - 5))  # 5% thereafter
            
            price = base_price * value_factor
            predictions.append({"year": year, "predicted_price": max(price, 2000)})  # Floor of $2000
            
        except Exception as e:
            continue

    if not predictions:
        return None
    
    predictions_df = pd.DataFrame(predictions)
    fig, ax = plt.subplots(figsize=(12, 6))
    ax.plot(predictions_df["year"], predictions_df["predicted_price"], color="#FF4B4B", linewidth=2)
    ax.set_title(f"Average Car Value by Age")
    ax.set_xlabel("Year")
    ax.set_ylabel("Value ($)")
    ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f'${x:,.0f}'))
    plt.grid(True, alpha=0.3)
    
    return fig

def inspect_model_features(model):
    # Check feature names the model expects
    try:
        if hasattr(model, "feature_names_in_"):
            print("Model feature names:", model.feature_names_in_)
        else:
            print("Model does not have 'feature_names_in_' attribute.")
    except Exception as e:
        print(f"Error inspecting model features: {e}")

def predict_with_ranges(inputs, model, label_encoders):
    input_df = prepare_input(inputs, label_encoders)
    base_prediction = float(np.expm1(model.predict(input_df)[0]))
    
    brand_categories = create_brand_categories()
    make = inputs['make'].lower()
    year = inputs['year']
    condition = inputs['condition']
    odometer = inputs['odometer']
    age = 2024 - year
    
    # Find brand category and price range
    price_range = None
    for category, brands in brand_categories.items():
        if make in brands:
            price_range = brands[make]
            break
    if not price_range:
        price_range = (15000, 35000)  # Default range
    
    # Calculate adjustment factors
    mileage_factor = max(1 - (odometer / 200000) * 0.3, 0.7)
    age_factor = 0.85 ** min(age, 15)
    condition_factor = {
        'new': 1.0,
        'like new': 0.9,
        'excellent': 0.8,
        'good': 0.7,
        'fair': 0.5,
        'salvage': 0.3
    }.get(condition, 0.7)
    
    # Apply all factors
    min_price = price_range[0] * mileage_factor * age_factor * condition_factor
    max_price = price_range[1] * mileage_factor * age_factor * condition_factor
    predicted_price = base_prediction * mileage_factor * age_factor * condition_factor
    
    # Use uniform distribution instead of clamping
    final_prediction = np.random.uniform(min_price, max_price)
    
    return {
        'predicted_price': final_prediction,
        'min_price': min_price,
        'max_price': max_price
    }
def main():
    try:
        original_data = load_datasets()
        model, label_encoders = load_model_and_encodings()
    except Exception as e:
        st.error(f"Error loading data or models: {str(e)}")
        st.stop()

    # Create tabs
    tab1, tab2 = st.tabs(["Price Prediction", "Image Analysis"])

    with tab1:
        st.title("Car Price Prediction")
        
        # Create two columns
        col1, col2 = st.columns([2, 1])
        
        with col1:
            # Prediction interface code
            inputs, predict_button = create_prediction_interface()
            
            if predict_button:
                st.write(f"Analyzing {inputs['year']} {inputs['make'].title()} {inputs['model'].title()}...")
                prediction_results = predict_with_ranges(inputs, model, label_encoders)
                
                st.markdown(f"""
                    ### Price Analysis
                    - **Estimated Range**: ${prediction_results['min_price']:,.2f} - ${prediction_results['max_price']:,.2f}
                    - **Model Prediction**: ${prediction_results['predicted_price']:,.2f}
                """)

                # Generate and display the graph
                fig = create_market_trends_plot_with_model(model, inputs["make"], inputs, label_encoders)
                if fig:
                    st.pyplot(fig)
        
        with col2:
            # Add the chat assistant here
            create_assistant_section(original_data)

    with tab2:
        st.title("Car Image Analysis")
        
        # File uploader and camera input
        uploaded_file = st.file_uploader("Choose a car image", type=["jpg", "jpeg", "png"])
        camera_image = st.camera_input("Or take a picture of the car")

        # Process the image
        if uploaded_file is not None:
            image = Image.open(uploaded_file)
        elif camera_image is not None:
            image = Image.open(camera_image)
        else:
            image = None

        if image is not None:
            st.image(image, caption='Uploaded Image', use_container_width=True)
            
            # Classify the image
            with st.spinner('Analyzing image...'):
                car_classifications = classify_image(image)

            if car_classifications:
                top_prediction = car_classifications[0]['label']
                make_name, model_name = top_prediction.split(' ', 1)
                current_year = datetime.now().year

                # Display results
                col1, col2 = st.columns(2)
                col1.metric("Identified Make", make_name)
                col2.metric("Identified Model", model_name)

                # Get car overview
                overview = get_car_overview(make_name, model_name, current_year)
                if overview:
                    st.subheader("Car Overview")
                    st.write(overview)

                # Use the prediction model with the identified car
                st.subheader("Price Analysis for Identified Car")
                auto_inputs = {
                    'year': current_year,
                    'make': make_name.lower(),
                    'model': model_name.lower(),
                    'condition': 'good',  # Default values
                    'fuel': 'gas',
                    'odometer': 0,
                    'title_status': 'clean',
                    'transmission': 'automatic',
                    'drive': 'fwd',
                    'size': 'mid-size',
                    'type': 'sedan',
                    'paint_color': 'white'
                }

                # Get prediction for the identified car
                prediction_results = predict_with_ranges(auto_inputs, model, label_encoders)
                
                st.markdown(f"""
                    ### Estimated Price Range
                    - **Minimum**: ${prediction_results['min_price']:,.2f}
                    - **Maximum**: ${prediction_results['max_price']:,.2f}
                    - **Predicted**: ${prediction_results['predicted_price']:,.2f}
                """)

if __name__ == "__main__":
    main()