File size: 5,174 Bytes
f905162
 
 
 
 
 
 
 
 
6990e30
f905162
 
 
 
6990e30
 
 
f905162
 
6990e30
f905162
6990e30
 
f905162
 
 
6990e30
f905162
 
 
6990e30
 
 
 
 
f905162
 
 
 
 
6990e30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f905162
 
6990e30
 
 
 
 
 
 
 
f905162
6990e30
 
 
 
f905162
6990e30
 
f905162
6990e30
 
 
 
f905162
 
6990e30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f905162
 
 
 
 
 
 
6990e30
f905162
 
 
6990e30
 
f905162
 
 
 
 
 
 
6990e30
 
 
f905162
 
 
 
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
import os
import joblib
import mysql.connector
import numpy as np
import pandas as pd
from flask import Flask, jsonify, request

app = Flask(__name__)

# Load Pre-trained Artifacts
model = joblib.load('steel_model.joblib')
scaler = joblib.load('scaler.joblib')
model_columns = joblib.load('model_columns.joblib')

# Local Fallback Log Memory (Used if remote MySQL is offline)
in_memory_logs = []


def get_db_connection():
  """Establishes connection to remote MySQL database with a 3-second timeout."""
  return mysql.connector.connect(
      host=os.getenv('DB_HOST', 'sql.freedatabase.com'),
      user=os.getenv('DB_USER', 'your_username'),
      password=os.getenv('DB_PASSWORD', 'your_password'),
      database=os.getenv('DB_NAME', 'your_dbname'),
      port=int(os.getenv('DB_PORT', 3306)),
      connection_timeout=3,
  )


@app.route('/health', methods=['GET'])
def health():
  return jsonify({'status': 'healthy'}), 200


@app.route('/predict', methods=['POST'])
def predict():
  try:
    data = request.get_json()

    # Map inputs to structured DataFrame
    raw_input = {
        'Lagging_Current_Reactive_Power_kVarh': float(
            data.get('lagging_kvarh', 0)
        ),
        'Leading_Current_Reactive_Power_kVarh': float(
            data.get('leading_kvarh', 0)
        ),
        'Lagging_Current_Power_Factor': float(data.get('lagging_pf', 100)),
        'Leading_Current_Power_Factor': float(data.get('leading_pf', 100)),
        'NSM': int(data.get('nsm', 0)),
        'WeekStatus': data.get('week_status', 'Weekday'),
        'Day_of_week': data.get('day_of_week', 'Monday'),
        'Load_Type': data.get('load_type', 'Light_Load'),
    }

    input_df = pd.DataFrame([raw_input])
    encoded_df = pd.get_dummies(input_df)
    encoded_df = encoded_df.reindex(columns=model_columns, fill_value=0)

    # Execute Model Inference
    scaled_input = scaler.transform(encoded_df)
    predicted_kwh = round(float(model.predict(scaled_input)[0]), 2)

    # Estimate CO2 Emissions (tCO2 factor per kWh in heavy industry grid)
    estimated_co2 = round(predicted_kwh * 0.00082, 4)

    # Power Grid Inefficiency & Mitigation Diagnostics
    grid_issues = []
    lag_pf = raw_input['Lagging_Current_Power_Factor']
    lag_kvarh = raw_input['Lagging_Current_Reactive_Power_kVarh']

    if lag_pf < 85.0:
      grid_issues.append(
          f'Low Lagging Power Factor ({lag_pf}%). Penalty risk!'
      )
    if lag_kvarh > 15.0:
      grid_issues.append(
          f'High Inductive Reactive Load ({lag_kvarh} kVarh). Inefficient'
          ' transformer draw.'
      )
    if predicted_kwh > 50.0:
      grid_issues.append('High Peak Demand (>50 kWh). Surge pricing applies.')

    mitigation_status = (
        ' | '.join(grid_issues)
        if grid_issues
        else 'Optimal Grid Efficiency (No Penalties)'
    )

    # Persistent MySQL Logging with Fallback
    db_status = 'Logged to MySQL'
    try:
      conn = get_db_connection()
      cursor = conn.cursor()
      query = """
                INSERT INTO energy_predictions 
                (lagging_reactive_power, leading_reactive_power, lagging_power_factor, leading_power_factor, nsm, week_status, day_of_week, load_type, predicted_usage_kwh)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
            """
      cursor.execute(
          query,
          (
              raw_input['Lagging_Current_Reactive_Power_kVarh'],
              raw_input['Leading_Current_Reactive_Power_kVarh'],
              raw_input['Lagging_Current_Power_Factor'],
              raw_input['Leading_Current_Power_Factor'],
              raw_input['NSM'],
              raw_input['WeekStatus'],
              raw_input['Day_of_week'],
              raw_input['Load_Type'],
              predicted_kwh,
          ),
      )
      conn.commit()
      cursor.close()
      conn.close()
    except Exception as db_err:
      db_status = 'In-Memory Fallback (MySQL Offline)'
      in_memory_logs.append({
          'id': len(in_memory_logs) + 1,
          'predicted_usage_kwh': predicted_kwh,
          'co2': estimated_co2,
      })

    return (
        jsonify({
            'status': 'success',
            'predicted_usage_kwh': predicted_kwh,
            'estimated_co2': estimated_co2,
            'power_factor_efficiency': f'{lag_pf}%',
            'mitigation_status': mitigation_status,
            'db_status': db_status,
        }),
        200,
    )

  except Exception as e:
    return jsonify({'status': 'error', 'message': str(e)}), 500


@app.route('/history', methods=['GET'])
def get_history():
  """Retrieves historical logs for analytics chart rendering."""
  try:
    conn = get_db_connection()
    df_logs = pd.read_sql(
        'SELECT id, predicted_usage_kwh FROM energy_predictions ORDER BY id'
        ' DESC LIMIT 20',
        conn,
    )
    conn.close()
    return jsonify({
        'status': 'success',
        'data': df_logs.to_dict(orient='records'),
    })
  except Exception:
    # Return local in-memory logs if MySQL fails
    return jsonify({'status': 'success', 'data': in_memory_logs[-20:]})


if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5000)