Spaces:
Sleeping
Sleeping
File size: 5,940 Bytes
f0801c7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
import streamlit as st
import os
from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
import pandas as pd
import matplotlib.pyplot as plt
# Streamlit App
st.title("SustainaBot: Solar Energy Advisor")
st.sidebar.header("User Input")
# Input for Groq API Key
GROQ_API_KEY = "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"
client = Groq(api_key = GROQ_API_KEY)
# Initialize the RAG components
tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq")
retriever = RagRetriever.from_pretrained("facebook/rag-token-nq")
model = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq")
# Helper function for energy demand calculation
def calculate_energy(appliances):
total_energy = 0
total_power = 0
for app, details in appliances.items():
total_energy += details['quantity'] * details['wattage'] * details['hours'] / 1000 # Energy in kWh
total_power += details['quantity'] * details['wattage'] # Power in Watts
return total_energy, total_power
# Predefined appliances with their default wattage
predefined_appliances = {
"Select Appliance": 0, # Default placeholder
"LED Light": 10,
"Air Conditioner": 2000,
"Refrigerator": 150,
"Washing Machine": 500,
"Fan": 75,
"Laptop": 50,
"Television": 100,
"Microwave Oven": 1000,
"Electric Water Heater": 1500,
"Dishwasher": 1200,
"Coffee Maker": 800,
"Toaster": 1200,
"Hair Dryer": 1500,
"Electric Kettle": 1500,
"Oven": 2000,
"Vacuum Cleaner": 1000,
"Iron": 1200,
"Blender": 300,
"Clothes Dryer": 1800,
"Space Heater": 1500,
"Dehumidifier": 700,
"Freezer": 400,
"Electric Grill": 1200,
"Sewing Machine": 100,
"Projector": 300,
"Gaming Console": 200,
"Electric Fan Heater": 1500
}
if "appliances" not in st.session_state:
st.session_state.appliances = {}
# Function to reset appliance state
def reset_appliances():
st.session_state.appliances = {}
# Add appliance inputs dynamically
appliance_count = len(st.session_state.appliances)
for i in range(appliance_count):
with st.sidebar.expander(f"Appliance {i+1} Details"):
app_name = st.selectbox(f"Appliance {i+1} Name", options=list(predefined_appliances.keys()), key=f"app{i}_name")
quantity = st.number_input(f"Quantity of {app_name}", min_value=1, step=1, key=f"app{i}_quantity", value=1)
wattage = predefined_appliances.get(app_name, 0) # Default wattage
hours = st.number_input(f"Hours used per day", min_value=1, step=1, key=f"app{i}_hours", value=1)
power = quantity * wattage
st.write(f"**Total Power (Watts):** {power} W")
if app_name and app_name != "Select Appliance":
st.session_state.appliances[app_name] = {"quantity": quantity, "wattage": wattage, "hours": hours}
# Button to add more appliances
if st.sidebar.button("Add Appliance"):
st.session_state.appliances[f"Appliance {len(st.session_state.appliances) + 1}"] = {"quantity": 1, "wattage": 0, "hours": 0}
# Button to reset appliances
if st.sidebar.button("Reset Appliances"):
reset_appliances()
# Input for location and budget
location = st.sidebar.text_input("Enter your Location (City, Country)")
budget = st.sidebar.number_input("Enter your Budget for Solar System (in USD)", min_value=100, step=10)
if st.sidebar.button("Submit"):
# Calculate energy demand
daily_energy, total_power = calculate_energy(st.session_state.appliances)
st.write(f"### Total Daily Energy Demand: {daily_energy:.2f} kWh")
st.write(f"### Total Power Demand: {total_power:.2f} W")
# RAG model interaction
prompt = f"Provide solar recommendations for a location: {location}, daily energy: {daily_energy:.2f} kWh, budget: {budget} USD."
# Tokenizing and retrieval process
inputs = tokenizer(prompt, return_tensors="pt")
question_input = inputs['input_ids']
doc_scores, docs = retriever(question_input)
# Generating the response
generated_output = model.generate(input_ids=question_input, context_input_ids=docs[0]['text'])
answer = tokenizer.decode(generated_output[0], skip_special_tokens=True)
st.write("### Solar Recommendations")
st.write(answer)
# Display potential savings and pricing (same as before)
savings = daily_energy * 30 * 0.2 # Assuming $0.2/kWh savings
st.write(f"By switching to solar, you could save approximately **${savings:.2f} per month!**")
# Approximate Pricing Section
st.write("### Solar Installation Prices")
st.write("""
- **1 kW System:** Approx. PKR 120,000 - 150,000
- **3 kW System:** Approx. PKR 350,000 - 400,000
- **5 kW System:** Approx. PKR 600,000 - 700,000
- **10 kW System:** Approx. PKR 1,200,000 - 1,500,000
""")
# Visualization
st.write("### Appliance Breakdown")
if st.session_state.appliances:
appliance_data = pd.DataFrame([
{"Appliance": k, "Quantity": v['quantity'], "Daily Energy (kWh)": v['quantity'] * v['wattage'] * v['hours'] / 1000, "Power (W)": v['quantity'] * v['wattage']}
for k, v in st.session_state.appliances.items()
])
st.table(appliance_data)
# Bar chart for visualization
st.write("### Energy Consumption by Appliance")
fig, ax = plt.subplots()
ax.bar(appliance_data["Appliance"], appliance_data["Daily Energy (kWh)"], color='skyblue')
ax.set_xlabel("Appliances")
ax.set_ylabel("Daily Energy (kWh)")
ax.set_title("Energy Consumption Breakdown")
plt.xticks(rotation=45, ha="right")
st.pyplot(fig)
# Highlight the most energy-consuming appliance
max_energy_app = appliance_data.loc[appliance_data["Daily Energy (kWh)"].idxmax()]
st.write(f"**Most Energy-Consuming Appliance:** {max_energy_app['Appliance']} consuming {max_energy_app['Daily Energy (kWh)']:.2f} kWh daily.")
|