ZbindChi commited on
Commit
08a02a1
·
verified ·
1 Parent(s): 33c53f2

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -112
app.py DELETED
@@ -1,112 +0,0 @@
1
- from flask import Flask, request
2
- from flask_cors import CORS
3
- import pandas as pd
4
- from sklearn.ensemble import RandomForestRegressor
5
- from sklearn.neighbors import KNeighborsClassifier
6
-
7
- import pickle
8
- import os
9
- import numpy as np
10
-
11
- import pandas as pd
12
-
13
-
14
- from io import BytesIO
15
- import base64
16
- import json
17
- import re
18
- import sys
19
-
20
- app = Flask(__name__)
21
- CORS(app)
22
- app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000
23
-
24
- mnist_model = None
25
-
26
- # 'tensorflow-local'
27
- # cats_model = None
28
-
29
- def load_mnist_model():
30
- # load the pre-trained model (here we are using a model
31
- # pre-trained of week 8, but you can
32
- # substitute in your own networks just as easily)
33
- global mnist_model
34
- # create prediction
35
- mnist_model = KNeighborsClassifier(n_neighbors=4, weights='distance')
36
- model_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "knn_clf.pkl")
37
- print(model_filename)
38
- with open(model_filename, 'rb') as f:
39
- mnist_model = pickle.load(f)
40
-
41
- @app.route('/api/prediction/mnist', methods=['POST'])
42
- def predict_mnist():
43
- try:
44
- image_data = re.sub('^data:image/.+;base64,', '', request.get_json()['image'])
45
- im = Image.open(BytesIO(base64.b64decode(image_data)))
46
- # im.save('canvas.png')
47
- im28x28 = im.resize((28, 28)).convert('L') #resize the image to 28x28 and converts it to gray scale
48
-
49
- # image to numpy
50
- np_image = np.asarray(im28x28)
51
- # assert(np_image.shape == (28, 28))
52
- print(np.abs(np_image.reshape(28*28)-[255]))
53
-
54
- # np.abs(np_image.reshape(28*28)-[255])
55
- # reshapes the image to 28x28 pixes, substracts 255 from every value and applys abs to the matrix.
56
- # this has to be done, becuase the mnist values are "Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black). " (s. http://yann.lecun.com/exdb/mnist/)
57
- # Grayscale uses 0 for black and 255 for white.
58
- predicted_number = mnist_model.predict([np.abs(np_image.reshape(28*28)-[255])])
59
- print(predicted_number)
60
-
61
- buffered = BytesIO()
62
- im28x28.save(buffered, format="PNG")
63
- im28x28.save('canvas2.png')
64
- img_str = base64.b64encode(buffered.getvalue())
65
- img_base64 = bytes("data:image/png;base64,", encoding='utf-8') + img_str
66
- return json.dumps({'image': str(img_base64.decode('utf-8')), 'prediction': predicted_number[0]}), 200, {'ContentType': 'application/json'}
67
- except Exception as err:
68
- return json.dumps({'error': str(err)})
69
-
70
- @app.route("/api/prediction/apartment", methods=['GET']) #URL for rest api
71
- def predict():
72
- bfs_number = int(request.args['bfs_number']) #transform them to numbers (int and float)
73
- area = float(request.args['area'])
74
- rooms = float(request.args['rooms'])
75
-
76
- df_bfs_data = pd.read_csv(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bfs_municipality_and_tax_data.csv'),
77
- sep=',', encoding='utf-8') #read CSV to get all the data from 'bfs_municipality_and_tax_data.csv'
78
-
79
- df_bfs_data['tax_income'] = df_bfs_data['tax_income'].str.replace("'", "")
80
- df = df_bfs_data[df_bfs_data['bfs_number']==bfs_number]
81
-
82
- randomforest_model = RandomForestRegressor()
83
- model_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "randomforest_regression.pkl")
84
- with open(model_filename, 'rb') as f:
85
- randomforest_model = pickle.load(f)
86
-
87
- # ['rooms' 'area' 'pop' 'pop_dens' 'frg_pct' 'emp' 'tax_income' 'm2_per_rooms']
88
- prediction = randomforest_model.predict([[rooms, area, df['pop'].iloc[0], df['pop_dens'].iloc[0], df['frg_pct'].iloc[0], df['emp'].iloc[0], df['tax_income'].iloc[0], area/rooms]])
89
- #search these numbers for the respondig bfs_number
90
-
91
- return str(round(prediction[0],2))
92
-
93
- @app.route("/")
94
- def hello_world():
95
-
96
- print(request.args)
97
- model_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mlp_clf.pkl")
98
- return "<p>Hello, World!</p> " + model_filename
99
-
100
- # if this is the main thread of execution first load the model and
101
- # then start the server
102
- if __name__ == "__main__" or __name__ == "app" or __name__ == "flask_app":
103
- print(("* Loading model and Flask starting server..."
104
- "please wait until server has fully started"))
105
- load_mnist_model()
106
-
107
- # 'tensorflow-local'
108
- #load_cats_model()
109
-
110
- print(sys.executable)
111
- print('running')
112
-