ZainMalik0925 commited on
Commit
aa39642
·
verified ·
1 Parent(s): 56b00ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -51
app.py CHANGED
@@ -17,49 +17,53 @@ st.markdown(
17
  """, unsafe_allow_html=True)
18
 
19
  # Google Drive Dataset Link
20
- DATASET_URL = "https://docs.google.com/uc?export=download&id=1CfuCrqRvu1LjBVmJh9b7mZiHBJ2kvJ0t"
21
 
22
- # Step 1: Function to fetch and process the Excel dataset
23
  @st.cache_data
24
  def fetch_and_process_excel(url):
25
- """Fetch and extract required data from the Excel dataset."""
26
  try:
27
  st.info("Fetching dataset from Google Drive...")
28
-
29
- # Download the file
30
  response = requests.get(url)
31
  if response.status_code != 200:
32
  raise Exception("Failed to download the file. Check the URL or permissions.")
33
 
34
- # Read the Excel file into a pandas DataFrame
35
  excel_content = BytesIO(response.content)
36
- df = pd.read_excel(excel_content)
37
-
38
- # Convert DataFrame into a dictionary for fiber impact data
39
- # Assuming the Excel file has columns: "Fiber", "Water", "Energy", "Carbon"
40
- if not all(col in df.columns for col in ["Fiber", "Water", "Energy", "Carbon"]):
41
- raise Exception("Excel file does not have the required columns: Fiber, Water, Energy, Carbon.")
42
-
43
- # Build the dictionary
44
- fiber_impact_data = {}
45
- for _, row in df.iterrows():
46
- fiber_impact_data[row["Fiber"]] = {
47
- "Water": row["Water"],
48
- "Energy": row["Energy"],
49
- "Carbon": row["Carbon"],
50
- }
51
-
52
- # Log the parsed dataset
53
- st.write("Parsed Fiber Impact Data:", fiber_impact_data)
 
 
 
 
54
  st.success("Dataset loaded successfully!")
55
- return fiber_impact_data
56
 
57
  except Exception as e:
58
  st.error(f"Error loading or processing the Excel file: {e}")
59
- return None
60
 
61
- # Load dataset dynamically
62
- fiber_impact_data = fetch_and_process_excel(DATASET_URL)
63
 
64
  # Sidebar for User Inputs
65
  st.sidebar.header("Input Product Details")
@@ -81,23 +85,20 @@ total_percentage = cotton_percent + polyester_percent + nylon_percent + acrylic_
81
  if total_percentage != 100:
82
  st.sidebar.error("The total of all fiber percentages must equal 100%!")
83
 
84
- st.sidebar.write(f"Total Material Percentage: {total_percentage}%") # Debugging sidebar inputs
85
 
86
  # Lifecycle Inputs
87
  st.sidebar.header("Lifecycle Details")
88
  washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
89
  washing_temperature = st.sidebar.selectbox("Washing Temperature", ["Cold", "30°C", "40°C", "60°C"])
90
  use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
91
- transport_mode = st.sidebar.selectbox("Transport Mode", ["Plane", "Ship", "Train", "Truck"])
92
  transport_distance = st.sidebar.number_input("Transport Distance (km)", min_value=0, step=50)
93
 
94
  # Function to calculate footprints
95
  def calculate_footprints(weight, composition, lifecycle_inputs):
96
  """Calculate water, energy, and carbon footprints."""
97
  try:
98
- # Log inputs
99
- st.write("Inputs to function:", weight, composition, lifecycle_inputs)
100
-
101
  # Initialize footprints
102
  water_footprint = 0
103
  energy_footprint = 0
@@ -108,31 +109,26 @@ def calculate_footprints(weight, composition, lifecycle_inputs):
108
  if fiber in fiber_impact_data:
109
  data = fiber_impact_data[fiber]
110
  fraction = percentage / 100
111
- water_footprint += data["Water"] * weight * fraction
112
- energy_footprint += data["Energy"] * weight * fraction
113
- carbon_footprint += data["Carbon"] * weight * fraction
114
  else:
115
  st.warning(f"No data found for fiber: {fiber}")
116
 
117
  # Transportation impacts
118
- transport_factor = {
119
- "Plane": 1.102,
120
- "Ship": 0.011,
121
- "Train": 0.05,
122
- "Truck": 0.25,
123
- }.get(lifecycle_inputs["transport_mode"], 0)
124
  carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
125
 
126
  # Washing and drying impacts
127
- washing_energy = {"Cold": 0.02, "30°C": 0.1, "40°C": 0.2, "60°C": 0.5}
128
- dryer_energy = 0.5 if lifecycle_inputs["use_dryer"] else 0
129
- carbon_footprint += (
130
- washing_energy[lifecycle_inputs["washing_temperature"]] * lifecycle_inputs["washing_cycles"] * 0.05
131
- )
132
- energy_footprint += dryer_energy * lifecycle_inputs["washing_cycles"]
133
-
134
- # Log final results
135
- st.write("Calculated Results:", water_footprint, energy_footprint, carbon_footprint)
136
  return water_footprint, energy_footprint, carbon_footprint
137
 
138
  except Exception as e:
 
17
  """, unsafe_allow_html=True)
18
 
19
  # Google Drive Dataset Link
20
+ DATASET_URL = "https://docs.google.com/uc?export=download&id=1K9elWl_s6lMlzY3JbPqKliNHBZ8n4BOr"
21
 
22
+ # Step 1: Function to fetch and process Excel dataset
23
  @st.cache_data
24
  def fetch_and_process_excel(url):
25
+ """Fetch and extract data from the updated .xlsx file."""
26
  try:
27
  st.info("Fetching dataset from Google Drive...")
28
+
29
+ # Download the Excel file
30
  response = requests.get(url)
31
  if response.status_code != 200:
32
  raise Exception("Failed to download the file. Check the URL or permissions.")
33
 
34
+ # Load the Excel file
35
  excel_content = BytesIO(response.content)
36
+
37
+ # Read all sheets into pandas DataFrames
38
+ fiber_data = pd.read_excel(excel_content, sheet_name="Fiber Impact Data")
39
+ transport_data = pd.read_excel(excel_content, sheet_name="Transport Data")
40
+ washing_data = pd.read_excel(excel_content, sheet_name="Washing Data")
41
+
42
+ # Convert Fiber Impact Data into a dictionary
43
+ fiber_impact_data = fiber_data.set_index("Fiber Type")[["Water (L/kg)", "Energy (MJ/kg)", "Carbon (kg CO2e/kg)"]].to_dict(orient="index")
44
+
45
+ # Convert Transport Data into a dictionary for dynamic lookup
46
+ transport_impact_data = transport_data.set_index("Transport Mode")["CFP (kg CO2e/km)"].to_dict()
47
+
48
+ # Convert Washing Data into a dictionary for dynamic lookup
49
+ washing_impact_data = washing_data.set_index("Washing Temperature")[
50
+ ["Energy Use (MJ/wash)", "Carbon (kg CO2e/wash)", "Dryer CFP (kg CO2e/cycle)"]
51
+ ].to_dict(orient="index")
52
+
53
+ # Debugging: Log extracted data for verification
54
+ st.write("Fiber Impact Data:", fiber_impact_data)
55
+ st.write("Transport Impact Data:", transport_impact_data)
56
+ st.write("Washing Impact Data:", washing_impact_data)
57
+
58
  st.success("Dataset loaded successfully!")
59
+ return fiber_impact_data, transport_impact_data, washing_impact_data
60
 
61
  except Exception as e:
62
  st.error(f"Error loading or processing the Excel file: {e}")
63
+ return None, None, None
64
 
65
+ # Load data dynamically from Google Drive
66
+ fiber_impact_data, transport_impact_data, washing_impact_data = fetch_and_process_excel(DATASET_URL)
67
 
68
  # Sidebar for User Inputs
69
  st.sidebar.header("Input Product Details")
 
85
  if total_percentage != 100:
86
  st.sidebar.error("The total of all fiber percentages must equal 100%!")
87
 
88
+ st.sidebar.write(f"Total Material Percentage: {total_percentage}%")
89
 
90
  # Lifecycle Inputs
91
  st.sidebar.header("Lifecycle Details")
92
  washing_cycles = st.sidebar.number_input("Number of Washing Cycles", min_value=0, step=10, value=30)
93
  washing_temperature = st.sidebar.selectbox("Washing Temperature", ["Cold", "30°C", "40°C", "60°C"])
94
  use_dryer = st.sidebar.checkbox("Use Tumble Dryer?")
95
+ transport_mode = st.sidebar.selectbox("Transport Mode", list(transport_impact_data.keys()))
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
  """Calculate water, energy, and carbon footprints."""
101
  try:
 
 
 
102
  # Initialize footprints
103
  water_footprint = 0
104
  energy_footprint = 0
 
109
  if fiber in fiber_impact_data:
110
  data = fiber_impact_data[fiber]
111
  fraction = percentage / 100
112
+ water_footprint += data["Water (L/kg)"] * weight * fraction
113
+ energy_footprint += data["Energy (MJ/kg)"] * weight * fraction
114
+ carbon_footprint += data["Carbon (kg CO2e/kg)"] * weight * fraction
115
  else:
116
  st.warning(f"No data found for fiber: {fiber}")
117
 
118
  # Transportation impacts
119
+ transport_factor = transport_impact_data.get(lifecycle_inputs["transport_mode"], 0)
 
 
 
 
 
120
  carbon_footprint += transport_factor * lifecycle_inputs["transport_distance"] * weight
121
 
122
  # Washing and drying impacts
123
+ washing_data = washing_impact_data.get(lifecycle_inputs["washing_temperature"], {})
124
+ washing_energy = washing_data.get("Energy Use (MJ/wash)", 0)
125
+ washing_carbon = washing_data.get("Carbon (kg CO2e/wash)", 0)
126
+ dryer_carbon = washing_data.get("Dryer CFP (kg CO2e/cycle)", 0) if lifecycle_inputs["use_dryer"] else 0
127
+
128
+ carbon_footprint += washing_carbon * lifecycle_inputs["washing_cycles"]
129
+ energy_footprint += washing_energy * lifecycle_inputs["washing_cycles"]
130
+ carbon_footprint += dryer_carbon * lifecycle_inputs["washing_cycles"]
131
+
132
  return water_footprint, energy_footprint, carbon_footprint
133
 
134
  except Exception as e: