Create server.py
Browse files
server.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import joblib
|
| 3 |
+
import mysql.connector
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from flask import Flask, jsonify, request
|
| 7 |
+
|
| 8 |
+
app = Flask(__name__)
|
| 9 |
+
|
| 10 |
+
# Load ML artifacts saved during training
|
| 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-host.com'),
|
| 19 |
+
user=os.getenv('DB_USER', 'your_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 |
+
# Create single-row DataFrame from input json
|
| 32 |
+
input_df = pd.DataFrame([data])
|
| 33 |
+
|
| 34 |
+
# Perform One-Hot Encoding consistent with trained schema
|
| 35 |
+
input_df = pd.get_dummies(input_df)
|
| 36 |
+
input_df = input_df.reindex(columns=model_columns, fill_value=0)
|
| 37 |
+
|
| 38 |
+
# Scale and Predict
|
| 39 |
+
scaled_features = scaler.transform(input_df)
|
| 40 |
+
predicted_kwh = round(float(model.predict(scaled_features)[0]), 2)
|
| 41 |
+
|
| 42 |
+
# Calculate CO2 Estimate (approx. 0.00082 tCO2 per kWh for steel grid power)
|
| 43 |
+
estimated_co2 = round(predicted_kwh * 0.00082, 4)
|
| 44 |
+
|
| 45 |
+
# Green-ML Optimization Logic
|
| 46 |
+
lag_pf = float(data.get('Lagging_Current_Power_Factor', 100))
|
| 47 |
+
if lag_pf < 75.0:
|
| 48 |
+
mitigation_status = (
|
| 49 |
+
'Critical: Low Power Factor. Engage capacitor banks.'
|
| 50 |
+
)
|
| 51 |
+
elif predicted_kwh > 60.0:
|
| 52 |
+
mitigation_status = (
|
| 53 |
+
'Warning: Peak Load Detected. Stagger furnace operations.'
|
| 54 |
+
)
|
| 55 |
+
else:
|
| 56 |
+
mitigation_status = 'Optimal Operational Efficiency'
|
| 57 |
+
|
| 58 |
+
# Save Log Entry to MySQL
|
| 59 |
+
conn = get_db_connection()
|
| 60 |
+
cursor = conn.cursor()
|
| 61 |
+
insert_query = """
|
| 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 |
+
return jsonify({
|
| 85 |
+
'status': 'success',
|
| 86 |
+
'predicted_usage_kwh': predicted_kwh,
|
| 87 |
+
'estimated_co2': estimated_co2,
|
| 88 |
+
'mitigation_status': mitigation_status,
|
| 89 |
+
})
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
return jsonify({'status': 'error', 'message': str(e)}), 500
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@app.route('/history', methods=['GET'])
|
| 96 |
+
def get_history():
|
| 97 |
+
"""Retrieves last 20 prediction logs from MySQL for chart rendering."""
|
| 98 |
+
try:
|
| 99 |
+
conn = get_db_connection()
|
| 100 |
+
df_logs = pd.read_sql(
|
| 101 |
+
'SELECT id, timestamp, predicted_usage_kwh FROM energy_predictions'
|
| 102 |
+
' ORDER BY id DESC LIMIT 20',
|
| 103 |
+
conn,
|
| 104 |
+
)
|
| 105 |
+
conn.close()
|
| 106 |
+
return jsonify({
|
| 107 |
+
'status': 'success',
|
| 108 |
+
'data': df_logs.to_dict(orient='records'),
|
| 109 |
+
})
|
| 110 |
+
except Exception as e:
|
| 111 |
+
return jsonify({'status': 'error', 'message': str(e)}), 500
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == '__main__':
|
| 115 |
+
app.run(host='127.0.0.1', port=5000)
|