-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
207 lines (166 loc) · 7.1 KB
/
app.py
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
from flask import Flask, request, send_file, abort, render_template
from wsgiref import simple_server
from insurance.util.util import read_yaml_file, write_yaml_file
from matplotlib.style import context
from insurance.logger import logging, get_log_dataframe
from insurance.exception import InsuranceException
from insurance.entity.predictor import InsurancePredictor, InsuranceData
from insurance.constant import CONFIG_DIR, get_current_time_stamp
from insurance.config.configuration import Configuartion
from insurance.pipeline.pipeline import Pipeline
import os, sys, pip, json
ROOT_DIR = os.getcwd()
LOG_FOLDER_NAME = "logs"
PIPELINE_FOLDER_NAME = "insurance"
SAVED_MODELS_DIR_NAME = "saved_models"
MODEL_CONFIG_FILE_PATH = os.path.join(ROOT_DIR, CONFIG_DIR, "model.yaml")
LOG_DIR = os.path.join(ROOT_DIR, LOG_FOLDER_NAME)
PIPELINE_DIR = os.path.join(ROOT_DIR, PIPELINE_FOLDER_NAME)
MODEL_DIR = os.path.join(ROOT_DIR, SAVED_MODELS_DIR_NAME)
INSURANCE_DATA_KEY = "insurance_data"
EXPENSES_VALUE_KEY = "expenses"
app = Flask(__name__)
@app.route('/artifact', defaults={'req_path': 'insurance'})
@app.route('/artifact/<path:req_path>')
def render_artifact_dir(req_path):
os.makedirs("insurance", exist_ok=True)
# Joining the base and the requested path
print(f"req_path: {req_path}")
abs_path = os.path.join(req_path)
print(abs_path)
# Return 404 if path doesn't exist
if not os.path.exists(abs_path):
return abort(404)
# Check if path is a file and serve
if os.path.isfile(abs_path):
if ".html" in abs_path:
with open(abs_path, "r", encoding="utf-8") as file:
content = ''
for line in file.readlines():
content = f"{content}{line}"
return content
return send_file(abs_path)
# Show directory contents
files = {os.path.join(abs_path, file_name): file_name for file_name in os.listdir(abs_path) if
"artifact" in os.path.join(abs_path, file_name)}
result = {
"files": files,
"parent_folder": os.path.dirname(abs_path),
"parent_label": abs_path}
return render_template('files.html', result=result)
@app.route('/', methods=['GET', 'POST'])
def index():
try:
return render_template('index.html')
except Exception as e:
return str(e)
@app.route('/view_experiment_hist', methods=['GET', 'POST'])
def view_experiment_history():
experiment_df = Pipeline.get_experiments_status()
context = {
"experiment": experiment_df.to_html(classes='table table-striped col-12')
}
return render_template('experiment_history.html', context=context)
@app.route('/train', methods=['GET', 'POST'])
def train():
message = ""
pipeline = Pipeline(config=Configuartion(current_time_stamp=get_current_time_stamp()))
if not Pipeline.experiment.running_status:
message = "Training started."
pipeline.start()
else:
message = "Training is already in progress."
context = {
"experiment": pipeline.get_experiments_status().to_html(classes='table table-striped col-12'),
"message": message
}
return render_template('train.html', context=context)
@app.route('/predict', methods=['GET', 'POST'])
def predict():
context = {
INSURANCE_DATA_KEY: None,
EXPENSES_VALUE_KEY: None
}
if request.method == 'POST':
age = int(request.form['age'])
sex = request.form['sex']
bmi = float(request.form['bmi'])
children = int(request.form['children'])
smoker = request.form['smoker']
region = request.form['region']
insurance_data = InsuranceData(age=age,
sex=sex,
bmi=bmi,
children=children,
smoker=smoker,
region=region)
insurance_df = insurance_data.get_insurance_input_data_frame()
insurance_predictor = InsurancePredictor(model_dir=MODEL_DIR)
expenses = insurance_predictor.predict(X=insurance_df)
context = {
INSURANCE_DATA_KEY: insurance_data.get_insurance_data_as_dict(),
EXPENSES_VALUE_KEY: expenses,}
return render_template('predict.html', context=context)
return render_template("predict.html", context=context)
@app.route('/saved_models', defaults={'req_path': 'saved_models'})
@app.route('/saved_models/<path:req_path>')
def saved_models_dir(req_path):
os.makedirs("saved_models", exist_ok=True)
# Joining the base and the requested path
print(f"req_path: {req_path}")
abs_path = os.path.join(req_path)
print(abs_path)
# Return 404 if path doesn't exist
if not os.path.exists(abs_path):
return abort(404)
# Check if path is a file and serve
if os.path.isfile(abs_path):
return send_file(abs_path)
# Show directory contents
files = {os.path.join(abs_path, file): file for file in os.listdir(abs_path)}
result = {
"files": files,
"parent_folder": os.path.dirname(abs_path),
"parent_label": abs_path
}
return render_template('saved_models_files.html', result=result)
@app.route("/update_model_config", methods=['GET', 'POST'])
def update_model_config():
try:
if request.method == 'POST':
model_config = request.form['new_model_config']
model_config = model_config.replace("'", '"')
print(model_config)
model_config = json.loads(model_config)
write_yaml_file(file_path=MODEL_CONFIG_FILE_PATH, data=model_config)
model_config = read_yaml_file(file_path=MODEL_CONFIG_FILE_PATH)
return render_template('update_model.html', result={"model_config": model_config})
except Exception as e:
logging.exception(e)
return str(e)
@app.route(f'/logs', defaults={'req_path': f'{LOG_FOLDER_NAME}'})
@app.route(f'/{LOG_FOLDER_NAME}/<path:req_path>')
def render_log_dir(req_path):
os.makedirs(LOG_FOLDER_NAME, exist_ok=True)
# Joining the base and the requested path
logging.info(f"req_path: {req_path}")
abs_path = os.path.join(req_path)
print(abs_path)
# Return 404 if path doesn't exist
if not os.path.exists(abs_path):
return abort(404)
# Check if path is a file and serve
if os.path.isfile(abs_path):
log_df = get_log_dataframe(abs_path)
context = {"log": log_df.to_html(classes="table-striped", index=False)}
return render_template('log.html', context=context)
# Show directory contents
files = {os.path.join(abs_path, file): file for file in os.listdir(abs_path)}
result = {
"files": files,
"parent_folder": os.path.dirname(abs_path),
"parent_label": abs_path
}
return render_template('log_files.html', result=result)
if __name__ == "__main__":
app.run(host='127.0.0.1', port=8000, debug=True)