Abdullah-Basar commited on
Commit
373619f
·
verified ·
1 Parent(s): dc10896

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -56
app.py CHANGED
@@ -1,21 +1,21 @@
1
  import streamlit as st
2
  import os
3
- from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
4
  import pandas as pd
5
  import matplotlib.pyplot as plt
 
6
 
7
- # Streamlit App
8
- st.title("SustainaBot: Solar Energy Advisor")
9
- st.sidebar.header("User Input")
10
-
11
- # Input for Groq API Key
12
  GROQ_API_KEY = "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"
13
  client = Groq(api_key = GROQ_API_KEY)
14
 
15
  # Initialize the RAG components
16
- tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
17
- retriever = RagRetriever.from_pretrained("facebook/rag-token-nq")
18
- model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq")
 
 
 
 
19
 
20
  # Helper function for energy demand calculation
21
  def calculate_energy(appliances):
@@ -58,6 +58,16 @@ predefined_appliances = {
58
  "Electric Fan Heater": 1500
59
  }
60
 
 
 
 
 
 
 
 
 
 
 
61
  if "appliances" not in st.session_state:
62
  st.session_state.appliances = {}
63
 
@@ -97,52 +107,27 @@ if st.sidebar.button("Submit"):
97
  st.write(f"### Total Power Demand: {total_power:.2f} W")
98
 
99
  # RAG model interaction
100
- prompt = f"Provide solar recommendations for a location: {location}, daily energy: {daily_energy:.2f} kWh, budget: {budget} USD."
101
-
102
- # Tokenizing and retrieval process
103
- inputs = tokenizer(prompt, return_tensors="pt")
104
- question_input = inputs['input_ids']
105
- doc_scores, docs = retriever(question_input)
106
-
107
- # Generating the response
108
- generated_output = model.generate(input_ids=question_input, context_input_ids=docs[0]['text'])
109
- answer = tokenizer.decode(generated_output[0], skip_special_tokens=True)
110
-
111
- st.write("### Solar Recommendations")
112
- st.write(answer)
113
-
114
- # Display potential savings and pricing (same as before)
 
 
 
 
 
 
 
115
  savings = daily_energy * 30 * 0.2 # Assuming $0.2/kWh savings
116
  st.write(f"By switching to solar, you could save approximately **${savings:.2f} per month!**")
117
-
118
- # Approximate Pricing Section
119
- st.write("### Solar Installation Prices")
120
- st.write("""
121
- - **1 kW System:** Approx. PKR 120,000 - 150,000
122
- - **3 kW System:** Approx. PKR 350,000 - 400,000
123
- - **5 kW System:** Approx. PKR 600,000 - 700,000
124
- - **10 kW System:** Approx. PKR 1,200,000 - 1,500,000
125
- """)
126
-
127
- # Visualization
128
- st.write("### Appliance Breakdown")
129
- if st.session_state.appliances:
130
- appliance_data = pd.DataFrame([
131
- {"Appliance": k, "Quantity": v['quantity'], "Daily Energy (kWh)": v['quantity'] * v['wattage'] * v['hours'] / 1000, "Power (W)": v['quantity'] * v['wattage']}
132
- for k, v in st.session_state.appliances.items()
133
- ])
134
- st.table(appliance_data)
135
-
136
- # Bar chart for visualization
137
- st.write("### Energy Consumption by Appliance")
138
- fig, ax = plt.subplots()
139
- ax.bar(appliance_data["Appliance"], appliance_data["Daily Energy (kWh)"], color='skyblue')
140
- ax.set_xlabel("Appliances")
141
- ax.set_ylabel("Daily Energy (kWh)")
142
- ax.set_title("Energy Consumption Breakdown")
143
- plt.xticks(rotation=45, ha="right")
144
- st.pyplot(fig)
145
-
146
- # Highlight the most energy-consuming appliance
147
- max_energy_app = appliance_data.loc[appliance_data["Daily Energy (kWh)"].idxmax()]
148
- st.write(f"**Most Energy-Consuming Appliance:** {max_energy_app['Appliance']} consuming {max_energy_app['Daily Energy (kWh)']:.2f} kWh daily.")
 
1
  import streamlit as st
2
  import os
3
+ import numpy as np
4
  import pandas as pd
5
  import matplotlib.pyplot as plt
6
+ from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
7
 
 
 
 
 
 
8
  GROQ_API_KEY = "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"
9
  client = Groq(api_key = GROQ_API_KEY)
10
 
11
  # Initialize the RAG components
12
+ try:
13
+ tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
14
+ retriever = RagRetriever.from_pretrained("facebook/rag-token-nq", use_dummy_dataset=True)
15
+ model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq")
16
+ except Exception as e:
17
+ st.error(f"Error loading RAG components: {e}")
18
+ st.stop()
19
 
20
  # Helper function for energy demand calculation
21
  def calculate_energy(appliances):
 
58
  "Electric Fan Heater": 1500
59
  }
60
 
61
+ # Streamlit App
62
+ st.title("SustainaBot: Solar Energy Advisor")
63
+ st.sidebar.header("User Input")
64
+
65
+ # Option for Groq API Key
66
+ #groq_api_key = st.sidebar.text_input("Enter your Groq API Key", type="password")
67
+
68
+ # Inputs
69
+ st.sidebar.subheader("Enter Appliance Details")
70
+
71
  if "appliances" not in st.session_state:
72
  st.session_state.appliances = {}
73
 
 
107
  st.write(f"### Total Power Demand: {total_power:.2f} W")
108
 
109
  # RAG model interaction
110
+ try:
111
+ if not groq_api_key:
112
+ st.warning("No Groq API Key provided. RAG model will be used locally.")
113
+ else:
114
+ st.write("Using Groq API Key for enhanced recommendations.")
115
+
116
+ prompt = f"Provide solar recommendations for a location: {location}, daily energy: {daily_energy:.2f} kWh, budget: {budget} USD."
117
+ # Tokenizing and retrieval process
118
+ inputs = tokenizer(prompt, return_tensors="pt")
119
+ question_input = inputs['input_ids']
120
+ doc_scores, docs = retriever(question_input)
121
+
122
+ # Generating the response
123
+ generated_output = model.generate(input_ids=question_input, context_input_ids=docs[0]['text'])
124
+ answer = tokenizer.decode(generated_output[0], skip_special_tokens=True)
125
+
126
+ st.write("### Solar Recommendations")
127
+ st.write(answer)
128
+ except Exception as e:
129
+ st.error(f"Error during RAG model processing: {e}")
130
+
131
+ # Display potential savings and pricing
132
  savings = daily_energy * 30 * 0.2 # Assuming $0.2/kWh savings
133
  st.write(f"By switching to solar, you could save approximately **${savings:.2f} per month!**")