ZainMalik0925 commited on
Commit
0b68406
·
verified ·
1 Parent(s): 7b7971b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -51
app.py CHANGED
@@ -14,15 +14,17 @@ st.markdown(
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=1K9elWl_s6lMlzY3JbPqKliNHBZ8n4BOr"
21
 
22
- # Step 1: Function to fetch and process Excel dataset
23
  @st.cache_data
24
  def fetch_and_process_excel(url):
25
- """Fetch and extract data from the updated .xlsx file."""
26
  try:
27
  st.info("Fetching dataset from Google Drive...")
28
 
@@ -31,30 +33,37 @@ def fetch_and_process_excel(url):
31
  if response.status_code != 200:
32
  raise Exception("Failed to download the file. Check the URL or permissions.")
33
 
34
- # Load the Excel file
35
  excel_content = BytesIO(response.content)
36
 
37
- # Read all sheets into pandas DataFrames
38
  fiber_data = pd.read_excel(excel_content, sheet_name="Fiber Impact Data")
39
- transport_data = pd.read_excel(excel_content, sheet_name="Transport Data")
40
  washing_data = pd.read_excel(excel_content, sheet_name="Washing Data")
41
 
42
- # Convert Fiber Impact Data into a dictionary
43
- fiber_impact_data = fiber_data.set_index("Fiber Type")[["Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"]].to_dict(orient="index")
44
-
45
- # Convert Transport Data into a dictionary for dynamic lookup
 
 
 
 
 
 
 
 
 
 
 
 
46
  transport_impact_data = transport_data.set_index("Transport Mode")["CFP (kg CO2e/km)"].to_dict()
47
 
48
- # Convert Washing Data into a dictionary for dynamic lookup
49
  washing_impact_data = washing_data.set_index("Washing Temperature")[
50
  ["Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]
51
  ].to_dict(orient="index")
52
 
53
- # Debugging: Log extracted data for verification
54
- st.write("Fiber Impact Data:", fiber_impact_data)
55
- st.write("Transport Impact Data:", transport_impact_data)
56
- st.write("Washing Impact Data:", washing_impact_data)
57
-
58
  st.success("Dataset loaded successfully!")
59
  return fiber_impact_data, transport_impact_data, washing_impact_data
60
 
@@ -62,13 +71,13 @@ def fetch_and_process_excel(url):
62
  st.error(f"Error loading or processing the Excel file: {e}")
63
  return None, None, None
64
 
 
65
  # Load data dynamically from Google Drive
66
  fiber_impact_data, transport_impact_data, washing_impact_data = fetch_and_process_excel(DATASET_URL)
67
 
68
  # Sidebar for User Inputs
69
  st.sidebar.header("Input Product Details")
70
 
71
- # Input Section: Product-Specific Inputs
72
  product_type = st.sidebar.selectbox("Product Type", ["T-shirt", "Jeans", "Shirt", "Carpet"])
73
  product_weight = st.sidebar.number_input("Product Weight (kg)", min_value=0.01, step=0.01, value=0.25)
74
 
@@ -90,9 +99,9 @@ st.sidebar.write(f"Total Material Percentage: {total_percentage}%")
90
  # Lifecycle Inputs
91
  st.sidebar.header("Lifecycle Details")
92
  washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
93
- washing_temperature = st.sidebar.selectbox("Washing Temperature", ["Cold", "30°C", "40°C", "60°C"])
94
  use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
95
- transport_mode = st.sidebar.selectbox("Transport Mode", list(transport_impact_data.keys()))
96
  transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
97
 
98
  # Function to calculate footprints
@@ -112,8 +121,6 @@ def calculate_footprints(weight, composition, lifecycle_inputs):
112
  water_footprint += data["Water (L/kg)"] * weight * fraction
113
  energy_footprint += data["Energy (MJ/kg)"] * weight * fraction
114
  carbon_footprint += data["Carbon (kg CO2e/kg)"] * weight * fraction
115
- else:
116
- st.warning(f"No data found for fiber: {fiber}")
117
 
118
  # Transportation impacts
119
  transport_factor = transport_impact_data.get(lifecycle_inputs["transport_mode"], 0)
@@ -121,13 +128,12 @@ def calculate_footprints(weight, composition, lifecycle_inputs):
121
 
122
  # Washing and drying impacts
123
  washing_data = washing_impact_data.get(lifecycle_inputs["washing_temperature"], {})
124
- washing_energy = washing_data.get("Energy Use (MJ/wash)", 0)
125
- washing_carbon = washing_data.get("Carbon (kg CO2e/wash)", 0)
126
  dryer_carbon = washing_data.get("Dryer CFP (kg CO2e/cycle)", 0) if lifecycle_inputs["use_dryer"] else 0
127
 
128
- carbon_footprint += washing_carbon * lifecycle_inputs["washing_cycles"]
129
- energy_footprint += washing_energy * lifecycle_inputs["washing_cycles"]
130
- carbon_footprint += dryer_carbon * lifecycle_inputs["washing_cycles"]
131
 
132
  return water_footprint, energy_footprint, carbon_footprint
133
 
@@ -135,6 +141,7 @@ def calculate_footprints(weight, composition, lifecycle_inputs):
135
  st.error(f"Error in calculations: {e}")
136
  return None, None, None
137
 
 
138
  # User inputs as a dictionary
139
  user_inputs = {
140
  "transport_mode": transport_mode,
@@ -155,27 +162,4 @@ composition = {
155
 
156
  # Run Calculations if conditions are met
157
  if fiber_impact_data and total_percentage == 100:
158
- water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
159
-
160
- if water_fp is not None:
161
- # Display results
162
- st.subheader("Calculated Results")
163
- st.markdown(f"""
164
- - **Water Footprint**: {water_fp:.2f} liters
165
- - **Energy Footprint**: {energy_fp:.2f} MJ
166
- - **Carbon Footprint**: {carbon_fp:.2f} kgCO2e
167
- """)
168
-
169
- # Visualization
170
- fig = go.Figure()
171
- fig.add_trace(go.Bar(
172
- x=["Water Footprint", "Energy Footprint", "Carbon Footprint"],
173
- y=[water_fp, energy_fp, carbon_fp],
174
- text=[f"{water_fp:.2f} L", f"{energy_fp:.2f} MJ", f"{carbon_fp:.2f} kgCO2e"],
175
- textposition="auto",
176
- marker=dict(color=["blue", "orange", "green"])
177
- ))
178
- fig.update_layout(title="Footprint Breakdown", xaxis_title="Footprint Type", yaxis_title="Value")
179
- st.plotly_chart(fig)
180
- else:
181
- st.error("Ensure dataset is loaded and the composition sums to 100%.")
 
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
+ """,
18
+ unsafe_allow_html=True,
19
+ )
20
 
21
  # Google Drive Dataset Link
22
+ DATASET_URL = "https://ppl-ai-file-upload.s3.amazonaws.com/web/direct-files/23453236/59122b29-51ec-4aab-8b41-5301f001a94b/DataSet01.xlsx"
23
 
24
+ # Function to fetch and process Excel dataset
25
  @st.cache_data
26
  def fetch_and_process_excel(url):
27
+ """Fetch and extract data from the provided .xlsx file."""
28
  try:
29
  st.info("Fetching dataset from Google Drive...")
30
 
 
33
  if response.status_code != 200:
34
  raise Exception("Failed to download the file. Check the URL or permissions.")
35
 
36
+ # Load the Excel file into a BytesIO object
37
  excel_content = BytesIO(response.content)
38
 
39
+ # Read all relevant sheets into pandas DataFrames
40
  fiber_data = pd.read_excel(excel_content, sheet_name="Fiber Impact Data")
41
+ transport_data = pd.read_excel(excel_content, sheet_name="Transport Impact Data")
42
  washing_data = pd.read_excel(excel_content, sheet_name="Washing Data")
43
 
44
+ # Verify required columns exist in all sheets
45
+ if not {"Fiber Type", "Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"}.issubset(fiber_data.columns):
46
+ raise Exception("Required columns missing in 'Fiber Impact Data'.")
47
+ if not {"Transport Mode", "CFP (kg CO2e/km)"}.issubset(transport_data.columns):
48
+ raise Exception("Required columns missing in 'Transport Impact Data'.")
49
+ if not {"Washing Temperature", "Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"}.issubset(
50
+ washing_data.columns
51
+ ):
52
+ raise Exception("Required columns missing in 'Washing Data'.")
53
+
54
+ # Process Fiber Impact Data
55
+ fiber_impact_data = fiber_data.set_index("Fiber Type")[["Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"]].to_dict(
56
+ orient="index"
57
+ )
58
+
59
+ # Process Transport Impact Data
60
  transport_impact_data = transport_data.set_index("Transport Mode")["CFP (kg CO2e/km)"].to_dict()
61
 
62
+ # Process Washing Data
63
  washing_impact_data = washing_data.set_index("Washing Temperature")[
64
  ["Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]
65
  ].to_dict(orient="index")
66
 
 
 
 
 
 
67
  st.success("Dataset loaded successfully!")
68
  return fiber_impact_data, transport_impact_data, washing_impact_data
69
 
 
71
  st.error(f"Error loading or processing the Excel file: {e}")
72
  return None, None, None
73
 
74
+
75
  # Load data dynamically from Google Drive
76
  fiber_impact_data, transport_impact_data, washing_impact_data = fetch_and_process_excel(DATASET_URL)
77
 
78
  # Sidebar for User Inputs
79
  st.sidebar.header("Input Product Details")
80
 
 
81
  product_type = st.sidebar.selectbox("Product Type", ["T-shirt", "Jeans", "Shirt", "Carpet"])
82
  product_weight = st.sidebar.number_input("Product Weight (kg)", min_value=0.01, step=0.01, value=0.25)
83
 
 
99
  # Lifecycle Inputs
100
  st.sidebar.header("Lifecycle Details")
101
  washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
102
+ washing_temperature = st.sidebar.selectbox("Washing Temperature", list(washing_impact_data.keys()) if washing_impact_data else [])
103
  use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
104
+ transport_mode = st.sidebar.selectbox("Transport Mode", list(transport_impact_data.keys()) if transport_impact_data else [])
105
  transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
106
 
107
  # Function to calculate footprints
 
121
  water_footprint += data["Water (L/kg)"] * weight * fraction
122
  energy_footprint += data["Energy (MJ/kg)"] * weight * fraction
123
  carbon_footprint += data["Carbon (kg CO2e/kg)"] * weight * fraction
 
 
124
 
125
  # Transportation impacts
126
  transport_factor = transport_impact_data.get(lifecycle_inputs["transport_mode"], 0)
 
128
 
129
  # Washing and drying impacts
130
  washing_data = washing_impact_data.get(lifecycle_inputs["washing_temperature"], {})
131
+ washing_energy = washing_data.get("Energy Use (MJ/wash)", 0) * lifecycle_inputs["washing_cycles"]
132
+ washing_carbon = washing_data.get("Carbon (kg CO2e/wash)", 0) * lifecycle_inputs["washing_cycles"]
133
  dryer_carbon = washing_data.get("Dryer CFP (kg CO2e/cycle)", 0) if lifecycle_inputs["use_dryer"] else 0
134
 
135
+ energy_footprint += washing_energy
136
+ carbon_footprint += washing_carbon + (dryer_carbon * lifecycle_inputs["washing_cycles"])
 
137
 
138
  return water_footprint, energy_footprint, carbon_footprint
139
 
 
141
  st.error(f"Error in calculations: {e}")
142
  return None, None, None
143
 
144
+
145
  # User inputs as a dictionary
146
  user_inputs = {
147
  "transport_mode": transport_mode,
 
162
 
163
  # Run Calculations if conditions are met
164
  if fiber_impact_data and total_percentage == 100:
165
+ water_fp, energy_fp, carb