Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,6 +7,8 @@ import plotly.graph_objects as go
|
|
7 |
|
8 |
# Set Page Configurations
|
9 |
st.set_page_config(page_title="GreenLens-AI", layout="wide")
|
|
|
|
|
10 |
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>GreenLens-AI</h1>", unsafe_allow_html=True)
|
11 |
st.markdown(
|
12 |
"""
|
@@ -16,63 +18,60 @@ st.markdown(
|
|
16 |
""", unsafe_allow_html=True)
|
17 |
|
18 |
# Google Drive Dataset Link
|
19 |
-
DATASET_URL = "https://drive.google.com/
|
20 |
|
21 |
# Step 1: Function to fetch and process PDF dataset
|
22 |
@st.cache_data
|
23 |
def fetch_and_process_pdf(url):
|
24 |
-
"""Fetch
|
25 |
-
progress_text = "Fetching dataset from Google Drive..."
|
26 |
-
progress_bar = st.progress(0)
|
27 |
-
|
28 |
try:
|
|
|
|
|
|
|
29 |
# Download the file
|
30 |
response = requests.get(url, stream=True)
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
for chunk in response.iter_content(chunk_size=8192):
|
36 |
-
downloaded_size += len(chunk)
|
37 |
-
progress_bar.progress(min(1.0, downloaded_size / total_size), text=progress_text)
|
38 |
-
chunks.append(chunk)
|
39 |
-
|
40 |
-
pdf_content = b"".join(chunks)
|
41 |
-
progress_bar.progress(1.0, text="Processing PDF...")
|
42 |
|
43 |
# Parse the PDF content
|
44 |
-
|
|
|
45 |
pdf_text = ""
|
46 |
for page in pdf_reader.pages:
|
47 |
-
pdf_text += page.extract_text()
|
|
|
|
|
|
|
48 |
|
49 |
-
# Extract necessary data
|
50 |
-
#
|
51 |
-
# "FIBER_NAME, WATER (L/kg), ENERGY (MJ/kg), CARBON (kgCO2e/kg)"
|
52 |
lines = pdf_text.split("\n")
|
53 |
fiber_impact_data = {}
|
54 |
for line in lines:
|
55 |
parts = line.split(",")
|
56 |
-
if len(parts) == 4: # Ensure
|
57 |
-
fiber, water, energy, carbon = parts
|
58 |
try:
|
59 |
-
fiber_impact_data[fiber
|
60 |
-
"Water": float(water
|
61 |
-
"Energy": float(energy
|
62 |
-
"Carbon": float(carbon
|
63 |
}
|
64 |
except ValueError:
|
65 |
-
|
66 |
continue
|
67 |
|
68 |
-
|
|
|
69 |
return fiber_impact_data
|
70 |
|
71 |
except Exception as e:
|
72 |
-
st.error(f"Error
|
73 |
return None
|
74 |
|
75 |
-
# Load dataset dynamically
|
76 |
fiber_impact_data = fetch_and_process_pdf(DATASET_URL)
|
77 |
|
78 |
# Sidebar for User Inputs
|
@@ -95,6 +94,8 @@ total_percentage = cotton_percent + polyester_percent + nylon_percent + acrylic_
|
|
95 |
if total_percentage != 100:
|
96 |
st.sidebar.error("The total of all fiber percentages must equal 100%!")
|
97 |
|
|
|
|
|
98 |
# Lifecycle Inputs
|
99 |
st.sidebar.header("Lifecycle Details")
|
100 |
washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
|
@@ -105,48 +106,51 @@ transport_distance = st.sidebar.number_input("Transport Distance (km)", min_valu
|
|
105 |
|
106 |
# Function to calculate footprints
|
107 |
def calculate_footprints(weight, composition, lifecycle_inputs):
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
|
|
|
|
|
|
150 |
|
151 |
# User inputs as a dictionary
|
152 |
user_inputs = {
|
@@ -166,11 +170,11 @@ composition = {
|
|
166 |
"Viscose": viscose_percent,
|
167 |
}
|
168 |
|
169 |
-
# Run Calculations
|
170 |
-
|
171 |
-
|
172 |
-
water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
|
173 |
|
|
|
174 |
# Display results
|
175 |
st.subheader("Calculated Results")
|
176 |
st.markdown(f"""
|
@@ -190,7 +194,5 @@ try:
|
|
190 |
))
|
191 |
fig.update_layout(title="Footprint Breakdown", xaxis_title="Footprint Type", yaxis_title="Value")
|
192 |
st.plotly_chart(fig)
|
193 |
-
|
194 |
-
|
195 |
-
except Exception as e:
|
196 |
-
st.error(f"An error occurred during calculations: {e}")
|
|
|
7 |
|
8 |
# Set Page Configurations
|
9 |
st.set_page_config(page_title="GreenLens-AI", layout="wide")
|
10 |
+
|
11 |
+
# Page title and description
|
12 |
st.markdown("<h1 style='text-align: center; color: #4CAF50;'>GreenLens-AI</h1>", unsafe_allow_html=True)
|
13 |
st.markdown(
|
14 |
"""
|
|
|
18 |
""", unsafe_allow_html=True)
|
19 |
|
20 |
# Google Drive Dataset Link
|
21 |
+
DATASET_URL = "https://drive.google.com/file/d/1JMECXBOPU5UD9hdEUA0uv1g_Qm1CkWYn/view?usp=drive_link"
|
22 |
|
23 |
# Step 1: Function to fetch and process PDF dataset
|
24 |
@st.cache_data
|
25 |
def fetch_and_process_pdf(url):
|
26 |
+
"""Fetch and extract required data from the PDF dataset."""
|
|
|
|
|
|
|
27 |
try:
|
28 |
+
# Log start of fetching
|
29 |
+
st.info("Fetching dataset from Google Drive...")
|
30 |
+
|
31 |
# Download the file
|
32 |
response = requests.get(url, stream=True)
|
33 |
+
if response.status_code != 200:
|
34 |
+
raise Exception("Failed to download the file. Check the URL or permissions.")
|
35 |
+
|
36 |
+
pdf_content = BytesIO(response.content)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
# Parse the PDF content
|
39 |
+
st.info("Processing the PDF file...")
|
40 |
+
pdf_reader = PdfReader(pdf_content)
|
41 |
pdf_text = ""
|
42 |
for page in pdf_reader.pages:
|
43 |
+
pdf_text += page.extract_text().strip() # Extract and clean text
|
44 |
+
|
45 |
+
# Log extracted text for debugging
|
46 |
+
st.write("Extracted Text from PDF:", pdf_text[:500]) # Show first 500 characters for verification
|
47 |
|
48 |
+
# Extract necessary data from the text
|
49 |
+
# Expected format: "FIBER_NAME, WATER (L/kg), ENERGY (MJ/kg), CARBON (kgCO2e/kg)"
|
|
|
50 |
lines = pdf_text.split("\n")
|
51 |
fiber_impact_data = {}
|
52 |
for line in lines:
|
53 |
parts = line.split(",")
|
54 |
+
if len(parts) == 4: # Ensure proper format
|
55 |
+
fiber, water, energy, carbon = map(str.strip, parts)
|
56 |
try:
|
57 |
+
fiber_impact_data[fiber] = {
|
58 |
+
"Water": float(water),
|
59 |
+
"Energy": float(energy),
|
60 |
+
"Carbon": float(carbon),
|
61 |
}
|
62 |
except ValueError:
|
63 |
+
st.warning(f"Invalid data format in line: {line}")
|
64 |
continue
|
65 |
|
66 |
+
# Log parsed dataset
|
67 |
+
st.write("Parsed Fiber Impact Data:", fiber_impact_data)
|
68 |
return fiber_impact_data
|
69 |
|
70 |
except Exception as e:
|
71 |
+
st.error(f"Error loading or processing the PDF: {e}")
|
72 |
return None
|
73 |
|
74 |
+
# Load dataset dynamically
|
75 |
fiber_impact_data = fetch_and_process_pdf(DATASET_URL)
|
76 |
|
77 |
# Sidebar for User Inputs
|
|
|
94 |
if total_percentage != 100:
|
95 |
st.sidebar.error("The total of all fiber percentages must equal 100%!")
|
96 |
|
97 |
+
st.sidebar.write(f"Total Material Percentage: {total_percentage}%") # Debugging sidebar inputs
|
98 |
+
|
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)
|
|
|
106 |
|
107 |
# Function to calculate footprints
|
108 |
def calculate_footprints(weight, composition, lifecycle_inputs):
|
109 |
+
"""Calculate water, energy, and carbon footprints."""
|
110 |
+
try:
|
111 |
+
# Log inputs
|
112 |
+
st.write("Inputs to function:", weight, composition, lifecycle_inputs)
|
113 |
+
|
114 |
+
# Initialize footprints
|
115 |
+
water_footprint = 0
|
116 |
+
energy_footprint = 0
|
117 |
+
carbon_footprint = 0
|
118 |
+
|
119 |
+
# Fiber contributions
|
120 |
+
for fiber, percentage in composition.items():
|
121 |
+
if fiber in fiber_impact_data:
|
122 |
+
data = fiber_impact_data[fiber]
|
123 |
+
fraction = percentage / 100
|
124 |
+
water_footprint += data["Water"] * weight * fraction
|
125 |
+
energy_footprint += data["Energy"] * weight * fraction
|
126 |
+
carbon_footprint += data["Carbon"] * weight * fraction
|
127 |
+
else:
|
128 |
+
st.warning(f"No data found for fiber: {fiber}")
|
129 |
+
|
130 |
+
# Transportation impacts
|
131 |
+
transport_factor = {
|
132 |
+
"Plane": 1.102,
|
133 |
+
"Ship": 0.011,
|
134 |
+
"Train": 0.05,
|
135 |
+
"Truck": 0.25,
|
136 |
+
}.get(lifecycle_inputs["transport_mode"], 0)
|
137 |
+
carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
|
138 |
+
|
139 |
+
# Washing and drying impacts
|
140 |
+
washing_energy = {"Cold": 0.02, "30°C": 0.1, "40°C": 0.2, "60°C": 0.5}
|
141 |
+
dryer_energy = 0.5 if lifecycle_inputs["use_dryer"] else 0
|
142 |
+
carbon_footprint += (
|
143 |
+
washing_energy[lifecycle_inputs["washing_temperature"]] * lifecycle_inputs["washing_cycles"] * 0.05
|
144 |
+
)
|
145 |
+
energy_footprint += dryer_energy * lifecycle_inputs["washing_cycles"]
|
146 |
+
|
147 |
+
# Log final results
|
148 |
+
st.write("Calculated Results:", water_footprint, energy_footprint, carbon_footprint)
|
149 |
+
return water_footprint, energy_footprint, carbon_footprint
|
150 |
+
|
151 |
+
except Exception as e:
|
152 |
+
st.error(f"Error in calculations: {e}")
|
153 |
+
return None, None, None
|
154 |
|
155 |
# User inputs as a dictionary
|
156 |
user_inputs = {
|
|
|
170 |
"Viscose": viscose_percent,
|
171 |
}
|
172 |
|
173 |
+
# Run Calculations if conditions are met
|
174 |
+
if fiber_impact_data and total_percentage == 100:
|
175 |
+
water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
|
|
|
176 |
|
177 |
+
if water_fp is not None:
|
178 |
# Display results
|
179 |
st.subheader("Calculated Results")
|
180 |
st.markdown(f"""
|
|
|
194 |
))
|
195 |
fig.update_layout(title="Footprint Breakdown", xaxis_title="Footprint Type", yaxis_title="Value")
|
196 |
st.plotly_chart(fig)
|
197 |
+
else:
|
198 |
+
st.error("Ensure dataset is loaded and the composition sums to 100%.")
|
|
|
|