ZainMalik0925 commited on
Commit
1858b46
·
verified ·
1 Parent(s): a2acbd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -136
app.py CHANGED
@@ -1,16 +1,12 @@
1
  import streamlit as st
2
  import pandas as pd
3
- from io import BytesIO
4
  import plotly.graph_objects as go
5
 
6
  # Set page configurations
7
  st.set_page_config(page_title="GreenLens-AI", layout="wide")
8
 
9
  # Page title and description
10
- st.markdown(
11
- "<h1 style='text-align: center; color: #4CAF50;'>GreenLens-AI</h1>",
12
- unsafe_allow_html=True,
13
- )
14
  st.markdown(
15
  """
16
  <p style='text-align: center; color: #4CAF50;'>
@@ -20,11 +16,11 @@ st.markdown(
20
  unsafe_allow_html=True,
21
  )
22
 
23
- # File uploader in the sidebar
24
  st.sidebar.header("Step 1: Upload Dataset")
25
- uploaded_file = st.sidebar.file_uploader("Upload Dataset to Initiate ", type=["xlsx"])
26
 
27
- # Initialize default values for data dicts
28
  fiber_impact_data = None
29
  transport_impact_data = None
30
  washing_impact_data = None
@@ -32,33 +28,16 @@ washing_impact_data = None
32
  # Function to process the uploaded Excel file
33
  @st.cache_data
34
  def process_excel(file):
35
- """Process the uploaded .xlsx file and extract required data."""
36
  try:
37
- # Load Excel content
38
  excel_content = pd.ExcelFile(file)
39
-
40
- # Required sheet names
41
- required_sheets = ["Fiber Impact Data", "Transport Impact Data", "Washing Data"]
42
- if not all(sheet in excel_content.sheet_names for sheet in required_sheets):
43
- raise Exception(f"Required sheets are missing. Expected: {', '.join(required_sheets)}")
44
-
45
- # Load and validate each sheet
46
  fiber_data = pd.read_excel(file, sheet_name="Fiber Impact Data")
47
  transport_data = pd.read_excel(file, sheet_name="Transport Impact Data")
48
  washing_data = pd.read_excel(file, sheet_name="Washing Data")
49
 
50
- # Validate required columns
51
- if not {"Fiber Type", "Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"}.issubset(fiber_data.columns):
52
- raise Exception("Missing required columns in the 'Fiber Impact Data' sheet.")
53
- if not {"Transport Mode", "CFP (kg CO2e/km)"}.issubset(transport_data.columns):
54
- raise Exception("Missing required columns in the 'Transport Impact Data' sheet.")
55
- if not {"Washing Temperature", "Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"}.issubset(washing_data.columns):
56
- raise Exception("Missing required columns in the 'Washing Data' sheet.")
57
-
58
- # Convert data into dictionaries for dynamic calculations
59
  fiber_impact_data = fiber_data.set_index("Fiber Type")[["Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"]].to_dict(orient="index")
60
  transport_impact_data = transport_data.set_index("Transport Mode")["CFP (kg CO2e/km)"].to_dict()
61
- washing_impact_data = washing_data.set_index("Washing Temperature")[["Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]].to_dict(orient="index")
62
 
63
  return fiber_impact_data, transport_impact_data, washing_impact_data
64
  except Exception as e:
@@ -69,117 +48,114 @@ def process_excel(file):
69
  if uploaded_file:
70
  fiber_impact_data, transport_impact_data, washing_impact_data = process_excel(uploaded_file)
71
 
72
- # Sidebar for user inputs
73
- st.sidebar.header("Step 2: Input Product Details")
74
-
75
- # Product-specific inputs (static values available before dataset upload)
76
- product_type = st.sidebar.selectbox("Product Type", ["T-shirt", "Jeans", "Shirt", "Carpet"])
77
- product_weight = st.sidebar.number_input("Product Weight (kg)", min_value=0.01, step=0.01, value=0.5)
78
-
79
- # Fiber composition inputs (static values)
80
- st.sidebar.subheader("Material Composition (%)")
81
- cotton_percent = st.sidebar.slider("Conventional Cotton (%)", 0, 100, 50)
82
- polyester_percent = st.sidebar.slider("Polyester (%)", 0, 100, 30)
83
- nylon_percent = st.sidebar.slider("Nylon 6 (%)", 0, 100, 10)
84
- acrylic_percent = st.sidebar.slider("Acrylic (%)", 0, 100, 5)
85
- viscose_percent = st.sidebar.slider("Viscose (%)", 0, 100, 5)
86
-
87
- # Validate composition percentages
88
- total_percentage = cotton_percent + polyester_percent + nylon_percent + acrylic_percent + viscose_percent
89
- if total_percentage != 100:
90
- st.sidebar.error("The total of all fiber percentages must equal 100%!")
91
-
92
- st.sidebar.write(f"Total Material Percentage: {total_percentage}%")
93
-
94
- # Lifecycle inputs (dynamic inputs added only if data is available)
95
- if washing_impact_data and transport_impact_data:
96
- st.sidebar.header("Step 3: Input Lifecycle Details")
97
- washing_temperature = st.sidebar.selectbox("Washing Temperature", list(washing_impact_data.keys()))
98
- washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
99
- use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
100
- transport_mode = st.sidebar.selectbox("Transport Mode", list(transport_impact_data.keys()))
101
- transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
102
-
103
- # Function to calculate footprints
104
- def calculate_footprints(weight, composition, lifecycle_inputs):
105
- try:
106
- water_footprint = 0
107
- energy_footprint = 0
108
- carbon_footprint = 0
109
-
110
- # Fiber contributions
111
- for fiber, percentage in composition.items():
112
- if fiber in fiber_impact_data:
113
- data = fiber_impact_data[fiber]
114
- fraction = percentage / 100
115
- water_footprint += data["Water (L/kg)"] * weight * fraction
116
- energy_footprint += data["Energy (MJ/kg)"] * weight * fraction
117
- carbon_footprint += data["Carbon (kg CO2e/kg)"] * weight * fraction
118
-
119
- # Transport impacts
120
- transport_factor = transport_impact_data.get(lifecycle_inputs["transport_mode"], 0)
121
- carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
122
-
123
- # Washing impacts
124
- washing_data = washing_impact_data.get(lifecycle_inputs["washing_temperature"], {})
125
- washing_energy = washing_data.get("Energy Use (MJ/wash)", 0) * lifecycle_inputs["washing_cycles"]
126
- washing_carbon = washing_data.get("Carbon (kg CO2e/wash)", 0) * lifecycle_inputs["washing_cycles"]
127
- dryer_carbon = washing_data.get("Dryer CFP (kg CO2e/cycle)", 0) if lifecycle_inputs["use_dryer"] else 0
128
- energy_footprint += washing_energy
129
- carbon_footprint += washing_carbon + (dryer_carbon * lifecycle_inputs["washing_cycles"])
130
-
131
- return water_footprint, energy_footprint, carbon_footprint
132
- except Exception as e:
133
- st.error(f"Error in calculations: {e}")
134
- return None, None, None
135
-
136
- # Composition dictionary
137
- composition = {
138
- "Conventional Cotton": cotton_percent,
139
- "Polyester": polyester_percent,
140
- "Nylon 6": nylon_percent,
141
- "Acrylic": acrylic_percent,
142
- "Viscose": viscose_percent,
143
  }
144
 
145
- # Perform calculations
146
- if total_percentage == 100:
147
- water_fp, energy_fp, carbon_fp = calculate_footprints(
148
- product_weight,
149
- composition,
150
- {
151
- "transport_mode": transport_mode,
152
- "transport_distance": transport_distance,
153
- "washing_temperature": washing_temperature,
154
- "washing_cycles": washing_cycles,
155
- "use_dryer": use_dryer,
156
- },
157
- )
158
-
159
- if water_fp is not None:
160
- st.subheader("Calculated Results")
161
- st.markdown(
162
- f"""
163
- - **Water Footprint**: {water_fp:.2f} liters
164
- - **Energy Footprint**: {energy_fp:.2f} MJ
165
- - **Carbon Footprint**: {carbon_fp:.2f} kgCO2e
166
- """
167
- )
168
-
169
- # Visualization
 
 
 
 
 
170
  fig = go.Figure()
171
- fig.add_trace(
172
- go.Bar(
173
- x=["Water Footprint", "Energy Footprint", "Carbon Footprint"],
174
- y=[water_fp, energy_fp, carbon_fp],
175
- text=[f"{water_fp:.2f} L", f"{energy_fp:.2f} MJ", f"{carbon_fp:.2f} kgCO2e"],
176
- textposition="auto",
177
- marker=dict(color=["blue", "orange", "green"]),
178
- )
179
- )
180
- fig.update_layout(
181
- title="Footprint Breakdown", xaxis_title="Footprint Type", yaxis_title="Value"
182
- )
183
  st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
 
 
184
  else:
185
- st.info("Please upload a valid Dataset to begin.")
 
1
  import streamlit as st
2
  import pandas as pd
 
3
  import plotly.graph_objects as go
4
 
5
  # Set page configurations
6
  st.set_page_config(page_title="GreenLens-AI", layout="wide")
7
 
8
  # Page title and description
9
+ st.markdown("<h1 style='text-align: center; color: #4CAF50;'>GreenLens-AI</h1>", unsafe_allow_html=True)
 
 
 
10
  st.markdown(
11
  """
12
  <p style='text-align: center; color: #4CAF50;'>
 
16
  unsafe_allow_html=True,
17
  )
18
 
19
+ # Sidebar for file upload
20
  st.sidebar.header("Step 1: Upload Dataset")
21
+ uploaded_file = st.sidebar.file_uploader("Upload your Excel file (.xlsx)", type=["xlsx"])
22
 
23
+ # Initialize empty data variables
24
  fiber_impact_data = None
25
  transport_impact_data = None
26
  washing_impact_data = None
 
28
  # Function to process the uploaded Excel file
29
  @st.cache_data
30
  def process_excel(file):
 
31
  try:
 
32
  excel_content = pd.ExcelFile(file)
 
 
 
 
 
 
 
33
  fiber_data = pd.read_excel(file, sheet_name="Fiber Impact Data")
34
  transport_data = pd.read_excel(file, sheet_name="Transport Impact Data")
35
  washing_data = pd.read_excel(file, sheet_name="Washing Data")
36
 
37
+ # Convert into dictionaries for dynamic calculations
 
 
 
 
 
 
 
 
38
  fiber_impact_data = fiber_data.set_index("Fiber Type")[["Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"]].to_dict(orient="index")
39
  transport_impact_data = transport_data.set_index("Transport Mode")["CFP (kg CO2e/km)"].to_dict()
40
+ washing_impact_data = washing_data.set_index("Washing Temperature")[["Water (L/kg)", "Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]].to_dict(orient="index")
41
 
42
  return fiber_impact_data, transport_impact_data, washing_impact_data
43
  except Exception as e:
 
48
  if uploaded_file:
49
  fiber_impact_data, transport_impact_data, washing_impact_data = process_excel(uploaded_file)
50
 
51
+ # Sidebar settings
52
+ st.sidebar.header("Optional: Enable Comparison")
53
+ comparison_mode = st.sidebar.checkbox("Enable Comparison Mode")
54
+
55
+ # Function to calculate footprints
56
+ def calculate_footprints(weight, composition, lifecycle_inputs):
57
+ water_footprint = 0
58
+ energy_footprint = 0
59
+ carbon_footprint = 0
60
+
61
+ for fiber, percentage in composition.items():
62
+ if fiber in fiber_impact_data:
63
+ data = fiber_impact_data[fiber]
64
+ fraction = percentage / 100
65
+ water_footprint += data["Water (L/kg)"] * weight * fraction
66
+ energy_footprint += data["Energy (MJ/kg)"] * weight * fraction
67
+ carbon_footprint += data["Carbon (kg CO2e/kg)"] * weight * fraction
68
+
69
+ transport_factor = transport_impact_data.get(lifecycle_inputs["transport_mode"], 0)
70
+ carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
71
+
72
+ washing_data = washing_impact_data.get(lifecycle_inputs["washing_temperature"], {})
73
+ washing_water = washing_data.get("Water (L/kg)", 0) * lifecycle_inputs["washing_cycles"]
74
+ washing_energy = washing_data.get("Energy Use (MJ/wash)", 0) * lifecycle_inputs["washing_cycles"]
75
+ washing_carbon = washing_data.get("Carbon (kg CO2e/wash)", 0) * lifecycle_inputs["washing_cycles"]
76
+ dryer_carbon = washing_data.get("Dryer CFP (kg CO2e/cycle)", 0) if lifecycle_inputs["use_dryer"] else 0
77
+
78
+ water_footprint += washing_water
79
+ energy_footprint += washing_energy
80
+ carbon_footprint += washing_carbon + (dryer_carbon * lifecycle_inputs["washing_cycles"])
81
+
82
+ return water_footprint, energy_footprint, carbon_footprint
83
+
84
+ # Composition input function
85
+ def composition_input():
86
+ st.subheader("Material Composition (%)")
87
+ cotton = st.number_input("Conventional Cotton (%)", min_value=0, max_value=100, value=50, step=1)
88
+ polyester = st.number_input("Polyester (%)", min_value=0, max_value=100, value=30, step=1)
89
+ nylon = st.number_input("Nylon 6 (%)", min_value=0, max_value=100, value=10, step=1)
90
+ acrylic = st.number_input("Acrylic (%)", min_value=0, max_value=100, value=5, step=1)
91
+ viscose = st.number_input("Viscose (%)", min_value=0, max_value=100, value=5, step=1)
92
+
93
+ total = cotton + polyester + nylon + acrylic + viscose
94
+ if total != 100:
95
+ st.error("Total fiber composition must equal 100%!")
96
+ return {"Conventional Cotton": cotton, "Polyester": polyester, "Nylon 6": nylon, "Acrylic": acrylic, "Viscose": viscose} if total == 100 else None
97
+
98
+ # Inputs for lifecycle details
99
+ def lifecycle_input():
100
+ st.subheader("Lifecycle Details")
101
+ washing_cycles = st.number_input("Number of Washing Cycles", min_value=0, value=30, step=1)
102
+ washing_temperature = st.selectbox("Washing Temperature", list(washing_impact_data.keys()))
103
+ use_dryer = st.checkbox("Use Tumble Dryer?")
104
+ transport_mode = st.selectbox("Transport Mode", list(transport_impact_data.keys()))
105
+ transport_distance = st.number_input("Transport Distance (km)", min_value=0, step=10, value=100)
106
+ return {
107
+ "washing_cycles": washing_cycles,
108
+ "washing_temperature": washing_temperature,
109
+ "use_dryer": use_dryer,
110
+ "transport_mode": transport_mode,
111
+ "transport_distance": transport_distance,
 
 
 
 
 
 
 
 
 
 
112
  }
113
 
114
+ # Main calculation logic
115
+ if uploaded_file and fiber_impact_data and transport_impact_data and washing_impact_data:
116
+ if comparison_mode:
117
+ # Comparison mode enabled
118
+ st.header("Scenario 1")
119
+ composition1 = composition_input()
120
+ lifecycle1 = lifecycle_input()
121
+
122
+ st.header("Scenario 2")
123
+ composition2 = composition_input()
124
+ lifecycle2 = lifecycle_input()
125
+
126
+ if composition1 and composition2:
127
+ water_fp1, energy_fp1, carbon_fp1 = calculate_footprints(1, composition1, lifecycle1)
128
+ water_fp2, energy_fp2, carbon_fp2 = calculate_footprints(1, composition2, lifecycle2)
129
+
130
+ # Display results side by side
131
+ col1, col2 = st.columns(2)
132
+ with col1:
133
+ st.subheader("Scenario 1 Results")
134
+ st.markdown(f"- **Water Footprint**: {water_fp1:.2f} liters")
135
+ st.markdown(f"- **Energy Footprint**: {energy_fp1:.2f} MJ")
136
+ st.markdown(f"- **Carbon Footprint**: {carbon_fp1:.2f} kg CO2e")
137
+ with col2:
138
+ st.subheader("Scenario 2 Results")
139
+ st.markdown(f"- **Water Footprint**: {water_fp2:.2f} liters")
140
+ st.markdown(f"- **Energy Footprint**: {energy_fp2:.2f} MJ")
141
+ st.markdown(f"- **Carbon Footprint**: {carbon_fp2:.2f} kg CO2e")
142
+
143
+ # Visual comparison
144
  fig = go.Figure()
145
+ fig.add_trace(go.Bar(name="Scenario 1", x=["Water", "Energy", "Carbon"], y=[water_fp1, energy_fp1, carbon_fp1]))
146
+ fig.add_trace(go.Bar(name="Scenario 2", x=["Water", "Energy", "Carbon"], y=[water_fp2, energy_fp2, carbon_fp2]))
147
+ fig.update_layout(barmode="group", title="Comparison of Scenarios")
 
 
 
 
 
 
 
 
 
148
  st.plotly_chart(fig)
149
+ else:
150
+ # Single calculation
151
+ composition = composition_input()
152
+ lifecycle = lifecycle_input()
153
+
154
+ if composition:
155
+ water_fp, energy_fp, carbon_fp = calculate_footprints(1, composition, lifecycle)
156
+ st.subheader("Results")
157
+ st.markdown(f"- **Water Footprint**: {water_fp:.2f} liters")
158
+ st.markdown(f"- **Energy Footprint**: {energy_fp:.2f} MJ")
159
+ st.markdown(f"- **Carbon Footprint**: {carbon_fp:.2f} kg CO2e")
160
  else:
161
+ st.info("Please upload a dataset to proceed.")