ZainMalik0925 commited on
Commit
3268523
·
verified ·
1 Parent(s): 74f4f09

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -64
app.py CHANGED
@@ -1,59 +1,173 @@
1
- import os
2
- from groq import Groq
3
  import streamlit as st
4
  import pandas as pd
5
  import plotly.express as px
 
 
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Groq API Initialization
9
-
10
- # Initialize the Groq client with the API key
11
- client = Groq(api_key="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")
12
-
13
-
14
 
15
- def analyze_results_with_groq(results, mode="single"):
16
- """
17
- Interacts with Groq API to analyze results and provide suggestions.
18
- Args:
19
- results (dict): The results containing water, energy, and carbon footprints.
20
- mode (str): Either 'single' or 'comparison' analysis mode.
21
 
22
- Returns:
23
- str: Suggestions or description of the results.
 
24
  """
25
- # Prepare the message content for Groq API
26
- if mode == "single":
27
- message_content = (
28
- f"Analyze the sustainability results for a single assessment: "
29
- f"Water: {results['water']:.2f} kL, Energy: {results['energy']:.2f} MJ, "
30
- f"Carbon: {results['carbon']:.2f} kg CO2e. Suggest alternative materials for better results."
31
- )
32
- else:
33
- message_content = (
34
- f"Compare two sustainability assessments:\n"
35
- f"Assessment 1 - Water: {results['water1']:.2f} kL, Energy: {results['energy1']:.2f} MJ, "
36
- f"Carbon: {results['carbon1']:.2f} kg CO2e.\n"
37
- f"Assessment 2 - Water: {results['water2']:.2f} kL, Energy: {results['energy2']:.2f} MJ, "
38
- f"Carbon: {results['carbon2']:.2f} kg CO2e.\n"
39
- f"Provide a brief analysis and suggest alternative materials if possible."
40
- )
41
-
42
- # Make a call to the Groq API
43
- chat_completion = client.chat.completions.create(
44
- messages=[{"role": "user", "content": message_content}],
45
- model="llama-3.3-70b-versatile",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- # Return the content of the response
49
- return chat_completion.choices[0].message.content
 
 
50
 
 
 
 
51
 
52
- # Other code remains unchanged...
53
- # Load dataset, calculate footprints, and inputs...
54
 
55
  if fiber_impact_data and transport_impact_data and washing_impact_data:
56
  comparison_mode = st.sidebar.checkbox("Enable Comparison Mode")
 
57
  if comparison_mode:
58
  # Input for two assessments
59
  col1, col2 = st.columns(2)
@@ -67,10 +181,13 @@ if fiber_impact_data and transport_impact_data and washing_impact_data:
67
  water2, energy2, carbon2 = calculate_footprints(weight2, composition2, lifecycle2)
68
 
69
  # Display numerical comparison
70
- st.markdown(f"""<div class="highlight"><h2>Numerical Comparison</h2>
71
- <p>Assessment 1: Water: {water1:.2f} kL, Energy: {energy1:.2f} MJ, Carbon: {carbon1:.2f} kg CO2e</p>
72
- <p>Assessment 2: Water: {water2:.2f} kL, Energy: {energy2:.2f} MJ, Carbon: {carbon2:.2f} kg CO2e</p>
73
- </div>""", unsafe_allow_html=True)
 
 
 
74
 
75
  # Bar chart comparison
76
  comparison_data = pd.DataFrame({
@@ -80,27 +197,26 @@ if fiber_impact_data and transport_impact_data and washing_impact_data:
80
  })
81
  fig = px.bar(
82
  comparison_data.melt(id_vars="Footprint Type", var_name="Assessment", value_name="Value"),
83
- x="Footprint Type", y="Value", color="Assessment", title="Comparison of Assessments"
 
 
 
84
  )
85
  st.plotly_chart(style_figure(fig))
86
-
87
- # Use Groq to analyze comparative results
88
- results = {"water1": water1, "energy1": energy1, "carbon1": carbon1,
89
- "water2": water2, "energy2": energy2, "carbon2": carbon2}
90
- suggestion = analyze_results_with_groq(results, mode="comparison")
91
- st.markdown(f"<div class='highlight'><h3>Groq Analysis</h3><p>{suggestion}</p></div>", unsafe_allow_html=True)
92
-
93
  else:
94
  # Input for a single assessment
95
  weight, composition, lifecycle = get_inputs("Single")
96
  water, energy, carbon = calculate_footprints(weight, composition, lifecycle)
97
 
98
  # Display results
99
- st.markdown(f"""<div class="highlight"><h2>Single Assessment Results</h2>
100
- <p>Water Footprint: {water:.2f} kL</p>
101
- <p>Energy Footprint: {energy:.2f} MJ</p>
102
- <p>Carbon Footprint: {carbon:.2f} kg CO2e</p>
103
- </div>""", unsafe_allow_html=True)
 
 
 
104
 
105
  # Bar chart for single assessment
106
  result_data = pd.DataFrame({
@@ -110,10 +226,14 @@ if fiber_impact_data and transport_impact_data and washing_impact_data:
110
  fig = px.bar(result_data, x="Footprint Type", y="Value", title="Single Assessment Footprint Breakdown")
111
  st.plotly_chart(style_figure(fig))
112
 
113
- # Use Groq to analyze single assessment results
114
- results = {"water": water, "energy": energy, "carbon": carbon}
115
- suggestion = analyze_results_with_groq(results, mode="single")
116
- st.markdown(f"<div class='highlight'><h3>Groq Analysis</h3><p>{suggestion}</p></div>", unsafe_allow_html=True)
117
-
 
 
 
 
118
  else:
119
- st.error("Failed to load dataset.")
 
 
 
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/BCK2.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,
44
+ )
45
+
46
+ # Dataset URL
47
+ DATASET_URL = "https://huggingface.co/spaces/ZainMalik0925/GreenLensAI_LCA/resolve/main/DataSet01.xlsx"
48
+
49
+ # Load dataset from Hugging Face Spaces
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: white;'>{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: white;'>{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)
 
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({
 
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({
 
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.")