-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
255 lines (197 loc) · 8.09 KB
/
app.py
File metadata and controls
255 lines (197 loc) · 8.09 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
from flask import Flask, request, jsonify, render_template,make_response, session, redirect
import sys
sys.path.append('./Simulations')
from Simulations.Multiprocess_Compute import multiprocess
from Simulations.geographicsimulation import geosim
from Simulations.inverterlogic import inverter_selection
from flask_cors import CORS
import pandas as pd
import os
from dotenv import load_dotenv
from google_solar_api import sendBuildingInsightsRequest, sendDataLayersRequest
import base64
import json
#flask request and response handling
app = Flask(__name__, template_folder='templates')
CORS(app) #enable Cross Origin Resource Sharing (CORS)
#load environment variables
load_dotenv()
# GET LE SECRETS
GOOGLE_SECRET_KEY = os.getenv('SECRET_KEY')
# Your user authentication function
def authenticate_user(username, password):
return username == "admin@admin.com" and password == "xyz222!!!"
# Read the secret key from the text file
def read_secret_key():
with open('secret_session_key.txt', 'r') as file:
return file.read().strip()
app.secret_key = read_secret_key()
@app.route('/')
def login():
return render_template('login.html')
@app.route('/index', methods=['GET','POST'])
def index():
if(request.method == 'POST'):
response_data = {}
status_code = 0
data = request.json
userID = data['userID']
passID = data['passID']
if authenticate_user(userID, passID):
status_code = 200
response_data = {"message": "success"}
session['logged_in'] = True
session['username'] = userID
else:
status_code = 400
response_data = {"message": "failed"}
response = make_response(jsonify(response_data), status_code)
return response
else:
if(session.get('logged_in')):
return render_template('index.html', secret_key=GOOGLE_SECRET_KEY)
else:
return redirect('/')
@app.route('/check-for-login', methods=['GET','POST'])
def check_for_login():
isLoggedIn = session.get('logged_in')
if isLoggedIn:
render_index()
else:
# do nothing
return make_response(jsonify({"message":'not logged in'}), 205)
return make_response(jsonify({"message":'success'}), 200)
# can use below for some backend data presentation and logout handling
@app.route('/dashboard')
def dashboard():
if session.get('logged_in'):
username = session['username']
return f"Welcome to the dashboard, {username.split('@')[0]}!"
else:
return redirect('/')
@app.route('/logout')
def logout():
session.pop('logged_in', None)
session.pop('username', None)
return redirect('/')
@app.route("/render-index", methods=['GET'])
def render_index():
return render_template("index.html")
@app.route("/boot-data", methods=['GET','POST'])
def bootData():
if(request.method == "POST"):
# get the dropdown data
# store dropdown data
array = data_function()
#format dropdown data into json
data = {'message': array}
#jsonify the returned data
return jsonify(data)
# bad request response
return 'method not allowed', 405
@app.route('/process-request', methods=['GET','POST'])
def process_request():
if(request.method == 'POST'):
data = request.json
selected_module = data.selected_module
selected_inverter = data.selected_inverter
start_azimuth = data.start_azimuth
end_azimuth = data.end_azimuth
increment_azimuth = data.increment_azimuth
start_gcr = data.start_gcr
end_gcr = data.end_gcr
increment_gcr = data.increment_gcr
start_tilt = data.start_tilt
end_tilt = data.end_tilt
increment_tilt = data.increment_tilt
capital_cost = data.capital_cost
number_of_inverters = data.number_of_inverters
array = data.array
module_per_string = data.module_per_string
# execute
return_values = execute_simulation(selected_module, selected_inverter, start_azimuth, end_azimuth, increment_azimuth, start_gcr, end_gcr, increment_gcr, start_tilt, end_tilt, increment_tilt, capital_cost, number_of_inverters, array, module_per_string)
#process input
chatbot_res = {'message' : return_values}
return jsonify(chatbot_res)
return 'method not allowed', 405
# CEC DATABASE PYTHON
# Fetch module data from the web address
modules_url = 'https://raw.githubusercontent.com/NREL/SAM/master/deploy/libraries/CEC%20Modules.csv'
modules_df = pd.read_csv(modules_url, index_col=0)
# Fetch Inverter data from the web address
inverters_url = 'https://raw.githubusercontent.com/NREL/SAM/patch/deploy/libraries/CEC%20Inverters.csv'
inverters_df = pd.read_csv(inverters_url, index_col=0)
## GLOBAL VARIABLES
inverter = 'Baldurs Gate'
module = 'Is the best, plus shadowheart'
def updateModule(newMod):
module = newMod
return module
def updateInverter(newInv):
inverter = newInv
return inverter
@app.route('/store_module_option', methods=['POST'])
def store_module_option():
#get the sleection from request
selected_option = request.json.get('selected_option')
print(selected_option)
# set the response of the update to a variable
res = updateModule(selected_option)
# return the response as a response to the OG JS request
# this goes for store inverter as well
return f'New module selection: {res}'
@app.route('/store_inverter_option', methods=['POST'])
def store_inverter_option():
selected_option = request.json.get('selected_option')
print(selected_option)
res = updateInverter(selected_option)
return f'New inverter selection: {res}'
@app.route('/search-modules', methods=['POST'])
def search_modules():
search_input = request.json.get('search_input', '').strip()
if(search_input == '' or search_input == ' '):
search_results = 'none!'
else:
search_results = modules_df.index[modules_df.index.str.contains(search_input, case=False)].tolist()
return jsonify(search_results)
@app.route('/search-inverters', methods=['POST'])
def search_inverters():
search_input = request.json.get('search_input', '').strip()
if(search_input == '' or search_input == ' '):
search_results = 'none!'
else:
search_results = inverters_df.index[inverters_df.index.str.contains(search_input, case=False)].tolist()
return jsonify(search_results)
@app.route('/optimize-in-dev', methods=['POST'])
def optimize_in_dev():
res = optimize()
return jsonify({"message":res})
@app.route('/run-that-sim', methods=['POST'])
def run_that_sim():
moduleSelected = request.json.get('module')
inverterSelected = request.json.get('inverter')
rowSpacing = request.json.get('row_spacing')
innerDistance = request.json.get('inner_distance')
coords = request.json.get('coords')
geodata = geosim(moduleSelected,rowSpacing,innerDistance,coords)
inverterdata = inverter_selection(geodata["max_modules"],inverterSelected, moduleSelected)
print(inverterdata)
multiprocess(moduleSelected, inverterSelected,inverterdata[0], inverterdata[1], inverterdata[2])
""" This will return a list of 5 optimized resutls at the end of the simulation. Check the end of multiprocess."""
# Encode the binary image data as base64
if 'plot_image' in geodata:
geodata['plot_image'] = base64.b64encode(geodata['plot_image']).decode('utf-8')
return jsonify(geodata)
# TESTING GOOGLE SOLAR API WITH SET COORDINATES
@app.route('/google-solar-api-data', methods=['POST'])
def google_solar_api_data():
# retrieve the center point from the request
lat = request.json.get('lat')
lng = request.json.get('lng')
#get the building insight data, and only return the ones we care about
insightReq = sendBuildingInsightsRequest(lat,lng)
#get the data layers response
dataLayersReq = sendDataLayersRequest(lat,lng)
return jsonify({"insights":insightReq, "dataLayers":dataLayersReq})
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0",port="8000", use_reloader=False)