Update server.py
Browse files
server.py
CHANGED
|
@@ -7,86 +7,133 @@ from flask import Flask, jsonify, request
|
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
-
# Load
|
| 11 |
model = joblib.load('steel_model.joblib')
|
| 12 |
scaler = joblib.load('scaler.joblib')
|
| 13 |
model_columns = joblib.load('model_columns.joblib')
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
def get_db_connection():
|
|
|
|
| 17 |
return mysql.connector.connect(
|
| 18 |
-
host=os.getenv('DB_HOST', 'freedatabase
|
| 19 |
-
user=os.getenv('DB_USER', '
|
| 20 |
password=os.getenv('DB_PASSWORD', 'your_password'),
|
| 21 |
database=os.getenv('DB_NAME', 'your_dbname'),
|
| 22 |
port=int(os.getenv('DB_PORT', 3306)),
|
|
|
|
| 23 |
)
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
@app.route('/predict', methods=['POST'])
|
| 27 |
def predict():
|
| 28 |
try:
|
| 29 |
data = request.get_json()
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
estimated_co2 = round(predicted_kwh * 0.00082, 4)
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
| 50 |
)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
'
|
|
|
|
| 54 |
)
|
| 55 |
-
|
| 56 |
-
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
INSERT INTO energy_predictions
|
| 63 |
-
(lagging_reactive_power, leading_reactive_power, lagging_power_factor, leading_power_factor, nsm, week_status, day_of_week, load_type, predicted_usage_kwh)
|
| 64 |
-
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
| 65 |
-
"""
|
| 66 |
-
cursor.execute(
|
| 67 |
-
insert_query,
|
| 68 |
-
(
|
| 69 |
-
data.get('Lagging_Current_Reactive_Power_kVarh'),
|
| 70 |
-
data.get('Leading_Current_Reactive_Power_kVarh'),
|
| 71 |
-
lag_pf,
|
| 72 |
-
data.get('Leading_Current_Power_Factor'),
|
| 73 |
-
data.get('NSM'),
|
| 74 |
-
data.get('WeekStatus'),
|
| 75 |
-
data.get('Day_of_week'),
|
| 76 |
-
data.get('Load_Type'),
|
| 77 |
-
predicted_kwh,
|
| 78 |
-
),
|
| 79 |
)
|
| 80 |
-
conn.commit()
|
| 81 |
-
cursor.close()
|
| 82 |
-
conn.close()
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
except Exception as e:
|
| 92 |
return jsonify({'status': 'error', 'message': str(e)}), 500
|
|
@@ -94,12 +141,12 @@ def predict():
|
|
| 94 |
|
| 95 |
@app.route('/history', methods=['GET'])
|
| 96 |
def get_history():
|
| 97 |
-
"""Retrieves
|
| 98 |
try:
|
| 99 |
conn = get_db_connection()
|
| 100 |
df_logs = pd.read_sql(
|
| 101 |
-
'SELECT id,
|
| 102 |
-
'
|
| 103 |
conn,
|
| 104 |
)
|
| 105 |
conn.close()
|
|
@@ -107,8 +154,9 @@ def get_history():
|
|
| 107 |
'status': 'success',
|
| 108 |
'data': df_logs.to_dict(orient='records'),
|
| 109 |
})
|
| 110 |
-
except Exception
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
|
| 114 |
if __name__ == '__main__':
|
|
|
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
+
# Load Pre-trained Artifacts
|
| 11 |
model = joblib.load('steel_model.joblib')
|
| 12 |
scaler = joblib.load('scaler.joblib')
|
| 13 |
model_columns = joblib.load('model_columns.joblib')
|
| 14 |
|
| 15 |
+
# Local Fallback Log Memory (Used if remote MySQL is offline)
|
| 16 |
+
in_memory_logs = []
|
| 17 |
+
|
| 18 |
|
| 19 |
def get_db_connection():
|
| 20 |
+
"""Establishes connection to remote MySQL database with a 3-second timeout."""
|
| 21 |
return mysql.connector.connect(
|
| 22 |
+
host=os.getenv('DB_HOST', 'sql.freedatabase.com'),
|
| 23 |
+
user=os.getenv('DB_USER', 'your_username'),
|
| 24 |
password=os.getenv('DB_PASSWORD', 'your_password'),
|
| 25 |
database=os.getenv('DB_NAME', 'your_dbname'),
|
| 26 |
port=int(os.getenv('DB_PORT', 3306)),
|
| 27 |
+
connection_timeout=3,
|
| 28 |
)
|
| 29 |
|
| 30 |
|
| 31 |
+
@app.route('/health', methods=['GET'])
|
| 32 |
+
def health():
|
| 33 |
+
return jsonify({'status': 'healthy'}), 200
|
| 34 |
+
|
| 35 |
+
|
| 36 |
@app.route('/predict', methods=['POST'])
|
| 37 |
def predict():
|
| 38 |
try:
|
| 39 |
data = request.get_json()
|
| 40 |
|
| 41 |
+
# Map inputs to structured DataFrame
|
| 42 |
+
raw_input = {
|
| 43 |
+
'Lagging_Current_Reactive_Power_kVarh': float(
|
| 44 |
+
data.get('lagging_kvarh', 0)
|
| 45 |
+
),
|
| 46 |
+
'Leading_Current_Reactive_Power_kVarh': float(
|
| 47 |
+
data.get('leading_kvarh', 0)
|
| 48 |
+
),
|
| 49 |
+
'Lagging_Current_Power_Factor': float(data.get('lagging_pf', 100)),
|
| 50 |
+
'Leading_Current_Power_Factor': float(data.get('leading_pf', 100)),
|
| 51 |
+
'NSM': int(data.get('nsm', 0)),
|
| 52 |
+
'WeekStatus': data.get('week_status', 'Weekday'),
|
| 53 |
+
'Day_of_week': data.get('day_of_week', 'Monday'),
|
| 54 |
+
'Load_Type': data.get('load_type', 'Light_Load'),
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
input_df = pd.DataFrame([raw_input])
|
| 58 |
+
encoded_df = pd.get_dummies(input_df)
|
| 59 |
+
encoded_df = encoded_df.reindex(columns=model_columns, fill_value=0)
|
| 60 |
+
|
| 61 |
+
# Execute Model Inference
|
| 62 |
+
scaled_input = scaler.transform(encoded_df)
|
| 63 |
+
predicted_kwh = round(float(model.predict(scaled_input)[0]), 2)
|
| 64 |
+
|
| 65 |
+
# Estimate CO2 Emissions (tCO2 factor per kWh in heavy industry grid)
|
| 66 |
estimated_co2 = round(predicted_kwh * 0.00082, 4)
|
| 67 |
|
| 68 |
+
# Power Grid Inefficiency & Mitigation Diagnostics
|
| 69 |
+
grid_issues = []
|
| 70 |
+
lag_pf = raw_input['Lagging_Current_Power_Factor']
|
| 71 |
+
lag_kvarh = raw_input['Lagging_Current_Reactive_Power_kVarh']
|
| 72 |
+
|
| 73 |
+
if lag_pf < 85.0:
|
| 74 |
+
grid_issues.append(
|
| 75 |
+
f'Low Lagging Power Factor ({lag_pf}%). Penalty risk!'
|
| 76 |
)
|
| 77 |
+
if lag_kvarh > 15.0:
|
| 78 |
+
grid_issues.append(
|
| 79 |
+
f'High Inductive Reactive Load ({lag_kvarh} kVarh). Inefficient'
|
| 80 |
+
' transformer draw.'
|
| 81 |
)
|
| 82 |
+
if predicted_kwh > 50.0:
|
| 83 |
+
grid_issues.append('High Peak Demand (>50 kWh). Surge pricing applies.')
|
| 84 |
|
| 85 |
+
mitigation_status = (
|
| 86 |
+
' | '.join(grid_issues)
|
| 87 |
+
if grid_issues
|
| 88 |
+
else 'Optimal Grid Efficiency (No Penalties)'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
)
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
+
# Persistent MySQL Logging with Fallback
|
| 92 |
+
db_status = 'Logged to MySQL'
|
| 93 |
+
try:
|
| 94 |
+
conn = get_db_connection()
|
| 95 |
+
cursor = conn.cursor()
|
| 96 |
+
query = """
|
| 97 |
+
INSERT INTO energy_predictions
|
| 98 |
+
(lagging_reactive_power, leading_reactive_power, lagging_power_factor, leading_power_factor, nsm, week_status, day_of_week, load_type, predicted_usage_kwh)
|
| 99 |
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
| 100 |
+
"""
|
| 101 |
+
cursor.execute(
|
| 102 |
+
query,
|
| 103 |
+
(
|
| 104 |
+
raw_input['Lagging_Current_Reactive_Power_kVarh'],
|
| 105 |
+
raw_input['Leading_Current_Reactive_Power_kVarh'],
|
| 106 |
+
raw_input['Lagging_Current_Power_Factor'],
|
| 107 |
+
raw_input['Leading_Current_Power_Factor'],
|
| 108 |
+
raw_input['NSM'],
|
| 109 |
+
raw_input['WeekStatus'],
|
| 110 |
+
raw_input['Day_of_week'],
|
| 111 |
+
raw_input['Load_Type'],
|
| 112 |
+
predicted_kwh,
|
| 113 |
+
),
|
| 114 |
+
)
|
| 115 |
+
conn.commit()
|
| 116 |
+
cursor.close()
|
| 117 |
+
conn.close()
|
| 118 |
+
except Exception as db_err:
|
| 119 |
+
db_status = 'In-Memory Fallback (MySQL Offline)'
|
| 120 |
+
in_memory_logs.append({
|
| 121 |
+
'id': len(in_memory_logs) + 1,
|
| 122 |
+
'predicted_usage_kwh': predicted_kwh,
|
| 123 |
+
'co2': estimated_co2,
|
| 124 |
+
})
|
| 125 |
+
|
| 126 |
+
return (
|
| 127 |
+
jsonify({
|
| 128 |
+
'status': 'success',
|
| 129 |
+
'predicted_usage_kwh': predicted_kwh,
|
| 130 |
+
'estimated_co2': estimated_co2,
|
| 131 |
+
'power_factor_efficiency': f'{lag_pf}%',
|
| 132 |
+
'mitigation_status': mitigation_status,
|
| 133 |
+
'db_status': db_status,
|
| 134 |
+
}),
|
| 135 |
+
200,
|
| 136 |
+
)
|
| 137 |
|
| 138 |
except Exception as e:
|
| 139 |
return jsonify({'status': 'error', 'message': str(e)}), 500
|
|
|
|
| 141 |
|
| 142 |
@app.route('/history', methods=['GET'])
|
| 143 |
def get_history():
|
| 144 |
+
"""Retrieves historical logs for analytics chart rendering."""
|
| 145 |
try:
|
| 146 |
conn = get_db_connection()
|
| 147 |
df_logs = pd.read_sql(
|
| 148 |
+
'SELECT id, predicted_usage_kwh FROM energy_predictions ORDER BY id'
|
| 149 |
+
' DESC LIMIT 20',
|
| 150 |
conn,
|
| 151 |
)
|
| 152 |
conn.close()
|
|
|
|
| 154 |
'status': 'success',
|
| 155 |
'data': df_logs.to_dict(orient='records'),
|
| 156 |
})
|
| 157 |
+
except Exception:
|
| 158 |
+
# Return local in-memory logs if MySQL fails
|
| 159 |
+
return jsonify({'status': 'success', 'data': in_memory_logs[-20:]})
|
| 160 |
|
| 161 |
|
| 162 |
if __name__ == '__main__':
|