Abdullah-Basar commited on
Commit
f0801c7
·
verified ·
1 Parent(s): 03319bb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
22
+ total_energy = 0
23
+ total_power = 0
24
+ for app, details in appliances.items():
25
+ total_energy += details['quantity'] * details['wattage'] * details['hours'] / 1000 # Energy in kWh
26
+ total_power += details['quantity'] * details['wattage'] # Power in Watts
27
+ return total_energy, total_power
28
+
29
+ # Predefined appliances with their default wattage
30
+ predefined_appliances = {
31
+ "Select Appliance": 0, # Default placeholder
32
+ "LED Light": 10,
33
+ "Air Conditioner": 2000,
34
+ "Refrigerator": 150,
35
+ "Washing Machine": 500,
36
+ "Fan": 75,
37
+ "Laptop": 50,
38
+ "Television": 100,
39
+ "Microwave Oven": 1000,
40
+ "Electric Water Heater": 1500,
41
+ "Dishwasher": 1200,
42
+ "Coffee Maker": 800,
43
+ "Toaster": 1200,
44
+ "Hair Dryer": 1500,
45
+ "Electric Kettle": 1500,
46
+ "Oven": 2000,
47
+ "Vacuum Cleaner": 1000,
48
+ "Iron": 1200,
49
+ "Blender": 300,
50
+ "Clothes Dryer": 1800,
51
+ "Space Heater": 1500,
52
+ "Dehumidifier": 700,
53
+ "Freezer": 400,
54
+ "Electric Grill": 1200,
55
+ "Sewing Machine": 100,
56
+ "Projector": 300,
57
+ "Gaming Console": 200,
58
+ "Electric Fan Heater": 1500
59
+ }
60
+
61
+ if "appliances" not in st.session_state:
62
+ st.session_state.appliances = {}
63
+
64
+ # Function to reset appliance state
65
+ def reset_appliances():
66
+ st.session_state.appliances = {}
67
+
68
+ # Add appliance inputs dynamically
69
+ appliance_count = len(st.session_state.appliances)
70
+ for i in range(appliance_count):
71
+ with st.sidebar.expander(f"Appliance {i+1} Details"):
72
+ app_name = st.selectbox(f"Appliance {i+1} Name", options=list(predefined_appliances.keys()), key=f"app{i}_name")
73
+ quantity = st.number_input(f"Quantity of {app_name}", min_value=1, step=1, key=f"app{i}_quantity", value=1)
74
+ wattage = predefined_appliances.get(app_name, 0) # Default wattage
75
+ hours = st.number_input(f"Hours used per day", min_value=1, step=1, key=f"app{i}_hours", value=1)
76
+ power = quantity * wattage
77
+ st.write(f"**Total Power (Watts):** {power} W")
78
+ if app_name and app_name != "Select Appliance":
79
+ st.session_state.appliances[app_name] = {"quantity": quantity, "wattage": wattage, "hours": hours}
80
+
81
+ # Button to add more appliances
82
+ if st.sidebar.button("Add Appliance"):
83
+ st.session_state.appliances[f"Appliance {len(st.session_state.appliances) + 1}"] = {"quantity": 1, "wattage": 0, "hours": 0}
84
+
85
+ # Button to reset appliances
86
+ if st.sidebar.button("Reset Appliances"):
87
+ reset_appliances()
88
+
89
+ # Input for location and budget
90
+ location = st.sidebar.text_input("Enter your Location (City, Country)")
91
+ budget = st.sidebar.number_input("Enter your Budget for Solar System (in USD)", min_value=100, step=10)
92
+
93
+ if st.sidebar.button("Submit"):
94
+ # Calculate energy demand
95
+ daily_energy, total_power = calculate_energy(st.session_state.appliances)
96
+ st.write(f"### Total Daily Energy Demand: {daily_energy:.2f} kWh")
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.")