ZainMalik0925 commited on
Commit
302abf1
·
verified ·
1 Parent(s): 93ebd36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -78
app.py CHANGED
@@ -1,76 +1,70 @@
1
  import streamlit as st
2
  import pandas as pd
 
 
3
  import requests
4
  from io import BytesIO
5
  from PyPDF2 import PdfReader
6
- import plotly.graph_objects as go
7
  import time
8
 
9
  # Set Page Configurations
10
  st.set_page_config(page_title="GreenLens-AI", layout="wide")
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://drive.google.com/uc?id=1QY9yv2mhz4n8bOTi4ahbjBpapltqXV6D"
21
 
22
- # Step 1: Function to fetch and process PDF dataset
23
  @st.cache_data
24
- def fetch_and_process_pdf(url):
25
- """Fetch the PDF dataset from Google Drive and process it."""
26
  progress_text = "Fetching dataset from Google Drive..."
27
  progress_bar = st.progress(0)
28
 
29
  try:
30
- # Download the file
31
  response = requests.get(url, stream=True)
32
  total_size = int(response.headers.get('content-length', 0))
33
  downloaded_size = 0
34
  chunks = []
35
 
36
- # Download with progress
37
  for chunk in response.iter_content(chunk_size=8192):
38
  downloaded_size += len(chunk)
39
  progress_bar.progress(min(1.0, downloaded_size / total_size), text=progress_text)
40
  chunks.append(chunk)
41
 
42
  pdf_content = b"".join(chunks)
43
- progress_bar.progress(1.0, text="Processing PDF...")
44
-
45
- # Parse the PDF content
46
- pdf_reader = PdfReader(BytesIO(pdf_content))
47
- pdf_text = ""
48
- for page in pdf_reader.pages:
49
- pdf_text += page.extract_text()
50
-
51
- # Parse relevant data from the text (mock implementation, adjust as needed)
52
- fiber_impact_data = {
53
- "Cotton": {"Water": 10000, "Energy": 60, "Carbon": 3.18},
54
- "Polyester": {"Water": 62, "Energy": 125, "Carbon": 4.8},
55
- "Nylon": {"Water": 70, "Energy": 120.47, "Carbon": 5.4},
56
- "Acrylic": {"Water": 50, "Energy": 175, "Carbon": 6.2},
57
- "Viscose": {"Water": 200, "Energy": 100, "Carbon": 4.2},
58
- }
59
-
60
- st.success("Dataset loaded successfully!")
61
- return fiber_impact_data
62
-
63
  except Exception as e:
64
- st.error(f"Error fetching or processing dataset: {e}")
65
  return None
66
 
67
- # Load dataset dynamically from Google Drive
68
- fiber_impact_data = fetch_and_process_pdf(DATASET_URL)
69
 
70
  # Sidebar for User Inputs
71
  st.sidebar.header("Input Product Details")
72
-
73
- # Input Section: Product-Specific Inputs
74
  product_type = st.sidebar.selectbox("Product Type", ["T-shirt", "Jeans", "Shirt", "Carpet"])
75
  product_weight = st.sidebar.number_input("Product Weight (kg)", min_value=0.01, step=0.01, value=0.25)
76
 
@@ -82,10 +76,10 @@ nylon_percent = st.sidebar.slider("Nylon (%)", 0, 100, 10)
82
  acrylic_percent = st.sidebar.slider("Acrylic (%)", 0, 100, 5)
83
  viscose_percent = st.sidebar.slider("Viscose (%)", 0, 100, 5)
84
 
85
- # Validation check: Percentages must add up to 100%
86
  total_percentage = cotton_percent + polyester_percent + nylon_percent + acrylic_percent + viscose_percent
87
  if total_percentage != 100:
88
- st.sidebar.error("The total of all fiber percentages must equal 100%!")
89
 
90
  # Lifecycle Inputs
91
  st.sidebar.header("Lifecycle Details")
@@ -95,14 +89,21 @@ use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
95
  transport_mode = st.sidebar.selectbox("Transport Mode", ["Plane", "Ship", "Train", "Truck"])
96
  transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
97
 
 
 
 
 
 
 
 
 
 
98
  # Function to calculate footprints
99
  def calculate_footprints(weight, composition, lifecycle_inputs):
100
- # Initialize footprints
101
  water_footprint = 0
102
  energy_footprint = 0
103
  carbon_footprint = 0
104
 
105
- # Fiber contributions
106
  for fiber, percentage in composition.items():
107
  if fiber in fiber_impact_data:
108
  data = fiber_impact_data[fiber]
@@ -111,35 +112,13 @@ def calculate_footprints(weight, composition, lifecycle_inputs):
111
  energy_footprint += data["Energy"] * weight * fraction
112
  carbon_footprint += data["Carbon"] * weight * fraction
113
 
114
- # Transportation impacts
115
- transport_factor = {
116
- "Plane": 1.102,
117
- "Ship": 0.011,
118
- "Train": 0.05,
119
- "Truck": 0.25,
120
- }[lifecycle_inputs["transport_mode"]]
121
-
122
- transport_emissions = transport_factor * lifecycle_inputs["transport_distance"] * weight
123
- carbon_footprint += transport_emissions
124
-
125
- # Washing and drying impacts
126
- washing_energy = {"Cold": 0.02, "30°C": 0.1, "40°C": 0.2, "60°C": 0.5}
127
- dryer_energy = 0.5 if lifecycle_inputs["use_dryer"] else 0
128
- carbon_footprint += (washing_energy[lifecycle_inputs["washing_temperature"]] * lifecycle_inputs["washing_cycles"] * 0.05)
129
- energy_footprint += dryer_energy * lifecycle_inputs["washing_cycles"]
130
 
131
  return water_footprint, energy_footprint, carbon_footprint
132
 
133
- # User inputs as a dictionary
134
- user_inputs = {
135
- "transport_mode": transport_mode,
136
- "transport_distance": transport_distance,
137
- "washing_temperature": washing_temperature,
138
- "washing_cycles": washing_cycles,
139
- "use_dryer": use_dryer,
140
- }
141
-
142
- # Collect the composition dictionary
143
  composition = {
144
  "Cotton": cotton_percent,
145
  "Polyester": polyester_percent,
@@ -148,8 +127,16 @@ composition = {
148
  "Viscose": viscose_percent,
149
  }
150
 
151
- # Run Calculations
152
- if fiber_impact_data and total_percentage == 100:
 
 
 
 
 
 
 
 
153
  water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
154
 
155
  # Display results
@@ -160,14 +147,14 @@ if fiber_impact_data and total_percentage == 100:
160
  - **Carbon Footprint**: {carbon_fp:.2f} kgCO2e
161
  """)
162
 
163
- # 3D Visualization
164
- fig = go.Figure()
165
- fig.add_trace(go.Bar(x=["Water Footprint", "Energy Footprint", "Carbon Footprint"],
166
- y=[water_fp, energy_fp, carbon_fp],
167
- text=[f"{water_fp:.2f} L", f"{energy_fp:.2f} MJ", f"{carbon_fp:.2f} kgCO2e"],
168
- textposition='auto',
169
- marker=dict(color=["blue", "orange", "green"])))
170
- fig.update_layout(title="Footprint Breakdown", xaxis_title="Footprint Type", yaxis_title="Value")
171
- st.plotly_chart(fig)
172
  else:
173
- st.error("Ensure dataset is loaded and composition sums to 100%.")
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import plotly.express as px
4
+ import plotly.graph_objects as go
5
  import requests
6
  from io import BytesIO
7
  from PyPDF2 import PdfReader
 
8
  import time
9
 
10
  # Set Page Configurations
11
  st.set_page_config(page_title="GreenLens-AI", layout="wide")
12
+
13
+ # Custom Styling for the App
14
  st.markdown(
15
  """
16
+ <style>
17
+ body {
18
+ background-color: #d4edda; /* Light green background */
19
+ }
20
+ .stSlider > div {
21
+ background-color: #50C878 !important; /* Green slider bar */
22
+ }
23
+ h1, h2, p {
24
+ text-align: center;
25
+ color: #4CAF50;
26
+ }
27
+ </style>
28
+ """,
29
+ unsafe_allow_html=True
30
+ )
31
+
32
+ # Title and Tagline
33
+ st.markdown("<h1>GreenLens-AI</h1>", unsafe_allow_html=True)
34
+ st.markdown("<p>A Sustainable Tool for Calculating Carbon, Energy, and Ecological Footprints 🌿</p>", unsafe_allow_html=True)
35
 
36
  # Google Drive Dataset Link
37
  DATASET_URL = "https://drive.google.com/uc?id=1QY9yv2mhz4n8bOTi4ahbjBpapltqXV6D"
38
 
39
+ # Function to fetch and process dataset
40
  @st.cache_data
41
+ def fetch_dataset(url):
42
+ """Fetch the dataset from Google Drive."""
43
  progress_text = "Fetching dataset from Google Drive..."
44
  progress_bar = st.progress(0)
45
 
46
  try:
 
47
  response = requests.get(url, stream=True)
48
  total_size = int(response.headers.get('content-length', 0))
49
  downloaded_size = 0
50
  chunks = []
51
 
 
52
  for chunk in response.iter_content(chunk_size=8192):
53
  downloaded_size += len(chunk)
54
  progress_bar.progress(min(1.0, downloaded_size / total_size), text=progress_text)
55
  chunks.append(chunk)
56
 
57
  pdf_content = b"".join(chunks)
58
+ progress_bar.progress(1.0, text="Processing dataset...")
59
+ return PdfReader(BytesIO(pdf_content))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  except Exception as e:
61
+ st.error(f"Error fetching dataset: {e}")
62
  return None
63
 
64
+ dataset = fetch_dataset(DATASET_URL)
 
65
 
66
  # Sidebar for User Inputs
67
  st.sidebar.header("Input Product Details")
 
 
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
 
 
76
  acrylic_percent = st.sidebar.slider("Acrylic (%)", 0, 100, 5)
77
  viscose_percent = st.sidebar.slider("Viscose (%)", 0, 100, 5)
78
 
79
+ # Validate percentage
80
  total_percentage = cotton_percent + polyester_percent + nylon_percent + acrylic_percent + viscose_percent
81
  if total_percentage != 100:
82
+ st.sidebar.warning("The total of all fiber percentages must equal 100%!")
83
 
84
  # Lifecycle Inputs
85
  st.sidebar.header("Lifecycle Details")
 
89
  transport_mode = st.sidebar.selectbox("Transport Mode", ["Plane", "Ship", "Train", "Truck"])
90
  transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
91
 
92
+ # Mock Fiber Impact Data
93
+ fiber_impact_data = {
94
+ "Cotton": {"Water": 10000, "Energy": 60, "Carbon": 3.18},
95
+ "Polyester": {"Water": 62, "Energy": 125, "Carbon": 4.8},
96
+ "Nylon": {"Water": 70, "Energy": 120.47, "Carbon": 5.4},
97
+ "Acrylic": {"Water": 50, "Energy": 175, "Carbon": 6.2},
98
+ "Viscose": {"Water": 200, "Energy": 100, "Carbon": 4.2},
99
+ }
100
+
101
  # Function to calculate footprints
102
  def calculate_footprints(weight, composition, lifecycle_inputs):
 
103
  water_footprint = 0
104
  energy_footprint = 0
105
  carbon_footprint = 0
106
 
 
107
  for fiber, percentage in composition.items():
108
  if fiber in fiber_impact_data:
109
  data = fiber_impact_data[fiber]
 
112
  energy_footprint += data["Energy"] * weight * fraction
113
  carbon_footprint += data["Carbon"] * weight * fraction
114
 
115
+ # Transportation footprint
116
+ transport_factor = {"Plane": 1.102, "Ship": 0.011, "Train": 0.05, "Truck": 0.25}[lifecycle_inputs["transport_mode"]]
117
+ carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  return water_footprint, energy_footprint, carbon_footprint
120
 
121
+ # Composition dictionary
 
 
 
 
 
 
 
 
 
122
  composition = {
123
  "Cotton": cotton_percent,
124
  "Polyester": polyester_percent,
 
127
  "Viscose": viscose_percent,
128
  }
129
 
130
+ user_inputs = {
131
+ "transport_mode": transport_mode,
132
+ "transport_distance": transport_distance,
133
+ "washing_temperature": washing_temperature,
134
+ "washing_cycles": washing_cycles,
135
+ "use_dryer": use_dryer,
136
+ }
137
+
138
+ # Perform calculations
139
+ if total_percentage == 100:
140
  water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
141
 
142
  # Display results
 
147
  - **Carbon Footprint**: {carbon_fp:.2f} kgCO2e
148
  """)
149
 
150
+ # Separate Graphs for Each Footprint
151
+ fig_cfp = px.bar(x=["Carbon Footprint"], y=[carbon_fp], labels={"x": "Type", "y": "Value (kgCO2e)"}, title="Carbon Footprint")
152
+ fig_ep = px.bar(x=["Energy Footprint"], y=[energy_fp], labels={"x": "Type", "y": "Value (MJ)"}, title="Energy Footprint")
153
+ fig_ef = px.bar(x=["Ecological Footprint"], y=[water_fp], labels={"x": "Type", "y": "Value (liters)"}, title="Ecological Footprint")
154
+
155
+ # Display Graphs
156
+ st.plotly_chart(fig_cfp, use_container_width=True)
157
+ st.plotly_chart(fig_ep, use_container_width=True)
158
+ st.plotly_chart(fig_ef, use_container_width=True)
159
  else:
160
+ st.error("Ensure that the material composition totals 100%.")