engr-awaisjamal commited on
Commit
08ae01a
·
verified ·
1 Parent(s): 90c0a88

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -0
app.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import pickle
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.linear_model import LinearRegression
6
+ from transformers import pipeline
7
+ from PyPDF2 import PdfReader
8
+
9
+ # Helper function to load different file types
10
+ def load_file(uploaded_file):
11
+ if uploaded_file.name.endswith('.csv'):
12
+ return pd.read_csv(uploaded_file)
13
+ elif uploaded_file.name.endswith('.xlsx'):
14
+ return pd.read_excel(uploaded_file)
15
+ elif uploaded_file.name.endswith('.pdf'):
16
+ reader = PdfReader(uploaded_file)
17
+ text = ''.join(page.extract_text() for page in reader.pages)
18
+ # PDF parsing logic here (customized for table extraction)
19
+ raise NotImplementedError("PDF parsing is not implemented.")
20
+ else:
21
+ raise ValueError("Unsupported file format. Please upload CSV, Excel, or PDF.")
22
+
23
+ # Train the model if it doesn't already exist
24
+ def train_model(data):
25
+ data['Hour'] = pd.to_datetime(data['Timestamp']).dt.hour
26
+ X = data[['Hour', 'Temperature', 'CloudCover']]
27
+ y = data['SolarOutput']
28
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
29
+ model = LinearRegression()
30
+ model.fit(X_train, y_train)
31
+ with open('solar_model.pkl', 'wb') as f:
32
+ pickle.dump(model, f)
33
+ return model
34
+
35
+ # Load the trained model
36
+ def load_model():
37
+ try:
38
+ with open('solar_model.pkl', 'rb') as f:
39
+ return pickle.load(f)
40
+ except FileNotFoundError:
41
+ return None
42
+
43
+ # Initialize the text generation pipeline
44
+ generator = pipeline('text-generation', model='gpt2', device=-1)
45
+
46
+ # Streamlit app
47
+ st.title("Smart Home Energy Advisor")
48
+
49
+ # File uploader
50
+ uploaded_file = st.file_uploader("Upload your data file (CSV, Excel, or PDF)", type=['csv', 'xlsx', 'pdf'])
51
+
52
+ if uploaded_file:
53
+ # Load and preprocess data
54
+ try:
55
+ data = load_file(uploaded_file)
56
+ st.write("Data Preview:", data.head())
57
+ except Exception as e:
58
+ st.error(f"Error loading file: {e}")
59
+ data = None
60
+
61
+ if data is not None:
62
+ # Load or train the model
63
+ model = load_model()
64
+ if not model:
65
+ st.warning("No pre-trained model found. Training a new model...")
66
+ model = train_model(data)
67
+ st.success("Model trained and saved successfully!")
68
+
69
+ # Preprocess data
70
+ data['Hour'] = pd.to_datetime(data['Timestamp']).dt.hour
71
+ data['PredictedSolarOutput'] = model.predict(data[['Hour', 'Temperature', 'CloudCover']])
72
+
73
+ # Determine the best hour for maximum solar energy
74
+ best_hour = data.loc[data['PredictedSolarOutput'].idxmax(), 'Hour']
75
+
76
+ # Generate advice
77
+ advice_prompt = f"The best time to use your appliances is between {best_hour}:00 and {best_hour + 2}:00."
78
+ advice = generator(advice_prompt, max_length=50)[0]['generated_text']
79
+
80
+ # Display predictions and advice
81
+ st.subheader("Predictions")
82
+ st.write(data)
83
+ st.subheader("Recommendation")
84
+ st.write(advice)
85
+
86
+ # Chatbot feature
87
+ st.subheader("Chat with the Advisor")
88
+ user_query = st.text_input("Ask your question:")
89
+ if user_query:
90
+ chatbot_response = generator(f"User asked: {user_query}. Response:", max_length=50)[0]['generated_text']
91
+ st.write("Advisor Response:", chatbot_response)