JAYPEE INSTITUTE OF INFORMATION TECHNOLOGY
Open Source Programming
Report for PBL
(24B51CS241)
Topic: Carbon Footprint Analysis of Purchases and Suggesting Sustainable
Alternatives using Python.
S.No. Name Enrolment Number Batch
1 Jayant Rana 23203004 CSC1
2 Shivansh Saraswat 23203014 CSC1
Submitted to:
Dr. Priya Abbi
JIIT, Noida-62
Objective
● Estimate Carbon Emissions of Purchases
Calculate the carbon emissions associated with individual purchases
using database containing emission factors of more than 200 products.
● Promote Sustainable Choices
Encourage environmentally responsible consumer behavior by offering
greener alternatives for commonly purchased items.
● Educate Users on Environmental Impact
Provide users with insightful feedback on the carbon emissions of their
purchasing habits to increase environmental awareness.
● Compare Products for Better Decisions
Present side-by-side comparisons between carbon emissions of regular
products and eco-friendly alternatives, highlighting emission differences.
Introduction
The Carbon Footprint Calculator is a Python-based project designed to help
users estimate their carbon emissions based on the products they have bought.
This tool raises awareness about the environmental impact of lifestyle choices
by quantifying the amount of carbon dioxide (CO₂) released into the
atmosphere during the manufacturing of various products.
By entering relevant data like product category, sub-category and quantity. Users
receive an estimate of their carbon footprint along with suggestions to reduce it.
The goal of this project is to promote sustainable living and help users make
environmentally conscious decisions.
Key Features :
1. Carbon Footprint Estimation
Users input purchase details, such as product type (e.g., electronics,
clothing, or groceries) and quantity
The application calculates the approximate carbon footprint based on a
pre-defined database that provides emission factors for various products.
2. Eco-Friendly Alternatives
The app suggests environmentally friendly alternatives (e.g., replacing
plastic bottles with reusable ones).
Alternatives are accompanied through an API which encourage more
sustainable choices.
3. Data Visualization
Graphical representation of carbon emissions includes a breakdown of
emissions by category (e.g., food, transport, and electronics).
Methodology
Programming Language: Python
Database: MySQL
Modules: Pandas, Matplotlib, mysql.connecter, re, os
API: Google Gemini API
Source code:
import streamlit as st
import mysql.connector
from mysql.connector import Error
import pandas as pd
import google.generativeai as genai
import matplotlib.pyplot as plt
import re
import os
# Database configuration
db_config = {
'host': 'localhost',
'user': 'root',
'password': 'root',
'database': 'def'
}
# Function to create and manage MySQL connection
def connect_to_db():
try:
# Test connection without database first
test_conn = mysql.connector.connect(
host=db_config['host'],
user=db_config['user'],
password=db_config['password']
if test_conn.is_connected():
cursor = test_conn.cursor()
# Check if database exists, create if not
cursor.execute("SHOW DATABASES LIKE 'def'")
if not cursor.fetchone():
cursor.execute("CREATE DATABASE IF NOT EXISTS def")
st.warning("Database 'def' was not found and has been created. Please populate it with
data.")
test_conn.close()
# Connect with database
connection = mysql.connector.connect(**db_config)
if connection.is_connected():
return connection
except Error as e:
st.error(f"Error connecting to MySQL: {e}")
if "Access denied" in str(e):
st.error("Check your username or password. Default MySQL root password might need
resetting.")
elif "Unknown database" in str(e):
st.error("Database 'def' not found. Ensure it exists or use 'carbon_db' if intended.")
elif "Can't connect" in str(e):
st.error("MySQL server might not be running. Start it with 'net start mysql80' on
Windows.")
return None
@st.cache_data
def load_data():
conn = connect_to_db()
if conn:
try:
query = "SELECT Category, Subcategory, Product, Functional_Unit,
Carbon_Footprint_kg_CO2e FROM carbon_emission_factors"
df = pd.read_sql(query, conn)
if df.empty:
st.warning("No data found in carbon_emission_factors table. Please ensure it is
populated.")
return df
except Exception as e:
st.error(f"Error loading data: {e}")
return pd.DataFrame()
finally:
conn.close()
return pd.DataFrame()
# Function to get alternative product details using Gemini API
def get_alternative_product_details(original_product, original_carbon_footprint):
try:
# Configure the Gemini API using environment variable or hardcoded fallback
api_key = os.getenv("API_KEY")
if not api_key:
api_key = "AIzaSyDyc9L4rTblYaBJNIqt_klJoAOAChWtpiQ" # Replace with your
actual API key as a fallback
#st.warning("API key not found in environment variable 'API_KEY'. Using hardcoded
key as fallback. Please set the environment variable (e.g., 'export API_KEY=your_key') for
security.")
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-1.5-pro') # Use the latest available model
prompt = f"For the product '{original_product}' with a carbon footprint of
{original_carbon_footprint:.2f} kg CO2e, suggest an eco-friendly alternative. Provide the
alternative product name, a 1-2 line description of it, and its estimated carbon footprint in kg
CO2e. Return the data as a list like: ['Alternative Name', 'Description line 1. Description line 2.',
carbon_value]."
response = model.generate_content(prompt)
text = response.text.strip()
# Parse the response to extract alternative product details
match = re.search(r"\['(.+?)', '(.+?)', (\d+\.?\d*)\]", text)
if match:
alt_name, alt_desc, alt_cf = match.groups()
return alt_name.strip(), alt_desc.strip(), float(alt_cf) if float(alt_cf) > 0 else 0.0
else:
return "N/A", "No description available.", 0.0
except Exception as e:
st.error(f"Error fetching alternative product details: {e}")
return "N/A", "No description available.", 0.0
# Streamlit Sidebar Navigation
st.sidebar.title("Navigation")
pages = ["Calculate Emissions", "View Statistics", "View Data"]
page = st.sidebar.radio("Go to", pages)
# Load data
data = load_data()
if data.empty:
st.error("No data available. Please check your database connection or populate the table.")
else:
# Page: Calculate Emissions
if page == "Calculate Emissions":
st.title("Calculate Purchase Emissions")
st.write("Trace your purchases and calculate their carbon footprint.")
# Dropdown for Category
selected_category = st.selectbox("Select a Category", options=['Select Category'] +
list(data['Category'].unique()), key="category")
# Filter Subcategories based on Category
if selected_category and selected_category != 'Select Category':
filtered_subcategories = ['Select Subcategory'] + list(data[data['Category'] ==
selected_category]['Subcategory'].unique())
selected_subcategory = st.selectbox("Select a Subcategory",
options=filtered_subcategories, key="subcategory")
# Filter Products based on Subcategory
if selected_subcategory and selected_subcategory != 'Select Subcategory':
filtered_products = data[data['Subcategory'] == selected_subcategory]
product_options = ['Select Product'] + list(filtered_products['Product'].unique())
selected_product = st.selectbox("Select a Product", options=product_options,
key="product")
# Display additional information
if selected_product and selected_product != 'Select Product':
product_info = filtered_products[filtered_products['Product'] == selected_product]
# Quantity input and emission calculation
quantity = st.number_input("Enter quantity", min_value=0.01, value=1.0, step=0.01,
format="%.2f")
carbon_footprint = product_info['Carbon_Footprint_kg_CO2e'].iloc[0] * quantity
st.write(f"**Total Carbon Footprint:** {carbon_footprint:.2f} kg CO2e")
# Get alternative product details and display
alt_name, alt_desc, alt_carbon_footprint =
get_alternative_product_details(selected_product,
product_info['Carbon_Footprint_kg_CO2e'].iloc[0])
total_alt_cf = alt_carbon_footprint * quantity
st.write(f"**Eco-Friendly Alternative:** {alt_name}")
st.write(f"**Description:** {alt_desc}")
st.write(f"**Alternative Carbon Footprint (per unit):** {alt_carbon_footprint:.2f}
kg CO2e")
# Display graph
plt.figure(figsize=(8, 5))
bars = plt.bar(['Original: ' + selected_product, 'Alternative: ' + alt_name],
[carbon_footprint, total_alt_cf], color=['coral', 'lightgreen'])
plt.xlabel('Product')
plt.ylabel('Carbon Footprint (kg CO2e)')
plt.title('Carbon Footprint Comparison')
plt.xticks(rotation=45, ha='right')
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., height,
f'{height:.2f}',
ha='center', va='bottom')
plt.tight_layout()
st.pyplot(plt)
# Page: View Statistics
elif page == "View Statistics":
st.title("Statistics Overview")
# Average Carbon Footprint by Category
avg_by_category =
data.groupby('Category')['Carbon_Footprint_kg_CO2e'].mean().reset_index()
st.subheader("Average Carbon Footprint by Category")
st.dataframe(avg_by_category)
plt.figure(figsize=(10, 6))
plt.bar(avg_by_category['Category'], avg_by_category['Carbon_Footprint_kg_CO2e'],
color='skyblue')
plt.xlabel('Category')
plt.ylabel('Average Carbon Footprint (kg CO2e)')
plt.title('Average Carbon Footprint by Category')
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
st.pyplot(plt)
# Top Products by Carbon Footprint
st.subheader("Top Products by Carbon Footprint")
top_products = data.nlargest(5, 'Carbon_Footprint_kg_CO2e')
st.dataframe(top_products[['Product', 'Category', 'Carbon_Footprint_kg_CO2e']])
plt.figure(figsize=(10, 6))
plt.barh(top_products['Product'], top_products['Carbon_Footprint_kg_CO2e'],
color='lightgreen')
plt.xlabel('Carbon Footprint (kg CO2e)')
plt.ylabel('Product')
plt.title('Top 5 Products by Carbon Footprint')
plt.tight_layout()
st.pyplot(plt)
# Page: View Data
elif page == "View Data":
st.title("View All Products Data")
rows_to_display = st.slider("Select number of rows to display", 10, len(data), 50)
st.dataframe(data.head(rows_to_display))
Output & Graphs:
Conclusion
The Carbon Footprint Calculator project demonstrates how technology can be
used to raise awareness about environmental sustainability and promote
responsible consumption. By allowing users to estimate the carbon emissions of
their purchases and offering practical, eco-friendly alternatives, the application
empowers individuals to make more informed and sustainable choices in their
daily lives.
The tool not only educates users about their environmental impact but also
motivates them to adopt greener habits. This project effectively combines
programming skills with real-world problem-solving, showcasing the potential
of Python in building applications that contribute to global environmental
goals.
References
● Carbon Catalogue:
http://springernature.figshare.com/ndownloader/files/31271269
● Our World in Data: https://ourworldindata.org/co2-emissions
● Clever Carbon: https://clevercarbon.io/
● Eupedia: https://www.eupedia.com/