rahgadda commited on
Commit
8514027
·
verified ·
1 Parent(s): 63f8a54

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +184 -4
  2. install.sh +2 -0
  3. requirements.txt +7 -0
app.py CHANGED
@@ -1,4 +1,184 @@
1
- import streamlit as st
2
-
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask
2
+ from flask_restx import Api, Resource, fields
3
+ from werkzeug.datastructures import FileStorage
4
+ import pandas as pd
5
+ import numpy as np
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.preprocessing import OneHotEncoder
8
+ from sklearn.compose import ColumnTransformer
9
+ from sklearn.pipeline import Pipeline
10
+ from sklearn.impute import SimpleImputer
11
+ from sklearn.linear_model import LinearRegression
12
+ from sklearn.metrics import mean_squared_error, r2_score
13
+ import joblib
14
+ import streamlit as st
15
+ import pandas as pd
16
+ import requests
17
+ import threading
18
+ import json
19
+
20
+ app = Flask(__name__)
21
+ api = Api(app, version='1.0', title='Car Depreciation Model API',
22
+ description='API for creating and testing car depreciation models')
23
+
24
+ model_ns = api.namespace('model', description='Model operations')
25
+ predict_ns = api.namespace('predict', description='Prediction operations')
26
+
27
+ # Define the expected input for file upload
28
+ upload_parser = api.parser()
29
+ upload_parser.add_argument('file', location='files', type=FileStorage, required=True)
30
+
31
+ # Define the expected input for prediction
32
+ input_model = api.model('PredictionInput', {
33
+ 'Car_Model': fields.String(required=True, description='Car model'),
34
+ 'Car_Year': fields.Integer(required=True, description='Year of the car'),
35
+ 'Assessment_Year': fields.Integer(required=True, description='Assessment year'),
36
+ 'Starting_Asset_Value': fields.Float(required=True, description='Starting asset value'),
37
+ 'Book_Residual_Value': fields.Float(required=True, description='Book residual value'),
38
+ 'Market_Value': fields.Float(required=True, description='Market value')
39
+ })
40
+
41
+ # Global variable to store the model
42
+ global_model = None
43
+
44
+ @model_ns.route('/create')
45
+ @api.expect(upload_parser)
46
+ class ModelCreation(Resource):
47
+ @api.doc(description='Create a new model from CSV data')
48
+ @api.response(200, 'Model created successfully')
49
+ @api.response(400, 'Invalid input')
50
+ def post(self):
51
+ global global_model
52
+ args = upload_parser.parse_args()
53
+ uploaded_file = args['file']
54
+
55
+ if uploaded_file and uploaded_file.filename.endswith('.csv'):
56
+ # Read the CSV file
57
+ data = pd.read_csv(uploaded_file)
58
+
59
+ # Prepare features and target
60
+ X = data.drop('Depreciation_Percent', axis=1)
61
+ y = data['Depreciation_Percent']
62
+
63
+ # Split the data into training and testing sets
64
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
65
+
66
+ # Create preprocessing steps
67
+ numeric_features = ['Car_Year', 'Assessment_Year', 'Starting_Asset_Value', 'Book_Residual_Value', 'Market_Value']
68
+ categorical_features = ['Car_Model']
69
+
70
+ numeric_transformer = SimpleImputer(strategy='median')
71
+ categorical_transformer = Pipeline(steps=[
72
+ ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
73
+ ('onehot', OneHotEncoder(handle_unknown='ignore'))
74
+ ])
75
+
76
+ preprocessor = ColumnTransformer(
77
+ transformers=[
78
+ ('num', numeric_transformer, numeric_features),
79
+ ('cat', categorical_transformer, categorical_features)
80
+ ])
81
+
82
+ # Create a pipeline with preprocessor and model
83
+ model = Pipeline(steps=[('preprocessor', preprocessor),
84
+ ('regressor', LinearRegression())])
85
+
86
+ # Fit the model
87
+ model.fit(X_train, y_train)
88
+
89
+ # Make predictions on the test set
90
+ y_pred = model.predict(X_test)
91
+
92
+ # Evaluate the model
93
+ mse = mean_squared_error(y_test, y_pred)
94
+ r2 = r2_score(y_test, y_pred)
95
+
96
+ # Save the model
97
+ joblib.dump(model, 'output/car_depreciation_model.joblib')
98
+ global_model = model
99
+
100
+ return {
101
+ 'message': 'Model created and saved successfully',
102
+ 'mse': float(mse),
103
+ 'r2': float(r2)
104
+ }, 200
105
+
106
+ return {'error': 'Invalid file format'}, 400
107
+
108
+ @predict_ns.route('/')
109
+ class Prediction(Resource):
110
+ @api.expect(input_model)
111
+ @api.doc(description='Predict car depreciation')
112
+ @api.response(200, 'Successful prediction')
113
+ @api.response(400, 'Invalid input')
114
+ @api.response(404, 'Model not found')
115
+ def post(self):
116
+ global global_model
117
+ try:
118
+ if global_model is None:
119
+ try:
120
+ global_model = joblib.load('output/car_depreciation_model.joblib')
121
+ except FileNotFoundError:
122
+ return {'error': 'Model not found. Please create a model first.'}, 404
123
+
124
+ # Get JSON data from the request
125
+ data = api.payload
126
+
127
+ # Convert JSON to DataFrame
128
+ new_data_df = pd.DataFrame([data])
129
+
130
+ # Make prediction
131
+ prediction = global_model.predict(new_data_df)
132
+
133
+ return {
134
+ 'predicted_depreciation': float(prediction[0])
135
+ }, 200
136
+
137
+ except Exception as e:
138
+ return {'error': str(e)}, 400
139
+
140
+
141
+ API_URL = "http://localhost:5000"
142
+ st.title('Car Depreciation Predictor')
143
+
144
+ # Input form for prediction
145
+ st.header('Predict Depreciation')
146
+ car_model = st.text_input('Car Model',value="Honda Civic")
147
+ car_year = st.number_input('Car Year', value=2022)
148
+ assessment_year = st.number_input('Assessment Year', min_value=1, max_value=5, value=1)
149
+ starting_asset_value = st.number_input('Starting Asset Value', min_value=0, value=20000)
150
+ book_residual_value = st.number_input('Book Residual Value', min_value=0, value=18000)
151
+ market_value = st.number_input('Market Value', min_value=0, value=19000)
152
+
153
+ if st.button('Predict'):
154
+ input_data = {
155
+ 'Car_Model': car_model,
156
+ 'Car_Year': int(car_year),
157
+ 'Assessment_Year': int(assessment_year),
158
+ 'Starting_Asset_Value': float(starting_asset_value),
159
+ 'Book_Residual_Value': float(book_residual_value),
160
+ 'Market_Value': float(market_value)
161
+ }
162
+
163
+ response = requests.post(f'{API_URL}/predict/', json=input_data)
164
+ if response.status_code == 200:
165
+ prediction = response.json()['predicted_depreciation']
166
+ st.success(f'Predicted Depreciation: {prediction:.2f}%')
167
+ elif response.status_code == 404:
168
+ st.error('Model not found. Please create a model first.')
169
+ else:
170
+ st.error(f'Error making prediction: {response.json().get("error", "Unknown error")}')
171
+
172
+ if __name__ == '__main__':
173
+ try:
174
+ # Start Flask in a separate thread
175
+ threading.Thread(target=lambda: app.run(debug=False, use_reloader=False)).start()
176
+
177
+ # Run Streamlit
178
+ import streamlit.web.cli as stcli
179
+ import sys
180
+
181
+ sys.argv = ["streamlit", "run", __file__]
182
+ sys.exit(stcli.main())
183
+ except:
184
+ print("An exception occurred")
install.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pip install -r requirements.txt
2
+ python app.py
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ flask
2
+ flask-restx
3
+ Werkzeug
4
+ scikit-learn
5
+ pandas
6
+ numpy
7
+ joblib