EdBoy2202 commited on
Commit
ecae6dc
·
verified ·
1 Parent(s): e99507b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -75
app.py CHANGED
@@ -10,6 +10,21 @@ import numpy as np
10
  from sklearn.preprocessing import LabelEncoder
11
  from huggingface_hub import hf_hub_download
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  # Function definitions
14
 
15
  def load_image(image_file):
@@ -33,29 +48,14 @@ def classify_image(image):
33
  st.error("Image classification failed. Please try again.")
34
  return None
35
 
36
- @st.cache_data
37
- def load_datasets():
38
- try:
39
- with st.spinner('Loading dataset...'):
40
- # Use BytesIO to read the CSV content
41
- original_data = pd.read_csv('CTP_Model1.csv', low_memory=False)
42
-
43
-
44
- # Ensure column names match the model's expectations
45
- original_data.columns = original_data.columns.str.strip().str.capitalize()
46
- return original_data
47
- except Exception as e:
48
- st.error(f"Error loading dataset: {str(e)}")
49
- raise e
50
-
51
  def find_closest_match(df, brand, model):
52
- match = df[(df['make'].str.contains(brand, case=False)) & (df['model'].str.contains(model, case=False))]
53
  if not match.empty:
54
  return match.iloc[0]
55
  return None
56
 
57
  def get_car_overview(car_data):
58
- prompt = f"Provide an overview of the following car:\nYear: {car_data['year']}\nMake: {car_data['make']}\nModel: {car_data['model']}\nTrim: {car_data['trim']}\nPrice: ${car_data['price']}\nCondition: {car_data['condition']}\n"
59
  response = openai.ChatCompletion.create(
60
  model="gpt-3.5-turbo",
61
  messages=[{"role": "user", "content": prompt}]
@@ -68,11 +68,12 @@ def load_model_and_encodings():
68
  model_content = hf_hub_download(repo_id="EdBoy2202/car_prediction_model", filename="car_price_modelv3.pkl")
69
  model = joblib.load(model_content)
70
 
71
- original_data = load_datasets() # Ensure this function loads your CSV data
 
72
 
73
  label_encoders = {}
74
- categorical_features = ['Make', 'model', 'condition', 'fuel', 'title_status',
75
- 'transmission', 'drive', 'size', 'type', 'paint_color']
76
 
77
  for feature in categorical_features:
78
  if feature in original_data.columns:
@@ -103,9 +104,6 @@ def predict_price(model, encoders, user_input):
103
  st.title("Auto Appraise")
104
  st.write("Capture a car image using your camera or upload an image to get its brand, model, overview, and expected price!")
105
 
106
- # Load the CSV file
107
- df = pd.read_csv('CTP_Model1.csv')
108
-
109
  # Load model and encoders
110
  model, label_encoders = load_model_and_encodings()
111
 
@@ -118,62 +116,66 @@ camera_image = st.camera_input("Take a picture of the car!")
118
 
119
  if camera_image is not None:
120
  image = load_image(camera_image)
121
- st.image(image, caption='Captured Image.', use_column_width=True)
122
 
123
  # Classify the car image
124
  car_info = classify_image(image)
125
  if car_info:
126
- brand = car_info['brand'] # Adjust according to response structure
127
- model_name = car_info['model']
128
- st.write(f"Identified Car: {brand} {model_name}")
129
-
130
- # Find the closest match in the CSV
131
- match = find_closest_match(df, brand, model_name)
132
- if match is not None:
133
- st.write("Closest Match Found:")
134
- st.write(match)
135
-
136
- # Get additional information using GPT-3.5-turbo
137
- overview = get_car_overview(match)
138
- st.write("Car Overview:")
139
- st.write(overview)
140
-
141
- # Interactive Price Prediction
142
- st.subheader("Price Prediction Over Time")
143
- selected_years = st.slider("Select range of years for price prediction",
144
- min_value=2000, max_value=2023, value=(2010, 2023))
145
-
146
- years = np.arange(selected_years[0], selected_years[1] + 1)
147
- predicted_prices = []
148
-
149
- for year in years:
150
- user_input = {
151
- 'Make': brand,
152
- 'model': model_name,
153
- 'condition': match['condition'],
154
- 'fuel': match['fuel'],
155
- 'title_status': match['title_status'],
156
- 'transmission': match['transmission'],
157
- 'drive': match['drive'],
158
- 'size': match['size'],
159
- 'type': match['type'],
160
- 'paint_color': match['paint_color'],
161
- 'year': year
162
- }
163
-
164
- price = predict_price(model, label_encoders, user_input)
165
- predicted_prices.append(price)
166
-
167
- # Plotting the results
168
- plt.figure(figsize=(10, 5))
169
- plt.plot(years, predicted_prices, marker='o')
170
- plt.title(f"Predicted Price of {brand} {model_name} Over Time")
171
- plt.xlabel("Year")
172
- plt.ylabel("Predicted Price ($)")
173
- plt.grid()
174
- st.pyplot(plt)
175
-
 
 
 
 
176
  else:
177
- st.write("No match found in the database.")
178
  else:
179
  st.write("Please take a picture of the car to proceed.")
 
10
  from sklearn.preprocessing import LabelEncoder
11
  from huggingface_hub import hf_hub_download
12
 
13
+ # Dataset loading function with caching
14
+ @st.cache_data
15
+ def load_datasets():
16
+ try:
17
+ with st.spinner('Loading dataset...'):
18
+ # Load the CSV content
19
+ original_data = pd.read_csv('CTP_Model1.csv', low_memory=False)
20
+
21
+ # Ensure column names match the model's expectations
22
+ original_data.columns = original_data.columns.str.strip().str.capitalize()
23
+ return original_data
24
+ except Exception as e:
25
+ st.error(f"Error loading dataset: {str(e)}")
26
+ raise e
27
+
28
  # Function definitions
29
 
30
  def load_image(image_file):
 
48
  st.error("Image classification failed. Please try again.")
49
  return None
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def find_closest_match(df, brand, model):
52
+ match = df[(df['Make'].str.contains(brand, case=False)) & (df['Model'].str.contains(model, case=False))]
53
  if not match.empty:
54
  return match.iloc[0]
55
  return None
56
 
57
  def get_car_overview(car_data):
58
+ prompt = f"Provide an overview of the following car:\nYear: {car_data['Year']}\nMake: {car_data['Make']}\nModel: {car_data['Model']}\nTrim: {car_data['Trim']}\nPrice: ${car_data['Price']}\nCondition: {car_data['Condition']}\n"
59
  response = openai.ChatCompletion.create(
60
  model="gpt-3.5-turbo",
61
  messages=[{"role": "user", "content": prompt}]
 
68
  model_content = hf_hub_download(repo_id="EdBoy2202/car_prediction_model", filename="car_price_modelv3.pkl")
69
  model = joblib.load(model_content)
70
 
71
+ # Load datasets
72
+ original_data = load_datasets()
73
 
74
  label_encoders = {}
75
+ categorical_features = ['Make', 'Model', 'Condition', 'Fuel', 'Title_status',
76
+ 'Transmission', 'Drive', 'Size', 'Type', 'Paint_color']
77
 
78
  for feature in categorical_features:
79
  if feature in original_data.columns:
 
104
  st.title("Auto Appraise")
105
  st.write("Capture a car image using your camera or upload an image to get its brand, model, overview, and expected price!")
106
 
 
 
 
107
  # Load model and encoders
108
  model, label_encoders = load_model_and_encodings()
109
 
 
116
 
117
  if camera_image is not None:
118
  image = load_image(camera_image)
119
+ st.image(image, caption='Captured Image.', use_container_width=True) # Updated parameter
120
 
121
  # Classify the car image
122
  car_info = classify_image(image)
123
  if car_info:
124
+ brand = car_info.get('brand', None) # Adjust according to the response structure
125
+ model_name = car_info.get('model', None)
126
+
127
+ if brand and model_name:
128
+ st.write(f"Identified Car: {brand} {model_name}")
129
+
130
+ # Find the closest match in the CSV
131
+ match = find_closest_match(df, brand, model_name)
132
+ if match is not None:
133
+ st.write("Closest Match Found:")
134
+ st.write(match)
135
+
136
+ # Get additional information using GPT-3.5-turbo
137
+ overview = get_car_overview(match)
138
+ st.write("Car Overview:")
139
+ st.write(overview)
140
+
141
+ # Interactive Price Prediction
142
+ st.subheader("Price Prediction Over Time")
143
+ selected_years = st.slider("Select range of years for price prediction",
144
+ min_value=2000, max_value=2023, value=(2010, 2023))
145
+
146
+ years = np.arange(selected_years[0], selected_years[1] + 1)
147
+ predicted_prices = []
148
+
149
+ for year in years:
150
+ user_input = {
151
+ 'Make': brand,
152
+ 'Model': model_name,
153
+ 'Condition': match['Condition'],
154
+ 'Fuel': match['Fuel'],
155
+ 'Title_status': match['Title_status'],
156
+ 'Transmission': match['Transmission'],
157
+ 'Drive': match['Drive'],
158
+ 'Size': match['Size'],
159
+ 'Type': match['Type'],
160
+ 'Paint_color': match['Paint_color'],
161
+ 'Year': year
162
+ }
163
+
164
+ price = predict_price(model, label_encoders, user_input)
165
+ predicted_prices.append(price)
166
+
167
+ # Plotting the results
168
+ plt.figure(figsize=(10, 5))
169
+ plt.plot(years, predicted_prices, marker='o')
170
+ plt.title(f"Predicted Price of {brand} {model_name} Over Time")
171
+ plt.xlabel("Year")
172
+ plt.ylabel("Predicted Price ($)")
173
+ plt.grid()
174
+ st.pyplot(plt)
175
+
176
+ else:
177
+ st.write("No match found in the database.")
178
  else:
179
+ st.error("Could not identify the brand or model. Please try again.")
180
  else:
181
  st.write("Please take a picture of the car to proceed.")