-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
210 lines (171 loc) · 6.87 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
208
209
210
from flask import Flask, request
import sys
import pip
from banking.util.util import read_yaml_file, write_yaml_file
from matplotlib.style import context
from banking.logger import logging
from banking.exception import BankingException
import os, sys
import json
from banking.config.configuration import Configuartion
from banking.constant import CONFIG_DIR, get_current_time_stamp
from banking.pipeline.pipeline import Pipeline
from banking.entity.banking_predictor import BankingPredictor, BankingData
from flask import send_file, abort, render_template
pipeline = Pipeline()
ROOT_DIR = os.getcwd()
LOG_FOLDER_NAME = "logs"
PIPELINE_FOLDER_NAME = "banking"
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)
from banking.logger import get_log_dataframe
BANKING_DATA_KEY = "banking_data"
IS_FRAUD_VALUE_KEY = "fraud"
app = Flask(__name__)
@app.route('/artifact', defaults={'req_path': 'banking'})
@app.route('/artifact/<path:req_path>')
def render_artifact_dir(req_path):
os.makedirs("banking", 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 = {
BANKING_DATA_KEY: None,
IS_FRAUD_VALUE_KEY: None
}
if request.method == 'POST':
step = float(request.form['step'])
amount = float(request.form['amount'])
newbalanceOrig = float(request.form['newbalanceOrig'])
newbalanceDest = float(request.form['newbalanceDest'])
isFlaggedFraud = float(request.form['isFlaggedFraud'])
banking_data = BankingData(step=step,
amount=amount,
newbalanceOrig=newbalanceOrig,
newbalanceDest=newbalanceDest,
isFlaggedFraud=isFlaggedFraud
)
banking_df = banking_data.get_banking_input_data_frame()
fraud_predictor = BankingPredictor(model_dir=MODEL_DIR)
is_Fraud_value = fraud_predictor.predict(X=banking_df)
context = {
BANKING_DATA_KEY: banking_data.get_banking_data_as_dict(),
IS_FRAUD_VALUE_KEY: is_Fraud_value
}
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()