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)