ZainMalik0925 commited on
Commit
6dd1918
·
verified ·
1 Parent(s): abef095

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +180 -67
app.py CHANGED
@@ -1,72 +1,185 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import requests
4
- import io
5
-
6
- # Function to load the data from the Google Sheets link
7
- def load_data_from_google_sheets(sheet_url):
8
- sheet_id = sheet_url.split('/d/')[1].split('/')[0]
9
- export_url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=xlsx"
10
-
11
- # Downloading the sheet content
12
- response = requests.get(export_url)
13
-
14
- if response.status_code == 200:
15
- file = io.BytesIO(response.content)
16
- data = pd.read_excel(file)
17
- return data
18
- else:
19
- st.error("Failed to load the dataset. Please check the link.")
20
- return None
21
 
22
- # Function to calculate CFP, Energy Footprints, Water Footprints, and Ecological Footprints
23
- def calculate_footprints(data, user_inputs):
24
- # Logic for calculation based on user inputs and loaded dataset
25
- # For the sake of example, let's assume you are calculating the CFP for the user's input
26
- # Here, we can write the necessary calculations as per the LCA logic
27
- cfp = user_inputs['carbon_emission'] * data['emission_factor'].mean() # Example calculation
28
- energy_fp = user_inputs['energy_consumed'] * data['energy_factor'].mean()
29
- water_fp = user_inputs['water_used'] * data['water_factor'].mean()
30
- ecological_fp = user_inputs['ecological_impact'] * data['ecological_factor'].mean()
31
-
32
- return cfp, energy_fp, water_fp, ecological_fp
33
-
34
- # Streamlit App Logic
35
- def main():
36
- st.title("Life Cycle Assessment (LCA) Calculator")
37
-
38
- # Load the dataset from the provided link
39
- sheet_url = "https://docs.google.com/spreadsheets/d/1CfuCrqRvu1LjBVmJh9b7mZiHBJ2kvJ0t/edit?usp=drive_link&ouid=108672166866225546443&rtpof=true&sd=true"
40
- data = load_data_from_google_sheets(sheet_url)
41
-
42
- if data is not None:
43
- st.write("Dataset loaded successfully.")
44
-
45
- # User Input for LCA variables
46
- st.subheader("Input Parameters")
47
-
48
- carbon_emission = st.number_input("Carbon Emission (kg CO2)", min_value=0.0)
49
- energy_consumed = st.number_input("Energy Consumed (kWh)", min_value=0.0)
50
- water_used = st.number_input("Water Used (liters)", min_value=0.0)
51
- ecological_impact = st.number_input("Ecological Impact (units)", min_value=0.0)
52
-
53
- user_inputs = {
54
- "carbon_emission": carbon_emission,
55
- "energy_consumed": energy_consumed,
56
- "water_used": water_used,
57
- "ecological_impact": ecological_impact
58
- }
59
 
60
- if st.button("Calculate LCA"):
61
- # Perform LCA calculations
62
- cfp, energy_fp, water_fp, ecological_fp = calculate_footprints(data, user_inputs)
63
-
64
- # Display results
65
- st.subheader("Results")
66
- st.write(f"Total Carbon Footprint (CFP): {cfp} kg CO2")
67
- st.write(f"Total Energy Footprint: {energy_fp} kWh")
68
- st.write(f"Total Water Footprint: {water_fp} liters")
69
- st.write(f"Total Ecological Footprint: {ecological_fp} units")
70
-
71
- if __name__ == "__main__":
72
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import requests
4
+ from io import BytesIO
5
+ import plotly.graph_objects as go
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Set Page Configurations
8
+ st.set_page_config(page_title="GreenLens-AI", layout="wide")
9
+
10
+ # Page title and description
11
+ st.markdown("<h1 style='text-align: center; color: #4CAF50;'>GreenLens-AI</h1>", unsafe_allow_html=True)
12
+ st.markdown(
13
+ """
14
+ <p style='text-align: center; color: #4CAF50; font-size: 18px;'>
15
+ A Comprehensive Tool for Calculating Water, Energy, and Carbon Footprints of Textile Products 🌍
16
+ </p>
17
+ """, unsafe_allow_html=True)
18
+
19
+ # Google Drive Dataset Link
20
+ DATASET_URL = "https://docs.google.com/uc?export=download&id=1CfuCrqRvu1LjBVmJh9b7mZiHBJ2kvJ0t"
21
+
22
+ # Step 1: Function to fetch and process the Excel dataset
23
+ @st.cache_data
24
+ def fetch_and_process_excel(url):
25
+ """Fetch and extract required data from the Excel dataset."""
26
+ try:
27
+ st.info("Fetching dataset from Google Drive...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ # Download the file
30
+ response = requests.get(url)
31
+ if response.status_code != 200:
32
+ raise Exception("Failed to download the file. Check the URL or permissions.")
33
+
34
+ # Read the Excel file into a pandas DataFrame
35
+ excel_content = BytesIO(response.content)
36
+ df = pd.read_excel(excel_content)
37
+
38
+ # Convert DataFrame into a dictionary for fiber impact data
39
+ # Assuming the Excel file has columns: "Fiber", "Water", "Energy", "Carbon"
40
+ if not all(col in df.columns for col in ["Fiber", "Water", "Energy", "Carbon"]):
41
+ raise Exception("Excel file does not have the required columns: Fiber, Water, Energy, Carbon.")
42
+
43
+ # Build the dictionary
44
+ fiber_impact_data = {}
45
+ for _, row in df.iterrows():
46
+ fiber_impact_data[row["Fiber"]] = {
47
+ "Water": row["Water"],
48
+ "Energy": row["Energy"],
49
+ "Carbon": row["Carbon"],
50
+ }
51
+
52
+ # Log the parsed dataset
53
+ st.write("Parsed Fiber Impact Data:", fiber_impact_data)
54
+ st.success("Dataset loaded successfully!")
55
+ return fiber_impact_data
56
+
57
+ except Exception as e:
58
+ st.error(f"Error loading or processing the Excel file: {e}")
59
+ return None
60
+
61
+ # Load dataset dynamically
62
+ fiber_impact_data = fetch_and_process_excel(DATASET_URL)
63
+
64
+ # Sidebar for User Inputs
65
+ st.sidebar.header("Input Product Details")
66
+
67
+ # Input Section: Product-Specific Inputs
68
+ product_type = st.sidebar.selectbox("Product Type", ["T-shirt", "Jeans", "Shirt", "Carpet"])
69
+ product_weight = st.sidebar.number_input("Product Weight (kg)", min_value=0.01, step=0.01, value=0.25)
70
+
71
+ # Fiber Composition Input
72
+ st.sidebar.subheader("Material Composition (%)")
73
+ cotton_percent = st.sidebar.slider("Cotton (%)", 0, 100, 50)
74
+ polyester_percent = st.sidebar.slider("Polyester (%)", 0, 100, 30)
75
+ nylon_percent = st.sidebar.slider("Nylon (%)", 0, 100, 10)
76
+ acrylic_percent = st.sidebar.slider("Acrylic (%)", 0, 100, 5)
77
+ viscose_percent = st.sidebar.slider("Viscose (%)", 0, 100, 5)
78
+
79
+ # Validation check: Percentages must add up to 100%
80
+ total_percentage = cotton_percent + polyester_percent + nylon_percent + acrylic_percent + viscose_percent
81
+ if total_percentage != 100:
82
+ st.sidebar.error("The total of all fiber percentages must equal 100%!")
83
+
84
+ st.sidebar.write(f"Total Material Percentage: {total_percentage}%") # Debugging sidebar inputs
85
+
86
+ # Lifecycle Inputs
87
+ st.sidebar.header("Lifecycle Details")
88
+ washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
89
+ washing_temperature = st.sidebar.selectbox("Washing Temperature", ["Cold", "30°C", "40°C", "60°C"])
90
+ use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
91
+ transport_mode = st.sidebar.selectbox("Transport Mode", ["Plane", "Ship", "Train", "Truck"])
92
+ transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
93
+
94
+ # Function to calculate footprints
95
+ def calculate_footprints(weight, composition, lifecycle_inputs):
96
+ """Calculate water, energy, and carbon footprints."""
97
+ try:
98
+ # Log inputs
99
+ st.write("Inputs to function:", weight, composition, lifecycle_inputs)
100
+
101
+ # Initialize footprints
102
+ water_footprint = 0
103
+ energy_footprint = 0
104
+ carbon_footprint = 0
105
+
106
+ # Fiber contributions
107
+ for fiber, percentage in composition.items():
108
+ if fiber in fiber_impact_data:
109
+ data = fiber_impact_data[fiber]
110
+ fraction = percentage / 100
111
+ water_footprint += data["Water"] * weight * fraction
112
+ energy_footprint += data["Energy"] * weight * fraction
113
+ carbon_footprint += data["Carbon"] * weight * fraction
114
+ else:
115
+ st.warning(f"No data found for fiber: {fiber}")
116
+
117
+ # Transportation impacts
118
+ transport_factor = {
119
+ "Plane": 1.102,
120
+ "Ship": 0.011,
121
+ "Train": 0.05,
122
+ "Truck": 0.25,
123
+ }.get(lifecycle_inputs["transport_mode"], 0)
124
+ carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
125
+
126
+ # Washing and drying impacts
127
+ washing_energy = {"Cold": 0.02, "30°C": 0.1, "40°C": 0.2, "60°C": 0.5}
128
+ dryer_energy = 0.5 if lifecycle_inputs["use_dryer"] else 0
129
+ carbon_footprint += (
130
+ washing_energy[lifecycle_inputs["washing_temperature"]] * lifecycle_inputs["washing_cycles"] * 0.05
131
+ )
132
+ energy_footprint += dryer_energy * lifecycle_inputs["washing_cycles"]
133
+
134
+ # Log final results
135
+ st.write("Calculated Results:", water_footprint, energy_footprint, carbon_footprint)
136
+ return water_footprint, energy_footprint, carbon_footprint
137
+
138
+ except Exception as e:
139
+ st.error(f"Error in calculations: {e}")
140
+ return None, None, None
141
+
142
+ # User inputs as a dictionary
143
+ user_inputs = {
144
+ "transport_mode": transport_mode,
145
+ "transport_distance": transport_distance,
146
+ "washing_temperature": washing_temperature,
147
+ "washing_cycles": washing_cycles,
148
+ "use_dryer": use_dryer,
149
+ }
150
+
151
+ # Collect the composition dictionary
152
+ composition = {
153
+ "Cotton": cotton_percent,
154
+ "Polyester": polyester_percent,
155
+ "Nylon": nylon_percent,
156
+ "Acrylic": acrylic_percent,
157
+ "Viscose": viscose_percent,
158
+ }
159
+
160
+ # Run Calculations if conditions are met
161
+ if fiber_impact_data and total_percentage == 100:
162
+ water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
163
+
164
+ if water_fp is not None:
165
+ # Display results
166
+ st.subheader("Calculated Results")
167
+ st.markdown(f"""
168
+ - **Water Footprint**: {water_fp:.2f} liters
169
+ - **Energy Footprint**: {energy_fp:.2f} MJ
170
+ - **Carbon Footprint**: {carbon_fp:.2f} kgCO2e
171
+ """)
172
+
173
+ # Visualization
174
+ fig = go.Figure()
175
+ fig.add_trace(go.Bar(
176
+ x=["Water Footprint", "Energy Footprint", "Carbon Footprint"],
177
+ y=[water_fp, energy_fp, carbon_fp],
178
+ text=[f"{water_fp:.2f} L", f"{energy_fp:.2f} MJ", f"{carbon_fp:.2f} kgCO2e"],
179
+ textposition="auto",
180
+ marker=dict(color=["blue", "orange", "green"])
181
+ ))
182
+ fig.update_layout(title="Footprint Breakdown", xaxis_title="Footprint Type", yaxis_title="Value")
183
+ st.plotly_chart(fig)
184
+ else:
185
+ st.error("Ensure dataset is loaded and the composition sums to 100%.")