Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242528 unmodified lines54555657585960616263646566676869707172737475767778798081828384858687888990919293943 unmodified lines98991001011021031041051061071081091101111121131141151161171 unmodified line1191201211221231241251261271281291302 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921014 unmodified lines2252262272282292302312322332342359 unmodified lines2452462472482492502512524 unmodified lines2572582592602612622634 unmodified linesimport 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 {28 unmodified linesmargin-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 datadate_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] = dfreturn dfdef 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 = {3 unmodified linespayload = {"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 responsecontent = response.json()["choices"][0]["message"]["content"]# Safely evaluate the string to get the listforecast = eval(content)return forecastexcept Exception as e:print(f"Error calling Groq API: {e}")1 unmodified linedef create_forecast_plot(historical_data, forecast_values):"""Create interactive plot with historical data and forecast"""# Create timestamps for forecast periodlast_timestamp = historical_data['timestamp'].iloc[-1]forecast_timestamps = [last_timestamp + timedelta(hours=i+1)for i in range(len(forecast_values))]# Create Plotly figurefig = go.Figure()# Add historical data2 unmodified linesy=historical_data['load'],mode='lines+markers',name='Historical Load',line=dict(color='#1f77b4')))# Add forecast datafig.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 layoutfig.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 figdef run_forecast(region, start_date, end_date, forecast_horizon):"""Main function to run the forecast"""try:# Convert string dates to datetime objectsstart_date = datetime.strptime(start_date, "%Y-%m-%d")end_date = datetime.strptime(end_date, "%Y-%m-%d")# Fetch historical datahistorical_data = fetch_openpower_data(region, start_date, end_date)# Generate forecastforecast_values = generate_forecast_with_groq(historical_data, forecast_horizon)if forecast_values is None:return "Error generating forecast. Please try again later.", None# Create plotfig = create_forecast_plot(historical_data, forecast_values)# Prepare forecast summaryforecast_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_dfexcept 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:14 unmodified lines)start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)",value=(datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d"))end_date = gr.Textbox(label="End Date (YYYY-MM-DD)",value=datetime.now().strftime("%Y-%m-%d"))forecast_horizon = gr.Slider(label="Forecast Horizon (hours)",9 unmodified linesforecast_table = gr.Dataframe(label="Forecast Details",headers=["Time", "Forecasted Load (MW)"],datatype=["datetime", "number"])gr.Markdown("""<div class="footer">4 unmodified linessubmit_btn.click(fn=run_forecast,inputs=[region, start_date, end_date, forecast_horizon],outputs=[plot_output, forecast_table])# Run the app4 unmodified lines56789101112131415161718192021222328 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251263 unmodified lines1301311321331341351361371381391401411421431441451461471481491 unmodified line1511521531541551562 unmodified lines15916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625714 unmodified lines2722732742752762772782792802812822832849 unmodified lines2942952962972982993003013024 unmodified lines3073083093103113123133143153163173183193203213223233243253263274 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 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"# CSS for stylingcustom_css = """.gradio-container {28 unmodified linesmargin-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 datadate_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 dfexcept Exception as e:print(f"Error generating synthetic data: {e}")return Nonedef extract_forecast_values(content):"""Extract forecast values from Groq API response"""try:# Try to find a list pattern in the responsematch = 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 directlynumbers = re.findall(r'\d+\.?\d*', content)if numbers:return [float(num) for num in numbers[:48]] # Limit to 48 hours maxreturn Noneexcept Exception as e:print(f"Error extracting forecast values: {e}")return Nonedef generate_forecast_with_groq(historical_data, forecast_horizon):"""Generate forecast using Groq API"""if historical_data is None or len(historical_data) == 0:return Noneprompt = 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 = {3 unmodified linespayload = {"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 Noneexcept Exception as e:print(f"Error calling Groq API: {e}")1 unmodified linedef create_forecast_plot(historical_data, forecast_values):"""Create interactive plot with historical data and forecast"""fig = go.Figure()# Add historical data2 unmodified linesy=historical_data['load'],mode='lines+markers',name='Historical Load',line=dict(color='#1f77b4', width=2),marker=dict(size=4)))# Add forecast data if availableif 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 intervalfig.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 figdef 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 inputsvalid, msg = validate_dates(start_date, end_date)if not valid:return None, None, msgstart_dt = datetime.strptime(start_date, "%Y-%m-%d")end_dt = datetime.strptime(end_date, "%Y-%m-%d")# Fetch historical datahistorical_data = fetch_openpower_data(region, start_dt, end_dt)if historical_data is None:return None, None, "Error loading historical data"# Generate forecastforecast_values = generate_forecast_with_groq(historical_data, forecast_horizon)# Create plotfig = create_forecast_plot(historical_data, forecast_values if forecast_values else [])# Prepare forecast tableforecast_df = Noneif 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 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"),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)",9 unmodified linesforecast_table = gr.Dataframe(label="Forecast Details",headers=["Time", "Forecasted Load (MW)"],interactive=False)error_output = gr.HTML()gr.Markdown("""<div class="footer">4 unmodified linessubmit_btn.click(fn=run_forecast,inputs=[region, start_date, end_date, forecast_horizon],outputs=[plot_output, forecast_table, error_output])# Add examples for quick testingexamples = 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
app.py+155-91