import gradio as gr import pandas as pd import numpy as np import requests import plotly.graph_objects as go from datetime import datetime, timedelta import os import re from dotenv import load_dotenv # Load environment variables load_dotenv() # Set your Groq API key GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Constants OPENPOWER_API_URL = "https://openpower.gridsingularity.com/api/v1/" GROQ_API_URL = "https://api.groq.com/v1/chat/completions" # CSS for styling custom_css = """ .gradio-container { background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); font-family: 'Arial', sans-serif; } .header { text-align: center; padding: 20px; background: linear-gradient(90deg, #1e3c72 0%, #2a5298 100%); color: white; border-radius: 10px; margin-bottom: 20px; } .footer { text-align: center; margin-top: 20px; padding: 10px; font-size: 12px; color: #666; } .plot-container { background: white; padding: 15px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .forecast-result { background: white; padding: 15px; border-radius: 10px; margin-top: 20px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .error { color: red; padding: 15px; background-color: #ffeeee; border-radius: 5px; margin-top: 10px; } """ def fetch_openpower_data(region, start_date, end_date): """Fetch data from OpenPower API (simulated for this example)""" try: # In a real implementation, you would call the actual API here # For this example, we'll generate realistic synthetic data date_range = pd.date_range(start=start_date, end=end_date, freq='H') # Create more realistic load patterns (higher during day, lower at night) base_load = 800 + 400 * np.sin(np.linspace(0, 2*np.pi, len(date_range))) noise = np.random.normal(0, 50, len(date_range)) load_data = np.clip(base_load + noise, 500, 1500) temperature = 15 + 10 * np.sin(np.linspace(0, 2*np.pi, len(date_range))) + np.random.normal(0, 2, len(date_range)) df = pd.DataFrame({ 'timestamp': date_range, 'load': load_data, 'temperature': temperature }) return df except Exception as e: print(f"Error generating synthetic data: {e}") return None def extract_forecast_values(content): """Extract forecast values from Groq API response""" try: # Try to find a list pattern in the response match = re.search(r'\[([\d\.,\s]+)\]', content) if match: numbers = match.group(1).split(',') return [float(num.strip()) for num in numbers] # If no list found, try to parse numbers directly numbers = re.findall(r'\d+\.?\d*', content) if numbers: return [float(num) for num in numbers[:48]] # Limit to 48 hours max return None except Exception as e: print(f"Error extracting forecast values: {e}") return None def generate_forecast_with_groq(historical_data, forecast_horizon): """Generate forecast using Groq API""" if historical_data is None or len(historical_data) == 0: return None prompt = f""" You are an energy load forecasting expert. Analyze this hourly energy load data and predict the next {forecast_horizon} hours. Historical Data Statistics: - Mean: {historical_data['load'].mean():.2f} MW - Min: {historical_data['load'].min():.2f} MW - Max: {historical_data['load'].max():.2f} MW - Last 5 values: {historical_data['load'].tail(5).values.tolist()} Provide only the forecasted values as a Python list of numbers, formatted like this: [1234.5, 1256.7, ...] Important: Return ONLY the list of numbers, no additional text or explanation. """ headers = { "Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json" } payload = { "messages": [{"role": "user", "content": prompt}], "model": "mixtral-8x7b-32768", "temperature": 0.3 # Reduce randomness for more consistent results } try: response = requests.post(GROQ_API_URL, headers=headers, json=payload, timeout=30) response.raise_for_status() content = response.json()["choices"][0]["message"]["content"] forecast = extract_forecast_values(content) if forecast and len(forecast) >= forecast_horizon: return forecast[:forecast_horizon] return None except Exception as e: print(f"Error calling Groq API: {e}") return None def create_forecast_plot(historical_data, forecast_values): """Create interactive plot with historical data and forecast""" fig = go.Figure() # Add historical data fig.add_trace(go.Scatter( x=historical_data['timestamp'], y=historical_data['load'], mode='lines+markers', name='Historical Load', line=dict(color='#1f77b4', width=2), marker=dict(size=4) )) # Add forecast data if available if forecast_values: forecast_timestamps = [historical_data['timestamp'].iloc[-1] + timedelta(hours=i+1) for i in range(len(forecast_values))] fig.add_trace(go.Scatter( x=forecast_timestamps, y=forecast_values, mode='lines+markers', name='Forecast', line=dict(color='#ff7f0e', width=2, dash='dot'), marker=dict(size=6, symbol='diamond') )) # Add confidence interval fig.add_trace(go.Scatter( x=forecast_timestamps + forecast_timestamps[::-1], y=[val * 1.1 for val in forecast_values] + [val * 0.9 for val in forecast_values[::-1]], fill='toself', fillcolor='rgba(255, 127, 14, 0.2)', line=dict(color='rgba(255,255,255,0)'), hoverinfo="skip", showlegend=False )) fig.update_layout( title='Energy Load Forecast (MW)', xaxis_title='Time', yaxis_title='Load (MW)', plot_bgcolor='rgba(255,255,255,0.9)', paper_bgcolor='rgba(255,255,255,0)', legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), margin=dict(l=50, r=50, b=50, t=50, pad=4), hovermode="x unified" ) return fig def validate_dates(start_date, end_date): """Validate date inputs""" try: start = datetime.strptime(start_date, "%Y-%m-%d") end = datetime.strptime(end_date, "%Y-%m-%d") if start > end: return False, "Start date must be before end date" if (end - start).days > 30: return False, "Date range cannot exceed 30 days" return True, "" except ValueError: return False, "Invalid date format. Use YYYY-MM-DD" def run_forecast(region, start_date, end_date, forecast_horizon): """Main function to run the forecast""" try: # Validate inputs valid, msg = validate_dates(start_date, end_date) if not valid: return None, None, msg start_dt = datetime.strptime(start_date, "%Y-%m-%d") end_dt = datetime.strptime(end_date, "%Y-%m-%d") # Fetch historical data historical_data = fetch_openpower_data(region, start_dt, end_dt) if historical_data is None: return None, None, "Error loading historical data" # Generate forecast forecast_values = generate_forecast_with_groq(historical_data, forecast_horizon) # Create plot fig = create_forecast_plot(historical_data, forecast_values if forecast_values else []) # Prepare forecast table forecast_df = None if forecast_values: forecast_df = pd.DataFrame({ 'Time': [historical_data['timestamp'].iloc[-1] + timedelta(hours=i+1) for i in range(len(forecast_values))], 'Forecasted Load (MW)': forecast_values }) return fig, forecast_df, "" except Exception as e: print(f"Error in run_forecast: {e}") return None, None, f"An error occurred: {str(e)}" # Create Gradio interface with gr.Blocks(css=custom_css) as demo: with gr.Column(): gr.Markdown("""

Smart Energy Load Forecasting

Predict future energy demand using AI and historical data

""") with gr.Row(): with gr.Column(scale=1): region = gr.Dropdown( label="Region", choices=["North", "South", "East", "West", "Central"], value="North" ) start_date = gr.Textbox( label="Start Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"), placeholder="YYYY-MM-DD" ) end_date = gr.Textbox( label="End Date (YYYY-MM-DD)", value=datetime.now().strftime("%Y-%m-%d"), placeholder="YYYY-MM-DD" ) forecast_horizon = gr.Slider( label="Forecast Horizon (hours)", minimum=1, maximum=48, step=1, value=24 ) submit_btn = gr.Button("Generate Forecast", variant="primary") with gr.Column(scale=2): plot_output = gr.Plot(label="Energy Load Forecast") forecast_table = gr.Dataframe( label="Forecast Details", headers=["Time", "Forecasted Load (MW)"], interactive=False ) error_output = gr.HTML() gr.Markdown(""" """) submit_btn.click( fn=run_forecast, inputs=[region, start_date, end_date, forecast_horizon], outputs=[plot_output, forecast_table, error_output] ) # Add examples for quick testing examples = gr.Examples( examples=[ ["North", (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"), datetime.now().strftime("%Y-%m-%d"), 24], ["South", (datetime.now() - timedelta(days=14)).strftime("%Y-%m-%d"), (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"), 12] ], inputs=[region, start_date, end_date, forecast_horizon], outputs=[plot_output, forecast_table, error_output], fn=run_forecast, cache_examples=False ) # Run the app if __name__ == "__main__": demo.launch()