ZainMalik0925 commited on
Commit
405dbb4
·
verified ·
1 Parent(s): 20421f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -57
app.py CHANGED
@@ -1,6 +1,8 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import requests
 
 
4
  import plotly.graph_objects as go
5
  import time
6
 
@@ -17,41 +19,53 @@ st.markdown(
17
  # Google Drive Dataset Link
18
  DATASET_URL = "https://drive.google.com/uc?id=1QY9yv2mhz4n8bOTi4ahbjBpapltqXV6D"
19
 
20
- # Step 1: Function to fetch and load dataset
21
  @st.cache_data
22
- def fetch_and_load_dataset(url):
23
- """Fetch the dataset from Google Drive."""
24
  progress_text = "Fetching dataset from Google Drive..."
25
  progress_bar = st.progress(0)
26
-
27
- # Download process
28
  try:
 
29
  response = requests.get(url, stream=True)
30
  total_size = int(response.headers.get('content-length', 0))
31
  downloaded_size = 0
32
  chunks = []
33
-
34
- for data in response.iter_content(chunk_size=8192):
35
- downloaded_size += len(data)
 
36
  progress_bar.progress(min(1.0, downloaded_size / total_size), text=progress_text)
37
- chunks.append(data)
 
 
 
 
 
 
 
 
 
38
 
39
- file_content = b''.join(chunks)
40
- df = pd.read_excel(file_content, engine="openpyxl") # Assuming an Excel file
 
 
 
 
 
 
 
41
  st.success("Dataset loaded successfully!")
42
- return df
43
-
44
  except Exception as e:
45
- st.error(f"Error fetching dataset: {e}")
46
  return None
47
 
48
  # Load dataset dynamically from Google Drive
49
- dataset = fetch_and_load_dataset(DATASET_URL)
50
-
51
- # Display the dataset preview
52
- if dataset is not None:
53
- st.subheader("Dataset Preview")
54
- st.dataframe(dataset.head())
55
 
56
  # Sidebar for User Inputs
57
  st.sidebar.header("Input Product Details")
@@ -81,22 +95,6 @@ use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
81
  transport_mode = st.sidebar.selectbox("Transport Mode", ["Plane", "Ship", "Train", "Truck"])
82
  transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
83
 
84
- # Step 2: Extract data dynamically from the loaded dataset
85
- @st.cache_data
86
- def extract_fiber_impact(dataset):
87
- """Extract relevant data for fiber impacts from the dataset."""
88
- fiber_data = {}
89
- for _, row in dataset.iterrows():
90
- fiber_name = row["Fiber"]
91
- water = row["Water Footprint"]
92
- energy = row["Energy Footprint"]
93
- carbon = row["Carbon Footprint"]
94
- fiber_data[fiber_name] = {"Water": water, "Energy": energy, "Carbon": carbon}
95
- return fiber_data
96
-
97
- # Load fiber impact data dynamically
98
- fiber_impact_data = extract_fiber_impact(dataset)
99
-
100
  # Function to calculate footprints
101
  def calculate_footprints(weight, composition, lifecycle_inputs):
102
  # Initialize footprints
@@ -114,16 +112,21 @@ def calculate_footprints(weight, composition, lifecycle_inputs):
114
  carbon_footprint += data["Carbon"] * weight * fraction
115
 
116
  # Transportation impacts
117
- transport_factor = transport_emissions_factors[lifecycle_inputs["transport_mode"]]
 
 
 
 
 
 
118
  transport_emissions = transport_factor * lifecycle_inputs["transport_distance"] * weight
119
  carbon_footprint += transport_emissions
120
 
121
  # Washing and drying impacts
122
- wash_energy = washing_energy[lifecycle_inputs["washing_temperature"]] * lifecycle_inputs["washing_cycles"]
123
- dryer_energy_impact = dryer_energy * lifecycle_inputs["washing_cycles"] if lifecycle_inputs["use_dryer"] else 0
124
-
125
- energy_footprint += wash_energy + dryer_energy_impact
126
- carbon_footprint += (wash_energy * 0.05) + (dryer_energy_impact * dryer_carbon)
127
 
128
  return water_footprint, energy_footprint, carbon_footprint
129
 
@@ -145,15 +148,8 @@ composition = {
145
  "Viscose": viscose_percent,
146
  }
147
 
148
- # Run Calculations and Display Progress Bar
149
- if total_percentage == 100:
150
- st.write("Processing calculations...")
151
- progress_bar = st.progress(0)
152
- for i in range(1, 101):
153
- time.sleep(0.01)
154
- progress_bar.progress(i)
155
-
156
- # Call the calculation function
157
  water_fp, energy_fp, carbon_fp = calculate_footprints(product_weight, composition, user_inputs)
158
 
159
  # Display results
@@ -171,11 +167,7 @@ if total_percentage == 100:
171
  text=[f"{water_fp:.2f} L", f"{energy_fp:.2f} MJ", f"{carbon_fp:.2f} kgCO2e"],
172
  textposition='auto',
173
  marker=dict(color=["blue", "orange", "green"])))
174
- fig.update_layout(title="Footprint Breakdown (3D Visualization)",
175
- xaxis_title="Footprint Type",
176
- yaxis_title="Footprint Value",
177
- template="plotly_white")
178
  st.plotly_chart(fig)
179
-
180
  else:
181
- st.error("Ensure that the material composition sums up to 100%.")
 
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
 
 
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")
 
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
 
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
 
 
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
 
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%.")