Create an application that has a text field to enter a URL (default value: /kaggle/input/electric-power-consumption-data-set). The app should read the CSV file (and cache it) from the URL and display a DataFrame. give me a app code for this dataset and which i give input like killowatt/hour and the give me predicted killowatt/hour next year prediction and any month
To upload files, please first save the app
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from datetime import datetime, timedelta
st.title("Power Consumption Predictor")
# Input for CSV URL
url = st.text_input(
"Enter CSV URL",
value="/kaggle/input/electric-power-consumption-data-set",
help="Enter the URL of your power consumption CSV file"
)
@st.cache_data
def load_data(url):
try:
# For demo purposes, generate sample data if URL is the default one
if url == "/kaggle/input/electric-power-consumption-data-set":
# Generate sample data
dates = pd.date_range(start='2020-01-01', end='2023-12-31', freq='D')
np.random.seed(42)
consumption = np.random.normal(loc=30, scale=5, size=len(dates))
consumption = consumption + np.sin(np.arange(len(dates)) * 2 * np.pi / 365) * 10 # Add seasonal pattern
df = pd.DataFrame({
'Date': dates,
'KWH': consumption
})
else:
df = pd.read_csv(url)
return df
except Exception as e:
st.error(f"Error loading data: {str(e)}")
return None
# Load data
data = load_data(url)
if data is not None:
st.subheader("Data Preview")
st.dataframe(data.head())
# Input for current consumption
current_kwh = st.number_input("Enter current kilowatt/hour consumption", min_value=0.0, value=25.0)
# Input for prediction month
prediction_month = st.selectbox(
"Select month for prediction",
["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
)
def train_model(data):
# For demo data
if 'Date' in data.columns:
data['Month'] = pd.to_datetime(data['Date']).dt.month
data['Year'] = pd.to_datetime(data['Date']).dt.year
X = data[['Month', 'Year']].values
y = data['KWH'].values
else:
st.warning("Please ensure your data has 'Date' and consumption columns")
return None
model = LinearRegression()
model.fit(X, y)
return model
if st.button("Predict"):
model = train_model(data)
if model is not None:
# Get current date info
current_date = datetime.now()
next_year = current_date.year + 1
prediction_month_num = datetime.strptime(prediction_month, '%B').month
# Make prediction
prediction = model.predict([[prediction_month_num, next_year]])[0]
# Display results
st.subheader("Prediction Results")
col1, col2 = st.columns(2)
with col1:
st.metric(
label="Current Consumption",
value=f"{current_kwh:.2f} KWH"
)
with col2:
st.metric(
label=f"Predicted Consumption ({prediction_month} {next_year})",
value=f"{prediction:.2f} KWH",
delta=f"{prediction - current_kwh:.2f} KWH"
)
# Plot historical data and prediction if using demo data
if 'Date' in data.columns:
st.subheader("Historical Consumption Pattern")
st.line_chart(data.set_index('Date')['KWH'])
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?