ZainMalik0925 commited on
Commit
665f64e
·
verified ·
1 Parent(s): 3bcae4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -111
app.py CHANGED
@@ -1,39 +1,43 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.express as px
 
 
4
 
5
- # Add custom CSS for the background and highlighted text
6
  def add_background():
7
  background_url = "https://huggingface.co/spaces/ZainMalik0925/GreenLensAI_LCA/resolve/main/BKG03.jpg"
8
  css = f"""
9
  <style>
10
- .stApp {{
11
- background-image: url("{background_url}");
12
- background-size: cover;
13
- background-position: center;
14
- background-attachment: fixed;
15
- }}
16
- .highlight {{
17
- background-color: rgba(27, 27, 27, 0.7); /* 70% opaque black */
18
- padding: 10px;
19
- border-radius: 5px;
20
- margin-bottom: 15px;
21
- color: white;
22
- }}
23
  </style>
24
  """
25
  st.markdown(css, unsafe_allow_html=True)
26
 
27
- # Set up page configuration
28
  st.set_page_config(page_title="GreenLens AI", layout="wide")
 
 
29
  add_background()
30
 
31
  # App title and subtitle
32
  st.markdown("<h1 style='text-align: center; color: white;'>GreenLens AI</h1>", unsafe_allow_html=True)
33
  st.markdown(
34
  """
35
- <p style='text-align: center; color: white; font-size: 18px;'>
36
- A Comprehensive Tool for Assessing Water, Energy, and Carbon Footprints of Textile Products 🌍
37
  </p>
38
  """,
39
  unsafe_allow_html=True,
@@ -46,122 +50,190 @@ DATASET_URL = "https://huggingface.co/spaces/ZainMalik0925/GreenLensAI_LCA/resol
46
  @st.cache_data
47
  def process_dataset(url):
48
  try:
49
- # Read the Excel file
50
  excel_content = pd.ExcelFile(url)
51
  fiber_data = pd.read_excel(excel_content, sheet_name="Fiber Impact Data")
52
  transport_data = pd.read_excel(excel_content, sheet_name="Transport Impact Data")
53
  washing_data = pd.read_excel(excel_content, sheet_name="Washing Data")
54
 
55
- # Convert data into dictionaries for calculations
56
- fiber_impact_data = fiber_data.set_index("Fiber Type")[
57
- ["Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"]
58
- ].to_dict(orient="index")
59
  transport_impact_data = transport_data.set_index("Transport Mode")["CFP (kg CO2e/km)"].to_dict()
60
- washing_impact_data = washing_data.set_index("Washing Temperature")[
61
- ["Water (L/kg)", "Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]
62
- ].to_dict(orient="index")
63
-
64
  return fiber_impact_data, transport_impact_data, washing_impact_data
65
  except Exception as e:
66
  st.error(f"Error loading dataset: {e}")
67
  return None, None, None
68
 
69
  # Calculate footprints
70
- def calculate_footprints(weight, composition, lifecycle_inputs, fiber_data, transport_data, washing_data):
71
- try:
72
- water_fp, energy_fp, carbon_fp = 0.0, 0.0, 0.0
73
-
74
- # Fiber impacts
75
- for fiber, percentage in composition.items():
76
- if fiber in fiber_data:
77
- data = fiber_data[fiber]
78
- fraction = percentage / 100
79
- water_fp += data["Water (L/kg)"] * weight * fraction
80
- energy_fp += data["Energy (MJ/kg)"] * weight * fraction
81
- carbon_fp += data["Carbon (kg CO2e/kg)"] * weight * fraction
82
-
83
- # Transportation impacts
84
- if lifecycle_inputs["transport_mode"] in transport_data:
85
- distance = lifecycle_inputs["transport_distance"]
86
- carbon_fp += transport_data[lifecycle_inputs["transport_mode"]] * distance * weight
87
-
88
- # Washing impacts
89
- if lifecycle_inputs["washing_temperature"] in washing_data:
90
- wash_data = washing_data[lifecycle_inputs["washing_temperature"]]
91
- washing_cycles = lifecycle_inputs["washing_cycles"]
92
- water_fp += wash_data["Water (L/kg)"] * washing_cycles
93
- energy_fp += wash_data["Energy Use (MJ/wash)"] * washing_cycles
94
- carbon_fp += wash_data["Carbon (kg CO2e/wash)"] * washing_cycles
95
-
96
- if lifecycle_inputs["use_dryer"]:
97
- carbon_fp += wash_data["Dryer CFP (kg CO2e/cycle)"] * washing_cycles
98
-
99
- # Convert water from liters to kiloliters
100
- water_fp /= 1000
101
-
102
- return water_fp, energy_fp, carbon_fp
103
- except Exception as e:
104
- st.error(f"Error calculating footprints: {e}")
105
- return 0.0, 0.0, 0.0
106
 
107
  # Sidebar inputs
108
- def get_inputs():
109
- weight = st.sidebar.number_input("Product Weight (kg)", min_value=0.0, value=1.0, step=0.1)
110
- st.sidebar.text("Material Composition (%)")
111
- materials = {
112
- "Conventional Cotton": st.sidebar.number_input("Cotton (%)", 0, 100, 50),
113
- "Polyester": st.sidebar.number_input("Polyester (%)", 0, 100, 50),
114
- "Nylon 6": st.sidebar.number_input("Nylon (%)", 0, 100, 0),
115
- "Acrylic": st.sidebar.number_input("Acrylic (%)", 0, 100, 0),
116
- "Viscose": st.sidebar.number_input("Viscose (%)", 0, 100, 0),
117
- }
118
-
119
- transport_mode = st.sidebar.selectbox("Transport Mode", ["Truck", "Airplane"])
120
- distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, value=1000)
121
-
122
- washing_cycles = st.sidebar.number_input("Washing Cycles", min_value=0, value=0)
123
- washing_temperature = st.sidebar.selectbox("Washing Temperature", ["Cold", "Warm", "Hot"])
124
- use_dryer = st.sidebar.checkbox("Use Dryer?", value=False)
125
 
126
  lifecycle_inputs = {
 
 
 
127
  "transport_mode": transport_mode,
128
- "transport_distance": distance,
129
- "washing_cycles": washing_cycles,
130
- "washing_temperature": washing_temperature,
131
- "use_dryer": use_dryer,
132
  }
133
 
134
- return weight, materials, lifecycle_inputs
135
-
136
- # Load data
137
- fiber_data, transport_data, washing_data = process_dataset(DATASET_URL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
- if fiber_data and transport_data and washing_data:
140
- # Get user inputs
141
- weight, composition, lifecycle = get_inputs()
142
- water, energy, carbon = calculate_footprints(weight, composition, lifecycle, fiber_data, transport_data, washing_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
- # Display numerical results
145
- st.markdown(
146
- f"""
147
- <div class='highlight'>
148
- <h2>Results</h2>
149
- <p>Water Footprint: {water:.2f} kL</p>
150
- <p>Energy Footprint: {energy:.2f} MJ</p>
151
- <p>Carbon Footprint: {carbon:.2f} kg CO2e</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  </div>
153
- """,
154
- unsafe_allow_html=True,
155
- )
156
 
157
- # Display bar chart
158
- footprint_data = pd.DataFrame(
159
- {
160
  "Footprint Type": ["Water (kL)", "Energy (MJ)", "Carbon (kg CO2e)"],
161
- "Values": [water, energy, carbon],
162
- }
163
- )
164
- fig = px.bar(footprint_data, x="Footprint Type", y="Values", title="Environmental Footprint Breakdown")
165
- st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
166
  else:
167
- st.error("Failed to load required data.")
 
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.express as px
4
+ import os
5
+ from groq import Groq
6
 
7
+ # Add custom CSS for the app background and highlighted text
8
  def add_background():
9
  background_url = "https://huggingface.co/spaces/ZainMalik0925/GreenLensAI_LCA/resolve/main/BKG03.jpg"
10
  css = f"""
11
  <style>
12
+ .stApp {{
13
+ background-image: url("{background_url}");
14
+ background-size: cover;
15
+ background-position: center;
16
+ background-attachment: fixed;
17
+ }}
18
+ .highlight {{
19
+ background-color: rgba(27, 27, 27, 0.7); /* 70% opaque black */
20
+ padding: 10px;
21
+ border-radius: 5px;
22
+ margin-bottom: 15px;
23
+ color: white;
24
+ }}
25
  </style>
26
  """
27
  st.markdown(css, unsafe_allow_html=True)
28
 
29
+ # Set page configuration
30
  st.set_page_config(page_title="GreenLens AI", layout="wide")
31
+
32
+ # Call the background function
33
  add_background()
34
 
35
  # App title and subtitle
36
  st.markdown("<h1 style='text-align: center; color: white;'>GreenLens AI</h1>", unsafe_allow_html=True)
37
  st.markdown(
38
  """
39
+ <p style='text-align: center; color: white; font-size: 18px;'>
40
+ A Comprehensive Tool for Assessing Water, Energy, and Carbon Footprints of Textile Products 🌍
41
  </p>
42
  """,
43
  unsafe_allow_html=True,
 
50
  @st.cache_data
51
  def process_dataset(url):
52
  try:
 
53
  excel_content = pd.ExcelFile(url)
54
  fiber_data = pd.read_excel(excel_content, sheet_name="Fiber Impact Data")
55
  transport_data = pd.read_excel(excel_content, sheet_name="Transport Impact Data")
56
  washing_data = pd.read_excel(excel_content, sheet_name="Washing Data")
57
 
58
+ # Convert data to dictionaries for 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")[["Water (L/kg)", "Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]].to_dict(orient="index")
 
 
 
62
  return fiber_impact_data, transport_impact_data, washing_impact_data
63
  except Exception as e:
64
  st.error(f"Error loading dataset: {e}")
65
  return None, None, None
66
 
67
  # Calculate footprints
68
+ def calculate_footprints(weight, composition, lifecycle_inputs):
69
+ water_fp, energy_fp, carbon_fp = 0, 0, 0
70
+ for fiber, percentage in composition.items():
71
+ if fiber in fiber_impact_data:
72
+ data = fiber_impact_data[fiber]
73
+ fraction = percentage / 100
74
+ water_fp += data["Water (L/kg)"] * weight * fraction
75
+ energy_fp += data["Energy (MJ/kg)"] * weight * fraction
76
+ carbon_fp += data["Carbon (kg CO2e/kg)"] * weight * fraction
77
+
78
+ # Add transport impact
79
+ if lifecycle_inputs["transport_mode"] in transport_impact_data:
80
+ carbon_fp += transport_impact_data[lifecycle_inputs["transport_mode"]] * lifecycle_inputs["transport_distance"] * weight
81
+
82
+ # Add washing impact
83
+ if lifecycle_inputs["washing_temperature"] in washing_impact_data:
84
+ washing_data = washing_impact_data[lifecycle_inputs["washing_temperature"]]
85
+ washing_water = washing_data["Water (L/kg)"] * lifecycle_inputs["washing_cycles"]
86
+ washing_energy = washing_data["Energy Use (MJ/wash)"] * lifecycle_inputs["washing_cycles"]
87
+ washing_carbon = washing_data["Carbon (kg CO2e/wash)"] * lifecycle_inputs["washing_cycles"]
88
+ dryer_carbon = washing_data["Dryer CFP (kg CO2e/cycle)"] if lifecycle_inputs["use_dryer"] else 0
89
+ water_fp += washing_water
90
+ energy_fp += washing_energy
91
+ carbon_fp += washing_carbon + (dryer_carbon * lifecycle_inputs["washing_cycles"])
92
+
93
+ # Convert water from liters to kiloliters
94
+ water_fp /= 1000
95
+ return water_fp, energy_fp, carbon_fp
 
 
 
 
 
 
 
 
96
 
97
  # Sidebar inputs
98
+ def get_inputs(prefix):
99
+ weight = st.sidebar.number_input(f"{prefix} Product Weight (kg)", min_value=0.0, value=0.0, step=0.01, key=f"{prefix}_weight")
100
+ st.sidebar.markdown(f"<h3 style='color: green;'>{prefix} Material Composition (%)</h3>", unsafe_allow_html=True)
101
+ cotton = st.sidebar.number_input("Conventional Cotton (%)", 0, 100, 0, step=1, key=f"{prefix}_cotton")
102
+ polyester = st.sidebar.number_input("Polyester (%)", 0, 100, 0, step=1, key=f"{prefix}_polyester")
103
+ nylon = st.sidebar.number_input("Nylon 6 (%)", 0, 100, 0, step=1, key=f"{prefix}_nylon")
104
+ acrylic = st.sidebar.number_input("Acrylic (%)", 0, 100, 0, step=1, key=f"{prefix}_acrylic")
105
+ viscose = st.sidebar.number_input("Viscose (%)", 0, 100, 0, step=1, key=f"{prefix}_viscose")
106
+
107
+ if cotton + polyester + nylon + acrylic + viscose != 100:
108
+ st.sidebar.error("Fiber composition must sum to 100%!")
109
+
110
+ st.sidebar.markdown(f"<h3 style='color: green;'>{prefix} Transport Inputs</h3>", unsafe_allow_html=True)
111
+ transport_mode = st.sidebar.selectbox(f"{prefix} Transport Mode", list(transport_impact_data.keys()), key=f"{prefix}_transport_mode")
112
+ transport_distance = st.sidebar.number_input(f"{prefix} Transport Distance (km)", min_value=0, value=0, step=10, key=f"{prefix}_transport_distance")
 
 
113
 
114
  lifecycle_inputs = {
115
+ "washing_cycles": st.sidebar.number_input(f"{prefix} Washing Cycles", min_value=0, value=0, key=f"{prefix}_wash_cycles"),
116
+ "washing_temperature": st.sidebar.selectbox(f"{prefix} Washing Temperature", list(washing_impact_data.keys()), key=f"{prefix}_wash_temp"),
117
+ "use_dryer": st.sidebar.checkbox(f"{prefix} Use Dryer?", key=f"{prefix}_use_dryer"),
118
  "transport_mode": transport_mode,
119
+ "transport_distance": transport_distance,
 
 
 
120
  }
121
 
122
+ composition = {
123
+ "Conventional Cotton": cotton,
124
+ "Polyester": polyester,
125
+ "Nylon 6": nylon,
126
+ "Acrylic": acrylic,
127
+ "Viscose": viscose,
128
+ }
129
+ return weight, composition, lifecycle_inputs
130
+
131
+ # Adjust graph styling
132
+ def style_figure(fig):
133
+ fig.update_layout(
134
+ plot_bgcolor="rgba(27, 27, 27, 0.8)", # 20% transparency
135
+ paper_bgcolor="rgba(27, 27, 27, 0.8)", # 20% transparency
136
+ font=dict(color="white"), # Font color set to white
137
+ title_font=dict(size=18, color="white"), # Title font white
138
+ xaxis=dict(title_font=dict(color="white"), tickfont=dict(color="white")),
139
+ yaxis=dict(title_font=dict(color="white"), tickfont=dict(color="white")),
140
+ )
141
+ fig.update_traces(marker=dict(color="white", line=dict(color="gray", width=1))) # Simulate 3D effect with border
142
+ return fig
143
 
144
+ # Generate recommendations using Groq API
145
+ def generate_recommendations(water, energy, carbon):
146
+ try:
147
+ client = Groq(api_key="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")
148
+ prompt = (
149
+ f"The environmental impact values for a textile product are as follows:\n"
150
+ f"Water Footprint: {water:.2f} kL\n"
151
+ f"Energy Footprint: {energy:.2f} MJ\n"
152
+ f"Carbon Footprint: {carbon:.2f} kg CO2e\n"
153
+ f"Provide recommendations to lower these impacts."
154
+ )
155
+
156
+ response = client.chat.completions.create(
157
+ messages=[{"role": "user", "content": prompt}],
158
+ model="llama-3.3-70b-versatile",
159
+ )
160
+
161
+ return response.choices[0].message.content
162
+ except Exception as e:
163
+ return f"Error generating recommendations: {e}"
164
+
165
+ # Main application logic
166
+ fiber_impact_data, transport_impact_data, washing_impact_data = process_dataset(DATASET_URL)
167
+
168
+ if fiber_impact_data and transport_impact_data and washing_impact_data:
169
+ comparison_mode = st.sidebar.checkbox("Enable Comparison Mode")
170
+
171
+ if comparison_mode:
172
+ # Input for two assessments
173
+ col1, col2 = st.columns(2)
174
+ with col1:
175
+ weight1, composition1, lifecycle1 = get_inputs("Assessment 1")
176
+ with col2:
177
+ weight2, composition2, lifecycle2 = get_inputs("Assessment 2")
178
+
179
+ # Calculate footprints for both assessments
180
+ water1, energy1, carbon1 = calculate_footprints(weight1, composition1, lifecycle1)
181
+ water2, energy2, carbon2 = calculate_footprints(weight2, composition2, lifecycle2)
182
+
183
+ # Display numerical comparison
184
+ st.markdown(f"""
185
+ <div class="highlight">
186
+ <h2>Numerical Comparison</h2>
187
+ <p>Assessment 1: Water: {water1:.2f} kL, Energy: {energy1:.2f} MJ, Carbon: {carbon1:.2f} kg CO2e</p>
188
+ <p>Assessment 2: Water: {water2:.2f} kL, Energy: {energy2:.2f} MJ, Carbon: {carbon2:.2f} kg CO2e</p>
189
+ </div>
190
+ """, unsafe_allow_html=True)
191
 
192
+ # Bar chart comparison
193
+ comparison_data = pd.DataFrame({
194
+ "Footprint Type": ["Water (kL)", "Energy (MJ)", "Carbon (kg CO2e)"],
195
+ "Assessment 1": [water1, energy1, carbon1],
196
+ "Assessment 2": [water2, energy2, carbon2],
197
+ })
198
+ fig = px.bar(
199
+ comparison_data.melt(id_vars="Footprint Type", var_name="Assessment", value_name="Value"),
200
+ x="Footprint Type",
201
+ y="Value",
202
+ color="Assessment",
203
+ title="Comparison of Assessments"
204
+ )
205
+ st.plotly_chart(style_figure(fig))
206
+ else:
207
+ # Input for a single assessment
208
+ weight, composition, lifecycle = get_inputs("Single")
209
+ water, energy, carbon = calculate_footprints(weight, composition, lifecycle)
210
+
211
+ # Display results
212
+ st.markdown(f"""
213
+ <div class="highlight">
214
+ <h2>Single Assessment Results</h2>
215
+ <p>Water Footprint: {water:.2f} kL</p>
216
+ <p>Energy Footprint: {energy:.2f} MJ</p>
217
+ <p>Carbon Footprint: {carbon:.2f} kg CO2e</p>
218
  </div>
219
+ """, unsafe_allow_html=True)
 
 
220
 
221
+ # Bar chart for single assessment
222
+ result_data = pd.DataFrame({
 
223
  "Footprint Type": ["Water (kL)", "Energy (MJ)", "Carbon (kg CO2e)"],
224
+ "Value": [water, energy, carbon]
225
+ })
226
+ fig = px.bar(result_data, x="Footprint Type", y="Value", title="Single Assessment Footprint Breakdown")
227
+ st.plotly_chart(style_figure(fig))
228
+
229
+ # Generate recommendations if impact values are not zero
230
+ if water > 0 or energy > 0 or carbon > 0:
231
+ recommendations = generate_recommendations(water, energy, carbon)
232
+ st.markdown(f"""
233
+ <div class="highlight">
234
+ <h2>Recommendations to Lower Environmental Impacts</h2>
235
+ <p>{recommendations}</p>
236
+ </div>
237
+ """, unsafe_allow_html=True)
238
  else:
239
+ st.error("Failed to load dataset.")