Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines5678910111213131415161718192020212221222328 unmodified lines525354555657585960616263646561626364656667686970717273747576777879666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121138485114115878811611711811912012190911221231241251263 unmodified lines1301311321011331341351361371051381391401081411421431111121131141441451461471481491 unmodified line1511521531221231241251261271541551562 unmodified lines15916016113613713813914014114214314414516216316416516616716816917017117217317417517617717817914814915015115215315415515615718018118218318418518618718818919015919116119219319419519616616716816917017117219719819920020120220320420520620720820921021121221321421521621721821922022122222322422518018118222622722822923018523123223323423523623719019119223819423924024124219619719819920020124324424524624724824920325025125225320725425525625714 unmodified lines2722732742282752762772782792322802812822832849 unmodified lines2942952962482972982993003013024 unmodified lines3073083092603103113123133143153163173183193203213223233243253263274 unmodified linesimport plotly.graph_objects as gofrom datetime import datetime, timedeltaimport osimport refrom dotenv import load_dotenv
# Load environment variablesload_dotenv()
# Set your Groq API key (you'll add this in Hugging Face secrets)# Set your Groq API keyGROQ_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 {28 unmodified lines 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)""" 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 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. Based on the following historical data, predict the energy load for the next {forecast_horizon} hours. You are an energy load forecasting expert. Analyze this hourly energy load data and predict the next {forecast_horizon} hours. Historical data (last 5 entries): {historical_data.tail(5).to_string()} 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, no additional text. Example format: [1234.5, 1256.7, 1189.2, ...] 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 = {3 unmodified lines payload = { "messages": [{"role": "user", "content": prompt}], "model": "mixtral-8x7b-32768" "model": "mixtral-8x7b-32768", "temperature": 0.3 # Reduce randomness for more consistent results } try: response = requests.post(GROQ_API_URL, headers=headers, json=payload) response = requests.post(GROQ_API_URL, headers=headers, json=payload, timeout=30) response.raise_for_status() # Extract the forecast values from the response content = response.json()["choices"][0]["message"]["content"] forecast = extract_forecast_values(content) # Safely evaluate the string to get the list forecast = eval(content) return forecast if forecast and len(forecast) >= forecast_horizon: return forecast[:forecast_horizon] return None except Exception as e: print(f"Error calling Groq API: {e}")1 unmodified line
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 data2 unmodified lines 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') 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 (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 )) # 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 )) # Update layout fig.update_layout( title='Energy Load Forecast', 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 ) 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 # Convert string dates to datetime objects start_date = datetime.strptime(start_date, "%Y-%m-%d") end_date = datetime.strptime(end_date, "%Y-%m-%d") 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_date, end_date) 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) if forecast_values is None: return "Error generating forecast. Please try again later.", None # Create plot fig = create_forecast_plot(historical_data, forecast_values) fig = create_forecast_plot(historical_data, forecast_values if forecast_values else []) # Prepare forecast table forecast_df = None # 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 }) 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 return fig, forecast_df, "" except Exception as e: print(f"Error in run_forecast: {e}") return f"An error occurred: {str(e)}", None return None, None, f"An error occurred: {str(e)}"
# Create Gradio interfacewith gr.Blocks(css=custom_css) as demo:14 unmodified lines ) start_date = gr.Textbox( label="Start Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d") 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") value=datetime.now().strftime("%Y-%m-%d"), placeholder="YYYY-MM-DD" ) forecast_horizon = gr.Slider( label="Forecast Horizon (hours)",9 unmodified lines forecast_table = gr.Dataframe( label="Forecast Details", headers=["Time", "Forecasted Load (MW)"], datatype=["datetime", "number"] interactive=False ) error_output = gr.HTML() gr.Markdown(""" <div class="footer">4 unmodified lines submit_btn.click( fn=run_forecast, inputs=[region, start_date, end_date, forecast_horizon], outputs=[plot_output, forecast_table] 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 appapp.py+155-91