Permalink
Browse files

uploaded capstone

  • Loading branch information...
rbharbert committed Dec 2, 2019
0 parents commit 54dfc0d9bb1a1411af96bb8c16a30ff9f7d2acc8
Binary file not shown.
@@ -0,0 +1,260 @@
import numpy as np
import pandas as pd
import pickle
import re
from flask import Flask, request, Response, render_template, send_file, session
# from flask.sessions import SessionInterface
import PyPDF2
import time
import os

#instantiating app
app = Flask('ModelPredictor')
app.secret_key = 'x42nig!.5207'
# app.config['SESSION_TYPE'] = 'filesystem'

@app.route('/home')
def home():
return render_template('/home.html')

@app.route('/submit', methods=("POST", "GET"))
def submit():
user_input = request.args
# print(*user_input, sep='\n')
data = [{
'age': int(user_input['age']),
'num_depend': int(user_input['num_depend']),
'monthly_inc': int(user_input['monthly_inc']),
'debt_ratio': float(user_input['debt_ratio']),
'past_due_30': int(user_input['past_due_30']),
'past_due_60': int(user_input['past_due_60']),
'past_due_90': int(user_input['past_due_90']),
'credit_bal': int(user_input['credit_bal']),
'num_credit_lines': int(user_input['num_credit_lines']),
'num_real_estate_lines': int(user_input['num_real_estate_lines'])
}]
model = pickle.load(open('./pickle/model_v2.pickle', 'rb'))
scenario = pd.DataFrame(data,index=[0])
scenario = scenario[['age', 'num_depend', 'monthly_inc', 'debt_ratio', 'past_due_30',
'past_due_60', 'past_due_90', 'credit_bal',
'num_credit_lines', 'num_real_estate_lines']]
features = scenario[['age', 'num_depend', 'monthly_inc', 'debt_ratio', 'past_due_30',
'past_due_60', 'past_due_90', 'credit_bal',
'num_credit_lines', 'num_real_estate_lines']]
scenario['delinq?'] = model.predict(features)
scenario['probability'] = model.predict_proba(features)[:,1]
# session['csv_string'] = scenario.to_csv()
filename = str(time.time()) + '.csv'
scenario.to_csv(filename)
session['filename'] = filename
return render_template('results.html', tables=[scenario.to_html()], titles=[scenario.columns.values])

@app.route('/return-files')
def return_files():
# csv_string = session.get('csv_string', None)
scenario_df = pd.read_csv(session.get('filename')).to_csv()
# file_path = derive_filepath_from_filename(filename)
# filename = request.files['filename']
print(session.get('filename'))
os.remove('filename')
return Response(scenario_df, mimetype="text/csv",
headers={"Content-disposition":"attachment; filename=output.csv"})
# return csv_string
# return send_file(scenario_df, attachment_filename='output.xlsx', as_attachment=True)

@app.route('/upload', methods=['POST', 'GET'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
data_xls = pd.read_excel(f)
features = data_xls[['age', 'num_depend', 'monthly_inc', 'debt_ratio', 'past_due_30',
'past_due_60', 'past_due_90', 'credit_bal',
'num_credit_lines', 'num_real_estate_lines']]
model = pickle.load(open('./pickle/model_v2.pickle', 'rb'))
data_xls['delinq?'] = model.predict(features)
data_xls['probability'] = model.predict_proba(features)[:,1]
# return data_xls.to_html()
# return render_template('upload.html')
return render_template('results.html', tables=[data_xls.to_html()], titles=[data_xls.columns.values])

@app.route('/pdf', methods=['POST', 'GET'])
def upload_pdf():
if request.method == 'POST':
# print(request.files['file'])
f = request.files['file']
pdfReader = PyPDF2.PdfFileReader(f)
page1 = pdfReader.getPage(0).extractText().replace('\n',',').rstrip(',').split(",")
list_odd = []
list_even = []
for x in range(len(page1)):
if x % 2 !=0:
list_odd.append(page1[x])
if x % 2 == 0:
list_even.append(page1[x])
res = {list_even[i]: list_odd[i] for i in range(len(list_even))}
df = pd.DataFrame(data=res, index=[0])
features_pdf = df[['age', 'num_depend', 'monthly_inc', 'debt_ratio', 'past_due_30',
'past_due_60', 'past_due_90', 'credit_bal',
'num_credit_lines', 'num_real_estate_lines']]
model = pickle.load(open('./pickle/model_v2.pickle', 'rb'))
df['delinq?'] = model.predict(features_pdf)
df['probability'] = model.predict_proba(features_pdf)[:,1]
return render_template('results.html', tables=[df.to_html()], titles=[df.columns.values])
# return df.to_html()
# return render_template('upload.html')



if __name__ == '__main__':
# app.run(host='0.0.0.0')
app.run(debug=True)


# @app.route('/demo')
# def demo():
# return render_template('results.html', tables=[1,2,3], titles=['a','b','c'])

# delinq_probability = model.predict_proba(scenario.values)[0][1]
# raw_prediction = model.predict(scenario.values)[0]
# prediction_dict = {0: 'Credit Pass', 1:'Credit Default'}
# prediction_type = prediction_dict[raw_prediction]
# return scenario.to_html()

# return render_template('results.html', tables=[1,2,3], titles=['a','b','c'])
# return render_template('results.html', data=scenario.to_html())
# return render_template('upload.html')
# return render_template('results.html', prediction=prediction_type,
# delinq_probability=round(delinq_probability*100,2))

# https://stackoverflow.com/questions/52644035/how-to-show-a-pandas-dataframe-into-a-existing-flask-html-table
# https://stackoverflow.com/questions/19011861/is-there-a-float-input-type-in-html5
# https://sarahleejane.github.io/learning/python/2015/08/09/simple-tables-in-webapps-using-flask-and-pandas-with-python.html

# app = Flask(__name__)

# @app.route('/upload', methods=['POST', 'GET'])
# @app.route('/home', methods=['POST', 'GET'])

# def upload():
# return render_template('upload.html')

# @app.route()
# @app.route('/table')

# def table():
# return render_template('table.html')

#creating form page
# @app.route('/form')

# def form():
# return render_template('form.html')

#creating output page
# @app.route('/submit')

# def submit():
# user_input = request.args
# print(*user_input, sep='\n')

# data = [{
# 'age': int(user_input['age']),
# 'num_depend': int(user_input['num_depend']),
# 'monthly_inc': int(user_input['monthly_inc']),
# 'debt_ratio': int(user_input['debt_ratio']),
# 'past_due_30': int(user_input['past_due_30']),
# 'past_due_60': int(user_input['past_due_60']),
# 'past_due_90': int(user_input['past_due_90']),
# 'credit_bal': int(user_input['credit_bal']),
# 'num_credit_lines': int(user_input['num_credit_lines']),
# 'num_real_estate_lines': int(user_input['num_real_estate_lines'])
# }]

# load pickled model
# model = pickle.load(open('./pickle/model_v1.pickle', 'rb'))

# create dataframe of scenario
# scenario = pd.DataFrame(data,index=[0])

# the order of the columns matters because using predict in XGBoost models requires numpy arrays
# the code below reorders the columns correctly since pandas makes them alphabetical initially
# delinq_probability = model.predict_proba(scenario.values)[0][1]
# raw_prediction = model.predict(scenario.values)[0]
# prediction_dict = {0: 'Credit Pass', 1:'Credit Default'}
# prediction_type = prediction_dict[raw_prediction]

# change background based on which play is predicted
# if prediction_play == 'Pass':
# url = 'https://i.imgur.com/yFeF801.jpg'
# else:
# url = 'https://i.imgur.com/ga8y1hJ.jpg'

# return render_template('results.html', prediction=prediction_type,
# delinq_probability=round(delinq_probability*100,2))




#app = Flask('PlayPredictor')
# return results html with prediction
# return render_template('results.html', prediction=prediction_play,
# pass_probability=round(pass_probability*100,2),
# run_probability=round(run_probability*100,2),
# url=url)
# scenario = scenario[['down','qtr','game_seconds_remaining',
# 'half_seconds_remaining','quarter_seconds_remaining','ydstogo',
# 'score_differential','yardline_100']]

# make prediction using pickled model
# pass_probability = model.predict_proba(scenario.values)[0][0]
# run_probability = model.predict_proba(scenario.values)[0][1]
# raw_prediction = model.predict(scenario.values)[0]
# prediction_dict = {0:'Pass',1:'Run'}
# prediction_play = prediction_dict[raw_prediction]
# check that time was inputted in the correct format using regex
# time_match = re.match('^[0-9]{1,2}\:[0-9]{2}',user_input['time'])

# if not time_match:
# error_message = 'Error: Time must be the format minute:seconds.'
# return render_template('form.html', error_message=error_message)

# parse through time to get minute and seconds
# minute = int(user_input['time'].split(':')[0])
# second = int(user_input['time'].split(':')[1])
# age = int(user_input['Age'])

# create error messages for times outside of scope of a game
# if minute not in range(0,16):
# error_message = 'Error: Minute must be greater than or equal to 0 and less than or equal to 15.'
# return render_template('form.html', error_message=error_message)

# if second not in range(0,60):
# error_message = 'Error: Seconds must be greater than or equal to 0 and less than 60.'
# return render_template('form.html', error_message=error_message)

# create quarter_seconds_remaining, game_seconds_remaining, half_seconds_remaining variables given time and quarter
# quarter_seconds_remaining = minute*60 + second

# if int(user_input['qtr']) == 1:
# game_seconds_remaining = minute*60 + second + 2700
# half_seconds_remaining = minute*60 + second + 900
# elif int(user_input['qtr']) == 2:
# game_seconds_remaining = minute*60 + second + 1800
# half_seconds_remaining = minute*60 + second
# elif int(user_input['qtr']) == 3:
# game_seconds_remaining = minute*60 + second + 900
# half_seconds_remaining = minute*60 + second + 900
# elif int(user_input['qtr']) == 4:
# game_seconds_remaining = minute*60 + second
# half_seconds_remaining = minute*60 + second

# create list that contains dictionary of inputs for model
# data = [{'down': int(user_input['down']),
# 'qtr': int(user_input['qtr']),
# 'game_seconds_remaining': game_seconds_remaining,
# 'half_seconds_remaining': half_seconds_remaining,
# 'quarter_seconds_remaining': quarter_seconds_remaining,
# 'ydstogo': int(user_input['ydstogo']),
# 'score_differential': int(user_input['score_differential']),
# 'yardline_100': int(user_input['yardline_100'])
# }]
Oops, something went wrong.

0 comments on commit 54dfc0d

Please sign in to comment.