Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,59 +1,14 @@
|
|
1 |
import streamlit as st
|
2 |
-
import pandas as pd
|
3 |
-
import openai
|
4 |
-
import joblib
|
5 |
from PIL import Image
|
6 |
-
import matplotlib.pyplot as plt
|
7 |
-
import numpy as np
|
8 |
-
from huggingface_hub import hf_hub_download
|
9 |
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
10 |
import torch
|
11 |
from datetime import datetime
|
12 |
-
|
13 |
-
|
14 |
-
# Initialize label encoders for categorical variables
|
15 |
-
make_encoder = LabelEncoder()
|
16 |
-
model_encoder = LabelEncoder()
|
17 |
-
condition_encoder = LabelEncoder()
|
18 |
-
fuel_encoder = LabelEncoder()
|
19 |
-
title_status_encoder = LabelEncoder()
|
20 |
-
transmission_encoder = LabelEncoder()
|
21 |
-
drive_encoder = LabelEncoder()
|
22 |
-
size_encoder = LabelEncoder()
|
23 |
-
type_encoder = LabelEncoder()
|
24 |
-
paint_color_encoder = LabelEncoder()
|
25 |
-
|
26 |
-
# Fit the encoders with some sample data (you may want to use your actual dataset for this)
|
27 |
-
sample_data = {
|
28 |
-
'Make': ['Toyota', 'Honda', 'Ford', 'Chevrolet', 'Nissan'],
|
29 |
-
'model': ['Camry', 'Civic', 'F-150', 'Silverado', 'Altima'],
|
30 |
-
'condition': ['Used', 'New', 'Excellent', 'Good', 'Fair'],
|
31 |
-
'fuel': ['Gasoline', 'Diesel', 'Electric', 'Hybrid', 'CNG'],
|
32 |
-
'title_status': ['Clean', 'Salvage', 'Rebuilt', 'Lien', 'Missing'],
|
33 |
-
'transmission': ['Automatic', 'Manual', 'CVT', 'DCT', 'AMT'],
|
34 |
-
'drive': ['Fwd', 'Rwd', 'Awd', '4wd', 'Other'],
|
35 |
-
'size': ['Mid-Size', 'Full-Size', 'Compact', 'Sub-Compact', 'Crossover'],
|
36 |
-
'type': ['Sedan', 'SUV', 'Truck', 'Coupe', 'Van'],
|
37 |
-
'paint_color': ['White', 'Black', 'Silver', 'Red', 'Blue']
|
38 |
-
}
|
39 |
-
|
40 |
-
for feature, encoder in [('Make', make_encoder), ('model', model_encoder), ('condition', condition_encoder),
|
41 |
-
('fuel', fuel_encoder), ('title_status', title_status_encoder),
|
42 |
-
('transmission', transmission_encoder), ('drive', drive_encoder),
|
43 |
-
('size', size_encoder), ('type', type_encoder), ('paint_color', paint_color_encoder)]:
|
44 |
-
encoder.fit(sample_data[feature])
|
45 |
-
|
46 |
-
# Dataset loading function with caching
|
47 |
-
@st.cache_data
|
48 |
-
def load_datasets():
|
49 |
-
try:
|
50 |
-
with st.spinner('Loading dataset...'):
|
51 |
-
original_data = pd.read_csv('CTP_Model1.csv', low_memory=False)
|
52 |
-
return original_data
|
53 |
-
except Exception as e:
|
54 |
-
st.error(f"Error loading dataset: {str(e)}")
|
55 |
-
raise e
|
56 |
|
|
|
|
|
|
|
|
|
57 |
def classify_image(image):
|
58 |
try:
|
59 |
# Load the model and feature extractor
|
@@ -83,6 +38,7 @@ def classify_image(image):
|
|
83 |
st.error(f"Classification error: {e}")
|
84 |
return None
|
85 |
|
|
|
86 |
def get_car_overview(brand, model, year):
|
87 |
prompt = f"Provide an overview of the following car:\nYear: {year}\nMake: {brand}\nModel: {model}\n"
|
88 |
response = openai.ChatCompletion.create(
|
@@ -91,61 +47,9 @@ def get_car_overview(brand, model, year):
|
|
91 |
)
|
92 |
return response.choices[0].message['content']
|
93 |
|
94 |
-
def load_model_and_encodings():
|
95 |
-
try:
|
96 |
-
with st.spinner('Loading model...'):
|
97 |
-
model_content = hf_hub_download(repo_id="EdBoy2202/car_prediction_model", filename="car_price_modelv3.pkl")
|
98 |
-
model = joblib.load(model_content)
|
99 |
-
|
100 |
-
# Debug: Print the expected feature names
|
101 |
-
st.write("Model loaded successfully.")
|
102 |
-
st.write("Expected feature names:")
|
103 |
-
st.write(model.feature_names_in_) # Display the feature names
|
104 |
-
return model
|
105 |
-
except Exception as e:
|
106 |
-
st.error(f"Error loading model: {str(e)}")
|
107 |
-
raise e
|
108 |
-
|
109 |
-
def predict_price(model, brand, model_name, year):
|
110 |
-
# Create a dictionary with default values for the specified categories
|
111 |
-
input_data = {
|
112 |
-
'year': year,
|
113 |
-
'odometer': year * 12000, # Estimate based on year and average annual mileage
|
114 |
-
'age': datetime.now().year - year,
|
115 |
-
'age_squared': (datetime.now().year - year) ** 2,
|
116 |
-
'mileage_per_year': 12000,
|
117 |
-
'Make': make_encoder.transform([brand])[0],
|
118 |
-
'model': model_encoder.transform([model_name])[0],
|
119 |
-
'condition': condition_encoder.transform(['Used'])[0],
|
120 |
-
'fuel': fuel_encoder.transform(['Gasoline'])[0],
|
121 |
-
'title_status': title_status_encoder.transform(['Clean'])[0],
|
122 |
-
'transmission': transmission_encoder.transform(['Automatic'])[0],
|
123 |
-
'drive': drive_encoder.transform(['Fwd'])[0],
|
124 |
-
'size': size_encoder.transform(['Mid-Size'])[0],
|
125 |
-
'type': type_encoder.transform(['Sedan'])[0],
|
126 |
-
'paint_color': paint_color_encoder.transform(['White'])[0]
|
127 |
-
}
|
128 |
-
|
129 |
-
# Prepare the input for the model
|
130 |
-
input_df = pd.DataFrame([input_data])
|
131 |
-
|
132 |
-
# Ensure all expected columns are present and in the correct order
|
133 |
-
expected_columns = ['year', 'odometer', 'age', 'age_squared', 'mileage_per_year', 'Make', 'model', 'condition', 'fuel', 'title_status', 'transmission', 'drive', 'size', 'type', 'paint_color']
|
134 |
-
input_df = input_df[expected_columns]
|
135 |
-
|
136 |
-
# Predict the price
|
137 |
-
predicted_price = model.predict(input_df)
|
138 |
-
return predicted_price[0]
|
139 |
-
|
140 |
# Streamlit App
|
141 |
st.title("Auto Appraise")
|
142 |
-
st.write("Upload a car image or take a picture to get its brand, model,
|
143 |
-
|
144 |
-
# Load model and encodings
|
145 |
-
model = load_model_and_encodings()
|
146 |
-
|
147 |
-
# Initialize OpenAI API key
|
148 |
-
openai.api_key = st.secrets["GPT_TOKEN"]
|
149 |
|
150 |
# Get the session state
|
151 |
if 'image' not in st.session_state:
|
@@ -201,28 +105,7 @@ if st.session_state.image is not None:
|
|
201 |
st.write("Car Overview:")
|
202 |
st.write(overview)
|
203 |
|
204 |
-
# Interactive Price Prediction
|
205 |
-
st.subheader("Price Prediction Over Time")
|
206 |
-
selected_years = st.slider("Select range of years for price prediction",
|
207 |
-
min_value=2000, max_value=2023, value=(2010, 2023))
|
208 |
-
|
209 |
-
years = np.arange(selected_years[0], selected_years[1] + 1)
|
210 |
-
predicted_prices = []
|
211 |
-
|
212 |
-
for year in years:
|
213 |
-
price = predict_price(model, make_name, model_name, year)
|
214 |
-
predicted_prices.append(price)
|
215 |
-
|
216 |
-
# Plotting the results
|
217 |
-
plt.figure(figsize=(10, 5))
|
218 |
-
plt.plot(years, predicted_prices, marker='o')
|
219 |
-
plt.title(f"Predicted Price of {make_name} {model_name} Over Time")
|
220 |
-
plt.xlabel("Year")
|
221 |
-
plt.ylabel("Predicted Price ($)")
|
222 |
-
plt.grid()
|
223 |
-
st.pyplot(plt)
|
224 |
-
|
225 |
else:
|
226 |
st.error("Could not classify the image. Please try again with a different image.")
|
227 |
else:
|
228 |
-
st.write("Please upload an image or take a picture to proceed.")
|
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
2 |
from PIL import Image
|
|
|
|
|
|
|
3 |
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
4 |
import torch
|
5 |
from datetime import datetime
|
6 |
+
import openai
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
+
# Initialize OpenAI API key
|
9 |
+
openai.api_key = st.secrets["GPT_TOKEN"]
|
10 |
+
|
11 |
+
# Function to classify the car image using pre-trained model
|
12 |
def classify_image(image):
|
13 |
try:
|
14 |
# Load the model and feature extractor
|
|
|
38 |
st.error(f"Classification error: {e}")
|
39 |
return None
|
40 |
|
41 |
+
# Function to get an overview of the car using OpenAI
|
42 |
def get_car_overview(brand, model, year):
|
43 |
prompt = f"Provide an overview of the following car:\nYear: {year}\nMake: {brand}\nModel: {model}\n"
|
44 |
response = openai.ChatCompletion.create(
|
|
|
47 |
)
|
48 |
return response.choices[0].message['content']
|
49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
# Streamlit App
|
51 |
st.title("Auto Appraise")
|
52 |
+
st.write("Upload a car image or take a picture to get its brand, model, and overview!")
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
# Get the session state
|
55 |
if 'image' not in st.session_state:
|
|
|
105 |
st.write("Car Overview:")
|
106 |
st.write(overview)
|
107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
else:
|
109 |
st.error("Could not classify the image. Please try again with a different image.")
|
110 |
else:
|
111 |
+
st.write("Please upload an image or take a picture to proceed.")
|