Update app.py
Browse files
app.py
CHANGED
@@ -1,95 +1,107 @@
|
|
1 |
import os
|
|
|
2 |
import pandas as pd
|
3 |
import numpy as np
|
4 |
-
import streamlit as st
|
5 |
from groq import Groq
|
|
|
|
|
6 |
|
7 |
GROQ_API_KEY = "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"
|
8 |
-
|
9 |
-
# Initialize Groq API client
|
10 |
client = Groq(api_key=GROQ_API_KEY)
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
if household_id:
|
15 |
-
# Filter data for a specific household
|
16 |
-
household_data = data[data["Household ID"] == household_id]
|
17 |
-
else:
|
18 |
-
household_data = data
|
19 |
-
|
20 |
-
# Check if the filtered data is empty
|
21 |
-
if household_data.empty:
|
22 |
-
return "No data available for the specified Household ID.", None
|
23 |
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
household_data.groupby("Time Period")["Energy Usage (kWh)"]
|
29 |
-
.sum()
|
30 |
-
.idxmax()
|
31 |
-
)
|
32 |
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
40 |
|
41 |
-
# Function to
|
42 |
-
def
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
],
|
51 |
-
model="llama3-8b-8192",
|
52 |
-
stream=False,
|
53 |
-
)
|
54 |
-
return response.choices[0].message.content
|
55 |
-
except Exception as e:
|
56 |
-
return f"An error occurred: {e}"
|
57 |
|
58 |
-
#
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
#
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
|
|
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
if filtered_data is None:
|
77 |
-
st.warning(report_summary) # Display message for no data
|
78 |
-
else:
|
79 |
-
st.subheader("Energy Usage Summary")
|
80 |
-
st.text(report_summary)
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
recommendations = generate_recommendations(context)
|
86 |
-
st.text(recommendations)
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
st.
|
91 |
-
""
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import streamlit as st
|
3 |
import pandas as pd
|
4 |
import numpy as np
|
|
|
5 |
from groq import Groq
|
6 |
+
from sentence_transformers import SentenceTransformer
|
7 |
+
import faiss
|
8 |
|
9 |
GROQ_API_KEY = "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"
|
10 |
+
# Initialize Groq API Client
|
|
|
11 |
client = Groq(api_key=GROQ_API_KEY)
|
12 |
|
13 |
+
# Load Pretrained Embedding Model
|
14 |
+
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
# Initialize global variables
|
17 |
+
uploaded_file = None
|
18 |
+
faiss_index = None
|
19 |
+
dataframe = None
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
# Function to load and preprocess dataset
|
22 |
+
def load_dataset(file):
|
23 |
+
global dataframe, faiss_index
|
24 |
+
dataframe = pd.read_csv(file)
|
25 |
+
st.success("Dataset loaded successfully!")
|
26 |
+
# Create FAISS index for the dataset
|
27 |
+
embeddings = embedding_model.encode(dataframe["Energy Usage (kWh)"].astype(str).tolist())
|
28 |
+
faiss_index = faiss.IndexFlatL2(embeddings.shape[1])
|
29 |
+
faiss_index.add(np.array(embeddings))
|
30 |
|
31 |
+
# Function to retrieve relevant rows
|
32 |
+
def retrieve_relevant_data(query, top_k=5):
|
33 |
+
if dataframe is None or faiss_index is None:
|
34 |
+
st.error("Please upload a dataset first.")
|
35 |
+
return []
|
36 |
+
query_embedding = embedding_model.encode([query])
|
37 |
+
distances, indices = faiss_index.search(np.array(query_embedding), top_k)
|
38 |
+
relevant_rows = dataframe.iloc[indices[0]].to_dict(orient="records")
|
39 |
+
return relevant_rows
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
+
# Function to analyze data and generate cost-saving recommendations
|
42 |
+
def generate_cost_saving_recommendations(data):
|
43 |
+
if not data:
|
44 |
+
return "No relevant data found for recommendations."
|
45 |
+
|
46 |
+
total_energy_usage = sum(row["Energy Usage (kWh)"] for row in data)
|
47 |
+
avg_energy_usage = total_energy_usage / len(data)
|
48 |
+
total_cost = sum(row["Cost"] for row in data)
|
49 |
+
|
50 |
+
recommendations = [
|
51 |
+
f"Total energy usage: {total_energy_usage:.2f} kWh",
|
52 |
+
f"Average energy usage per household: {avg_energy_usage:.2f} kWh",
|
53 |
+
f"Total cost: ${total_cost:.2f}",
|
54 |
+
"Recommendations:",
|
55 |
+
"- Implement energy-efficient appliances.",
|
56 |
+
"- Use renewable energy sources like solar or wind.",
|
57 |
+
"- Schedule high-energy tasks during off-peak hours.",
|
58 |
+
"- Conduct regular maintenance to reduce energy wastage."
|
59 |
+
]
|
60 |
+
return "\n".join(recommendations)
|
61 |
|
62 |
+
# Function to generate a detailed analysis report
|
63 |
+
def generate_report(query):
|
64 |
+
relevant_data = retrieve_relevant_data(query)
|
65 |
+
context = "\n".join([str(row) for row in relevant_data])
|
66 |
+
chat_completion = client.chat.completions.create(
|
67 |
+
messages=[
|
68 |
+
{
|
69 |
+
"role": "user",
|
70 |
+
"content": f"Based on the following query: '{query}' and context:\n{context}\nProvide an energy usage analysis report."
|
71 |
+
}
|
72 |
+
],
|
73 |
+
model="llama3-8b-8192",
|
74 |
+
stream=False,
|
75 |
+
)
|
76 |
+
detailed_report = chat_completion.choices[0].message.content
|
77 |
+
cost_saving_recommendations = generate_cost_saving_recommendations(relevant_data)
|
78 |
+
return detailed_report, cost_saving_recommendations
|
79 |
|
80 |
+
# Streamlit app configuration
|
81 |
+
st.title("Energy Usage Analysis & Cost-Saving Report Generator")
|
82 |
+
st.sidebar.header("Upload Dataset")
|
83 |
|
84 |
+
# File upload
|
85 |
+
uploaded_file = st.sidebar.file_uploader("Upload your energy usage dataset (CSV)", type=["csv"])
|
86 |
+
if uploaded_file is not None:
|
87 |
+
load_dataset(uploaded_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
+
# Query input
|
90 |
+
st.header("Generate Energy Usage Report")
|
91 |
+
query = st.text_input("Enter your query (e.g., 'Analyze peak usage times in urban areas')")
|
|
|
|
|
92 |
|
93 |
+
if st.button("Generate Report"):
|
94 |
+
if uploaded_file is None:
|
95 |
+
st.error("Please upload a dataset first.")
|
96 |
+
elif query.strip() == "":
|
97 |
+
st.error("Please enter a query.")
|
98 |
+
else:
|
99 |
+
with st.spinner("Generating report..."):
|
100 |
+
try:
|
101 |
+
detailed_report, cost_saving_recommendations = generate_report(query)
|
102 |
+
st.subheader("Energy Usage Analysis Report")
|
103 |
+
st.write(detailed_report)
|
104 |
+
st.subheader("Cost-Saving Recommendations")
|
105 |
+
st.write(cost_saving_recommendations)
|
106 |
+
except Exception as e:
|
107 |
+
st.error(f"An error occurred: {e}")
|