-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
207 lines (166 loc) · 6.71 KB
/
Copy pathapp.py
File metadata and controls
207 lines (166 loc) · 6.71 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
from flask import Flask, request, jsonify
from flask_cors import CORS
import pandas as pd
import numpy as np
import joblib
import calendar
app = Flask(__name__)
CORS(app)
# Load model and features
model = joblib.load("model.pkl")
features = joblib.load("features.pkl")
df = pd.read_csv("electricity_demand_dataset.csv")
default_vals = {
"Temperature_C": 28,
"CDD65": 5,
"Humidity_Percent": 70,
"DISCO_IBEDC": 1,
"DISCO_IE": 0
}
@app.route("/")
def home():
return "🔌 Electricity Demand Forecast API"
@app.route("/predict", methods=["POST"])
def predict():
"""Single month prediction - existing endpoint"""
data = request.get_json()
try:
year = int(data.get("year"))
month = int(data.get("month"))
disco = data.get("disco", "IBEDC").upper()
month_sin = np.sin(2 * np.pi * month / 12)
month_cos = np.cos(2 * np.pi * month / 12)
input_data = {
"Year": year,
"Month_sin": month_sin,
"Month_cos": month_cos,
"Temperature_C": default_vals["Temperature_C"],
"CDD65": default_vals["CDD65"],
"Humidity_Percent": default_vals["Humidity_Percent"],
"DISCO_IBEDC": 1 if disco == "IBEDC" else 0,
"DISCO_IE": 1 if disco == "IE" else 0,
}
df_input = pd.DataFrame([input_data])
df_input = df_input.reindex(columns=features, fill_value=0)
prediction = model.predict(df_input)[0]
# Find actual consumption for same year/month/disco
actual_row = df[
(df["Year"] == year) &
(df["Month"] == month) &
(df["DISCO"].str.upper() == disco)
]
actual_value = actual_row["Consumption_MWh"].values[0] if not actual_row.empty else None
return jsonify({
"forecast": round(prediction, 2),
"actual": round(actual_value, 2) if actual_value is not None else None
})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/forecast", methods=["POST"])
def forecast_year():
"""Generate forecast for entire year - new endpoint for chart"""
data = request.get_json()
try:
year = int(data.get("year"))
disco = data.get("disco", "IBEDC").upper()
results = []
for month in range(1, 13):
month_sin = np.sin(2 * np.pi * month / 12)
month_cos = np.cos(2 * np.pi * month / 12)
input_data = {
"Year": year,
"Month_sin": month_sin,
"Month_cos": month_cos,
"Temperature_C": default_vals["Temperature_C"],
"CDD65": default_vals["CDD65"],
"Humidity_Percent": default_vals["Humidity_Percent"],
"DISCO_IBEDC": 1 if disco == "IBEDC" else 0,
"DISCO_IE": 1 if disco == "IE" else 0,
}
df_input = pd.DataFrame([input_data])
df_input = df_input.reindex(columns=features, fill_value=0)
prediction = model.predict(df_input)[0]
# Find actual consumption for same year/month/disco
actual_row = df[
(df["Year"] == year) &
(df["Month"] == month) &
(df["DISCO"].str.upper() == disco)
]
actual_value = actual_row["Consumption_MWh"].values[0] if not actual_row.empty else None
results.append({
"month": calendar.month_abbr[month], # Jan, Feb, Mar, etc.
"forecast": round(prediction, 2),
"actual": round(actual_value, 2) if actual_value is not None else None
})
return jsonify({
"year": year,
"disco": disco,
"data": results
})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/forecast-range", methods=["POST"])
def forecast_range():
"""Generate forecast for a range of months - flexible endpoint"""
data = request.get_json()
try:
start_year = int(data.get("start_year"))
end_year = int(data.get("end_year", start_year))
start_month = int(data.get("start_month", 1))
end_month = int(data.get("end_month", 12))
disco = data.get("disco", "IBEDC").upper()
results = []
for year in range(start_year, end_year + 1):
month_start = start_month if year == start_year else 1
month_end = end_month if year == end_year else 12
for month in range(month_start, month_end + 1):
month_sin = np.sin(2 * np.pi * month / 12)
month_cos = np.cos(2 * np.pi * month / 12)
input_data = {
"Year": year,
"Month_sin": month_sin,
"Month_cos": month_cos,
"Temperature_C": default_vals["Temperature_C"],
"CDD65": default_vals["CDD65"],
"Humidity_Percent": default_vals["Humidity_Percent"],
"DISCO_IBEDC": 1 if disco == "IBEDC" else 0,
"DISCO_IE": 1 if disco == "IE" else 0,
}
df_input = pd.DataFrame([input_data])
df_input = df_input.reindex(columns=features, fill_value=0)
prediction = model.predict(df_input)[0]
# Find actual consumption
actual_row = df[
(df["Year"] == year) &
(df["Month"] == month) &
(df["DISCO"].str.upper() == disco)
]
actual_value = actual_row["Consumption_MWh"].values[0] if not actual_row.empty else None
# Create month label (e.g., "Jan 2024" for multi-year ranges)
month_label = calendar.month_abbr[month]
if end_year > start_year:
month_label += f" {year}"
results.append({
"month": month_label,
"forecast": round(prediction, 2),
"actual": round(actual_value, 2) if actual_value is not None else None
})
return jsonify({
"start_year": start_year,
"end_year": end_year,
"disco": disco,
"data": results
})
except Exception as e:
return jsonify({"error": str(e)}), 400
@app.route("/api/login", methods=["POST"])
def login():
data = request.get_json()
email = data.get("email")
password = data.get("password")
if email == "admin@example.com" and password == "admin123":
return jsonify({"email": email}), 200
else:
return jsonify({"message": "Invalid credentials"}), 401
if __name__ == "__main__":
app.run(debug=True)