kariukireuben commited on
Commit
b3384bd
·
verified ·
1 Parent(s): 02fbe4f

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +66 -56
app.py CHANGED
@@ -12,7 +12,16 @@ from datetime import datetime
12
  def load_model():
13
  # Use the path where the model was saved in the notebook
14
  saved_model_path = "deployment_files/car_prediction_model_v1_0.joblib"
15
- return joblib.load(saved_model_path)
 
 
 
 
 
 
 
 
 
16
 
17
  model = load_model()
18
 
@@ -40,37 +49,37 @@ def main():
40
  # -------------------------------
41
  # User Inputs
42
  # -------------------------------
43
- manufacture_year = st.number_input(
44
  "Year of Manufacture",
45
  min_value=1990, max_value=datetime.now().year, value=2015,
46
  help="Enter the year the car was made"
47
  )
48
 
49
- kms_driven = st.number_input(
50
  "Total Kilometers Driven",
51
  min_value=0, value=50000, step=1000,
52
  help="Enter total kilometers driven"
53
  )
54
 
55
- owner = st.number_input(
56
  "Number of Previous Owners",
57
  min_value=0, max_value=10, value=0, step=1,
58
  help="Enter the number of previous owners"
59
  )
60
 
61
- fuel_type = st.selectbox(
62
  "Fuel Type",
63
  ["Petrol", "Diesel", "CNG"],
64
  help="Select the fuel type"
65
  )
66
 
67
- seller_type = st.selectbox(
68
  "Seller Type",
69
  ["Dealer", "Individual"],
70
  help="Select the seller type"
71
  )
72
 
73
- transmission = st.selectbox(
74
  "Transmission Type",
75
  ["Manual", "Automatic"],
76
  help="Select the transmission type"
@@ -80,52 +89,53 @@ def main():
80
  # Prediction Logic
81
  # -------------------------------
82
  if st.button("Predict Selling Price"):
83
- # Create a DataFrame from user inputs
84
- # Ensure column order matches the training data used for the model
85
- # The model was trained on: ['Year', 'Kms_Driven', 'Owner', 'Fuel_Type_Diesel', 'Fuel_Type_Petrol', 'Seller_Type_Individual', 'Transmission_Manual']
86
-
87
- # Calculate Car Age
88
- car_age = datetime.now().year - manufacture_year
89
-
90
- input_data = pd.DataFrame({
91
- 'Year': [car_age], # Use calculated car age
92
- 'Kms_Driven': [kms_driven],
93
- 'Owner': [owner],
94
- # One-hot encode Fuel_Type
95
- 'Fuel_Type_Diesel': [1 if fuel_type == 'Diesel' else 0],
96
- 'Fuel_Type_Petrol': [1 if fuel_type == 'Petrol' else 0],
97
- # One-hot encode Seller_Type
98
- 'Seller_Type_Individual': [1 if seller_type == 'Individual' else 0],
99
- # One-hot encode Transmission
100
- 'Transmission_Manual': [1 if transmission == 'Manual' else 0]
101
- })
102
-
103
-
104
- # Ensure numerical columns have correct types
105
- numerical_cols = ['Year', 'Kms_Driven', 'Owner']
106
- for col in numerical_cols:
107
- input_data[col] = pd.to_numeric(input_data[col], errors='coerce')
108
-
109
- # Ensure one-hot encoded columns have correct types (int)
110
- encoded_cols = ['Fuel_Type_Diesel', 'Fuel_Type_Petrol', 'Seller_Type_Individual', 'Transmission_Manual']
111
- for col in encoded_cols:
112
- input_data[col] = input_data[col].astype(int)
113
-
114
-
115
- try:
116
- # Make prediction
117
- predicted_price = model.predict(input_data)[0]
118
-
119
- # Display prediction
120
- st.success(f"Predicted Selling Price: **${predicted_price:,.2f}**")
121
-
122
- except Exception as e:
123
- st.error(f"An error occurred during prediction: {e}")
124
- st.write("Please check your input values.")
125
-
126
-
127
- # -------------------------------
128
- # Run the App
129
- # -------------------------------
130
- if __name__ == "__main__":
131
- main()
 
 
12
  def load_model():
13
  # Use the path where the model was saved in the notebook
14
  saved_model_path = "deployment_files/car_prediction_model_v1_0.joblib"
15
+ try:
16
+ model = joblib.load(saved_model_path)
17
+ return model
18
+ except FileNotFoundError:
19
+ st.error(f"Model file not found at {saved_model_path}. Please ensure the model is saved correctly.")
20
+ return None
21
+ except Exception as e:
22
+ st.error(f"An error occurred while loading the model: {e}")
23
+ return None
24
+
25
 
26
  model = load_model()
27
 
 
49
  # -------------------------------
50
  # User Inputs
51
  # -------------------------------
52
+ manufacture_year_input = st.number_input(
53
  "Year of Manufacture",
54
  min_value=1990, max_value=datetime.now().year, value=2015,
55
  help="Enter the year the car was made"
56
  )
57
 
58
+ kms_driven_input = st.number_input(
59
  "Total Kilometers Driven",
60
  min_value=0, value=50000, step=1000,
61
  help="Enter total kilometers driven"
62
  )
63
 
64
+ owner_input = st.number_input(
65
  "Number of Previous Owners",
66
  min_value=0, max_value=10, value=0, step=1,
67
  help="Enter the number of previous owners"
68
  )
69
 
70
+ fuel_type_input = st.selectbox(
71
  "Fuel Type",
72
  ["Petrol", "Diesel", "CNG"],
73
  help="Select the fuel type"
74
  )
75
 
76
+ seller_type_input = st.selectbox(
77
  "Seller Type",
78
  ["Dealer", "Individual"],
79
  help="Select the seller type"
80
  )
81
 
82
+ transmission_input = st.selectbox(
83
  "Transmission Type",
84
  ["Manual", "Automatic"],
85
  help="Select the transmission type"
 
89
  # Prediction Logic
90
  # -------------------------------
91
  if st.button("Predict Selling Price"):
92
+ if model is not None:
93
+ # Create a DataFrame from user inputs
94
+ # Ensure column order matches the training data used for the model
95
+ # The model was trained on: ['Year', 'Kms_Driven', 'Owner', 'Fuel_Type_Diesel', 'Fuel_Type_Petrol', 'Seller_Type_Individual', 'Transmission_Manual']
96
+
97
+ # Calculate Car Age
98
+ current_year = datetime.now().year
99
+ car_age = current_year - manufacture_year_input
100
+
101
+ input_data = pd.DataFrame({
102
+ 'Year': [car_age], # Use calculated car age
103
+ 'Kms_Driven': [kms_driven_input],
104
+ 'Owner': [owner_input],
105
+ # One-hot encode Fuel_Type
106
+ 'Fuel_Type_Diesel': [1 if fuel_type_input == 'Diesel' else 0],
107
+ 'Fuel_Type_Petrol': [1 if fuel_type_input == 'Petrol' else 0],
108
+ # One-hot encode Seller_Type
109
+ 'Seller_Type_Individual': [1 if seller_type_input == 'Individual' else 0],
110
+ # One-hot encode Transmission
111
+ 'Transmission_Manual': [1 if transmission_input == 'Manual' else 0]
112
+ })
113
+
114
+ # Ensure numerical columns have correct types and check for NaNs
115
+ numerical_cols = ['Year', 'Kms_Driven', 'Owner']
116
+ for col in numerical_cols:
117
+ input_data[col] = pd.to_numeric(input_data[col], errors='coerce')
118
+
119
+ if input_data[numerical_cols].isnull().any().any():
120
+ st.error("Invalid input detected for numerical fields. Please check your values.")
121
+ return # Stop execution if invalid input is found
122
+
123
+
124
+ # Ensure one-hot encoded columns have correct types (int)
125
+ encoded_cols = ['Fuel_Type_Diesel', 'Fuel_Type_Petrol', 'Seller_Type_Individual', 'Transmission_Manual']
126
+ for col in encoded_cols:
127
+ input_data[col] = input_data[col].astype(int)
128
+
129
+
130
+ try:
131
+ # Make prediction
132
+ predicted_price = model.predict(input_data)[0]
133
+
134
+ # Display prediction
135
+ st.success(f"Predicted Selling Price: **${predicted_price:,.2f}**")
136
+
137
+ except Exception as e:
138
+ st.error(f"An error occurred during prediction: {e}")
139
+ st.write("Please check your input values and ensure the model is loaded correctly.")
140
+ else:
141
+ st.warning("Model not loaded. Please check the model file path and try again.")