Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261import gradio as grimport pandas as pdimport numpy as npimport requestsimport plotly.graph_objects as gofrom datetime import datetime, timedeltaimport osfrom dotenv import load_dotenv
# Load environment variablesload_dotenv()
# Set your Groq API key (you'll add this in Hugging Face secrets)GROQ_API_KEY = os.getenv("GROQ_API_KEY")
# ConstantsOPENPOWER_API_URL = "https://openpower.gridsingularity.com/api/v1/"GROQ_API_URL = "https://api.groq.com/v1/chat/completions"
# Sample data cache (in a real app, you'd use proper caching)data_cache = {}
# CSS for stylingcustom_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);}"""
def fetch_openpower_data(region, start_date, end_date): """Fetch data from OpenPower API (simulated for this example)""" cache_key = f"{region}_{start_date}_{end_date}" if cache_key in data_cache: return data_cache[cache_key] # In a real implementation, you would call the actual API here # For this example, we'll generate synthetic data date_range = pd.date_range(start=start_date, end=end_date, freq='H') load_data = np.random.normal(loc=1000, scale=200, size=len(date_range)) temperature = np.random.normal(loc=20, scale=5, size=len(date_range)) df = pd.DataFrame({ 'timestamp': date_range, 'load': load_data, 'temperature': temperature }) data_cache[cache_key] = df return df
def generate_forecast_with_groq(historical_data, forecast_horizon): """Generate forecast using Groq API""" prompt = f""" You are an energy load forecasting expert. Based on the following historical data, predict the energy load for the next {forecast_horizon} hours. Historical data (last 5 entries): {historical_data.tail(5).to_string()} Provide only the forecasted values as a Python list of numbers, no additional text. Example format: [1234.5, 1256.7, 1189.2, ...] """ headers = { "Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json" } payload = { "messages": [{"role": "user", "content": prompt}], "model": "mixtral-8x7b-32768" } try: response = requests.post(GROQ_API_URL, headers=headers, json=payload) response.raise_for_status() # Extract the forecast values from the response content = response.json()["choices"][0]["message"]["content"] # Safely evaluate the string to get the list forecast = eval(content) return forecast 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""" # Create timestamps for forecast period last_timestamp = historical_data['timestamp'].iloc[-1] forecast_timestamps = [last_timestamp + timedelta(hours=i+1) for i in range(len(forecast_values))] # Create Plotly figure 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') )) # Add forecast data fig.add_trace(go.Scatter( x=forecast_timestamps, y=forecast_values, mode='lines+markers', name='Forecast', line=dict(color='#ff7f0e', dash='dot') )) # Add confidence interval (simulated) 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 )) # Update layout fig.update_layout( title='Energy Load Forecast', 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 ) ) return fig
def run_forecast(region, start_date, end_date, forecast_horizon): """Main function to run the forecast""" try: # Fetch historical data historical_data = fetch_openpower_data(region, start_date, end_date) # Generate forecast forecast_values = generate_forecast_with_groq(historical_data, forecast_horizon) if forecast_values is None: return "Error generating forecast. Please try again later.", None # Create plot fig = create_forecast_plot(historical_data, forecast_values) # Prepare forecast summary forecast_df = pd.DataFrame({ 'Time': [historical_data['timestamp'].iloc[-1] + timedelta(hours=i+1) for i in range(forecast_horizon)], 'Forecasted Load (MW)': forecast_values }) return fig, forecast_df except Exception as e: print(f"Error in run_forecast: {e}") return f"An error occurred: {str(e)}", None
# Create Gradio interfacewith gr.Blocks(css=custom_css) as demo: with gr.Column(): gr.Markdown(""" <div class="header"> <h1>Smart Energy Load Forecasting</h1> <p>Predict future energy demand using AI and historical data</p> </div> """) with gr.Row(): with gr.Column(scale=1): region = gr.Dropdown( label="Region", choices=["North", "South", "East", "West", "Central"], value="North" ) start_date = gr.DatePicker( label="Start Date", value=(datetime.now() - timedelta(days=7)).date() ) end_date = gr.DatePicker( label="End Date", value=datetime.now().date() ) 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)"], datatype=["datetime", "number"] ) gr.Markdown(""" <div class="footer"> <p>Powered by Groq API and OpenPower data | Built with Gradio</p> </div> """) submit_btn.click( fn=run_forecast, inputs=[region, start_date, end_date, forecast_horizon], outputs=[plot_output, forecast_table] )
# Run the appif __name__ == "__main__": demo.launch()app.pyAdded+261