Spaces:
Sleeping
Sleeping
# Standard library imports | |
import collections | |
import os | |
import pickle | |
from PIL import Image | |
import io | |
import base64 | |
# Third-party imports | |
import matplotlib.pyplot as plt | |
import openai | |
import pandas as pd | |
import numpy as np | |
import requests | |
import random | |
import streamlit as st | |
from bs4 import BeautifulSoup | |
from dotenv import load_dotenv | |
from streamlit_option_menu import option_menu | |
# Local/application-specific imports | |
from langchain.chains import RetrievalQA | |
from langchain.chains.summarize import load_summarize_chain | |
from langchain.chat_models import ChatOpenAI | |
from langchain.document_loaders import WebBaseLoader, YoutubeLoader | |
from langchain.embeddings import OpenAIEmbeddings | |
from langchain.prompts.chat import ( | |
ChatPromptTemplate, | |
HumanMessagePromptTemplate, | |
SystemMessagePromptTemplate | |
) | |
from langchain.text_splitter import TokenTextSplitter, CharacterTextSplitter | |
from langchain.vectorstores import Chroma, FAISS | |
from langchain.llms import OpenAI | |
from langchain.chains.question_answering import load_qa_chain | |
from langchain.callbacks import get_openai_callback | |
st.set_option('deprecation.showPyplotGlobalUse', False) | |
# Load and set our key | |
openai.api_key = open("key.txt", "r").read().strip("\n") | |
st.set_page_config(page_title="Sustainable Shipping and Logistics Advisor", page_icon="GH", initial_sidebar_state="expanded") | |
hide_streamlit_style = """ | |
<style> | |
#MainMenu {visibility: hidden;} | |
footer {visibility: hidden;} | |
</style> | |
""" | |
st.markdown(hide_streamlit_style, unsafe_allow_html=True) | |
css_style = { | |
"icon": {"color": "white"}, | |
"nav-link": {"--hover-color": "grey"}, | |
"nav-link-selected": {"background-color": "#FF4C1B"}, | |
} | |
def home_page(): | |
st.write("<center><h1>Sustainable Shipping and Logistics Advisor</h1></center>", unsafe_allow_html=True) | |
st.image("main.png", use_column_width=True) | |
st.write(f"""<h2>The Challenge</h2> | |
<p>The shipping, port, and logistics industry faces growing sustainability challenges in the face of increasing global trade and environmental awareness. Key factors and challenges include:</p> | |
<ul> | |
<li>Rising carbon emissions from global shipping operations.</li> | |
<li>Waste management challenges in ports and logistics facilities.</li> | |
<li>Operational inefficiencies leading to increased environmental footprint.</li> | |
<li>Lack of integration of green technologies and renewable energy sources.</li> | |
<li>Increasing regulatory and compliance pressures.</li> | |
<li>Growing consumer demand for sustainable shipping options.</li> | |
<li>Impact of shipping activities on marine biodiversity.</li> | |
<li>Resource depletion and increasing waste generation.</li> | |
<li>Addressing the socio-economic aspects of sustainability in shipping communities.</li> | |
</ul> | |
<p>To navigate these challenges, the industry requires comprehensive strategies and tools that can assess, manage, and mitigate its environmental and social impact, while also ensuring operational efficiency and profitability.</p> | |
""", unsafe_allow_html=True) | |
st.write(f"""<h2>Project Goals</h2> | |
<p>The Sustainable Shipping and Logistics Advisor aims to champion sustainability in the shipping, port, and logistics domain by:</p> | |
<ul> | |
<li>Quantifying Carbon Emissions: Providing tools to measure and analyze carbon footprints of shipping operations.</li> | |
<li>Offering Sustainability Insights: Generating personalized advice for businesses to optimize operations, reduce emissions, and implement green technologies.</li> | |
<li>Promoting Green Practices: Educating stakeholders about best practices in sustainable shipping and logistics.</li> | |
<li>Facilitating Sustainable Decisions: Empowering businesses with the information and tools they need to make sustainability-driven decisions in their operations.</li> | |
</ul> | |
<p>By achieving these goals, the Sustainable Shipping and Logistics Advisor aims to transform the industry towards a more sustainable future, fostering environmental responsibility and economic growth.</p> | |
""", unsafe_allow_html=True) | |
def about_page(): | |
st.write("<center><h1>Sustainable Shipping and Logistics Advisor</h1></center>", unsafe_allow_html=True) | |
st.image("about.png", use_column_width=True) | |
st.write(""" | |
<p>The Sustainable Shipping and Logistics Advisor is an ambitious project stemming from the AI for Good 2023 Hackathon, organized by Quy Nhon AI Community. This hackathon, with its emphasis on leveraging the immense potential of Artificial Intelligence for social benefits, serves as an innovative platform where technology and sustainability meet. Our commitment to AI-driven solutions is underpinned by a belief that such technology can significantly propel the maritime sector towards a sustainable trajectory.</p> | |
<p>The focal objectives of the AI for Good 2023 Hackathon are:</p> | |
<ul> | |
<li><strong>Empower with AI:</strong> The hackathon seeks to push the boundaries of AI, venturing beyond conventional realms, to address complex socio-economic challenges.</li> | |
<li><strong>Cultivate Technological Advancement:</strong> By fostering an environment of collaboration and innovation, the hackathon aspires to spur developments in AI that are both revolutionary and beneficial for society.</li> | |
<li><strong>Champion Sustainable Solutions:</strong> With an eye on the broader horizon, the hackathon emphasizes AI solutions that are sustainable, ethical, and poised to make a long-lasting positive impact.</li> | |
</ul> | |
<p>In this backdrop, the Sustainable Shipping and Logistics Advisor emerges as a pioneering solution navigating the intricate landscape of maritime sustainability. Conceived and crafted by the dedicated duo - Alidu Abubakari from Ghana and Adejumobi Joshua from Nigeria, this advisor offers invaluable insights into sustainable practices in the realm of shipping and logistics. It's more than just an application; it's a beacon calling the maritime industry towards eco-friendly practices, carbon footprint reduction, and a sustainable future.</p> | |
""", unsafe_allow_html=True) | |
st.header("Chat with Sustainability Code π¬") | |
query = st.text_input("Ask questions about the sustainability code:") | |
def process_query(query): | |
store_name = 'sustainablecodebase' | |
if os.path.exists(f"{store_name}.pkl"): | |
with open(f"{store_name}.pkl", "rb") as f: | |
VectorStore = pickle.load(f) | |
else: | |
st.write("Pickle file not found. Please upload the PDF to generate the pickle file.") | |
return | |
docs = VectorStore.similarity_search(query=query, k=3) | |
llm = OpenAI(openai_api_key=openai.api_key) | |
chain = load_qa_chain(llm=llm, chain_type="stuff") | |
with get_openai_callback() as cb: | |
response = chain.run(input_documents=docs, question=query) | |
return response | |
if st.button("Submit"): | |
response = process_query(query) | |
if response: | |
st.write(response) | |
if st.button("Download Question and Answer"): | |
qa_text = f"Question: {query}\nAnswer: {response}" | |
st.download_button("Download Q&A", qa_text, "qa.txt") | |
def page1(): | |
# Load and set our key | |
#openai.api_key = open("key.txt", "r").read().strip("\n") | |
st.write("<center><h1>Energizing Sustainability: Powering a Greener Future</h1></center>", unsafe_allow_html=True) | |
st.image("page2.1.png", use_column_width=True) | |
st.write("Assess and improve the sustainability of your logistics operations.") | |
st.header("Company Information") | |
input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"]) | |
# Function to extract logistics information from a website URL | |
def extract_logistics_info_from_website(url): | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for HTTP errors (e.g., 404) | |
# Parse the HTML content of the page | |
soup = BeautifulSoup(response.text, 'html.parser') | |
# Example: Extract company description from the website | |
company_description = soup.find('meta', attrs={'name': 'description'}) | |
if company_description: | |
return company_description['content'] | |
except requests.exceptions.RequestException as e: | |
return f"Error: Unable to connect to the website ({e})" | |
except Exception as e: | |
return f"Error: {e}" | |
return None | |
# Function to summarize logistics information using OpenAI's GPT-3 model | |
def summarize_logistics_info(logistics_info): | |
prompt = f""" | |
Please extract the following information from the logistics company's description: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
Description: | |
{logistics_info} | |
Please provide responses while avoiding speculative or unfounded information. | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=100, | |
temperature=0 | |
) | |
company_summary = response.choices[0].message['content'] | |
return company_summary | |
except Exception as e: | |
return f"Error: {e}" | |
# Streamlit UI | |
st.title("Logistics Information Extractor") | |
st.write("Extract logistics information from a logistics company's website URL.") | |
if input_option == "Enter logistics company's website URL": | |
example_url = "https://quangninhport.com.vn/en/home" | |
website_url = st.text_input("Please enter the logistics company's website URL:", example_url) | |
if website_url: | |
# Ensure the URL starts with http/https | |
website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url | |
logistics_info = extract_logistics_info_from_website(website_url) | |
if logistics_info: | |
company_summary = summarize_logistics_info(logistics_info) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
elif input_option == "Provide company description manually": | |
st.markdown(""" | |
Please provide a description of the logistics company, focusing on the following: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
""") | |
company_description = st.text_area("Please provide the company description:", "") | |
if company_description: | |
company_summary = summarize_logistics_info(company_description) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
st.header("Logistics Sustainability Information") | |
# Definitions for logistics sustainability levels | |
sustainability_info = { | |
"None": "No sustainability info available", | |
"Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.", | |
"Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.", | |
"Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.", | |
} | |
sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys())) | |
# Display the definition when the user selects a sustainability level | |
if sustainability_level in sustainability_info: | |
st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}") | |
# Additional sustainability-related information | |
carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0) | |
renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?") | |
# Certification and Sustainability Initiatives | |
st.subheader("Certifications and Sustainability Initiatives") | |
# Explanations for logistics-related certifications | |
logistics_certification_info = { | |
"None": "No certifications or initiatives related to logistics.", | |
"ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.", | |
"SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.", | |
"C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.", | |
"Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.", | |
"Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.", | |
} | |
selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys())) | |
# Display explanations for selected certifications | |
for certification in selected_certifications: | |
if certification in logistics_certification_info: | |
st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}") | |
# Define the company_data dictionary | |
company_data = { | |
"Logistics Sustainability Level": sustainability_level, | |
"Annual Carbon Emissions (in metric tons)": carbon_emissions, | |
"Utilize Renewable Energy Sources": renewable_energy, | |
"Selected Logistics Certifications and Initiatives": selected_certifications | |
} | |
# If company_summary is generated, add it to company_data dictionary | |
if 'company_summary' in locals() or 'company_summary' in globals(): | |
company_data["Company Summary"] = company_summary | |
#st.write(company_data) | |
# Define your questions and their types | |
sections = { | |
"Energy Usage": [ | |
("23. What is the primary source of energy used in your logistics operations?", 'selectbox', ["Electricity", "Diesel", "Natural Gas", "Other"]), | |
("24. Percentage of electricity consumption from renewable sources in logistics (0-100%)", 'number_input', {"min_value": 0, "max_value": 100}), | |
("25. Average annual energy consumption in logistics operations (kWh)", 'number_input', {"min_value": 0}), | |
("26. Do you use energy-efficient technologies (e.g., LED lighting, energy-efficient HVAC) in your facilities?", 'radio', ["Yes", "No"]), | |
("27. Do you implement measures to reduce energy waste during non-operational hours?", 'radio', ["Yes", "No"]), | |
("28. Are there initiatives to optimize energy usage in transportation (e.g., route planning, load optimization)?", 'radio', ["Yes", "No"]), | |
("29. Do you have energy management systems to monitor and control energy usage?", 'radio', ["Yes", "No"]), | |
("30. Have you implemented specific energy efficiency measures or technologies in logistics operations?", 'radio', ["Yes", "No"]), | |
("31. Are you adopting renewable energy sources (e.g., solar panels, wind turbines)?", 'radio', ["Yes", "No"]), | |
("32. Have you conducted energy audits to identify energy savings opportunities?", 'radio', ["Yes", "No"]), | |
("33. Do you have a system for reporting energy consumption and sustainability efforts?", 'radio', ["Yes", "No"]), | |
("34. Do you have specific energy efficiency or renewable energy goals for logistics?", 'radio', ["Yes", "No"]), | |
("35. How frequently do you monitor and analyze energy usage data?", 'selectbox', ["Regularly", "Occasionally", "Rarely", "Never"]), | |
("36. Are you involved in partnerships to enhance energy efficiency and sustainability?", 'radio', ["Yes", "No"]), | |
("37. Are you actively managing and reducing energy consumption in your operations?", 'radio', ["Yes", "No"]), | |
("38. Do you have future plans or initiatives for energy sustainability in logistics?", 'radio', ["Yes", "No"]) | |
], | |
} | |
# Initialize a dictionary to store the answers | |
all_answers = {} | |
# Display the section header | |
st.subheader("Energy Usage") | |
st.write("<hr>", unsafe_allow_html=True) | |
# Create the columns outside the loop | |
num_columns = 3 | |
columns = [st.columns(num_columns) for _ in range((len(sections["Energy Usage"]) + num_columns - 1) // num_columns)] | |
# Display each question in columns and collect responses | |
for i, (question_text, input_type, *options) in enumerate(sections["Energy Usage"]): | |
col = columns[i // num_columns][i % num_columns] | |
with col: | |
if input_type == 'selectbox': | |
all_answers[question_text] = col.selectbox(question_text, options[0]) | |
elif input_type == 'number_input': | |
params = options[0] | |
all_answers[question_text] = col.number_input(question_text, **params) | |
elif input_type == 'radio': | |
all_answers[question_text] = col.radio(question_text, options[0]) | |
#st.write(all_answers) | |
# Convert answers to a DataFrame | |
answers_df = pd.DataFrame([all_answers]) | |
def calculate_energy_score(df): | |
score = 0 | |
# Scoring for primary energy source | |
primary_energy = df.at[0, "23. What is the primary source of energy used in your logistics operations?"].lower() | |
energy_source_scores = {"electricity": 10, "diesel": 5, "natural gas": 7, "other": 3} | |
score += energy_source_scores.get(primary_energy, 0) | |
# Renewable energy percentage (linear scoring) | |
renewable_percentage = df.at[0, "24. Percentage of electricity consumption from renewable sources in logistics (0-100%)"] | |
score += int(renewable_percentage / 10) # Every 10% adds 1 point | |
# Scoring for average annual energy consumption | |
annual_consumption = df.at[0, "25. Average annual energy consumption in logistics operations (kWh)"] | |
if annual_consumption > 0: # Lower consumption gets higher score | |
score += 5 - min(4, int(annual_consumption / 10000)) # Example scoring, adjust as needed | |
# Scoring for Yes/No questions (5 points for each 'Yes') | |
# Generate the list of Yes/No questions | |
yes_no_questions = [question[0] for question in sections["Energy Usage"] if question[1] == 'radio'] | |
for question in yes_no_questions: | |
response = df.at[0, question].strip().lower() | |
if response == 'yes': | |
score += 5 | |
# Additional scoring based on energy monitoring frequency | |
monitoring_frequency = df.at[0, "35. How frequently do you monitor and analyze energy usage data?"].lower() | |
frequency_scores = {"regularly": 5, "occasionally": 3, "rarely": 1, "never": 0} | |
score += frequency_scores.get(monitoring_frequency, 0) | |
# Ensure score is within 0-100 range | |
score = max(0, min(100, score)) | |
return score | |
def visualize_score_explanation(df): | |
# Define scoring parameters | |
energy_source_scores = {"electricity": 10, "diesel": 5, "natural gas": 7, "other": 3} | |
frequency_scores = {"regularly": 5, "occasionally": 3, "rarely": 1, "never": 0} | |
yes_no_questions = [question[0] for question in sections["Energy Usage"] if question[1] == 'radio'] | |
# Calculate the components of the score | |
primary_energy_score = energy_source_scores.get(df.at[0, "23. What is the primary source of energy used in your logistics operations?"].lower(), 0) | |
renewable_energy_score = int(df.at[0, "24. Percentage of electricity consumption from renewable sources in logistics (0-100%)"] / 10) | |
annual_consumption = df.at[0, "25. Average annual energy consumption in logistics operations (kWh)"] | |
annual_consumption_score = 5 - min(4, int(annual_consumption / 10000)) | |
yes_no_score = sum(df.at[0, question].strip().lower() == 'yes' for question in yes_no_questions) * 5 | |
monitoring_score = frequency_scores.get(df.at[0, "35. How frequently do you monitor and analyze energy usage data?"].lower(), 0) | |
# Components for visualization | |
components = { | |
'Primary Energy Source': primary_energy_score, | |
'Renewable Energy %': renewable_energy_score, | |
'Annual Energy Consumption': annual_consumption_score, | |
'Yes/No Questions': yes_no_score, | |
'Monitoring Frequency': monitoring_score | |
} | |
# Create a pie chart | |
fig, ax = plt.subplots() | |
ax.pie(components.values(), labels=components.keys(), autopct='%1.1f%%', startangle=90) | |
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. | |
plt.title('Contribution to Total Energy Sustainability Score') | |
# Display the plot in Streamlit | |
st.pyplot(fig) | |
# Explanation for the energy sustainability score calculation | |
explanation_E_eval = """ | |
The Energy Sustainability Score is calculated based on several factors related to sustainable energy practices in logistics operations. Here's how the score is composed: | |
- **Primary Energy Source:** Points are allocated based on the type of primary energy used, with renewable sources scoring higher. | |
- **Renewable Energy Percentage:** The percentage of electricity consumption from renewable sources contributes linearly to the score. | |
- **Average Annual Energy Consumption:** Lower consumption rates are rewarded with higher points, promoting energy efficiency. | |
- **Yes/No Questions:** Each 'Yes' answer to questions about sustainable practices adds to the score, reflecting proactive measures taken. | |
- **Energy Monitoring Frequency:** Regular monitoring of energy usage indicates a commitment to sustainability and adds additional points. | |
A higher score indicates a stronger commitment to sustainable energy practices in logistics operations. | |
""" | |
def evaluate_sustainability_practice(score, df): | |
# Calculate the energy sustainability score | |
#score = calculate_energy_score(df) | |
# Counting 'Yes' responses for Yes/No questions | |
yes_no_questions = [question[0] for question in sections["Energy Usage"] if question[1] == 'radio'] | |
yes_count = sum(df[question].eq('Yes').sum() for question in yes_no_questions if question in df.columns) | |
yes_percentage = (yes_count / len(yes_no_questions)) * 100 | |
# Calculate a combined sustainability index (example: 60% weight to score, 40% to yes_percentage) | |
combined_index = (0.6 * score) + (0.4 * yes_percentage) | |
# Grading system with detailed advice | |
if combined_index >= 80: | |
grade = "A (Eco-Champion π)" | |
st.image("Eco-Champion.png", use_column_width=True) | |
Explanation = "You are at the forefront of sustainability in shipping and logistics, showcasing exemplary practices and commitment." | |
advice = " Continue leading by example and exploring new frontiers in sustainability. Consider being a mentor or partner for smaller companies striving to become more sustainable. Invest in research and development for sustainable technologies. Advocate for sustainable policies in your industry. Strive for continuous improvement and set visionary goals like a completely zero-emission operation" | |
elif combined_index >= 60: | |
grade = "B (Sustainability Steward π)" | |
st.image("Sustainability_Steward.png", use_column_width=True) | |
Explanation = "Your operations demonstrate a high level of sustainability, setting you apart as a leader in green practices." | |
advice = "Innovate by investing in cutting-edge technologies like AI and IoT for predictive maintenance and better energy management. Consider setting ambitious targets like achieving carbon-neutral operations. Share your knowledge and experiences in sustainability forums and workshops. Look for opportunities to collaborate on sustainability projects and pilot new eco-friendly technologies." | |
elif combined_index >= 40: | |
grade = "C (Eco-Advancer πΏ)" | |
st.image("Eco-Advancer.png", use_column_width=True) | |
Explanation = "You are actively engaging in sustainable practices, showing a clear commitment to improving your operations." | |
advice = " Leverage technology to further optimize your logistics routes for fuel efficiency and reduced emissions. Consider investing in advanced energy management systems for real-time monitoring and control. Explore certifications for sustainability to benchmark your performance against industry standards. Engage with suppliers and clients who also prioritize sustainability, creating a green supply chain." | |
elif combined_index >= 20: | |
grade = "D (Green Learner πΌ)" | |
st.image("Green_Learner.png", use_column_width=True) | |
Explanation = "You've made some initial steps towards sustainability but haven't fully integrated these practices into your operations yet." | |
advice = "Start tracking your carbon footprint to set a baseline for improvement. Explore opportunities to incorporate more renewable energy sources, like solar or wind power, in your facilities. Engage in partnerships with other companies to learn from best practices in the industry. Look into eco-friendly packaging options and explore the possibility of using electric or hybrid vehicles for transportation." | |
else: | |
grade = "E (Eco-Novice π±)" | |
st.image("Eco-Novice.png", use_column_width=True) | |
Explanation = "You are at the early stages of implementing sustainable practices in your logistics operations. This is a great starting point, and there's much room for growth." | |
advice = "Begin by conducting a thorough energy audit to understand your current energy usage and identify areas for improvement. Focus on low-hanging fruits like switching to LED lighting, optimizing route planning to reduce fuel consumption, and training staff on energy conservation techniques. Consider simple measures like ensuring vehicles and equipment are well-maintained to improve fuel efficiency." | |
return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{Explanation} \n\n**Basic Advice:** \n{advice}" | |
def visualize_data(df): | |
renewable_energy = df["24. Percentage of electricity consumption from renewable sources in logistics (0-100%)"] | |
labels = ['Renewable', 'Non-Renewable'] | |
sizes = [renewable_energy.mean(), 100 - renewable_energy.mean()] | |
fig, ax = plt.subplots() | |
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140, colors=['lightgreen', 'lightcoral']) | |
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. | |
st.pyplot(fig) | |
def format_answer(answer): | |
"""Format the answer based on its type for better readability.""" | |
if isinstance(answer, bool): | |
return "Yes" if answer else "No" | |
elif isinstance(answer, (int, float)): | |
return str(answer) | |
return answer # Assume the answer is already in a string format | |
def extract_data(data): | |
"""Extract and format data from a dictionary.""" | |
formatted_data = {} | |
for key, value in data.items(): | |
formatted_data[key] = format_answer(value) | |
return formatted_data | |
def generate_swot_analysis(company_data): | |
# Extracting relevant data from company_data | |
logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None") | |
annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0) | |
utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False) | |
selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", []) | |
company_summary = company_data.get("Company Summary", "No specific information provided.") | |
# Constructing a dynamic SWOT analysis based on extracted data | |
strengths = [ | |
"Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None" | |
] | |
weaknesses = [ | |
"Lack of Logistics Sustainability Level: " + logistics_sustainability_level, | |
"Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present", | |
"Company Summary: " + company_summary | |
] | |
opportunities = [ | |
"Exploration of Logistics Certifications" if not selected_certifications else "None" | |
] | |
threats = [ | |
"Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None" | |
] | |
# Constructing a SWOT analysis prompt dynamically | |
swot_analysis_prompt = f""" | |
Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis: | |
Strengths: | |
Strengths Analysis: | |
{", ".join(strengths)} | |
Weaknesses: | |
Weaknesses Analysis: | |
{", ".join(weaknesses)} | |
Opportunities: | |
Opportunities Analysis: | |
{", ".join(opportunities)} | |
Threats: | |
Threats Analysis: | |
{", ".join(threats)} | |
""" | |
# OpenAI API call for SWOT analysis | |
response_swot = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are analyzing the company's sustainability practices."}, | |
{"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."}, | |
{"role": "user", "content": swot_analysis_prompt} | |
], | |
max_tokens=1000, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = response_swot.choices[0].message['content'] | |
return swot_analysis_content | |
def get_energy_report(all_answers, score): | |
"""Generates an Energy Sustainability report based on responses to a questionnaire.""" | |
extracted_data = extract_data(all_answers) | |
# Consolidate data using extracted data | |
energy_source_info = f"Primary Energy Source: {extracted_data.get('23. What is the primary source of energy used in your logistics operations?', 'N/A')}, Renewable Source Percentage: {extracted_data.get('24. Percentage of electricity consumption from renewable sources in logistics (0-100%)', 'N/A')}%, Average Annual Consumption: {extracted_data.get('25. Average annual energy consumption in logistics operations (kWh)', 'N/A')}" | |
efficiency_measures = f"Efficiency Technologies: {extracted_data.get('26. Do you use energy-efficient technologies (e.g., LED lighting, energy-efficient HVAC) in your facilities?', 'N/A')}, Energy Management Practices: {extracted_data.get('29. Do you have energy management systems to monitor and control energy usage?', 'N/A')}, Renewable Energy Adoption: {extracted_data.get('31. Are you adopting renewable energy sources (e.g., solar panels, wind turbines)?', 'N/A')}" | |
consolidated_report = f""" | |
Energy Sustainability Report | |
Score: {score}/100 | |
Report Details: | |
{energy_source_info} | |
{efficiency_measures} | |
""" | |
# Prompt for the OpenAI API | |
prompt = f""" | |
As an energy sustainability advisor, analyze the Energy Sustainability Report with a score of {score}/100. Review the data points provided and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement. Provide specific recommendations to improve the energy sustainability score, considering the current energy mix and efficiency measures. | |
Data Points: | |
{energy_source_info} | |
{efficiency_measures} | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=3000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0, | |
presence_penalty=0 | |
) | |
evaluation_content = response.choices[0].message['content'] | |
refined_report = f"{consolidated_report}\n\n{evaluation_content}" | |
return refined_report | |
except Exception as e: | |
return f"Error: {e}" | |
def get_energy_sustainability_advice(all_answers, company_data): | |
# Extracting and formatting data from all_answers and company_data | |
extracted_all_answers = extract_data(all_answers) | |
extracted_company_data = extract_data(company_data) | |
# Forming the prompt with extracted data | |
prompt = f""" | |
Based on the provided company and energy sustainability assessment data, provide energy sustainability Strategy: | |
**Company Info**: | |
- Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')} | |
- Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons | |
- Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')} | |
- Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')} | |
- Company Summary: {extracted_company_data.get('Company Summary', 'N/A')} | |
**Energy Sustainability Assessment Data**: | |
- Primary Energy Source: {extracted_all_answers.get("23. What is the primary source of energy used in your logistics operations?", "N/A")} | |
- Renewable Source Percentage: {extracted_all_answers.get("24. Percentage of electricity consumption from renewable sources in logistics (0-100%)", "N/A")}% | |
- Average Annual Consumption: {extracted_all_answers.get("25. Average annual energy consumption in logistics operations (kWh)", "N/A")} kWh | |
- Efficiency Technologies: {extracted_all_answers.get("26. Do you use energy-efficient technologies (e.g., LED lighting, energy-efficient HVAC) in your facilities?", "N/A")} | |
- Energy Management Practices: {extracted_all_answers.get("29. Do you have energy management systems to monitor and control energy usage?", "N/A")} | |
- Renewable Energy Adoption: {extracted_all_answers.get("31. Are you adopting renewable energy sources (e.g., solar panels, wind turbines)?", "N/A")} | |
Offer actionable strategy considering the company's specific context. | |
""" | |
additional_context = f"Provide detailed sustainability stratey using context data from the above company info and in responses to the energy sustainability assessment." | |
# Assuming you have an API call here to generate a response based on the prompt | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are an energy sustainability strategy advisor."}, | |
{"role": "user", "content": prompt}, | |
{"role": "user", "content": additional_context} | |
], | |
max_tokens=3000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
return response.choices[0].message['content'] | |
def get_certification_details(certification_name): | |
# Prepare the prompt for the API call | |
messages = [ | |
{"role": "system", "content": "You are a knowledgeable assistant about global certifications."}, | |
{"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."} | |
] | |
# Query the OpenAI API for information on the certification process | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
max_tokens=1500, | |
temperature=0.3, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Return the content of the response | |
return response.choices[0].message['content'] | |
def advise_on_energy_sustainability_certification(company_data): | |
# Extract company data | |
annual_carbon_emissions = company_data.get('Annual Carbon Emissions', 0) | |
use_renewable_energy = company_data.get('Use Renewable Energy', False) | |
selected_certifications_and_initiatives = company_data.get('Selected Certifications and Initiatives', []) | |
#country_of_operation = company_data.get('Country of Operation', 'N/A') | |
# Initialize a string to store recommendations | |
recommendations_text = "" | |
# If the company uses renewable energy, suggest certifications that validate this practice | |
if use_renewable_energy: | |
recommendations_text += "To certify that your energy is sourced from renewable resources, consider obtaining the Renewable Energy Certificate (REC). " | |
# Recommend energy management certifications based on carbon emissions | |
if annual_carbon_emissions > 0: | |
recommendations_text += "To measure, manage, and reduce your carbon emissions, pursuing the Carbon Trust Standard would be beneficial. " | |
# If the company does not have an energy management system, recommend establishing one | |
if "ISO 50001" not in selected_certifications_and_initiatives: | |
recommendations_text += "Implementing an ISO 50001 Energy Management System can help you continuously improve energy efficiency. " | |
# Suggest building certifications if the company operates physical locations | |
recommendations_text += "For sustainable building operations, consider LEED or BREEAM certifications. " | |
# Recommend product-specific energy certifications | |
recommendations_text += "Achieving Energy Star certification can enhance the marketability of your energy-efficient products. " | |
# For each recommendation, get more details on how to obtain the certification | |
for certification in ["Renewable Energy Certificate", "Carbon Trust Standard", "ISO 50001", "LEED", "BREEAM", "Energy Star"]: | |
certification_details = get_certification_details(certification) | |
recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}" | |
# Return the combined recommendations as a single formatted string | |
return recommendations_text | |
st.markdown("<br>"*1, unsafe_allow_html=True) | |
if st.button('Submit'): | |
try: | |
# Use a spinner for generating advice | |
with st.spinner("Generating report and advice..."): | |
st.subheader("Visualize Energy Data") | |
visualize_data(answers_df) | |
st.subheader("Visualize Energy Scores") | |
score = calculate_energy_score(answers_df) | |
st.write(f"**Energy Sustainability Score:**") | |
st.markdown(f"**{score:.1f}%**") | |
# Call the function with the DataFrame | |
visualize_score_explanation(answers_df) | |
# Display the explanation in Streamlit | |
st.markdown(explanation_E_eval) | |
st.subheader("Visualize Sustainability Grade") | |
# Call the function with the DataFrame | |
result = evaluate_sustainability_practice(score, answers_df) | |
# Display the result in Streamlit | |
st.write(result) | |
strategy = get_energy_sustainability_advice(all_answers, company_data) | |
#strategy = get_energy_sustainability_advice(strategy, company_data) | |
report = get_energy_report(all_answers, score) | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = generate_swot_analysis(company_data) | |
#st.subheader("Energy Sustainability Strategy") | |
st.subheader("Company SWOT Report") | |
st.write(swot_analysis_content) | |
#st.subheader("Energy Sustainability Strategy") | |
st.subheader("Energy Sustainability Report") | |
st.write(report) | |
st.download_button( | |
label="Download Energy Sustainability Report", | |
data=report, | |
file_name='Energy_sustainability_report.txt', | |
mime='text/txt', | |
key="download_report_button", # Unique key for this button | |
) | |
st.subheader("Energy Sustainability Strategy") | |
st.write(strategy) | |
st.download_button( | |
label="Download Energy Sustainability Strategy", | |
data=strategy, | |
file_name='Energy_sustainability_strategy.txt', | |
mime='text/txt', | |
key="download_strategy_button", # Unique key for this button | |
) | |
st.subheader("Energy Sustainability Certification") | |
energy_cert=advise_on_energy_sustainability_certification(company_data) | |
st.write(energy_cert) | |
# Embed a YouTube video after processing | |
st.subheader("Watch More on Sustainability") | |
# Define a list of video URLs | |
video_urls = [ | |
"https://www.youtube.com/watch?v=olOjPWpYo4U", | |
#"https://www.youtube.com/watch?v=your_video_url_2", | |
#"https://www.youtube.com/watch?v=your_video_url_3", | |
# Add more video URLs as needed | |
] | |
# Select a random video URL from the list | |
random_video_url = random.choice(video_urls) | |
# Display the random video | |
st.video(random_video_url) | |
except Exception as e: | |
st.error(f"An error occurred: {e}") | |
def page2(): | |
st.write("<center><h1>Sustainable Logistics Strategy and Transportation</h1></center>", unsafe_allow_html=True) | |
st.image("page1.1.png", use_column_width=True) | |
st.write("Assess and improve the sustainability of your logistics operations.") | |
st.header("Company Information") | |
input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"]) | |
# Function to extract logistics information from a website URL | |
def extract_logistics_info_from_website(url): | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for HTTP errors (e.g., 404) | |
# Parse the HTML content of the page | |
soup = BeautifulSoup(response.text, 'html.parser') | |
# Example: Extract company description from the website | |
company_description = soup.find('meta', attrs={'name': 'description'}) | |
if company_description: | |
return company_description['content'] | |
except requests.exceptions.RequestException as e: | |
return f"Error: Unable to connect to the website ({e})" | |
except Exception as e: | |
return f"Error: {e}" | |
return None | |
# Function to summarize logistics information using OpenAI's GPT-3 model | |
def summarize_logistics_info(logistics_info): | |
prompt = f""" | |
Please extract the following information from the logistics company's description: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
Description: | |
{logistics_info} | |
Please provide responses while avoiding speculative or unfounded information. | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=100, | |
temperature=0 | |
) | |
company_summary = response.choices[0].message['content'] | |
return company_summary | |
except Exception as e: | |
return f"Error: {e}" | |
# Streamlit UI | |
st.title("Logistics Information Extractor") | |
st.write("Extract logistics information from a logistics company's website URL.") | |
if input_option == "Enter logistics company's website URL": | |
example_url = "https://quangninhport.com.vn/en/home" | |
website_url = st.text_input("Please enter the logistics company's website URL:", example_url) | |
if website_url: | |
# Ensure the URL starts with http/https | |
website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url | |
logistics_info = extract_logistics_info_from_website(website_url) | |
if logistics_info: | |
company_summary = summarize_logistics_info(logistics_info) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
elif input_option == "Provide company description manually": | |
st.markdown(""" | |
Please provide a description of the logistics company, focusing on the following: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
""") | |
company_description = st.text_area("Please provide the company description:", "") | |
if company_description: | |
company_summary = summarize_logistics_info(company_description) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
st.header("Logistics Sustainability Information") | |
# Definitions for logistics sustainability levels | |
sustainability_info = { | |
"None": "No sustainability info available", | |
"Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.", | |
"Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.", | |
"Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.", | |
} | |
sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys())) | |
# Display the definition when the user selects a sustainability level | |
if sustainability_level in sustainability_info: | |
st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}") | |
# Additional sustainability-related information | |
carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0) | |
renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?") | |
# Certification and Sustainability Initiatives | |
st.subheader("Certifications and Sustainability Initiatives") | |
# Explanations for logistics-related certifications | |
logistics_certification_info = { | |
"None": "No certifications or initiatives related to logistics.", | |
"ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.", | |
"SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.", | |
"C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.", | |
"Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.", | |
"Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.", | |
} | |
selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys())) | |
# Display explanations for selected certifications | |
for certification in selected_certifications: | |
if certification in logistics_certification_info: | |
st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}") | |
# Define the company_data dictionary | |
company_data = { | |
"Logistics Sustainability Level": sustainability_level, | |
"Annual Carbon Emissions (in metric tons)": carbon_emissions, | |
"Utilize Renewable Energy Sources": renewable_energy, | |
"Selected Logistics Certifications and Initiatives": selected_certifications | |
} | |
# If company_summary is generated, add it to company_data dictionary | |
if 'company_summary' in locals() or 'company_summary' in globals(): | |
company_data["Company Summary"] = company_summary | |
#st.write(company_data) | |
st.write("<hr>", unsafe_allow_html=True) | |
st.write("In this section, we'll assess your company's commitment to environmental management, progress in reducing its environmental impact, transparency in reporting environmental performance to stakeholders, preparedness in managing climate change risks, and commitment to protecting biodiversity.") | |
st.write("<hr>", unsafe_allow_html=True) | |
sections = { | |
"Transport and Environmental Commitment": [ | |
# Environmental Commitment related to Transport | |
("1. Environmental Management Commitment (0-10):", 'slider'), | |
("2. Progress in Reducing Environmental Impact of Transport (0-10):", 'slider'), | |
("3. Transparency in Transport-Related Environmental Reporting (0-10):", 'slider'), | |
("4. Commitment to Digital Transformation for Sustainable Transport (0-10):", 'slider'), | |
("5. Integration of Transport Sustainability Goals in Business Strategy (0-10):", 'slider'), | |
("6. Commitment to Increasing Energy Efficiency in Transport (0-10):", 'slider'), | |
("7. Commitment to Sustainable Packaging in Transport (0-10):", 'slider'), | |
("8. Commitment to Emission Reduction in Transport Operations (0-10):", 'slider'), | |
("9. Commitment to Sustainable Waste Management in Transport (0-10):", 'slider'), | |
# Transport Method | |
("10. Type of Vehicle (Select primary type):", ['Truck', 'Ship', 'Train', 'Airplane'], 'selectbox'), | |
("11. Fuel Type (Select primary type):", ['Diesel', 'Gasoline', 'Natural Gas', 'Electric'], 'selectbox'), | |
("12. Average Vehicle Fuel Efficiency (MPG or L/Km):", 'number_input', {"min_value": 0}), | |
("13. Frequency of Vehicle Trips (per month):", 'number_input', {"min_value": 0}), | |
("14. Use of Alternative Transportation Methods:", 'radio', ["Yes", "No"]), | |
("15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:", 'radio', ["Yes", "No"]), | |
("16. Monitoring and Reduction of Vehicle Idling Time:", 'radio', ["Yes", "No"]), | |
("17. Equipped with Fuel-Efficient Technologies:", 'radio', ["Yes", "No"]), | |
("18. Strategies or Technologies for Vehicle Emission Management:", 'radio', ["Yes", "No"]), | |
("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 'number_input', {"min_value": 0, "max_value": 100}), | |
("20. Vehicle Maintenance for Optimal Fuel Efficiency and Emissions Control:", 'radio', ["Yes", "No"]), | |
("21. Average Age of Vehicle Fleet (in years):", 'number_input', {"min_value": 0}), | |
("22. Environmentally Friendly Disposal/Recycling of End-of-Life Vehicles:", 'radio', ["Yes", "No"]) | |
] | |
} | |
# Initialize a dictionary to store the answers | |
all_answers = {} | |
# Display the section header | |
st.subheader("Transport and Environmental Commitment") | |
st.write("<hr>", unsafe_allow_html=True) | |
# Create columns outside the loop | |
col1, col2, col3 = st.columns(3) | |
# Iterate through each question and display them in columns | |
for i, (question_text, input_type, *options) in enumerate(sections["Transport and Environmental Commitment"]): | |
# Determine which column to use based on the question index | |
if i % 3 == 0: | |
col = col1 | |
elif i % 3 == 1: | |
col = col2 | |
else: | |
col = col3 | |
with col: | |
if input_type == 'selectbox': | |
all_answers[question_text] = st.selectbox(question_text, options[0]) | |
elif input_type == 'number_input': | |
params = options[0] | |
all_answers[question_text] = st.number_input(question_text, **params) | |
elif input_type == 'radio': | |
all_answers[question_text] = st.radio(question_text, options[0]) | |
elif input_type == 'slider': | |
all_answers[question_text] = st.slider(question_text, 0, 10) | |
# Convert answers to a DataFrame for analysis | |
answers_df = pd.DataFrame([all_answers]) | |
#st.write(all_answers) | |
# Display the collected answers | |
#st.write("Collected Answers:", answers_df) | |
def calculate_transport_score(all_answers): | |
score = 0 | |
# Scoring for transport-related commitment (sliders) | |
for i in range(1, 10): | |
commitment_score = all_answers.get(f"{i}. Environmental Management Commitment (0-10):", 0) | |
score += commitment_score | |
# Scoring for vehicle type | |
vehicle_type_score = {"Truck": 5, "Ship": 7, "Train": 10, "Airplane": 3} | |
primary_vehicle = all_answers.get("10. Type of Vehicle (Select primary type):", "").lower() | |
score += vehicle_type_score.get(primary_vehicle, 0) | |
# Scoring for fuel type | |
fuel_type_score = {"Diesel": 3, "Gasoline": 2, "Natural Gas": 5, "Electric": 10} | |
primary_fuel = all_answers.get("11. Fuel Type (Select primary type):", "").lower() | |
score += fuel_type_score.get(primary_fuel, 0) | |
# Scoring for fuel efficiency | |
fuel_efficiency = all_answers.get("12. Average Vehicle Fuel Efficiency (MPG or L/Km)", 0) | |
if fuel_efficiency > 0: | |
score += min(10, int(fuel_efficiency / 10)) # Scale as needed | |
# Scoring for frequency of trips | |
trip_frequency = all_answers.get("13. Frequency of Vehicle Trips (per month):", 0) | |
if trip_frequency > 0: | |
score -= min(5, int(trip_frequency / 10)) # Lower frequency, higher score | |
# Scoring for Yes/No questions (5 points for each 'Yes') | |
yes_no_questions = [ | |
"14. Use of Alternative Transportation Methods:", | |
"15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:", | |
"16. Monitoring and Reduction of Vehicle Idling Time:", | |
"17. Equipped with Fuel-Efficient Technologies:", | |
"18. Strategies or Technologies for Vehicle Emission Management:", | |
"20. Vehicle Maintenance for Optimal Fuel Efficiency and Emissions Control:", | |
"22. Environmentally Friendly Disposal/Recycling of End-of-Life Vehicles:" | |
] | |
for question in yes_no_questions: | |
response = all_answers.get(question, "No").lower() | |
if response == 'yes': | |
score += 5 | |
# Scoring based on fleet meeting emission standards | |
emission_standards_percentage = all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 0) | |
score += int(emission_standards_percentage / 10) | |
# Scoring based on fleet age | |
fleet_age = all_answers.get("21. Average Age of Vehicle Fleet (in years):", 0) | |
if fleet_age > 0: | |
score -= min(5, int(fleet_age / 5)) # Newer fleet gets higher score | |
# Ensure score is within 0-100 range | |
score = max(0, min(100, score)) | |
return score | |
def visualize_data(all_answers): | |
# For commitment-related questions (questions 1 to 9) | |
commitment_scores = [all_answers.get(f"{i}. Environmental Management Commitment (0-10):", 0) for i in range(1, 10)] | |
total_commitment_score = sum(commitment_scores) | |
max_commitment_score = 10 * len(commitment_scores) # Maximum possible score | |
average_commitment_score = total_commitment_score / max_commitment_score # Fraction of maximum | |
# Determine commitment level based on fraction | |
commitment_level = "Eco-Enthusiast" if average_commitment_score > 0.5 else "Eco-Beginner" | |
explanation = "" | |
if average_commitment_score > 0.5: | |
explanation = "With an above-average commitment score, your company has shown a strong commitment to sustainable practices." | |
else: | |
explanation = "Your commitment to sustainability is just beginning. There's much potential for growth in this area." | |
# Creating two columns in Streamlit | |
col1, col2 = st.columns(2) | |
with col1: | |
st.subheader("Transport Environmental Commitment") | |
st.write(f"**Commitment Level:** {commitment_level}") | |
st.write(explanation) | |
# Plotting commitment level | |
plt.figure(figsize=(6, 4)) | |
plt.bar(["Commitment Level"], [average_commitment_score], color='green' if average_commitment_score > 0.5 else 'red') | |
plt.xlabel('Category') | |
plt.ylabel('Average Score') | |
plt.title('Transport Environmental Commitment') | |
plt.ylim(0, 1) # Assuming you want to scale the bar to 1 for visual consistency | |
plt.xticks([0], ['Commitment Score']) # Setting x-ticks to show "Commitment Score" | |
plt.yticks([0, 0.5, 1], ['0%', '50%', '100%']) # Setting y-ticks to show percentages | |
st.pyplot(plt.gcf()) | |
with col2: | |
st.subheader("Digital Transformation for Sustainable Transport") | |
# For Digital Transformation score visualization (replace with actual score variable) | |
digital_transformation = all_answers.get("4. Commitment to Digital Transformation for Sustainable Transport (0-10):", 0) | |
st.write(f"**Digital Transformation Score:** {digital_transformation}/10") | |
st.write("This score represents the commitment to digital transformation for sustainable transport.") | |
# Plotting Digital Transformation score | |
plt.figure(figsize=(6, 4)) | |
plt.bar(["Digital Transformation"], [digital_transformation], color='lightblue') | |
plt.xlabel('Category') | |
plt.ylabel('Score') | |
plt.title('Commitment to Digital Transformation for Sustainable Transport') | |
plt.ylim(0, 10) # Assuming scores range from 0 to 10 | |
plt.xticks([0], ['Digital Transformation Score']) # Setting x-ticks to show "Digital Transformation Score" | |
st.pyplot(plt.gcf()) | |
def visualize_data1(all_answers): | |
# Extracting data for visualization | |
emission_reduction_commitment = all_answers.get("8. Commitment to Emission Reduction in Transport Operations (0-10):", 0) | |
fleet_meeting_emission_standards = all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 0) | |
# Creating two columns in Streamlit | |
col1, col2 = st.columns(2) | |
# Visualizing "8. Commitment to Emission Reduction in Transport Operations (0-10):" | |
with col1: | |
st.subheader("Commitment to Emission Reduction") | |
st.write(f"**Commitment Score:** {emission_reduction_commitment}/10") | |
st.write("This score represents the commitment to reducing emissions in transport operations.") | |
fig_emission = plt.figure(figsize=(6, 4)) | |
bar1 = plt.bar("Emission Reduction Commitment", emission_reduction_commitment, color='skyblue') | |
plt.xlabel('Commitment') | |
plt.ylabel('Score') | |
plt.title('Commitment to Emission Reduction in Transport Operations') | |
plt.legend([bar1], ['Emission Reduction Commitment']) | |
# Add data label | |
plt.text(bar1[0].get_x() + bar1[0].get_width() / 2., bar1[0].get_height(), | |
f'{emission_reduction_commitment}/10', ha='center', va='bottom') | |
st.pyplot(fig_emission) | |
# Visualizing "19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):" | |
with col2: | |
st.subheader("Fleet Meeting Emission Standards") | |
st.write(f"**Emission Standards Percentage:** {fleet_meeting_emission_standards}%") | |
st.write("This represents the percentage of the fleet meeting the latest emission standards.") | |
fig_fleet_emission = plt.figure(figsize=(6, 4)) | |
bar2 = plt.bar("Fleet Meeting Emission Standards", fleet_meeting_emission_standards, color='lightgreen') | |
plt.xlabel('Fleet Emission Standards') | |
plt.ylabel('Percentage') | |
plt.title('Percentage of Fleet Meeting Latest Emission Standards') | |
plt.legend([bar2], ['Fleet Meeting Emission Standards']) | |
# Add data label | |
plt.text(bar2[0].get_x() + bar2[0].get_width() / 2., bar2[0].get_height(), | |
f'{fleet_meeting_emission_standards}%', ha='center', va='bottom') | |
st.pyplot(fig_fleet_emission) | |
#visualize_data(all_answers) | |
#st.subheader("Visualize Transport Scores") | |
#score = calculate_transport_score(all_answers) | |
#st.write("Transport Sustainability Score:", score) | |
def visualize_transport_score(all_answers): | |
# Scoring parameters | |
vehicle_type_score = {"Truck": 5, "Ship": 7, "Train": 10, "Airplane": 3} | |
fuel_type_score = {"Diesel": 3, "Gasoline": 2, "Natural Gas": 5, "Electric": 10} | |
yes_no_score_value = 5 # Points for each 'Yes' in yes/no questions | |
# Extracting data from all_answers | |
vehicle_type = all_answers.get("10. Type of Vehicle (Select primary type):", "").lower() | |
fuel_type = all_answers.get("11. Fuel Type (Select primary type):", "").lower() | |
fuel_efficiency = all_answers.get("12. Average Vehicle Fuel Efficiency (MPG or L/Km)", 0) | |
emission_standards_percentage = all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", 0) | |
fleet_age = all_answers.get("21. Average Age of Vehicle Fleet (in years):", 0) | |
# Scoring components | |
vehicle_type_score = vehicle_type_score.get(vehicle_type, 0) | |
fuel_type_score = fuel_type_score.get(fuel_type, 0) | |
fuel_efficiency_score = min(10, int(fuel_efficiency / 10)) | |
emission_standards_score = int(emission_standards_percentage / 10) | |
fleet_age_score = max(0, 5 - int(fleet_age / 5)) | |
# Yes/No questions scoring | |
yes_no_questions = [ | |
"14. Use of Alternative Transportation Methods:", | |
"15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:", | |
"16. Monitoring and Reduction of Vehicle Idling Time:", | |
"17. Equipped with Fuel-Efficient Technologies:", | |
"18. Strategies or Technologies for Vehicle Emission Management:", | |
"20. Vehicle Maintenance for Optimal Fuel Efficiency and Emissions Control:", | |
"22. Environmentally Friendly Disposal/Recycling of End-of-Life Vehicles:" | |
] | |
yes_no_score = sum(all_answers.get(question, "No").lower() == 'yes' for question in yes_no_questions) * yes_no_score_value | |
# Components for visualization | |
components = { | |
'Vehicle Type': vehicle_type_score, | |
'Fuel Type': fuel_type_score, | |
'Fuel Efficiency': fuel_efficiency_score, | |
'Emission Standards Compliance': emission_standards_score, | |
'Fleet Age': fleet_age_score, | |
'Yes/No Sustainability Practices': yes_no_score | |
} | |
# Define colors for the bar chart | |
colors = ['skyblue', 'orange', 'lightgreen', 'red', 'purple', 'pink'] # Define colors as needed | |
# Create a horizontal bar chart | |
plt.figure(figsize=(10, 6)) | |
plt.barh(list(components.keys()), list(components.values()), color=colors) | |
# Add data labels to the bars | |
for index, value in enumerate(components.values()): | |
plt.text(value, index, str(value), va='center', color='black', fontweight='bold') | |
# Set labels and title | |
plt.xlabel('Score') | |
plt.title('Contribution to Total Transport Sustainability Score') | |
# Show grid and invert y-axis for better readability | |
plt.grid(axis='x') | |
plt.gca().invert_yaxis() | |
plt.tight_layout() | |
plt.show() | |
explanation_T_metric = """ | |
The Transport Sustainability Score is calculated based on various factors that reflect sustainable practices in transport operations. Here's a breakdown of how the score is composed: | |
- **Vehicle Type:** Different types of vehicles are scored based on their environmental impact. More sustainable vehicle types, like trains, score higher points. | |
- **Fuel Type:** The primary fuel type used in vehicles influences the score. Renewable and cleaner fuels like electric power receive higher points. | |
- **Fuel Efficiency:** Points are awarded based on the average fuel efficiency of the vehicle fleet. Higher fuel efficiency, indicating less fuel consumption per mile, contributes more points. | |
- **Emission Standards Compliance:** The percentage of the vehicle fleet meeting the latest emission standards is a key factor. A higher percentage indicates better compliance with environmental standards and contributes positively to the score. | |
- **Yes/No Sustainability Practices:** Responses to yes/no questions about sustainable transport practices such as the use of alternative transportation methods, strategies to reduce emissions, and maintenance for optimal fuel efficiency contribute to the score. Each 'Yes' response reflects a proactive measure in sustainable transport and adds points. | |
- **Vehicle Maintenance and Disposal Practices:** Good maintenance practices that ensure optimal fuel efficiency and responsible disposal or recycling of end-of-life vehicles are crucial. These practices are scored to encourage sustainability throughout the vehicle's lifecycle. | |
A higher score indicates a stronger commitment to sustainable transport practices and efficient environmental management in transport operations. | |
""" | |
def evaluate_transport_sustainability_practice(score, df): | |
# Calculate the transport sustainability score | |
# Assuming score is calculated using calculate_transport_score(df) | |
# Counting 'Yes' responses for transport-related Yes/No questions | |
transport_yes_no_questions = [question[0] for question in sections["Transport and Environmental Commitment"] if question[1] == 'radio'] | |
yes_count = sum(df[question].eq('Yes').sum() for question in transport_yes_no_questions if question in df.columns) | |
yes_percentage = (yes_count / len(transport_yes_no_questions)) * 100 if transport_yes_no_questions else 0 | |
# Calculate a combined transport sustainability index | |
combined_index = (0.6 * score) + (0.4 * yes_percentage) | |
# Grading system with detailed advice for transport sustainability | |
if combined_index >= 80: | |
grade = "A (Transport Eco-Champion π)" | |
st.image("Eco-Champion.png") | |
Explanation = "Your transport operations are at the forefront of sustainability, setting a high standard for the industry." | |
advice = "Continue to innovate and lead in sustainable transport practices. Explore new technologies and collaborate on industry-wide sustainability initiatives." | |
elif combined_index >= 60: | |
grade = "B (Transport Sustainability Steward π)" | |
st.image("Sustainability_Steward.png", use_column_width=True) | |
Explanation = "Your transport operations are highly sustainable, demonstrating a strong commitment to environmental stewardship." | |
advice = "Seek opportunities for further improvement in areas like fuel efficiency, emissions reduction, and green logistics." | |
elif combined_index >= 40: | |
grade = "C (Transport Eco-Advancer πΏ)" | |
st.image("Eco-Advancer.png", use_column_width=True) | |
Explanation = "You are making significant strides in sustainable transport, but there's room for further progress." | |
advice = "Focus on areas such as increasing the use of renewable fuels, optimizing routes for efficiency, and reducing idle times." | |
elif combined_index >= 20: | |
grade = "D (Transport Green Learner πΌ)" | |
st.image("Green_Learner.png", use_column_width=True) | |
Explanation = "You've started to integrate sustainable practices in your transport operations, but there's much to learn and implement." | |
advice = "Begin with achievable goals like improving vehicle maintenance for better fuel efficiency and exploring eco-friendly transport options." | |
else: | |
grade = "E (Transport Eco-Novice π±)" | |
st.image("Eco-Novice.png", use_column_width=True) | |
Explanation = "You are at the beginning of your journey towards sustainable transport." | |
advice = "Start with basic measures such as monitoring fuel consumption, training drivers in eco-driving techniques, and planning efficient routes." | |
return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{Explanation} \n\n**Detailed Advice:** \n{advice}" | |
#st.markdown(evaluate_transport_sustainability_practice(score, answers_df), unsafe_allow_html=True) | |
def generate_swot_analysis(company_data): | |
# Extracting relevant data from company_data | |
logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None") | |
annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0) | |
utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False) | |
selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", []) | |
company_summary = company_data.get("Company Summary", "No specific information provided.") | |
# Constructing a dynamic SWOT analysis based on extracted data | |
strengths = [ | |
"Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None" | |
] | |
weaknesses = [ | |
"Lack of Logistics Sustainability Level: " + logistics_sustainability_level, | |
"Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present", | |
"Company Summary: " + company_summary | |
] | |
opportunities = [ | |
"Exploration of Logistics Certifications" if not selected_certifications else "None" | |
] | |
threats = [ | |
"Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None" | |
] | |
# Constructing a SWOT analysis prompt dynamically | |
swot_analysis_prompt = f""" | |
Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis: | |
Strengths: | |
Strengths Analysis: | |
{", ".join(strengths)} | |
Weaknesses: | |
Weaknesses Analysis: | |
{", ".join(weaknesses)} | |
Opportunities: | |
Opportunities Analysis: | |
{", ".join(opportunities)} | |
Threats: | |
Threats Analysis: | |
{", ".join(threats)} | |
""" | |
# OpenAI API call for SWOT analysis | |
response_swot = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are analyzing the company's sustainability practices."}, | |
{"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."}, | |
{"role": "user", "content": swot_analysis_prompt} | |
], | |
max_tokens=1000, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = response_swot.choices[0].message['content'] | |
return swot_analysis_content | |
def get_transport_sustainability_report(all_answers, score): | |
"""Generates a Transport Sustainability report based on responses to a questionnaire.""" | |
extracted_data = extract_data(all_answers) | |
# Consolidate data for transport method using extracted data | |
vehicle_info = f"Vehicle Type: {extracted_data.get('10. Type of Vehicle (Select primary type):', 'N/A')}, Fuel Type: {extracted_data.get('11. Fuel Type (Select primary type):', 'N/A')}" | |
transport_efficiency_measures = f"Average Fuel Efficiency: {extracted_data.get('12. Average Vehicle Fuel Efficiency (MPG or L/Km):', 'N/A')}, Frequency of Trips: {extracted_data.get('13. Frequency of Vehicle Trips (per month):', 'N/A')}" | |
environmental_commitment = f"Alternative Transportation Methods: {extracted_data.get('14. Use of Alternative Transportation Methods:', 'N/A')}, Empty Trip Reduction: {extracted_data.get('15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:', 'N/A')}" | |
consolidated_report = f""" | |
Transport Sustainability Report | |
Score: {score}/100 | |
Report Details: | |
{vehicle_info} | |
{transport_efficiency_measures} | |
{environmental_commitment} | |
""" | |
# Prompt for the OpenAI API | |
prompt = f""" | |
As a transport sustainability advisor, analyze the Transport Sustainability Report with a score of {score}/100. Review the data points provided and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement. Provide specific recommendations to improve the transport sustainability score, considering the current vehicle mix, fuel efficiency, and environmental initiatives. | |
Data Points: | |
{vehicle_info} | |
{transport_efficiency_measures} | |
{environmental_commitment} | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=3000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0, | |
presence_penalty=0 | |
) | |
evaluation_content = response.choices[0].message['content'] | |
refined_report = f"{consolidated_report}\n\n{evaluation_content}" | |
return refined_report | |
except Exception as e: | |
return f"Error: {e}" | |
def format_answer(answer): | |
"""Format the answer based on its type for better readability.""" | |
if isinstance(answer, bool): | |
return "Yes" if answer else "No" | |
elif isinstance(answer, (int, float)): | |
return str(answer) | |
return answer # Assume the answer is already in a string format | |
def extract_data(data): | |
"""Extract and format data from a dictionary.""" | |
formatted_data = {} | |
for key, value in data.items(): | |
formatted_data[key] = format_answer(value) | |
return formatted_data | |
def get_transport_sustainability_strategy(all_answers, company_data): | |
# Extracting and formatting data from all_answers and company_data | |
extracted_all_answers = extract_data(all_answers) | |
extracted_company_data = extract_data(company_data) | |
# Forming the prompt with extracted data | |
prompt = f""" | |
Based on the provided company and transport sustainability assessment data, provide a transport sustainability strategy: | |
**Company Info**: | |
- Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')} | |
- Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons | |
- Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')} | |
- Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')} | |
- Company Summary: {extracted_company_data.get('Company Summary', 'N/A')} | |
**Transport Sustainability Assessment Data**: | |
- Vehicle Type: {extracted_all_answers.get("10. Type of Vehicle (Select primary type):", "N/A")} | |
- Fuel Type: {extracted_all_answers.get("11. Fuel Type (Select primary type):", "N/A")} | |
- Average Fuel Efficiency: {extracted_all_answers.get("12. Average Vehicle Fuel Efficiency (MPG or L/Km):", "N/A")} | |
- Use of Alternative Transportation Methods: {extracted_all_answers.get("14. Use of Alternative Transportation Methods:", "N/A")} | |
- Initiatives for Efficiency: {extracted_all_answers.get("15. Initiatives to Reduce Empty or Partially Filled Vehicle Trips:", "N/A")} | |
- Emission Standards Compliance: {extracted_all_answers.get("19. Percentage of Fleet Meeting Latest Emission Standards (0-100%):", "N/A")}% | |
Offer actionable strategy considering the company's specific context and transport sustainability data. | |
""" | |
additional_context = f"Provide detailed transport sustainability strategy using context data from the above company info and in responses to the transport sustainability assessment." | |
# Assuming you have an API call here to generate a response based on the prompt | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are an energy sustainability strategy advisor."}, | |
{"role": "user", "content": prompt}, | |
{"role": "user", "content": additional_context} | |
], | |
max_tokens=3000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
return response.choices[0].message['content'] | |
def get_certification_details(certification_name): | |
# Prepare the prompt for the API call | |
messages = [ | |
{"role": "system", "content": "You are a knowledgeable assistant about global certifications."}, | |
{"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."} | |
] | |
# Query the OpenAI API for information on the certification process | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
max_tokens=1500, | |
temperature=0.3, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Return the content of the response | |
return response.choices[0].message['content'] | |
def advise_on_transport_sustainability_certification(company_data): | |
# Check if company_data is a dictionary | |
if not isinstance(company_data, dict): | |
raise ValueError("company_data must be a dictionary") | |
# Extract company data | |
annual_carbon_emissions = company_data.get('Annual Carbon Emissions', 0) | |
use_alternative_transport_methods = company_data.get('Use Alternative Transport Methods', False) | |
selected_transport_certifications = company_data.get('Selected Transport Certifications and Initiatives', []) | |
# Initialize a string to store recommendations | |
recommendations_text = "" | |
# Determine which certifications to suggest | |
certifications_to_consider = { | |
"SmartWay": use_alternative_transport_methods, | |
"Clean Cargo": use_alternative_transport_methods, | |
"Carbon Trust Standard": annual_carbon_emissions > 0, | |
"GLEC Framework": annual_carbon_emissions > 0, | |
"ISO 39001": "ISO 39001" not in selected_transport_certifications, | |
"EcoVadis": True, | |
"Green Logistics": True | |
} | |
for certification, consider in certifications_to_consider.items(): | |
if consider: | |
try: | |
certification_details = get_certification_details(certification) | |
recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}" | |
except Exception as e: | |
recommendations_text += f"\n\nError retrieving details for {certification}: {e}" | |
# If no certifications are suggested, add a message | |
if not recommendations_text.strip(): | |
recommendations_text = "Based on the provided data, there are no specific certifications recommended at this time." | |
# Return the combined recommendations as a single formatted string | |
return recommendations_text | |
st.markdown("<br>"*1, unsafe_allow_html=True) | |
if st.button('Submit'): | |
try: | |
# Use a spinner for generating advice | |
with st.spinner("Generating report and advice..."): | |
st.subheader("Visualize Transport Data") | |
visualize_data(all_answers) | |
visualize_data1(all_answers) | |
st.subheader("Transport Scores") | |
score = calculate_transport_score(all_answers) | |
#st.write("Transport Sustainability Score:", score) | |
# Display formatted score | |
st.write(f"**Transport Sustainability Score:**") | |
st.markdown(f"**{score:.1f}%**") | |
st.subheader("Visualize Transport Scores") | |
# Call the function to get the figure | |
fig = visualize_transport_score(all_answers) | |
# Display the figure in Streamlit, using a column layout | |
st.pyplot(fig) | |
st.markdown(explanation_T_metric) | |
st.subheader("Visualize Sustainability Grade") | |
# Call the function with the DataFrame | |
st.markdown(evaluate_transport_sustainability_practice(score, answers_df), unsafe_allow_html=True) | |
strategy = get_transport_sustainability_strategy(all_answers, company_data) | |
#strategy = get_energy_sustainability_advice(strategy, company_data) | |
report = get_transport_sustainability_report(all_answers, score) | |
#st.subheader("Energy Sustainability Strategy") | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = generate_swot_analysis(company_data) | |
#st.subheader("Energy Sustainability Strategy") | |
st.subheader("Company SWOT Report") | |
st.write(swot_analysis_content) | |
st.subheader("Transport Sustainability Report") | |
st.write(report) | |
st.download_button( | |
label="Download Transport Sustainability Report", | |
data=report, | |
file_name='sustainability_report.txt', | |
mime='text/txt', | |
key="download_report_button", # Unique key for this button | |
) | |
st.subheader("Sustainability Strategy") | |
st.write(strategy) | |
st.download_button( | |
label="Download Sustainability Strategy", | |
data=strategy, | |
file_name='sustainability_strategy.txt', | |
mime='text/txt', | |
key="download_strategy_button", # Unique key for this button | |
) | |
st.subheader("Advice on Sustainability Certification") | |
#certification_advice = advise_on_transport_sustainability_certification(company_data) | |
try: | |
advice = advise_on_transport_sustainability_certification(company_data) | |
st.write(advice) | |
except ValueError as e: | |
print(e) | |
# Embed a YouTube video after processing | |
st.subheader("Watch More on Sustainability") | |
video_urls = [ | |
"https://www.youtube.com/watch?v=BawgdP1jmPo", | |
#"https://www.youtube.com/watch?v=your_video_url_2", | |
#"https://www.youtube.com/watch?v=your_video_url_3", | |
# Add more video URLs as needed | |
] | |
# Select a random video URL from the list | |
random_video_url = random.choice(video_urls) | |
# Display the random video | |
st.video(random_video_url) | |
except Exception as e: | |
st.error(f"An error occurred: {e}") | |
st.write(""" | |
--- | |
*Powered by Streamlit, CarbonInterface API, and OpenAI.* | |
""") | |
def page3(): | |
st.write("<center><h1>Waste Warriors: Navigating Sustainable Logistics</h1></center>", unsafe_allow_html=True) | |
st.image("page6.1.png", use_column_width=True) | |
st.write("Assess and improve the sustainability of your logistics operations.") | |
st.header("Company Information") | |
input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"]) | |
# Function to extract logistics information from a website URL | |
def extract_logistics_info_from_website(url): | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for HTTP errors (e.g., 404) | |
# Parse the HTML content of the page | |
soup = BeautifulSoup(response.text, 'html.parser') | |
# Example: Extract company description from the website | |
company_description = soup.find('meta', attrs={'name': 'description'}) | |
if company_description: | |
return company_description['content'] | |
except requests.exceptions.RequestException as e: | |
return f"Error: Unable to connect to the website ({e})" | |
except Exception as e: | |
return f"Error: {e}" | |
return None | |
# Function to summarize logistics information using OpenAI's GPT-3 model | |
def summarize_logistics_info(logistics_info): | |
prompt = f""" | |
Please extract the following information from the logistics company's description: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
Description: | |
{logistics_info} | |
Please provide responses while avoiding speculative or unfounded information. | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=100, | |
temperature=0 | |
) | |
company_summary = response.choices[0].message['content'] | |
return company_summary | |
except Exception as e: | |
return f"Error: {e}" | |
# Streamlit UI | |
st.title("Logistics Information Extractor") | |
st.write("Extract logistics information from a logistics company's website URL.") | |
# User input field for the website URL | |
#website_url = st.text_input("Enter the logistics company's website URL:") | |
if input_option == "Enter logistics company's website URL": | |
example_url = "https://quangninhport.com.vn/en/home" | |
website_url = st.text_input("Please enter the logistics company's website URL:", example_url) | |
if website_url: | |
# Ensure the URL starts with http/https | |
website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url | |
logistics_info = extract_logistics_info_from_website(website_url) | |
if logistics_info: | |
company_summary = summarize_logistics_info(logistics_info) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
elif input_option == "Provide company description manually": | |
st.markdown(""" | |
Please provide a description of the logistics company, focusing on the following: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
""") | |
company_description = st.text_area("Please provide the company description:", "") | |
if company_description: | |
company_summary = summarize_logistics_info(company_description) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
st.header("Logistics Sustainability Information") | |
# Definitions for logistics sustainability levels | |
sustainability_info = { | |
"None": "No sustainability info available", | |
"Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.", | |
"Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.", | |
"Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.", | |
} | |
sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys())) | |
# Display the definition when the user selects a sustainability level | |
if sustainability_level in sustainability_info: | |
st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}") | |
# Additional sustainability-related information | |
carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0) | |
renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?") | |
# Certification and Sustainability Initiatives | |
st.subheader("Certifications and Sustainability Initiatives") | |
# Explanations for logistics-related certifications | |
logistics_certification_info = { | |
"None": "No certifications or initiatives related to logistics.", | |
"ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.", | |
"SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.", | |
"C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.", | |
"Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.", | |
"Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.", | |
} | |
selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys())) | |
# Display explanations for selected certifications | |
for certification in selected_certifications: | |
if certification in logistics_certification_info: | |
st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}") | |
# Define the company_data dictionary | |
company_data = { | |
"Logistics Sustainability Level": sustainability_level, | |
"Annual Carbon Emissions (in metric tons)": carbon_emissions, | |
"Utilize Renewable Energy Sources": renewable_energy, | |
"Selected Logistics Certifications and Initiatives": selected_certifications | |
} | |
# If company_summary is generated, add it to company_data dictionary | |
if 'company_summary' in locals() or 'company_summary' in globals(): | |
company_data["Company Summary"] = company_summary | |
#st.write(company_data) | |
# Display the section header | |
st.subheader("Waste Management") | |
st.write("<hr>", unsafe_allow_html=True) | |
st.write("In this section, we'll delve into your company's waste management practices and sustainability efforts. We'll examine how you handle waste, reduce single-use items, and manage waste in an environmentally friendly manner.") | |
st.write("<hr>", unsafe_allow_html=True) | |
sections = { | |
"Waste Management": [ | |
("80. Do you have a waste management plan in place for your logistics operations?", 'radio', ["Yes", "No"]), | |
("81. Do you actively implement waste reduction and recycling initiatives?", 'radio', ["Yes", "No"]), | |
("82. Is waste segregated according to type (hazardous, non-hazardous, recyclable) at your facilities?", 'radio', ["Yes", "No"]), | |
("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", 'radio', ["Yes", "No"]), | |
("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", 'radio', ["Yes", "No"]), | |
("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", 'radio', ["Yes", "No"]), | |
("86. Are waste reduction and recycling efforts communicated to logistics employees?", 'radio', ["Yes", "No"]), | |
("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 'number_input', {"min_value": 0, "max_value": 100}), | |
("88. Have you conducted waste audits or assessments to evaluate waste management practices?", 'radio', ["Yes", "No"]), | |
("89. Are there plans to improve waste management and recycling efforts in the future?", 'radio', ["Yes", "No"]), | |
("90. Do you use software or systems for waste tracking and reporting?", 'radio', ["Yes", "No"]), | |
("91. Have you set quantifiable goals for waste reduction in the next year?", 'radio', ["Yes", "No"]), | |
("92. What is your target percentage for waste reduction in the next year?", 'number_input', {"min_value": 0, "max_value": 100}), | |
("93. Do you have partnerships with recycling or waste management companies?", 'radio', ["Yes", "No"]), | |
("94. Do you provide training on waste management for new employees?", 'radio', ["Yes", "No"]), | |
("95. Have you implemented a policy to reduce single-use items within logistics operations?", 'radio', ["Yes", "No"]), | |
("96. Do you conduct regular waste management compliance checks?", 'radio', ["Yes", "No"]), | |
("97. Do you participate in or support community waste management programs?", 'radio', ["Yes", "No"]), | |
("98. What percentage of your logistics operations are zero-waste to landfill?", 'number_input', {"min_value": 0, "max_value": 100}), | |
("99. Have you received any certifications or awards for your waste management practices?", 'radio', ["Yes", "No"]), | |
("100. Is there a designated team or department responsible for waste management?", 'radio', ["Yes", "No"]) | |
], | |
} | |
# Initialize a dictionary to store the answers | |
all_answers = {} | |
st.write("<hr>", unsafe_allow_html=True) | |
# Create columns outside the loop | |
col1, col2, col3 = st.columns(3) | |
# Iterate through each question and display them in columns | |
for i, (question_text, input_type, *options) in enumerate(sections["Waste Management"]): | |
# Determine which column to use based on the question index | |
if i % 3 == 0: | |
col = col1 | |
elif i % 3 == 1: | |
col = col2 | |
else: | |
col = col3 | |
with col: | |
if input_type == 'selectbox': | |
all_answers[question_text] = st.selectbox(question_text, options[0]) | |
elif input_type == 'number_input': | |
params = options[0] | |
all_answers[question_text] = st.number_input(question_text, **params) | |
elif input_type == 'radio': | |
all_answers[question_text] = st.radio(question_text, options[0]) | |
elif input_type == 'slider': | |
all_answers[question_text] = st.slider(question_text, 0, 10) | |
# Convert answers to a DataFrame for analysis | |
answers_df = pd.DataFrame([all_answers]) | |
#st.write(all_answers) | |
# Display the collected answers | |
#st.write("Collected Answers:", answers_df) | |
def visualize_data1(all_answers): | |
# Extracting data for visualization | |
target_waste_reduction = all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0) | |
zero_waste_to_landfill = all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0) | |
# Creating two columns in Streamlit | |
col1, col2 = st.columns(2) | |
# Visualizing "92. What is your target percentage for waste reduction in the next year?" | |
with col1: | |
st.header("Target Percentage for Waste Reduction") | |
st.write(f"**Target Percentage:** {target_waste_reduction}%") | |
st.write("This target represents the company's goal for reducing waste over the next year.") | |
fig_target = plt.figure(figsize=(6, 4)) | |
bar1 = plt.bar("Target Reduction", target_waste_reduction, color='skyblue') | |
plt.xlabel('Target') | |
plt.ylabel('Percentage') | |
plt.title('Target Percentage for Waste Reduction') | |
plt.legend([bar1], ['Waste Reduction Target']) | |
# Add data label | |
plt.text(bar1[0].get_x() + bar1[0].get_width()/2., bar1[0].get_height(), f'{target_waste_reduction}%', ha='center', va='bottom') | |
st.pyplot(fig_target) | |
# Visualizing "98. What percentage of your logistics operations are zero-waste to landfill?" | |
with col2: | |
st.header("Percentage of Zero-Waste to Landfill") | |
st.write(f"**Zero-Waste Percentage:** {zero_waste_to_landfill}%") | |
st.write("This indicates the proportion of the company's logistics operations that successfully avoid sending waste to landfills.") | |
fig_zero_waste = plt.figure(figsize=(6, 4)) | |
bar2 = plt.bar("Zero-Waste to Landfill", zero_waste_to_landfill, color='lightgreen') | |
plt.xlabel('Zero-Waste') | |
plt.ylabel('Percentage') | |
plt.title('Percentage of Zero-Waste to Landfill') | |
plt.legend([bar2], ['Zero-Waste to Landfill']) | |
# Add data label | |
plt.text(bar2[0].get_x() + bar2[0].get_width()/2., bar2[0].get_height(), f'{zero_waste_to_landfill}%', ha='center', va='bottom') | |
st.pyplot(fig_zero_waste) | |
def Waste_Management_Practices(all_answers): | |
# Visualize Count of 'Yes' and 'No' Responses | |
st.subheader("Waste Management Practices") | |
st.write("**Yes/No Responses Overview:**") | |
st.write("This chart shows the count of 'Yes' and 'No' responses to questions about waste management practices. A higher count of 'Yes' responses indicates proactive engagement in sustainable waste management.") | |
# Counting 'Yes' and 'No' responses | |
yes_count = sum(1 for response in all_answers.values() if response == 'Yes') | |
no_count = len(all_answers) - yes_count | |
# Creating a horizontal bar chart | |
fig = plt.figure(figsize=(8, 6)) | |
plt.barh(['Yes', 'No'], [yes_count, no_count], color=['green', 'red']) | |
plt.xlabel('Count') | |
plt.title('Count of "Yes" and "No" Responses for Waste Management Practices') | |
# Adding data labels to the bars | |
for index, value in enumerate([yes_count, no_count]): | |
plt.text(value, index, f'{value}', ha='right', va='center') | |
st.pyplot(fig) | |
def calculate_waste_score(all_answers): | |
score = 0 | |
max_possible_score = 0 | |
# Scoring for Yes/No questions (5 points for each 'Yes') | |
yes_no_questions = [ | |
"80. Do you have a waste management plan in place for your logistics operations?", | |
"81. Do you actively implement waste reduction and recycling initiatives?", | |
"82. Is waste segregated according to type (hazardous, non-hazardous, recyclable) at your facilities?", | |
"83. Are there measures to minimize waste generation in cargo handling or packaging processes?", | |
"84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", | |
"85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", | |
"86. Are waste reduction and recycling efforts communicated to logistics employees?", | |
"88. Have you conducted waste audits or assessments to evaluate waste management practices?", | |
"89. Are there plans to improve waste management and recycling efforts in the future?", | |
"90. Do you use software or systems for waste tracking and reporting?", | |
"91. Have you set quantifiable goals for waste reduction in the next year?", | |
"93. Do you have partnerships with recycling or waste management companies?", | |
"94. Do you provide training on waste management for new employees?", | |
"95. Have you implemented a policy to reduce single-use items within logistics operations?", | |
"96. Do you conduct regular waste management compliance checks?", | |
"97. Do you participate in or support community waste management programs?", | |
"99. Have you received any certifications or awards for your waste management practices?", | |
"100. Is there a designated team or department responsible for waste management?" | |
] | |
for question in yes_no_questions: | |
response = all_answers.get(question, "No").lower() | |
if response == 'yes': | |
score += 5 | |
max_possible_score += 5 | |
# Scoring for quantitative questions | |
recycling_percentage = all_answers.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0) | |
waste_reduction_target = all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0) | |
zero_waste_to_landfill = all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0) | |
# Adding up to 10 points for each of the percentage-based questions based on their value | |
score += min(10, int(recycling_percentage / 10)) | |
score += min(10, int(waste_reduction_target / 10)) | |
score += min(10, int(zero_waste_to_landfill / 10)) | |
max_possible_score += 30 | |
# Ensure score is within 0-100 range and calculate the percentage score | |
score = max(0, min(score, max_possible_score)) | |
percentage_score = (score / max_possible_score) * 100 | |
return percentage_score | |
# Calculate sustainability score | |
score = calculate_waste_score(all_answers) | |
# Display formatted score | |
#st.write(f"**Waste Sustainability Score:**") | |
#st.write(f"**{score:.1f}%**") | |
def visualize_waste_score(all_answers): | |
# Calculate the waste score | |
waste_score = calculate_waste_score(all_answers) | |
# Scoring components for visualization | |
# Scoring components for visualization | |
components = { | |
'Waste Management Plan': 5 if all_answers.get("80. Do you have a waste management plan in place for your logistics operations?", "No") == "Yes" else 0, | |
'Recycling Initiatives': 5 if all_answers.get("81. Do you actively implement waste reduction and recycling initiatives?", "No") == "Yes" else 0, | |
'Waste Segregation': 5 if all_answers.get("82. Is waste segregated according to type (hazardous, non-hazardous, recyclable) at your facilities?", "No") == "Yes" else 0, | |
'Minimize Waste Generation': 5 if all_answers.get("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", "No") == "Yes" else 0, | |
'Reuse/Repurpose Initiatives': 5 if all_answers.get("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", "No") == "Yes" else 0, | |
'Proper Disposal of Hazardous Materials': 5 if all_answers.get("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", "No") == "Yes" else 0, | |
'Employee Communication on Waste': 5 if all_answers.get("86. Are waste reduction and recycling efforts communicated to logistics employees?", "No") == "Yes" else 0, | |
'Waste Audits': 5 if all_answers.get("88. Have you conducted waste audits or assessments to evaluate waste management practices?", "No") == "Yes" else 0, | |
'Future Improvement Plans': 5 if all_answers.get("89. Are there plans to improve waste management and recycling efforts in the future?", "No") == "Yes" else 0, | |
'Waste Tracking Software': 5 if all_answers.get("90. Do you use software or systems for waste tracking and reporting?", "No") == "Yes" else 0, | |
'Waste Reduction Goals': 5 if all_answers.get("91. Have you set quantifiable goals for waste reduction in the next year?", "No") == "Yes" else 0, | |
'Recycling Partnerships': 5 if all_answers.get("93. Do you have partnerships with recycling or waste management companies?", "No") == "Yes" else 0, | |
'Employee Training on Waste': 5 if all_answers.get("94. Do you provide training on waste management for new employees?", "No") == "Yes" else 0, | |
'Single-Use Item Reduction': 5 if all_answers.get("95. Have you implemented a policy to reduce single-use items within logistics operations?", "No") == "Yes" else 0, | |
'Compliance Checks': 5 if all_answers.get("96. Do you conduct regular waste management compliance checks?", "No") == "Yes" else 0, | |
'Community Program Participation': 5 if all_answers.get("97. Do you participate in or support community waste management programs?", "No") == "Yes" else 0, | |
'Waste Management Awards': 5 if all_answers.get("99. Have you received any certifications or awards for your waste management practices?", "No") == "Yes" else 0, | |
'Dedicated Waste Team': 5 if all_answers.get("100. Is there a designated team or department responsible for waste management?", "No") == "Yes" else 0, | |
'Recycling Percentage': min(10, int(all_answers.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0) / 10)), | |
'Zero Waste to Landfill': min(10, int(all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0) / 10)), | |
'Waste Reduction Target': min(10, int(all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0) / 10)) | |
} | |
component_names = list(components.keys()) | |
component_scores = list(components.values()) | |
# Split the scores into positive and negative scores for the stacked bar chart | |
positive_scores = [score if score > 0 else 0 for score in component_scores] | |
negative_scores = [score if score < 0 else 0 for score in component_scores] | |
# Create a stacked bar chart | |
fig, ax = plt.subplots(figsize=(10, 8)) | |
ax.barh(component_names, positive_scores, color='skyblue', label='Positive Scores') | |
ax.barh(component_names, negative_scores, color='salmon', label='Negative Scores') | |
# Add waste score as text to the right of the bar | |
for i, (pos_score, neg_score) in enumerate(zip(positive_scores, negative_scores)): | |
total_score = pos_score + neg_score | |
ax.text(max(total_score, 0) + 0.2, i, | |
f'{total_score:.1f}', | |
va='center', fontsize=10, fontweight='bold', color='grey') | |
# Set labels and title | |
ax.set_xlabel('Scores') | |
ax.set_title(f'Waste Management Score: {waste_score:.1f}%') | |
ax.legend() | |
# Adjust layout | |
plt.tight_layout() | |
return fig | |
# Assuming all_answers is a dictionary with the answers | |
# Call the function with the answers dictionary | |
#fig = visualize_waste_score(all_answers) | |
#st.pyplot(fig) | |
explanation_W_metric = """ | |
The Waste Management Score is calculated based on various factors that reflect sustainable waste management practices in logistics operations. Here's a breakdown of how the score is composed: | |
- **Waste Management Plan:** Whether there is a waste management plan in place for logistics operations. Having a plan contributes positively to the score. | |
- **Recycling Initiatives:** Actively implementing waste reduction and recycling initiatives adds points to the score. | |
- **Waste Segregation:** Segregation of waste according to type (hazardous, non-hazardous, recyclable) at facilities contributes positively to the score. | |
- **Minimize Waste Generation:** Measures to minimize waste generation in cargo handling or packaging processes are scored positively. | |
- **Reuse/Repurpose Initiatives:** Initiatives for reusing or repurposing materials and equipment to reduce waste contribute to a higher score. | |
- **Proper Disposal of Hazardous Materials:** Ensuring proper disposal of hazardous materials and chemicals used in logistics operations adds points to the score. | |
- **Employee Communication on Waste:** Communicating waste reduction and recycling efforts to logistics employees positively affects the score. | |
- **Waste Audits:** Conducting waste audits or assessments to evaluate waste management practices contributes positively to the score. | |
- **Future Improvement Plans:** Having plans to improve waste management and recycling efforts in the future adds to the score. | |
- **Waste Tracking Software:** Using software or systems for waste tracking and reporting contributes positively to the score. | |
- **Waste Reduction Goals:** Setting quantifiable goals for waste reduction in the next year adds points to the score. | |
- **Recycling Partnerships:** Having partnerships with recycling or waste management companies contributes positively to the score. | |
- **Employee Training on Waste:** Providing training on waste management for new employees adds points to the score. | |
- **Single-Use Item Reduction:** Implementing a policy to reduce single-use items within logistics operations contributes to a higher score. | |
- **Compliance Checks:** Conducting regular waste management compliance checks adds points to the score. | |
- **Community Program Participation:** Participating in or supporting community waste management programs contributes positively to the score. | |
- **Waste Management Awards:** Receiving certifications or awards for waste management practices adds points to the score. | |
- **Dedicated Waste Team:** Having a designated team or department responsible for waste management contributes positively to the score. | |
- **Recycling Percentage:** The percentage of waste recycled or diverted from landfills impacts the score positively. | |
- **Zero Waste to Landfill:** The percentage of logistics operations being zero-waste to landfill contributes positively to the score. | |
- **Waste Reduction Target:** Setting a target percentage for waste reduction in the next year adds points to the score. | |
A higher Waste Management Score indicates a stronger commitment to sustainable waste management practices and efficient waste reduction strategies in logistics operations. | |
""" | |
#st.markdown(explanation_W_metric) | |
def evaluate_waste_sustainability_practice(score, df): | |
# Counting 'Yes' responses for waste-related Yes/No questions | |
waste_yes_no_questions = [ | |
question[0] for question in sections["Waste Management"] if question[1] == 'radio' | |
] | |
yes_count = sum( | |
df[question].eq('Yes').sum() for question in waste_yes_no_questions if question in df.columns | |
) | |
yes_percentage = (yes_count / len(waste_yes_no_questions)) * 100 if waste_yes_no_questions else 0 | |
# Calculate a combined waste sustainability index | |
combined_index = (0.6 * score) + (0.4 * yes_percentage) | |
# Grading system with detailed advice for waste sustainability | |
if combined_index >= 80: | |
grade = "A (Eco-Champion π)" | |
st.image("Eco-Champion.png") | |
explanation = "You demonstrate exemplary waste management practices, setting a high benchmark in sustainability." | |
advice = "Continue leading and innovating in waste management, and share your successful practices with others." | |
elif combined_index >= 60: | |
grade = "B (Sustainability Steward π)" | |
st.image("Sustainability_Steward.png", use_column_width=True) | |
explanation = "Your efforts in waste management reflect a strong commitment to sustainability." | |
advice = "Keep improving your waste reduction strategies and explore new technologies for recycling and waste-to-energy conversion." | |
elif combined_index >= 40: | |
grade = "C (Eco-Advancer πΏ)" | |
st.image("Eco-Advancer.png") | |
explanation = "You're actively working towards better waste management but have room to grow." | |
advice = "Enhance your waste reduction and recycling programs, and consider community engagement for broader impact." | |
elif combined_index >= 20: | |
grade = "D (Green Learner πΌ)" | |
st.image("Green_Learner.png") | |
explanation = "You've started to engage in sustainable waste management practices, but there's much to develop." | |
advice = "Focus on establishing a solid waste management plan and educate your team about its importance and implementation." | |
else: | |
grade = "E (Eco-Novice π±)" | |
st.image("Eco-Novice.png", use_column_width=True) | |
explanation = "You are at the early stages of adopting sustainable waste management practices." | |
advice = "Begin with basic steps like segregation of waste, regular audits, and simple recycling initiatives to build a foundation for sustainable practices." | |
return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{explanation} \n\n**Detailed Advice:** \n{advice}" | |
#st.markdown(evaluate_waste_sustainability_practice(score, answers_df), unsafe_allow_html=True) | |
def generate_swot_analysis(company_data): | |
# Extracting relevant data from company_data | |
logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None") | |
annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0) | |
utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False) | |
selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", []) | |
company_summary = company_data.get("Company Summary", "No specific information provided.") | |
# Constructing a dynamic SWOT analysis based on extracted data | |
strengths = [ | |
"Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None" | |
] | |
weaknesses = [ | |
"Lack of Logistics Sustainability Level: " + logistics_sustainability_level, | |
"Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present", | |
"Company Summary: " + company_summary | |
] | |
opportunities = [ | |
"Exploration of Logistics Certifications" if not selected_certifications else "None" | |
] | |
threats = [ | |
"Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None" | |
] | |
# Constructing a SWOT analysis prompt dynamically | |
swot_analysis_prompt = f""" | |
Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis: | |
Strengths: | |
Strengths Analysis: | |
{", ".join(strengths)} | |
Weaknesses: | |
Weaknesses Analysis: | |
{", ".join(weaknesses)} | |
Opportunities: | |
Opportunities Analysis: | |
{", ".join(opportunities)} | |
Threats: | |
Threats Analysis: | |
{", ".join(threats)} | |
""" | |
# OpenAI API call for SWOT analysis | |
response_swot = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=[ | |
{"role": "assistant", "content": "You are analyzing the company's sustainability practices."}, | |
{"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."}, | |
{"role": "user", "content": swot_analysis_prompt} | |
], | |
max_tokens=1000, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = response_swot.choices[0].message['content'] | |
return swot_analysis_content | |
def evaluate_waste_sustainability_report(all_answers, score): | |
"""Generates a Waste Sustainability report based on responses to a questionnaire.""" | |
extracted_data = extract_data(all_answers) | |
# Consolidate data for waste sustainability | |
waste_management_plan = extracted_data.get("80. Do you have a waste management plan in place for your logistics operations?", "N/A") | |
waste_reduction_initiatives = extracted_data.get("81. Do you actively implement waste reduction and recycling initiatives?", "N/A") | |
waste_segregation = extracted_data.get("82. Is waste segregated according to type at your facilities?", "N/A") | |
waste_minimization_measures = extracted_data.get("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", "N/A") | |
waste_reuse_repurpose = extracted_data.get("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", "N/A") | |
proper_disposal_hazardous = extracted_data.get("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", "N/A") | |
waste_communication_employees = extracted_data.get("86. Are waste reduction and recycling efforts communicated to logistics employees?", "N/A") | |
waste_recycling_percentage = extracted_data.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0) | |
waste_audits_assessments = extracted_data.get("88. Have you conducted waste audits or assessments to evaluate waste management practices?", "N/A") | |
future_improvement_plans = extracted_data.get("89. Are there plans to improve waste management and recycling efforts in the future?", "N/A") | |
waste_tracking_software = extracted_data.get("90. Do you use software or systems for waste tracking and reporting?", "N/A") | |
quantifiable_goals_waste_reduction = extracted_data.get("91. Have you set quantifiable goals for waste reduction in the next year?", "N/A") | |
target_percentage_waste_reduction = extracted_data.get("92. What is your target percentage for waste reduction in the next year?", 0) | |
recycling_partnerships = extracted_data.get("93. Do you have partnerships with recycling or waste management companies?", "N/A") | |
waste_management_training_employees = extracted_data.get("94. Do you provide training on waste management for new employees?", "N/A") | |
policy_reduce_single_use_items = extracted_data.get("95. Have you implemented a policy to reduce single-use items within logistics operations?", "N/A") | |
compliance_checks = extracted_data.get("96. Do you conduct regular waste management compliance checks?", "N/A") | |
community_programs_participation = extracted_data.get("97. Do you participate in or support community waste management programs?", "N/A") | |
zero_waste_to_landfill = extracted_data.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0) | |
waste_management_certifications_awards = extracted_data.get("99. Have you received any certifications or awards for your waste management practices?", "N/A") | |
designated_waste_team = extracted_data.get("100. Is there a designated team or department responsible for waste management?", "N/A") | |
consolidated_report = f""" | |
Waste Sustainability Report | |
Score: {score}/100 | |
Report Details: | |
Waste Management Plan: {waste_management_plan} | |
Recycling Initiatives: {waste_reduction_initiatives} | |
Waste Segregation: {waste_segregation} | |
Minimize Waste Generation: {waste_minimization_measures} | |
Reuse/Repurpose Initiatives: {waste_reuse_repurpose} | |
Proper Disposal of Hazardous Materials: {proper_disposal_hazardous} | |
Employee Communication on Waste: {waste_communication_employees} | |
Recycling Percentage: {waste_recycling_percentage}% | |
Waste Audits/Assessments: {waste_audits_assessments} | |
Future Improvement Plans: {future_improvement_plans} | |
Waste Tracking Software: {waste_tracking_software} | |
Quantifiable Goals for Waste Reduction: {quantifiable_goals_waste_reduction} | |
Target Percentage for Waste Reduction: {target_percentage_waste_reduction}% | |
Recycling Partnerships: {recycling_partnerships} | |
Waste Management Training for Employees: {waste_management_training_employees} | |
Policy to Reduce Single-Use Items: {policy_reduce_single_use_items} | |
Compliance Checks: {compliance_checks} | |
Community Programs Participation: {community_programs_participation} | |
Zero Waste to Landfill: {zero_waste_to_landfill}% | |
Waste Management Certifications/Awards: {waste_management_certifications_awards} | |
Designated Waste Team: {designated_waste_team} | |
""" | |
# Include further analysis via OpenAI API | |
prompt = f""" | |
As a waste sustainability advisor, analyze the Waste Sustainability Report with a score of {score}/100. Review the provided data points and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement in waste management practices. Provide specific recommendations to enhance waste sustainability considering the current waste management initiatives and recycling strategies. | |
Data Points: | |
{consolidated_report} | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=[ | |
{"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=4000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0, | |
presence_penalty=0 | |
) | |
evaluation_content = response.choices[0].message['content'] | |
refined_report = f"{consolidated_report}\n\n{evaluation_content}" | |
return refined_report | |
except Exception as e: | |
return f"Error: {e}" | |
# Function to format answer for better readability | |
def format_answer(answer): | |
if isinstance(answer, bool): | |
return "Yes" if answer else "No" | |
elif isinstance(answer, (int, float)): | |
return str(answer) | |
return answer # Assume the answer is already in a string format | |
# Function to extract and format data from a dictionary | |
def extract_data(data): | |
formatted_data = {} | |
for key, value in data.items(): | |
formatted_data[key] = format_answer(value) | |
return formatted_data | |
#report = evaluate_waste_sustainability_report(all_answers, score) | |
#st.write(report) | |
def get_waste_sustainability_strategy(all_answers, company_data): | |
# Extracting and formatting data from all_answers and company_data | |
extracted_all_answers = extract_data(all_answers) | |
extracted_company_data = extract_data(company_data) | |
# Forming the prompt with extracted data | |
prompt = f""" | |
Based on the provided company and waste sustainability assessment data, provide a waste sustainability strategy: | |
**Company Info**: | |
- Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')} | |
- Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons | |
- Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')} | |
- Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')} | |
- Company Summary: {extracted_company_data.get('Company Summary', 'N/A')} | |
**Waste Sustainability Assessment Data**: | |
- Waste Management Plan: {extracted_all_answers.get("80. Do you have a waste management plan in place for your logistics operations?", "N/A")} | |
- Recycling Initiatives: {extracted_all_answers.get("81. Do you actively implement waste reduction and recycling initiatives?", "N/A")} | |
- Waste Segregation: {extracted_all_answers.get("82. Is waste segregated according to type at your facilities?", "N/A")} | |
- Minimize Waste Generation: {extracted_all_answers.get("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", "N/A")} | |
- Reuse/Repurpose Initiatives: {extracted_all_answers.get("84. Do you have initiatives for reusing or repurposing materials and equipment to reduce waste?", "N/A")} | |
- Proper Disposal of Hazardous Materials: {extracted_all_answers.get("85. Do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", "N/A")} | |
- Employee Communication on Waste: {extracted_all_answers.get("86. Are waste reduction and recycling efforts communicated to logistics employees?", "N/A")} | |
- Recycling Percentage: {extracted_all_answers.get("87. What percentage of waste is recycled or diverted from landfills in your logistics operations?", 0)}% | |
- Waste Audits/Assessments: {extracted_all_answers.get("88. Have you conducted waste audits or assessments to evaluate waste management practices?", "N/A")} | |
- Future Improvement Plans: {extracted_all_answers.get("89. Are there plans to improve waste management and recycling efforts in the future?", "N/A")} | |
- Waste Tracking Software: {extracted_all_answers.get("90. Do you use software or systems for waste tracking and reporting?", "N/A")} | |
- Quantifiable Goals for Waste Reduction: {extracted_all_answers.get("91. Have you set quantifiable goals for waste reduction in the next year?", "N/A")} | |
- Target Percentage for Waste Reduction: {extracted_all_answers.get("92. What is your target percentage for waste reduction in the next year?", 0)}% | |
- Recycling Partnerships: {extracted_all_answers.get("93. Do you have partnerships with recycling or waste management companies?", "N/A")} | |
- Waste Management Training for Employees: {extracted_all_answers.get("94. Do you provide training on waste management for new employees?", "N/A")} | |
- Policy to Reduce Single-Use Items: {extracted_all_answers.get("95. Have you implemented a policy to reduce single-use items within logistics operations?", "N/A")} | |
- Compliance Checks: {extracted_all_answers.get("96. Do you conduct regular waste management compliance checks?", "N/A")} | |
- Community Programs Participation: {extracted_all_answers.get("97. Do you participate in or support community waste management programs?", "N/A")} | |
- Zero Waste to Landfill: {extracted_all_answers.get("98. What percentage of your logistics operations are zero-waste to landfill?", 0)}% | |
- Waste Management Certifications/Awards: {extracted_all_answers.get("99. Have you received any certifications or awards for your waste management practices?", "N/A")} | |
- Designated Waste Team: {extracted_all_answers.get("100. Is there a designated team or department responsible for waste management?", "N/A")} | |
Offer an actionable strategy considering the company's specific context and waste sustainability data. | |
""" | |
additional_context = f"Provide a detailed waste sustainability strategy using context data from the above company info and in responses to the waste sustainability assessment." | |
# Assuming you have an API call here to generate a response based on the prompt | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=[ | |
{"role": "assistant", "content": "You are a waste sustainability strategy advisor."}, | |
{"role": "user", "content": prompt}, | |
{"role": "user", "content": additional_context} | |
], | |
max_tokens=4000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
return response.choices[0].message['content'] | |
#strategy = get_waste_sustainability_strategy(all_answers, company_data) | |
#st.write(strategy) | |
def get_certification_details(certification_name): | |
# Prepare the prompt for the API call | |
messages = [ | |
{"role": "system", "content": "You are a knowledgeable assistant about global certifications."}, | |
{"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."} | |
] | |
# Query the OpenAI API for information on the certification process | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=messages, | |
max_tokens=2000, | |
temperature=0.3, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Return the content of the response | |
return response.choices[0].message['content'] | |
def advise_on_waste_sustainability_certification(company_data): | |
# Check if company_data is a dictionary | |
if not isinstance(company_data, dict): | |
raise ValueError("company_data must be a dictionary") | |
# Extract company data relevant to waste sustainability certifications | |
has_waste_management_plan = company_data.get('Do you have a waste management plan?', False) | |
waste_reduction_initiatives = company_data.get('Implement waste reduction initiatives?', False) | |
segregate_waste = company_data.get('Segregate waste at facilities?', False) | |
recycling_percentage = company_data.get('Recycling percentage', 0) | |
partnerships_recycling_companies = company_data.get('Partnerships with recycling companies?', False) | |
waste_management_certifications = company_data.get('Waste management certifications', []) | |
# Initialize a string to store recommendations | |
recommendations_text = "" | |
# Determine which waste sustainability certifications to suggest based on the provided data | |
waste_certifications_to_consider = { | |
"Zero Waste Certification": not has_waste_management_plan, | |
"Recycling Initiative Certification": not waste_reduction_initiatives, | |
"Waste Segregation Certification": not segregate_waste, | |
"Recycling Percentage Improvement Certification": recycling_percentage < 30, | |
"Partnership with Recycling Companies Certification": not partnerships_recycling_companies, | |
"Advanced Waste Management Certification": "Advanced Waste Management" not in waste_management_certifications | |
} | |
for certification, consider in waste_certifications_to_consider.items(): | |
if consider: | |
try: | |
certification_details = get_certification_details(certification) | |
recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}" | |
except Exception as e: | |
recommendations_text += f"\n\nError retrieving details for {certification}: {e}" | |
# If no waste sustainability certifications are suggested, add a message | |
if not recommendations_text.strip(): | |
recommendations_text = "Based on the provided data, there are no specific waste sustainability certifications recommended at this time." | |
# Return the combined recommendations as a single formatted string | |
return recommendations_text | |
#reply = advise_on_waste_sustainability_certification(company_data) | |
#st.write(reply) | |
st.markdown("<br>"*1, unsafe_allow_html=True) | |
if st.button('Submit'): | |
try: | |
# Use a spinner for generating advice | |
with st.spinner("Generating report and advice..."): | |
st.subheader("Visualize Waste Data") | |
Waste_Management_Practices(all_answers) | |
visualize_data1(all_answers) # Call the function with the dictionary containing the answers | |
st.subheader("Visualize Waste Scores") | |
# Calculate sustainability score | |
score = calculate_waste_score(all_answers) | |
# Display formatted score | |
st.write(f"**Waste Sustainability Score:**") | |
st.markdown(f"**{score:.1f}%**") | |
fig = visualize_waste_score(all_answers) | |
st.pyplot(fig) | |
st.markdown(explanation_W_metric) | |
st.subheader("Visualize Sustainability Grade") | |
# Call the function with the DataFrame | |
st.markdown(evaluate_waste_sustainability_practice(score, answers_df), unsafe_allow_html=True) | |
strategy = get_waste_sustainability_strategy(all_answers, company_data) | |
#strategy = get_energy_sustainability_advice(strategy, company_data) | |
report = evaluate_waste_sustainability_report(all_answers, score) | |
#st.subheader("Energy Sustainability Strategy") | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = generate_swot_analysis(company_data) | |
#st.subheader("Energy Sustainability Strategy") | |
st.subheader("Company SWOT Report") | |
st.write(swot_analysis_content) | |
st.subheader("Waste Sustainability Report") | |
st.write(report) | |
st.download_button( | |
label="Download Waste Sustainability Report", | |
data=report, | |
file_name='sustainability_report.txt', | |
mime='text/txt', | |
key="download_report_button", # Unique key for this button | |
) | |
st.subheader("Sustainability Strategy") | |
st.write(strategy) | |
st.download_button( | |
label="Download Waste Sustainability Strategy", | |
data=strategy, | |
file_name='sustainability_strategy.txt', | |
mime='text/txt', | |
key="download_strategy_button", # Unique key for this button | |
) | |
st.subheader("Advice on Sustainability Certification") | |
#certification_advice = advise_on_transport_sustainability_certification(company_data) | |
try: | |
advice = advise_on_waste_sustainability_certification(company_data) | |
st.write(advice) | |
except ValueError as e: | |
print(e) | |
# Embed a YouTube video after processing | |
st.subheader("Watch More on Sustainability") | |
video_urls = [ | |
"https://www.youtube.com/watch?v=BawgdP1jmPo", | |
#"https://www.youtube.com/watch?v=your_video_url_2", | |
#"https://www.youtube.com/watch?v=your_video_url_3", | |
# Add more video URLs as needed | |
] | |
# Select a random video URL from the list | |
random_video_url = random.choice(video_urls) | |
# Display the random video | |
st.video(random_video_url) | |
except Exception as e: | |
st.error(f"An error occurred: {e}") | |
st.write(""" | |
--- | |
*Powered by Streamlit, CarbonInterface API, and OpenAI.* | |
""") | |
def page4(): | |
# Function to encode the image to base64 | |
def encode_image(image): | |
buffered = io.BytesIO() | |
image.save(buffered, format="JPEG") | |
return base64.b64encode(buffered.getvalue()).decode('utf-8') | |
# Function to provide sustainability advice based on trash information | |
def sustainability_advice_with_elements(key_elements): | |
try: | |
messages = [ | |
{"role": "system", "content": "You are a knowledgeable assistant on waste management and sustainability."}, | |
{"role": "user", "content": f"Please generate sustainable methods to dispose of the identified waste elements.\n\nKey Waste Elements:\n{key_elements}"} | |
] | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
max_tokens=1000, | |
temperature=0 | |
) | |
advice = response.choices[0].message['content'] | |
return advice | |
except Exception as e: | |
return f"Error: {e}" | |
def extract_key_elements_with_openai(trash_info): | |
messages=[ | |
{"role": "system", "content": "Identify waste elements from the given information."}, | |
{"role": "user", "content": trash_info} | |
], | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "Identify waste elements from the given information."}, | |
{"role": "user", "content": trash_info} | |
], | |
max_tokens=300, | |
temperature=0.3, | |
top_p=1.0, | |
frequency_penalty=0.0, | |
presence_penalty=0.0, | |
stop=["."] | |
) | |
elements = response.choices[0].message['content'] | |
return elements | |
except Exception as e: | |
return f"Error: {e}" | |
def sustainability_advice(trash_info): | |
# Prepare the prompt for the API call | |
messages = [ | |
{"role": "system", "content": "You are an environmental sustainability advisor."}, | |
{"role": "user", "content": f"Provide sustainable methods to dispose of this trash. Description: {trash_info}"} | |
] | |
# Query the OpenAI API for advice on sustainable trash disposal methods | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
max_tokens=1500, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.0, | |
presence_penalty=0.0 | |
) | |
# Get the advice on sustainable trash disposal methods | |
advice = response.choices[0].message['content'] | |
# Streamlit app | |
st.write("<center><h1>Trash Ninja: Waste Classification Assistant</h1></center>", unsafe_allow_html=True) | |
#st.title('Trash Ninja: Waste Classification Assistant') | |
st.image("banner1.png", use_column_width=True) | |
# Provide instructions for image upload | |
# Providing instructions for image upload | |
st.markdown(""" | |
**Step 1: Capture a Clear Image** | |
- Center the trash item in your photo. | |
- Use a plain, contrasting background. | |
- Ensure good lighting to make the item clearly visible. | |
**Step 2: Upload Your Image** | |
- Click 'Browse' to select your image file (JPG, JPEG, or PNG format). | |
**Step 3: Analyze and Get Insights** | |
- Once the image is uploaded, click 'Analyze Image' to receive your classification and sustainable disposal advice. | |
**Note:** For best results, avoid including multiple items or excessive background clutter in your image. | |
""") | |
# Instructions and other static content can go here | |
# User uploads an image of trash | |
uploaded_file = st.file_uploader("Upload an image of the trash item you want to classify", type=["jpg", "jpeg", "png"]) | |
# Button to analyze the image and provide sustainability advice | |
if st.button(label='Analyze Image'): | |
if uploaded_file is not None: | |
# Display the uploaded image | |
image = Image.open(uploaded_file) | |
st.image(image, caption='Uploaded Trash Image', use_column_width=True) | |
# Placeholder for analysis function call | |
st.success("Image analysis successful! (Placeholder for actual analysis results)") | |
# Encode the image for GPT-4 Vision API | |
encoded_image = encode_image(image) | |
# Call to GPT-4 Vision API (replace with your actual API call) | |
with st.spinner('Analyzing the image...'): | |
result = openai.ChatCompletion.create( | |
model="gpt-4-vision-preview", | |
messages=[ | |
{ | |
"role": "user", | |
"content": [ | |
{"type": "text", "text": "Analyze this picture of trash and identify the type."}, | |
{"type": "image_url", "image_url": f"data:image/jpeg;base64,{encoded_image}"}, | |
] | |
}, | |
], | |
max_tokens=900 | |
) | |
# Check if a response was received | |
if result.choices: | |
trash_info = result.choices[0].message.content | |
st.write("Analysis Result:") | |
st.info(trash_info) | |
# Provide sustainability advice based on the analysis | |
with st.spinner('Generating sustainability advice...'): | |
# Extract key elements using OpenAI GPT-3 model | |
extracted_elements = extract_key_elements_with_openai(trash_info) | |
# Generate sustainability advice based on extracted key elements | |
advice_based_on_elements = sustainability_advice_with_elements(extracted_elements) | |
st.write("Sustainability Advice:") | |
st.info(advice_based_on_elements) | |
else: | |
st.error("No response was received. Please try again with a different image.") | |
else: | |
st.error("Please upload an image to proceed.") | |
# Provide educational content after the analysis | |
st.markdown(""" | |
**Why Recycle?** | |
- **Environmental Protection:** Recycling reduces the need for extracting, refining, and processing raw materials, which create substantial air and water pollution. Recycling saves energy and reduces greenhouse gas emissions, helping to tackle climate change. | |
- **Conservation:** Recycling conserves natural resources such as timber, water, and minerals, ensuring they last longer for future generations. | |
- **Energy Efficiency:** Manufacturing with recycled materials uses less energy than creating products from virgin materials. | |
- **Economic Benefits:** Recycling creates jobs in the collection, processing, and selling of recyclable materials. | |
""") | |
def page5(): | |
st.write("<center><h1>Emission Excellence: Paving the Way to Sustainability</h1></center>", unsafe_allow_html=True) | |
st.image("page5.1.png", use_column_width=True) | |
st.write("Assess and improve the sustainability of your logistics operations.") | |
st.header("Company Information") | |
input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide company description manually"]) | |
# Function to extract logistics information from a website URL | |
def extract_logistics_info_from_website(url): | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an exception for HTTP errors (e.g., 404) | |
# Parse the HTML content of the page | |
soup = BeautifulSoup(response.text, 'html.parser') | |
# Example: Extract company description from the website | |
company_description = soup.find('meta', attrs={'name': 'description'}) | |
if company_description: | |
return company_description['content'] | |
except requests.exceptions.RequestException as e: | |
return f"Error: Unable to connect to the website ({e})" | |
except Exception as e: | |
return f"Error: {e}" | |
return None | |
# Function to summarize logistics information using OpenAI's GPT-3 model | |
def summarize_logistics_info(logistics_info): | |
prompt = f""" | |
Please extract the following information from the logistics company's description: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
Description: | |
{logistics_info} | |
Please provide responses while avoiding speculative or unfounded information. | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "system", "content": "You are an excellent sustainability assessment tool for logistics."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=100, | |
temperature=0 | |
) | |
company_summary = response.choices[0].message['content'] | |
return company_summary | |
except Exception as e: | |
return f"Error: {e}" | |
# Streamlit UI | |
st.title("Logistics Information Extractor") | |
st.write("Extract logistics information from a logistics company's website URL.") | |
# User input field for the website URL | |
#website_url = st.text_input("Enter the logistics company's website URL:") | |
if input_option == "Enter logistics company's website URL": | |
example_url = "https://quangninhport.com.vn/en/home" | |
website_url = st.text_input("Please enter the logistics company's website URL:", example_url) | |
if website_url: | |
# Ensure the URL starts with http/https | |
website_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + website_url | |
logistics_info = extract_logistics_info_from_website(website_url) | |
if logistics_info: | |
company_summary = summarize_logistics_info(logistics_info) | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
elif input_option == "Provide company description manually": | |
st.markdown(""" | |
Please provide a description of the logistics company, focusing on the following: | |
- Core logistics services offered | |
- Sustainability practices or initiatives related to logistics | |
""") | |
company_description = st.text_area("Please provide the company description:", "") | |
if company_description: | |
company_summary = summarize_logistics_info(company_description) | |
st.header("Logistics Sustainability Information") | |
# Definitions for logistics sustainability levels | |
sustainability_info = { | |
"None": "No sustainability info available", | |
"Green Logistics": "Green logistics refers to environmentally friendly practices in logistics operations, such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.", | |
"Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor practices, and reducing the carbon footprint throughout the supply chain.", | |
"Circular Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing waste in packaging and materials, leading to a more sustainable and resource-efficient approach.", | |
} | |
sustainability_level = st.selectbox("Logistics Sustainability Level", list(sustainability_info.keys())) | |
# Display the definition when the user selects a sustainability level | |
if sustainability_level in sustainability_info: | |
st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}") | |
# Additional sustainability-related information | |
carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", min_value=0) | |
renewable_energy = st.checkbox("Does the company utilize Renewable Energy Sources in its operations?") | |
# Certification and Sustainability Initiatives | |
st.subheader("Certifications and Sustainability Initiatives") | |
# Explanations for logistics-related certifications | |
logistics_certification_info = { | |
"None": "No certifications or initiatives related to logistics.", | |
"ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets requirements for an environmental management system in logistics operations.", | |
"SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that reduce fuel use and emissions through efficient transportation practices.", | |
"C-TPAT Certification": "C-TPAT (Customs-Trade Partnership Against Terrorism) certification ensures secure and sustainable supply chain practices in logistics.", | |
"Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of freight transportation through efficiency improvements.", | |
"Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a commitment to using zero-emission vehicles and reducing emissions in specific areas.", | |
} | |
selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", list(logistics_certification_info.keys())) | |
# Display explanations for selected certifications | |
for certification in selected_certifications: | |
if certification in logistics_certification_info: | |
st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}") | |
# Define the company_data dictionary | |
company_data = { | |
"Logistics Sustainability Level": sustainability_level, | |
"Annual Carbon Emissions (in metric tons)": carbon_emissions, | |
"Utilize Renewable Energy Sources": renewable_energy, | |
"Selected Logistics Certifications and Initiatives": selected_certifications | |
} | |
# If company_summary is generated, add it to company_data dictionary | |
if 'company_summary' in locals() or 'company_summary' in globals(): | |
company_data["Company Summary"] = company_summary | |
#st.write("Company Summary:") | |
#st.write(company_summary) | |
st.write("<hr>", unsafe_allow_html=True) | |
st.write("In this section, we'll explore your company's commitment to emission reduction initiatives. We'll assess your efforts and investments in reducing emissions, as well as any strategies and technologies you employ to achieve this sustainability goal.") | |
st.write("<hr>", unsafe_allow_html=True) | |
sections = { | |
"Emission Reduction Initiatives": [ | |
("65. Do you monitor CO2 emissions in your logistics operations?", 'radio', ["Yes", "No"]), | |
("66. Do you have emissions reduction targets in place for your logistics operations?", 'radio', ["Yes", "No"]), | |
("67. Percentage reduction target for CO2 emissions in the next year:", 'number_input', {"min_value": 0, "max_value": 100}), | |
("68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", 'radio', ["Yes", "No"]), | |
("69. Do you have initiatives to minimize particulate matter emissions?", 'radio', ["Yes", "No"]), | |
("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", 'radio', ["Yes", "No"]), | |
("71. Do you manage emissions from refrigerated cargo containers?", 'radio', ["Yes", "No"]), | |
("72. Do you have strategies to reduce emissions from idling vehicles and equipment?", 'radio', ["Yes", "No"]), | |
("73. Do you employ emission-reducing practices in your facilityβs lighting, heating, and cooling systems?", 'radio', ["Yes", "No"]), | |
("74. Are renewable energy sources used to power your logistics facilities?", 'radio', ["Yes", "No"]), | |
("75. How do you manage emissions from equipment maintenance and repair activities?", 'radio', ["Yes", "No"]), | |
("76. Do you have specific percentage goals for emission reduction in logistics operations?", 'radio', ["Yes", "No"]), | |
("77. Percentage of emission reduction goal achieved last year:", 'number_input', {"min_value": 0, "max_value": 100}), | |
("78. Are emission reduction efforts audited or assessed regularly?", 'radio', ["Yes", "No"]), | |
("79. Are there plans for future emission reduction initiatives in logistics?", 'radio', ["Yes", "No"]), | |
("80. Do you participate in any carbon offset programs?", 'radio', ["Yes", "No"]), | |
("81. Is there a system for tracking and reporting emissions data?", 'radio', ["Yes", "No"]), | |
("82. Do you engage in partnerships or collaborations for emission reduction initiatives?", 'radio', ["Yes", "No"]), | |
("83. Do you provide training or awareness programs on emission reduction for employees?", 'radio', ["Yes", "No"]), | |
("84. Are emission reduction initiatives integrated into your overall business strategy?", 'radio', ["Yes", "No"]) | |
] | |
} | |
# Initialize a dictionary to store the answers | |
all_answers = {} | |
# Create columns outside the loop | |
col1, col2, col3 = st.columns(3) | |
# Iterate through each question and display them in columns | |
for i, (question_text, input_type, *options) in enumerate(sections["Emission Reduction Initiatives"]): | |
# Determine which column to use based on the question index | |
if i % 3 == 0: | |
col = col1 | |
elif i % 3 == 1: | |
col = col2 | |
else: | |
col = col3 | |
with col: | |
if input_type == 'selectbox': | |
all_answers[question_text] = st.selectbox(question_text, options[0]) | |
elif input_type == 'number_input': | |
params = options[0] | |
all_answers[question_text] = st.number_input(question_text, **params) | |
elif input_type == 'radio': | |
all_answers[question_text] = st.radio(question_text, options[0]) | |
elif input_type == 'slider': | |
all_answers[question_text] = st.slider(question_text, 0, 10) | |
# Convert answers to a DataFrame for analysis | |
answers_df = pd.DataFrame([all_answers]) | |
#st.write(all_answers) | |
# Display the collected answers | |
#st.write("Collected Answers:", answers_df) | |
def visualize_emission_reduction_data(all_answers): | |
# Extracting data for visualization | |
next_year_co2_reduction_target = all_answers.get("67. Percentage reduction target for CO2 emissions in the next year:", 0) | |
last_year_emission_reduction_achieved = all_answers.get("77. Percentage of emission reduction goal achieved last year:", 0) | |
# Creating two columns in Streamlit | |
col1, col2 = st.columns(2) | |
# Visualizing "67. Percentage reduction target for CO2 emissions in the next year:" | |
with col1: | |
st.header("CO2 Emission Reduction Target for Next Year") | |
st.write(f"**Target Percentage:** {next_year_co2_reduction_target}%") | |
st.write("This target represents the company's goal for reducing CO2 emissions over the next year.") | |
fig_target_co2 = plt.figure(figsize=(6, 4)) | |
bar1 = plt.bar("CO2 Reduction Target", next_year_co2_reduction_target, color='skyblue') | |
plt.xlabel('Target') | |
plt.ylabel('Percentage') | |
plt.title('CO2 Emission Reduction Target for Next Year') | |
plt.legend([bar1], ['CO2 Reduction Target']) | |
# Add data label | |
plt.text(bar1[0].get_x() + bar1[0].get_width() / 2., bar1[0].get_height(), | |
f'{next_year_co2_reduction_target}%', ha='center', va='bottom') | |
st.pyplot(fig_target_co2) | |
# Visualizing "77. Percentage of emission reduction goal achieved last year:" | |
with col2: | |
st.header("Achieved Emission Reduction Last Year") | |
st.write(f"**Achieved Percentage:** {last_year_emission_reduction_achieved}%") | |
st.write("This indicates the proportion of the company's achieved emission reduction goal from last year.") | |
fig_achieved_last_year = plt.figure(figsize=(6, 4)) | |
bar2 = plt.bar("Achieved Last Year", last_year_emission_reduction_achieved, color='lightgreen') | |
plt.xlabel('Achieved') | |
plt.ylabel('Percentage') | |
plt.title('Achieved Emission Reduction Last Year') | |
plt.legend([bar2], ['Achieved Last Year']) | |
# Add data label | |
plt.text(bar2[0].get_x() + bar2[0].get_width() / 2., bar2[0].get_height(), | |
f'{last_year_emission_reduction_achieved}%', ha='center', va='bottom') | |
st.pyplot(fig_achieved_last_year) | |
def visualize_emission_reduction_responses(all_answers): | |
# Visualize Count of 'Yes' and 'No' Responses for Emission Reduction Initiatives | |
st.header("Emission Reduction Initiatives") | |
st.write("**Yes/No Responses Overview:**") | |
st.write("This chart shows the count of 'Yes' and 'No' responses to questions about emission reduction initiatives. A higher count of 'Yes' responses indicates proactive engagement in emission reduction strategies.") | |
# Emission reduction-related questions | |
emission_reduction_questions = [ | |
"65. Do you monitor CO2 emissions in your logistics operations?", | |
"66. Do you have emissions reduction targets in place for your logistics operations?", | |
"67. Percentage reduction target for CO2 emissions in the next year:", | |
"68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", | |
"69. Do you have initiatives to minimize particulate matter emissions?", | |
"70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", | |
"71. Do you manage emissions from refrigerated cargo containers?", | |
"72. Do you have strategies to reduce emissions from idling vehicles and equipment?", | |
"73. Do you employ emission-reducing practices in your facilityβs lighting, heating, and cooling systems?", | |
"74. Are renewable energy sources used to power your logistics facilities?", | |
"75. How do you manage emissions from equipment maintenance and repair activities?", | |
"76. Do you have specific percentage goals for emission reduction in logistics operations?", | |
"77. Percentage of emission reduction goal achieved last year:", | |
"78. Are emission reduction efforts audited or assessed regularly?", | |
"79. Are there plans for future emission reduction initiatives in logistics?", | |
"80. Do you participate in any carbon offset programs?", | |
"81. Is there a system for tracking and reporting emissions data?", | |
"82. Do you engage in partnerships or collaborations for emission reduction initiatives?", | |
"83. Do you provide training or awareness programs on emission reduction for employees?", | |
"84. Are emission reduction initiatives integrated into your overall business strategy?" | |
] | |
# Counting 'Yes' and 'No' responses | |
yes_count_emission = sum(1 for question in emission_reduction_questions if all_answers.get(question, "No") == 'Yes') | |
no_count_emission = len(emission_reduction_questions) - yes_count_emission | |
# Creating a horizontal bar chart | |
fig_emission = plt.figure(figsize=(8, 6)) | |
plt.barh(['Yes', 'No'], [yes_count_emission, no_count_emission], color=['green', 'red']) | |
plt.xlabel('Count') | |
plt.title('Count of "Yes" and "No" Responses for Emission Reduction Initiatives') | |
# Adding data labels to the bars | |
for index, value in enumerate([yes_count_emission, no_count_emission]): | |
plt.text(value, index, f'{value}', ha='right', va='center') | |
st.pyplot(fig_emission) | |
def calculate_emission_score(all_answers): | |
score = 0 | |
max_possible_score = 0 | |
# Scoring for Yes/No questions (5 points for each 'Yes') | |
yes_no_questions = [ | |
"65. Do you monitor CO2 emissions in your logistics operations?", | |
"66. Do you have emissions reduction targets in place for your logistics operations?", | |
"68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", | |
"69. Do you have initiatives to minimize particulate matter emissions?", | |
"70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", | |
"71. Do you manage emissions from refrigerated cargo containers?", | |
"72. Do you have strategies to reduce emissions from idling vehicles and equipment?", | |
"73. Do you employ emission-reducing practices in your facilityβs lighting, heating, and cooling systems?", | |
"74. Are renewable energy sources used to power your logistics facilities?", | |
"75. How do you manage emissions from equipment maintenance and repair activities?", | |
"76. Do you have specific percentage goals for emission reduction in logistics operations?", | |
"78. Are emission reduction efforts audited or assessed regularly?", | |
"79. Are there plans for future emission reduction initiatives in logistics?", | |
"80. Do you participate in any carbon offset programs?", | |
"81. Is there a system for tracking and reporting emissions data?", | |
"82. Do you engage in partnerships or collaborations for emission reduction initiatives?", | |
"83. Do you provide training or awareness programs on emission reduction for employees?", | |
"84. Are emission reduction initiatives integrated into your overall business strategy?" | |
] | |
for question in yes_no_questions: | |
response = all_answers.get(question, "No").lower() | |
if response == 'yes': | |
score += 5 | |
max_possible_score += 5 | |
# Scoring for quantitative questions | |
emission_reduction_goal = all_answers.get("67. Percentage reduction target for CO2 emissions in the next year:", 0) | |
emission_reduction_achieved = all_answers.get("77. Percentage of emission reduction goal achieved last year:", 0) | |
# Adding up to 10 points for each of the percentage-based questions based on their value | |
score += min(10, int(emission_reduction_goal / 10)) | |
score += min(10, int(emission_reduction_achieved / 10)) | |
max_possible_score += 20 | |
# Ensure score is within 0-100 range and calculate the percentage score | |
score = max(0, min(score, max_possible_score)) | |
percentage_score = (score / max_possible_score) * 100 | |
return percentage_score | |
def visualize_emission_score(all_answers): | |
# Calculate the emission reduction score | |
emission_score = calculate_emission_score(all_answers) | |
# Scoring components for visualization | |
components = { | |
'CO2 Emissions Monitoring': 5 if all_answers.get("65. Do you monitor CO2 emissions in your logistics operations?", "No") == "Yes" else 0, | |
'Emission Reduction Targets': 5 if all_answers.get("66. Do you have emissions reduction targets in place for your logistics operations?", "No") == "Yes" else 0, | |
'NOx and SOx Reduction Measures': 5 if all_answers.get("68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", "No") == "Yes" else 0, | |
'Particulate Matter Emission Initiatives': 5 if all_answers.get("69. Do you have initiatives to minimize particulate matter emissions?", "No") == "Yes" else 0, | |
'Fuel-Efficient Technologies Adoption': 5 if all_answers.get("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", "No") == "Yes" else 0, | |
'Management of Emissions from Refrigerated Cargo Containers': 5 if all_answers.get("71. Do you manage emissions from refrigerated cargo containers?", "No") == "Yes" else 0, | |
'Strategies to Reduce Emissions from Idling Vehicles and Equipment': 5 if all_answers.get("72. Do you have strategies to reduce emissions from idling vehicles and equipment?", "No") == "Yes" else 0, | |
'Emission-Reducing Practices in Lighting, Heating, and Cooling Systems': 5 if all_answers.get("73. Do you employ emission-reducing practices in your facilityβs lighting, heating, and cooling systems?", "No") == "Yes" else 0, | |
'Use of Renewable Energy Sources': 5 if all_answers.get("74. Are renewable energy sources used to power your logistics facilities?", "No") == "Yes" else 0, | |
'Management of Emissions from Equipment Maintenance and Repair Activities': 5 if all_answers.get("75. How do you manage emissions from equipment maintenance and repair activities?", "No") == "Yes" else 0, | |
'Specific Percentage Goals for Emission Reduction': 5 if all_answers.get("76. Do you have specific percentage goals for emission reduction in logistics operations?", "No") == "Yes" else 0, | |
'Regular Audits or Assessments for Emission Reduction Efforts': 5 if all_answers.get("78. Are emission reduction efforts audited or assessed regularly?", "No") == "Yes" else 0, | |
'Plans for Future Emission Reduction Initiatives': 5 if all_answers.get("79. Are there plans for future emission reduction initiatives in logistics?", "No") == "Yes" else 0, | |
'Participation in Carbon Offset Programs': 5 if all_answers.get("80. Do you participate in any carbon offset programs?", "No") == "Yes" else 0, | |
'System for Tracking and Reporting Emissions Data': 5 if all_answers.get("81. Is there a system for tracking and reporting emissions data?", "No") == "Yes" else 0, | |
'Engagement in Partnerships or Collaborations for Emission Reduction Initiatives': 5 if all_answers.get("82. Do you engage in partnerships or collaborations for emission reduction initiatives?", "No") == "Yes" else 0, | |
'Training or Awareness Programs on Emission Reduction for Employees': 5 if all_answers.get("83. Do you provide training or awareness programs on emission reduction for employees?", "No") == "Yes" else 0, | |
'Integration of Emission Reduction Initiatives into Business Strategy': 5 if all_answers.get("84. Are emission reduction initiatives integrated into your overall business strategy?", "No") == "Yes" else 0, | |
# Percentage-based components | |
'Reduction Target for CO2 Emissions': min(10, int(all_answers.get("67. Percentage reduction target for CO2 emissions in the next year:", 0) / 10)), | |
'Percentage of Goal Achieved Last Year': min(10, int(all_answers.get("77. Percentage of emission reduction goal achieved last year:", 0) / 10)) | |
} | |
component_names = list(components.keys()) | |
component_scores = list(components.values()) | |
# Split the scores into positive and negative scores for the stacked bar chart | |
positive_scores = [score if score > 0 else 0 for score in component_scores] | |
negative_scores = [score if score < 0 else 0 for score in component_scores] | |
# Create a stacked bar chart | |
fig, ax = plt.subplots(figsize=(10, 8)) | |
ax.barh(component_names, positive_scores, color='skyblue', label='Positive Scores') | |
ax.barh(component_names, negative_scores, color='salmon', label='Negative Scores') | |
# Add emission score as text to the right of the bar | |
for i, (pos_score, neg_score) in enumerate(zip(positive_scores, negative_scores)): | |
total_score = pos_score + neg_score | |
ax.text(max(total_score, 0) + 0.2, i, | |
f'{total_score:.1f}', | |
va='center', fontsize=10, fontweight='bold', color='grey') | |
# Set labels and title | |
ax.set_xlabel('Scores') | |
ax.set_title(f'Emission Reduction Score: {emission_score:.1f}%') | |
ax.legend() | |
# Adjust layout | |
plt.tight_layout() | |
return fig | |
explanation_E_metric = """ | |
The Emission Score reflects the commitment to reducing environmental emissions associated with logistics operations. It encompasses various factors that contribute to sustainable practices and emission reduction initiatives. Here's a detailed breakdown of how the Emission Score is composed: | |
- **CO2 Emissions Monitoring:** Monitoring CO2 emissions in logistics operations positively impacts the score by indicating a commitment to tracking environmental impact. | |
- **Emission Reduction Targets:** Having established targets for reducing emissions within logistics operations contributes positively to the score. | |
- **NOx and SOx Reduction Measures:** Implementing measures to reduce NOx and SOx emissions in transportation equipment or facilities adds points to the score. | |
- **Particulate Matter Emission Initiatives:** Initiatives aimed at minimizing particulate matter emissions contribute positively to the score. | |
- **Fuel-Efficient Technologies Adoption:** Adoption of fuel-efficient technologies or alternative fuels within the logistics fleet impacts the score positively. | |
- **Management of Emissions from Refrigerated Cargo Containers:** Efficiently managing emissions from refrigerated cargo containers adds to the score. | |
- **Strategies to Reduce Emissions from Idling Vehicles and Equipment:** Having strategies in place to reduce emissions from idling vehicles and equipment positively impacts the score. | |
- **Emission-Reducing Practices in Lighting, Heating, and Cooling Systems:** Employing emission-reducing practices in facility lighting, heating, and cooling systems contributes to a higher score. | |
- **Use of Renewable Energy Sources:** Utilizing renewable energy sources to power logistics facilities adds points to the score. | |
- **Management of Emissions from Equipment Maintenance and Repair Activities:** Efficiently managing emissions from equipment maintenance and repair activities impacts the score positively. | |
- **Specific Percentage Goals for Emission Reduction:** Setting specific percentage goals for emission reduction within logistics operations adds to the score. | |
- **Regular Audits or Assessments for Emission Reduction Efforts:** Regularly auditing or assessing emission reduction efforts contributes positively to the score. | |
- **Plans for Future Emission Reduction Initiatives:** Having plans for future emission reduction initiatives within logistics operations adds points to the score. | |
- **Participation in Carbon Offset Programs:** Actively participating in carbon offset programs impacts the score positively. | |
- **System for Tracking and Reporting Emissions Data:** Implementing a system for tracking and reporting emissions data positively affects the score. | |
- **Engagement in Partnerships or Collaborations for Emission Reduction Initiatives:** Engaging in partnerships or collaborations for emission reduction positively impacts the score. | |
- **Training or Awareness Programs on Emission Reduction for Employees:** Providing training or awareness programs on emission reduction for employees adds points to the score. | |
- **Integration of Emission Reduction Initiatives into Business Strategy:** Integrating emission reduction initiatives into the overall business strategy contributes positively to the score. | |
- **Reduction Target for CO2 Emissions:** Setting targets for reducing CO2 emissions in the upcoming year adds to the score. | |
- **Percentage of Goal Achieved Last Year:** The percentage of achieved emission reduction goals from the previous year impacts the score positively. | |
A higher Emission Score reflects a stronger dedication to minimizing environmental emissions, implementing sustainable practices, and achieving emission reduction goals within logistics operations. | |
""" | |
def evaluate_emission_sustainability_practice(score, df): | |
# Counting 'Yes' responses for emission-related Yes/No questions | |
emission_yes_no_questions = [ | |
question[0] for question in sections["Emission Reduction Initiatives"] if question[1] == 'radio' | |
] | |
yes_count = sum( | |
df[question].eq('Yes').sum() for question in emission_yes_no_questions if question in df.columns | |
) | |
yes_percentage = (yes_count / len(emission_yes_no_questions)) * 100 if emission_yes_no_questions else 0 | |
# Calculate a combined emission sustainability index | |
combined_index = (0.6 * score) + (0.4 * yes_percentage) | |
# Grading system with detailed advice for emission sustainability | |
if combined_index >= 80: | |
grade = "A (Eco-Champion π)" | |
st.image("Eco-Champion.png") | |
explanation = "You demonstrate exemplary emission reduction practices, setting a high benchmark in sustainability." | |
advice = "Continue leading and innovating in emission reduction, and share your successful practices with others." | |
elif combined_index >= 60: | |
grade = "B (Sustainability Steward π)" | |
st.image("Sustainability_Steward.png", use_column_width=True) | |
explanation = "Your efforts in emission reduction reflect a strong commitment to sustainability." | |
advice = "Keep improving your strategies for reducing emissions and explore new technologies for further reduction." | |
elif combined_index >= 40: | |
grade = "C (Eco-Advancer πΏ)" | |
st.image("Eco-Advancer.png") | |
explanation = "You're actively working towards better emission reduction but have room to grow." | |
advice = "Enhance your emission reduction initiatives and consider partnerships or collaborations for wider impact." | |
elif combined_index >= 20: | |
grade = "D (Green Learner πΌ)" | |
st.image("Green_Learner.png") | |
explanation = "You've started to engage in sustainable emission reduction practices, but there's much to develop." | |
advice = "Focus on establishing specific emission reduction goals and educate your team about their importance and implementation." | |
else: | |
grade = "E (Eco-Novice π±)" | |
st.image("Eco-Novice.png", use_column_width=True) | |
explanation = "You are at the early stages of adopting sustainable emission reduction practices." | |
advice = "Begin by monitoring emissions, setting targets, and implementing basic strategies to reduce emissions." | |
# Expanded advice on satisfying emission requirements | |
advice += "\n\n**Advice on Satisfying Emission Requirements:**" | |
advice += "\n- Ensure rigorous monitoring of emissions across all operations." | |
advice += "\n- Set ambitious yet achievable targets for reducing emissions." | |
advice += "\n- Implement measures to reduce various types of emissions, including CO2, NOx, SOx, and particulate matter." | |
advice += "\n- Consider the adoption of fuel-efficient technologies and alternative fuels." | |
advice += "\n- Regularly assess and audit emission reduction efforts to ensure effectiveness." | |
advice += "\n- Establish strategies to engage in carbon offset programs or support renewable energy sources." | |
advice += "\n- Integrate emission reduction initiatives into your overall business strategy for holistic impact." | |
return f"**Sustainability Grade: {grade}** \n\n**Explanation:** \n{explanation} \n\n**Detailed Advice:** \n{advice}" | |
def generate_swot_analysis(company_data): | |
# Extracting relevant data from company_data | |
logistics_sustainability_level = company_data.get("Logistics Sustainability Level", "None") | |
annual_carbon_emissions = company_data.get("Annual Carbon Emissions (in metric tons)", 0) | |
utilize_renewable_energy = company_data.get("Utilize Renewable Energy Sources", False) | |
selected_certifications = company_data.get("Selected Logistics Certifications and Initiatives", []) | |
company_summary = company_data.get("Company Summary", "No specific information provided.") | |
# Constructing a dynamic SWOT analysis based on extracted data | |
strengths = [ | |
"Utilization of Renewable Energy Sources" if utilize_renewable_energy else "None" | |
] | |
weaknesses = [ | |
"Lack of Logistics Sustainability Level: " + logistics_sustainability_level, | |
"Zero Annual Carbon Emissions" if annual_carbon_emissions == 0 else "Annual Carbon Emissions Present", | |
"Company Summary: " + company_summary | |
] | |
opportunities = [ | |
"Exploration of Logistics Certifications" if not selected_certifications else "None" | |
] | |
threats = [ | |
"Competitive Disadvantage Due to Lack of Certifications" if not selected_certifications else "None" | |
] | |
# Constructing a SWOT analysis prompt dynamically | |
swot_analysis_prompt = f""" | |
Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis: | |
Strengths: | |
Strengths Analysis: | |
{", ".join(strengths)} | |
Weaknesses: | |
Weaknesses Analysis: | |
{", ".join(weaknesses)} | |
Opportunities: | |
Opportunities Analysis: | |
{", ".join(opportunities)} | |
Threats: | |
Threats Analysis: | |
{", ".join(threats)} | |
""" | |
# OpenAI API call for SWOT analysis | |
response_swot = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are analyzing the company's sustainability practices."}, | |
{"role": "system", "content": "Conduct a SWOT analysis based on the provided company data."}, | |
{"role": "user", "content": swot_analysis_prompt} | |
], | |
max_tokens=1000, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Extracting the SWOT analysis content from the response | |
swot_analysis_content = response_swot.choices[0].message['content'] | |
return swot_analysis_content | |
def evaluate_emission_sustainability_report(all_answers, score): | |
"""Generates an Emission Sustainability report based on responses to a questionnaire.""" | |
extracted_data = extract_data(all_answers) | |
# Consolidate data for emission sustainability | |
co2_emissions_monitoring = extracted_data.get("65. Do you monitor CO2 emissions in your logistics operations?", "N/A") | |
emission_reduction_targets = extracted_data.get("66. Do you have emissions reduction targets in place for your logistics operations?", "N/A") | |
nox_sox_reduction_measures = extracted_data.get("68. Are measures in place to reduce NOx and SOx emissions in your transportation equipment or facilities?", "N/A") | |
particulate_matter_emission_initiatives = extracted_data.get("69. Do you have initiatives to minimize particulate matter emissions?", "N/A") | |
fuel_efficient_technologies = extracted_data.get("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", "N/A") | |
# ... include more emissions-related data as needed ... | |
emission_report = f""" | |
Emission Sustainability Report | |
Score: {score}/100 | |
Report Details: | |
CO2 Emissions Monitoring: {co2_emissions_monitoring} | |
Emission Reduction Targets: {emission_reduction_targets} | |
NOx and SOx Reduction Measures: {nox_sox_reduction_measures} | |
Particulate Matter Emission Initiatives: {particulate_matter_emission_initiatives} | |
Fuel-Efficient Technologies Adoption: {fuel_efficient_technologies} | |
Manage Emissions from Refrigerated Cargo Containers: {extracted_data.get("71. Do you manage emissions from refrigerated cargo containers?", "N/A")} | |
Emission-Reducing Practices in Lighting, Heating, and Cooling Systems: {extracted_data.get("73. Do you employ emission-reducing practices in your facilityβs lighting, heating, and cooling systems?", "N/A")} | |
Use of Renewable Energy Sources to Power Logistics Facilities: {extracted_data.get("74. Are renewable energy sources used to power your logistics facilities?", "N/A")} | |
Specific Percentage Goals for Emission Reduction in Logistics Operations: {extracted_data.get("76. Do you have specific percentage goals for emission reduction in logistics operations?", "N/A")} | |
Percentage of Emission Reduction Goal Achieved Last Year: {extracted_data.get("77. Percentage of emission reduction goal achieved last year:", 0)} | |
Regular Audits or Assessments for Emission Reduction Efforts: {extracted_data.get("78. Are emission reduction efforts audited or assessed regularly?", "N/A")} | |
Plans for Future Emission Reduction Initiatives in Logistics: {extracted_data.get("79. Are there plans for future emission reduction initiatives in logistics?", "N/A")} | |
Participation in Carbon Offset Programs: {extracted_data.get("80. Do you participate in any carbon offset programs?", "N/A")} | |
System for Tracking and Reporting Emissions Data: {extracted_data.get("81. Is there a system for tracking and reporting emissions data?", "N/A")} | |
""" | |
# Include further analysis via OpenAI API | |
prompt = f""" | |
As an emission sustainability advisor, analyze the Emission Sustainability Report with a score of {score}/100. Review the provided data points and offer a detailed analysis. Identify strengths, weaknesses, and areas for improvement in emission reduction practices. Provide specific recommendations to enhance emission sustainability considering the current emission reduction strategies and initiatives. | |
Data Points: | |
{emission_report} | |
""" | |
try: | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=[ | |
{"role": "system", "content": "Analyze the data and provide comprehensive insights and recommendations."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=3000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0, | |
presence_penalty=0 | |
) | |
evaluation_content = response.choices[0].message['content'] | |
refined_report = f"{emission_report}\n\n{evaluation_content}" | |
return refined_report | |
except Exception as e: | |
return f"Error: {e}" | |
# Function to format answer for better readability | |
def format_answer(answer): | |
if isinstance(answer, bool): | |
return "Yes" if answer else "No" | |
elif isinstance(answer, (int, float)): | |
return str(answer) | |
return answer # Assume the answer is already in a string format | |
# Function to extract and format data from a dictionary | |
def extract_data(data): | |
formatted_data = {} | |
for key, value in data.items(): | |
formatted_data[key] = format_answer(value) | |
return formatted_data | |
#report = evaluate_emission_sustainability_report(all_answers, score) | |
#st.write(report) | |
#Manage Emissions from Refrigerated Cargo Containers: {extracted_data.get("71. Do you manage emissions from refrigerated cargo containers?", "N/A")} | |
#- Strategies to Reduce Emissions from Idling Vehicles and Equipment: {extracted_data.get("72. Do you have strategies to reduce emissions from idling vehicles and equipment?", "N/A")} | |
#- Emission-Reducing Practices in Lighting, Heating, and Cooling Systems: {extracted_data.get("73. Do you employ emission-reducing practices in your facilityβs lighting, heating, and cooling systems?", "N/A")} | |
#- Use of Renewable Energy Sources to Power Logistics Facilities: {extracted_data.get("74. Are renewable energy sources used to power your logistics facilities?", "N/A")} | |
#- Participation in Carbon Offset Programs: {extracted_data.get("80. Do you participate in any carbon offset programs?", "N/A")} | |
#- System for Tracking and Reporting Emissions Data: {extracted_data.get("81. Is there a system for tracking and reporting emissions data?", "N/A")} | |
#- Engagement in Partnerships or Collaborations for Emission Reduction Initiatives: {extracted_data.get("82. Do you engage in partnerships or collaborations for emission reduction initiatives?", "N/A")} | |
def get_emission_sustainability_strategy(all_answers, company_data): | |
# Extracting and formatting data from all_answers and company_data | |
extracted_all_answers = extract_data(all_answers) | |
extracted_company_data = extract_data(company_data) | |
# Forming the prompt with extracted data for emission sustainability | |
prompt = f""" | |
Based on the provided company and emission sustainability assessment data, provide an emission sustainability strategy: | |
**Company Info**: | |
- Logistics Sustainability Level: {extracted_company_data.get('Logistics Sustainability Level', 'N/A')} | |
- Annual Carbon Emissions: {extracted_company_data.get('Annual Carbon Emissions (in metric tons)', 'N/A')} metric tons | |
- Utilize Renewable Energy Sources: {extracted_company_data.get('Utilize Renewable Energy Sources', 'No')} | |
- Certifications: {extracted_company_data.get('Selected Logistics Certifications and Initiatives', 'N/A')} | |
- Company Summary: {extracted_company_data.get('Company Summary', 'N/A')} | |
**Emission Sustainability Assessment Data**: | |
- CO2 Emissions Monitoring: {extracted_all_answers.get("65. Do you monitor CO2 emissions in your logistics operations?", "N/A")} | |
- Emission Reduction Targets: {extracted_all_answers.get("66. Do you have emissions reduction targets in place for your logistics operations?", "N/A")} | |
- Particulate Matter Emission Initiatives: {extracted_all_answers.get("69. Do you have initiatives to minimize particulate matter emissions?", "N/A")} | |
- Fuel-Efficient Technologies Adoption: {extracted_all_answers.get("70. Have you adopted fuel-efficient technologies or alternative fuels in your logistics fleet?", "N/A")} | |
- Training or Awareness Programs on Emission Reduction for Employees: {extracted_all_answers.get("83. Do you provide training or awareness programs on emission reduction for employees?", "N/A")} | |
- Integration of Emission Reduction Initiatives into Overall Business Strategy: {extracted_all_answers.get("84. Are emission reduction initiatives integrated into your overall business strategy?", "N/A")} | |
Offer an actionable strategy considering the company's specific context and emission sustainability data. | |
""" | |
additional_context = f"Provide a detailed emission sustainability strategy using context data from the above company info and in responses to the emission sustainability assessment." | |
# Assuming you have an API call here to generate a response based on the prompt | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=[ | |
{"role": "assistant", "content": "You are an emission sustainability strategy advisor."}, | |
{"role": "user", "content": prompt}, | |
{"role": "user", "content": additional_context} | |
], | |
max_tokens=3000, | |
temperature=0.7, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
return response.choices[0].message['content'] | |
#strategy= get_emission_sustainability_strategy(all_answers, company_data) | |
#st.write(strategy) | |
def get_certification_details(certification_name): | |
# Prepare the prompt for the API call | |
messages = [ | |
{"role": "system", "content": "You are a knowledgeable assistant about global certifications."}, | |
{"role": "user", "content": f"Provide detailed information on how to obtain the {certification_name} certification."} | |
] | |
# Query the OpenAI API for information on the certification process | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=messages, | |
max_tokens=2000, | |
temperature=0.3, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Return the content of the response | |
return response.choices[0].message['content'] | |
def advise_on_emission_sustainability_certification(company_data): | |
# Check if company_data is a dictionary | |
if not isinstance(company_data, dict): | |
raise ValueError("company_data must be a dictionary") | |
# Extract company data relevant to emission sustainability certifications | |
co2_emissions_monitoring = company_data.get('Do you monitor CO2 emissions?', False) | |
emission_reduction_targets = company_data.get('Have emissions reduction targets?', False) | |
nox_sox_reduction_measures = company_data.get('Measures to reduce NOx and SOx emissions?', False) | |
particulate_matter_initiatives = company_data.get('Initiatives to minimize particulate matter emissions?', False) | |
renewable_energy_sources = company_data.get('Use renewable energy sources?', False) | |
emission_management_certifications = company_data.get('Emission management certifications', []) | |
# Initialize a string to store recommendations | |
recommendations_text = "" | |
# Determine which emission sustainability certifications to suggest based on the provided data | |
emission_certifications_to_consider = { | |
"CO2 Emissions Monitoring Certification": not co2_emissions_monitoring, | |
"Emission Reduction Targets Certification": not emission_reduction_targets, | |
"NOx and SOx Reduction Measures Certification": not nox_sox_reduction_measures, | |
"Particulate Matter Emission Initiatives Certification": not particulate_matter_initiatives, | |
"Renewable Energy Sources Certification": not renewable_energy_sources, | |
"Advanced Emission Management Certification": "Advanced Emission Management" not in emission_management_certifications | |
} | |
for certification, consider in emission_certifications_to_consider.items(): | |
if consider: | |
try: | |
certification_details = get_certification_details(certification) | |
recommendations_text += f"\n\nFor {certification}, here's what you need to know: {certification_details}" | |
except Exception as e: | |
recommendations_text += f"\n\nError retrieving details for {certification}: {e}" | |
# If no emission sustainability certifications are suggested, add a message | |
if not recommendations_text.strip(): | |
recommendations_text = "Based on the provided data, there are no specific emission sustainability certifications recommended at this time." | |
# Return the combined recommendations as a single formatted string | |
return recommendations_text | |
#strategy = advise_on_emission_sustainability_certification(company_data) | |
#st.write(strategy) | |
if st.button('Submit'): | |
try: | |
# Use a spinner for generating advice | |
with st.spinner("Generating report and advice..."): | |
st.subheader("Visualize Emission Data") | |
visualize_emission_reduction_responses(all_answers) | |
visualize_emission_reduction_data(all_answers) | |
st.subheader("Emission Scores") | |
score = calculate_emission_score(all_answers) | |
# Display formatted score | |
st.write(f"**Emission Sustainability Score:**") | |
st.markdown(f"**{score:.1f}%**") | |
st.subheader("Visualize Emission Scores") | |
fig = visualize_emission_score(all_answers) | |
#fig = visualize_waste_score(all_answers) | |
st.pyplot(fig) | |
st.markdown(explanation_E_metric) | |
st.subheader("Visualize Sustainability Grade") | |
# Call the function with the DataFrame | |
st.markdown(evaluate_emission_sustainability_practice(score, answers_df), unsafe_allow_html=True) | |
swot_analysis_content = generate_swot_analysis(company_data) | |
#st.subheader("Energy Sustainability Strategy") | |
st.subheader("Company SWOT Report") | |
st.write(swot_analysis_content) | |
strategy = get_emission_sustainability_strategy(all_answers, company_data) | |
#strategy = get_energy_sustainability_advice(strategy, company_data) | |
report = evaluate_emission_sustainability_report(all_answers, score) | |
#st.subheader("Energy Sustainability Strategy") | |
st.subheader("Emission Sustainability Report") | |
st.write(report) | |
st.download_button( | |
label="Download Emission Sustainability Report", | |
data=report, | |
file_name='sustainability_report.txt', | |
mime='text/txt', | |
key="download_report_button", # Unique key for this button | |
) | |
st.subheader("Sustainability Strategy") | |
st.write(strategy) | |
st.download_button( | |
label="Download Emission Sustainability Strategy", | |
data=strategy, | |
file_name='sustainability_strategy.txt', | |
mime='text/txt', | |
key="download_strategy_button", # Unique key for this button | |
) | |
st.subheader("Advice on Sustainability Certification") | |
#certification_advice = advise_on_transport_sustainability_certification(company_data) | |
try: | |
advice = advise_on_emission_sustainability_certification(company_data) | |
st.write(advice) | |
except ValueError as e: | |
print(e) | |
# Embed a YouTube video after processing | |
st.subheader("Watch More on Sustainability") | |
video_urls = [ | |
"https://www.youtube.com/watch?v=RYzcE1OiwRE", | |
#"https://www.youtube.com/watch?v=your_video_url_2", | |
#"https://www.youtube.com/watch?v=your_video_url_3", | |
# Add more video URLs as needed | |
] | |
# Select a random video URL from the list | |
random_video_url = random.choice(video_urls) | |
# Display the random video | |
st.video(random_video_url) | |
except Exception as e: | |
st.error(f"An error occurred: {e}") | |
st.write(""" | |
--- | |
*Powered by Streamlit, CarbonInterface API, and OpenAI.* | |
""") | |
def page6(): | |
st.write("<center><h1>Carbon Footprint Calculator: Measure Your Environmental Impact</h1></center>", unsafe_allow_html=True) | |
st.image("page11.1.png", use_column_width=True) | |
#st.write("Assess and improve the sustainability of your logistics operations.") | |
# Define the API endpoint and your API key | |
API_URL = "https://www.carboninterface.com/api/v1/estimates" | |
API_KEY = "XXtYmhThBssK41ufq2JJOA" | |
# Define headers for the API call | |
headers = { | |
"Authorization": f"Bearer {API_KEY}", | |
"Content-Type": "application/json" | |
} | |
# Streamlit UI | |
#st.title("Carbon Emission Estimate Calculator for Shipping & Logistics") | |
# Streamlined Subheader and Descriptions | |
st.write(""" | |
### Instructions: | |
Input the necessary data related to your shipping and logistics operations to get an estimate of your carbon emissions. | |
The calculator will provide actionable insights to reduce your carbon footprint based on the data provided. | |
""") | |
st.title("Carbon Footprint Information Extractor") | |
# -- Shipping Routes -- | |
st.subheader("1. Shipping Routes") | |
average_ship_distance = st.number_input("Average Distance Per Shipping Route (km)", min_value=1, value=500) | |
most_common_ship_type = st.selectbox("Most Common Ship Type", ["Bulk Carrier", "Container Ship", "Tanker Ship", "Cargo Ship", "Passenger Ship", "Other"]) | |
# -- Warehousing and Storage -- | |
st.subheader("2. Warehousing and Storage") | |
warehouse_energy_source = st.selectbox("Primary Energy Source", ["Coal", "Natural Gas", "Renewable (Wind/Solar)", "Nuclear", "Other"]) | |
warehouse_size = st.number_input("Total Warehouse Space (sq.m)", min_value=1, value=5000) | |
warehouse_insulation = st.selectbox("Insulation Quality", ["Poor", "Average", "Good", "Excellent"]) | |
# -- Packaging -- | |
st.subheader("3. Packaging") | |
packaging_material = st.selectbox("Primary Packaging Material", ["Plastic", "Cardboard", "Biodegradable", "Recycled", "Other"]) | |
# -- Fleet Management -- | |
st.subheader("4. Fleet Management") | |
percentage_electric_vehicles = st.slider("Percentage of Electric Vehicles in Fleet", 0, 100, 10) | |
average_age_of_ships = st.slider("Average Age of Ships (years)", 1, 50, 15) | |
results = {} # Initialize an empty dictionary to store results | |
# Electricity | |
st.subheader("5. Port Operations Electricity Consumption") | |
st.write("****") | |
electricity_unit = st.selectbox("Unit", ["mwh", "kwh"], key='electricity_unit') | |
electricity_value = st.number_input("Value", min_value=0.1, value=42.0, key='electricity_value') | |
#country = st.text_input("Country (ISO Code)", "US", key='country') | |
country = "US" | |
# Vehicle | |
st.subheader("6. Vehicular Emissions") | |
distance_unit_vehicle = st.selectbox("Distance Unit", ["mi", "km"], key='distance_unit_vehicle') | |
distance_value_vehicle = st.number_input("Distance Value", min_value=0.1, value=100.0, key='distance_value_vehicle') | |
#vehicle_model_id = st.text_input("Vehicle Model ID (Optional)", key='vehicle_model_id') | |
vehicle_model_id = "7268a9b7-17e8-4c8d-acca-57059252afe9" | |
# Flight | |
st.subheader("7. Flight Emissions") | |
passengers = st.number_input("Number of Passengers", min_value=1, value=2, key='passengers') | |
# Section 4: Emission Reduction Goals | |
st.subheader("8. Emission Reduction Goals") | |
reduction_target = st.slider("Select Reduction Target (%)", 0, 100, 10) | |
# List of sample IATA Codes | |
iata_samples = [ | |
{ | |
"departure_airport": "SFO", | |
"destination_airport": "YYZ" | |
}, | |
{ | |
"departure_airport": "YYZ", | |
"destination_airport": "SFO" | |
} | |
] | |
# Dropdown for Departure Airport | |
#departure_airport = [sample["departure_airport"] for sample in iata_samples] | |
#departure_airport = st.selectbox("Departure Airport (IATA Code)", departure_airport_options, key='departure_airport') | |
departure_airport = "SFO" | |
destination_airport = "YYZ" | |
# Dropdown for Destination Airport | |
# Filter destinations based on selected departure airport | |
#destination_airport = [sample["destination_airport"] for sample in iata_samples if sample["departure_airport"] == departure_airport] | |
#destination_airport = st.selectbox("Destination Airport (IATA Code)", destination_airport_options, key='destination_airport') | |
# Simplified CO2 Emission Coefficients (in gCO2 per unit) | |
COEFFICIENTS = { | |
"diesel": 2640, # gCO2 per liter | |
"gasoline": 2392, # gCO2 per liter | |
"natural_gas": 1870, # gCO2 per cubic meter | |
"electricity": 0, # gCO2 per kWh (placeholder, actual value varies) | |
} | |
fuel_source_units = { | |
"diesel": ["gallons", "liters", "btu"], | |
"gasoline": ["gallons", "liters", "btu"], | |
"natural_gas": ["btu", "mcf", "therms"], | |
#"electricity": ["kWh", "btu"], | |
} | |
def calculate_emissions(fuel_type, fuel_unit, fuel_value): | |
# Conversion constants to standardize units to liters or cubic meters | |
unit_conversion = { | |
"gallons": 3.78541, # 1 gallon to liters | |
"mcf": 28.3168, # 1 mcf to cubic meters | |
"therms": 2.83168, # 1 therm to cubic meters | |
"btu": 0.000001 # Placeholder for BTU conversion, actual value depends on fuel type. | |
} | |
# Specific BTU conversions to liters equivalent for each fuel type | |
btu_conversion = { | |
"diesel": 0.000065, | |
"gasoline": 0.000074, | |
"natural_gas": 0.000036, # Approximated value for natural gas | |
} | |
# Adjust BTU conversion based on fuel type | |
if fuel_unit == "btu": | |
unit_conversion["btu"] = btu_conversion.get(fuel_type, 0.000001) | |
converted_value = fuel_value * unit_conversion.get(fuel_unit, 1) | |
return COEFFICIENTS.get(fuel_type, 0) * converted_value | |
# User Interface Simplification | |
#st.write("**Fuel Combustion CO2 Emissions Calculator**") | |
st.subheader("8. Fuel Combustion Emissions") | |
# Reduced list of selectable fuel sources | |
selected_fuel_sources = st.multiselect("Choose Fuel Source", ["diesel", "gasoline", "natural_gas"], key='fuel_source') | |
# Initialize an empty dictionary to store results | |
inputs = {} | |
total_emissions = 0 | |
for fuel_source in selected_fuel_sources: | |
st.write(f"### {fuel_source} Emissions") | |
# Set the unit options based on the selected fuel source | |
fuel_source_unit = st.selectbox(f"Unit of {fuel_source}", fuel_source_units[fuel_source], key=f'unit_{fuel_source}') | |
# Input for fuel quantity | |
fuel_source_value = st.number_input(f"Amount of {fuel_source}", min_value=0.1, value=2.0, step=0.1, key=f'value_{fuel_source}') | |
# Calculate and display the emissions | |
emission = calculate_emissions(fuel_source, fuel_source_unit, fuel_source_value) | |
st.write(f"CO2 emissions for {fuel_source}: {emission:.2f} grams") | |
total_emissions += emission | |
# Button to trigger the calculations | |
if st.button("Calculate Carbon Emission"): | |
with st.spinner("Calculating..."): | |
#results = {} # Initialize an empty dictionary to store results | |
# Electricity API Call | |
payload_electricity = { | |
"type": "electricity", | |
"electricity_unit": electricity_unit, | |
"electricity_value": electricity_value, | |
"country": country | |
} | |
response_electricity = requests.post(API_URL, json=payload_electricity, headers=headers) | |
if response_electricity.status_code == 201: | |
results["Electricity"] = response_electricity.json().get("data", {}).get("attributes", {}) | |
else: | |
results["Electricity Error"] = f"Error: {response_electricity.status_code} - {response_electricity.text}" | |
# Vehicle API Call | |
if vehicle_model_id: # Only make the API call if a vehicle_model_id is provided | |
payload_vehicle = { | |
"type": "vehicle", | |
"distance_unit": distance_unit_vehicle, | |
"distance_value": distance_value_vehicle, | |
"vehicle_model_id": vehicle_model_id | |
} | |
response_vehicle = requests.post(API_URL, json=payload_vehicle, headers=headers) | |
if response_vehicle.status_code == 201: | |
results["Vehicle"] = response_vehicle.json().get("data", {}).get("attributes", {}) | |
else: | |
results["Vehicle Error"] = f"Error: {response_vehicle.status_code} - {response_vehicle.text}" | |
# Flight API Call | |
payload_flight = { | |
"type": "flight", | |
"passengers": passengers, | |
"legs": [ | |
{"departure_airport": departure_airport, "destination_airport": destination_airport} | |
] | |
} | |
response_flight = requests.post(API_URL, json=payload_flight, headers=headers) | |
if response_flight.status_code == 201: | |
results["Flight"] = response_flight.json().get("data", {}).get("attributes", {}) | |
else: | |
results["Flight Error"] = f"Error: {response_flight.status_code} - {response_flight.text}" | |
data_for_df = [] | |
for key, value in results.items(): | |
if not key.endswith("_error"): | |
try: | |
data_for_df.append((key, value['carbon_g'])) | |
except TypeError: | |
st.error(f"Unexpected value type for key: {key}. Value: {value}") | |
st.subheader("Carbon Emission Visual Analysis") | |
df = pd.DataFrame(data_for_df, columns=["Segment", "Emissions (g)"]) | |
st.bar_chart(df.set_index("Segment"), use_container_width=True) | |
#pie_chart_data = df.set_index("Segment") | |
#st.pyplot(pie_chart_data.plot.pie(y='Emissions (g)', autopct='%1.1f%%', legend=False)) | |
# Set the index of your dataframe to 'Segment' for the pie chart | |
pie_chart_data = df.set_index("Segment") | |
# Create a pie chart as a Figure object | |
fig, ax = plt.subplots() | |
ax.pie(pie_chart_data['Emissions (g)'], labels=pie_chart_data.index, autopct='%1.1f%%') | |
# Hide the legend if you don't want it | |
ax.legend().set_visible(False) | |
# Display the pie chart in Streamlit | |
st.pyplot(fig) | |
st.subheader("Table of Emission Factors") | |
st.table(COEFFICIENTS) | |
st.subheader("Emission Reduction Goals Visualization") | |
# Use the total calculated emissions as the baseline | |
total_emissions = df["Emissions (g)"].sum() | |
# Assuming the goal is zero emissions (100% reduction) | |
goal_emissions = 0 | |
# Calculate the emissions after the desired reduction target is applied | |
emissions_after_reduction = total_emissions * (1 - (reduction_target / 100)) | |
# Create a bar chart to compare current and post-reduction emissions | |
reduction_data = { | |
"Emission Type": ["Current Emissions", "Emissions After Target"], | |
"Amount": [total_emissions, emissions_after_reduction] | |
} | |
df_reduction = pd.DataFrame(reduction_data) | |
st.bar_chart(df_reduction.set_index("Emission Type")) | |
# Calculate the current progress | |
current_progress = reduction_target / 100 | |
# Display a label indicating the goal above the progress bar | |
st.markdown(f"### Progress Towards Reduction Target ({reduction_target}% goal)") | |
# Visualize the progress with a progress bar | |
st.progress(current_progress) | |
# Textual description of the reduction progress | |
st.markdown(f"The reduction target is set to **{reduction_target}%**.") | |
st.markdown(f"With current emissions at **{total_emissions} g**, the target after reduction is **{emissions_after_reduction} g**.") | |
st.markdown(f"To reach the goal of zero emissions, a further reduction of **{total_emissions - emissions_after_reduction} g** is needed.") | |
st.subheader("Emission Reduction Goals Visualization") | |
# Constants | |
price_per_ton_CO2 = 20 # $20 per ton of CO2 | |
conversion_factor = 1e6 # 1,000,000 grams in a ton | |
transmission_factor = 0.8 | |
reduction_target = reduction_target # Example reduction target percentage | |
total_emissions = total_emissions # Example total emissions in grams | |
# Assuming two reduction targets: a specific target and 100% | |
reduction_targets = set([reduction_target, 100]) | |
# Lists to store the results | |
money_earned_list = [] | |
# Check if we have two distinct reduction targets | |
if len(reduction_targets) != 2: | |
raise ValueError("Reduction targets must be two distinct values.") | |
reduction_targets_sorted = [] | |
# Calculate the money earned for each reduction target | |
for target in sorted(reduction_targets): | |
emissions_after_reduction = total_emissions * (1 - (target / 100)) | |
emissions_reduced = total_emissions - emissions_after_reduction | |
emissions_reduced_in_tons = emissions_reduced / conversion_factor | |
money_earned = emissions_reduced_in_tons * price_per_ton_CO2 * transmission_factor | |
money_earned_list.append(money_earned) | |
reduction_targets_sorted.append(target) | |
money_earned_target = money_earned_list[0] # For the specific reduction target | |
money_earned_total = money_earned_list[1] # For total reduction | |
# Create DataFrame for plotting | |
data = {"Reduction Target (%)": reduction_targets_sorted, "Money Earned ($)": money_earned_list} | |
df_money = pd.DataFrame(data) | |
# Using st.markdown to display the dynamic message in a Streamlit app | |
# Displaying the assumptions | |
st.markdown(f"Assuming a transmission factor of **{transmission_factor}** and a price of **${price_per_ton_CO2}** per ton of CO2,") | |
# Displaying the potential gain with the specified reduction target | |
st.markdown(f"your company is likely to gain an amount of **${money_earned_target:.2f}** with a **{reduction_target}%** reduction target,") | |
# Displaying the potential gain with total carbon reduction | |
st.markdown(f"and **${money_earned_total:.2f}** with total carbon reduction.") | |
# Displaying the advisory note | |
st.markdown("This is an assumption, and you are advised to look into carbon-cash exchange models for more accurate estimations.") | |
# Plotting the data | |
plt.figure(figsize=(10, 6)) | |
plt.plot(df_money["Reduction Target (%)"], df_money["Money Earned ($)"], marker='o') | |
plt.title("Potential Money Earned by Reducing Carbon Emissions") | |
plt.xlabel("Reduction Target (%)") | |
plt.ylabel("Money Earned ($)") | |
plt.grid(True) | |
# Using st.pyplot() to display the plot in Streamlit | |
st.pyplot(plt) | |
responses = { | |
"shipping_routes": { | |
"average_distance": "average_ship_distance", | |
"common_ship_type": "most_common_ship_type", | |
}, | |
"warehousing": { | |
"energy_source": "warehouse_energy_source", | |
"size": "warehouse_size", | |
"insulation": "warehouse_insulation", | |
}, | |
"packaging": { | |
"material": "packaging_material", | |
}, | |
"fleet_management": { | |
"percentage_electric": "percentage_electric_vehicles", | |
"average_age": "average_age_of_ships", | |
}, | |
"vehicular_emissions": { | |
"distance_unit": "distance_unit_vehicle", | |
"distance_value": "distance_value_vehicle", | |
"model_id": "vehicle_model_id", | |
}, | |
"fuel_combustion_emissions": { | |
"selected_fuel_sources": "selected_fuel_sources", | |
"total_emissions": "total_emissions", | |
}, | |
"emission_reduction_goals": { | |
# Initialize with empty strings or appropriate placeholders | |
"current_emissions": "", | |
"emissions_after_target": "", | |
"reduction_target": "", | |
}, | |
} | |
#- Current total emissions and the goal of reaching zero emissions | |
#- Reduction target for emissions | |
#- Fuel combustion emissions | |
#- Electricity use in port operations | |
#- Fleet management practices | |
#- Shipping route efficiency | |
inputs = { | |
"Average Shipping Distance (km)": average_ship_distance, | |
"Most Common Ship Type": most_common_ship_type, | |
"Primary Warehouse Energy Source": warehouse_energy_source, | |
"Total Warehouse Space (sq.m)": warehouse_size, | |
"Warehouse Insulation Quality": warehouse_insulation, | |
"Primary Packaging Material": packaging_material, | |
"Fleet Electric Vehicles (%)": percentage_electric_vehicles, | |
"Average Age of Ships (years)": average_age_of_ships, | |
"Port Operations Electricity Unit": electricity_unit, | |
"Port Operations Electricity Consumption": electricity_value, | |
"Vehicle Distance Unit": distance_unit_vehicle, | |
"Vehicle Distance Traveled": distance_value_vehicle, | |
"Emission Reduction Target (%)": reduction_target, | |
"Total Annual Carbon Emissions (grams)": total_emissions | |
} | |
# Calculate the emissions after the desired reduction target is applied | |
emissions_after_reduction = total_emissions * (1 - (reduction_target / 100)) | |
# Update the inputs dictionary with the new key-value pair | |
inputs.update({ | |
f"Emissions After {reduction_target}% Reduction Target (grams)": emissions_after_reduction | |
}) | |
#st.write(inputs) | |
# Formulate the prompt for GPT | |
# Constructing the prompt based on input parameters | |
report_prompt = f""" | |
Detailed Carbon Emission Analysis Report: | |
- Total annual emissions: {inputs["Total Annual Carbon Emissions (grams)"]} grams | |
- Emission reduction target: {inputs["Emission Reduction Target (%)"]}% | |
- Impact of {inputs["Most Common Ship Type"]} and its average age ({inputs["Average Age of Ships (years)"]} years) on fuel combustion emissions. | |
- Electricity consumption in port operations: {inputs["Port Operations Electricity Consumption"]} {inputs["Port Operations Electricity Unit"]} | |
- Fleet management practices: {inputs["Fleet Electric Vehicles (%)"]} electric vehicles in the fleet. | |
- Average shipping distance efficiency: {inputs["Average Shipping Distance (km)"]} km | |
Please generate a detailed report analyzing the current carbon emissions scenario, considering the mentioned parameters, and propose recommendations to effectively reduce the organization's carbon footprint in shipping and logistics. The report should encompass comprehensive insights, statistical analysis, and a clear assessment of potential strategies and their impact on carbon reduction. Consider feasibility, cost-effectiveness, and alignment with industry best practices. | |
""" | |
# OpenAI API call for the response | |
response = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo-16k", | |
messages=[ | |
{"role": "assistant", "content": "You are a carbon management and reduction strategist."}, | |
{"role": "system", "content": "Provide report based on the carbon emission data."}, | |
{"role": "user", "content": report_prompt} | |
], | |
max_tokens=700, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Constructing a prompt for SWOT analysis based on provided data | |
swot_analysis_prompt = f""" | |
Strengths, Weaknesses, Opportunities, Threats (SWOT) Analysis: | |
Strengths: | |
Strengths Analysis: | |
The company's carbon activities show several positive attributes: | |
1. Efficient Shipping: Utilizing {inputs["Average Shipping Distance (km)"]} km as the average shipping distance showcases efficiency in transportation. | |
2. Electric Vehicles: With {inputs["Fleet Electric Vehicles (%)"]} of the fleet being electric, it exhibits a commitment to eco-friendly transportation. | |
3. Warehouse Insulation: The warehouse insulation quality, rated as {inputs["Warehouse Insulation Quality"]}, contributes positively to energy conservation. | |
Weaknesses: | |
Weaknesses Analysis: | |
Despite positive aspects, the company's carbon activities display areas needing improvement: | |
1. Fuel-Dependent Ships: The average age of ships ({inputs["Average Age of Ships (years)"]} years) and the prevalent ship type ({inputs["Most Common Ship Type"]}) might indicate higher fuel combustion emissions. | |
2. Warehouse Energy Source: Dependency on {inputs["Primary Warehouse Energy Source"]} as the primary energy source might contribute to carbon emissions. | |
3. Packaging Material Impact: The choice of {inputs["Primary Packaging Material"]} might have environmental implications. | |
Opportunities: | |
Opportunities Analysis: | |
Exploring areas for growth or improvement in the company's carbon activities: | |
1. Renewable Energy Adoption: Consider adopting renewable sources like solar or wind power for warehouses. | |
2. Fleet Upgrade: Investing in newer, more fuel-efficient ship types can significantly reduce emissions. | |
3. Sustainable Packaging: Explore and adopt environmentally friendly packaging alternatives. | |
Threats: | |
Threats Analysis: | |
Identifying potential risks or threats affecting the company's carbon activities: | |
1. Regulatory Changes: Anticipate changes in environmental regulations impacting carbon emissions in shipping and logistics. | |
2. Rising Energy Costs: Potential increases in electricity prices may impact operational expenses. | |
3. Market Shifts: Changes in market dynamics may affect shipping route efficiency or demand. | |
""" | |
# OpenAI API call for SWOT analysis | |
response_swot = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are analyzing the company's carbon activities."}, | |
{"role": "system", "content": "Conduct a SWOT analysis based on the provided data."}, | |
{"role": "user", "content": swot_analysis_prompt} | |
], | |
max_tokens=1000, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Constructing the prompt for the Carbon Reduction Strategy Advisor | |
strategy_prompt = f""" | |
Carbon Reduction Strategy Advisor: | |
Given the specific parameters provided for carbon emissions in the shipping and logistics domain: | |
- Total annual emissions: {inputs["Total Annual Carbon Emissions (grams)"]} grams | |
- Emission reduction target: {inputs["Emission Reduction Target (%)"]}% reduction target | |
- Fuel combustion emissions related to {inputs["Most Common Ship Type"]} with an average age of {inputs["Average Age of Ships (years)"]} years. | |
- Electricity use in port operations: {inputs["Port Operations Electricity Consumption"]} {inputs["Port Operations Electricity Unit"]} used in port operations. | |
- Fleet management practices: {inputs["Fleet Electric Vehicles (%)"]} of fleet being electric vehicles. | |
- Shipping route efficiency: Average shipping distance is {inputs["Average Shipping Distance (km)"]} km. | |
The objective is to achieve significant carbon reduction while considering cost-effectiveness and industry best practices. | |
Please provide detailed strategies, innovative approaches, and practical steps to significantly reduce carbon emissions in the shipping and logistics operations. Focus on actionable advice, implementation frameworks, and potential challenges to consider when adopting these strategies. | |
""" | |
# OpenAI API call for carbon reduction strategies | |
response_strategies = openai.ChatCompletion.create( | |
model="gpt-3.5-turbo", | |
messages=[ | |
{"role": "assistant", "content": "You are a carbon management and reduction strategist."}, | |
{"role": "system", "content": "Provide strategies to achieve significant carbon reduction."}, | |
{"role": "user", "content": strategy_prompt} | |
], | |
max_tokens=1000, | |
temperature=0.5, | |
top_p=1.0, | |
frequency_penalty=0.5, | |
presence_penalty=0.0 | |
) | |
# Display the strategies to the user or use it as needed in your application | |
# strategies_content contains the generated strategies for carbon reduction | |
swot_result = response_swot.choices[0].message['content'] | |
# Display the advice to the user | |
st.subheader("Carbon Swot Analysis") | |
st.write(swot_result) | |
st.download_button( | |
label="Download SWOT Analysis", | |
data=swot_result, | |
file_name='SWOT_Anlysis.txt', | |
mime='text/txt', | |
key="download_SWOT_button", # Unique key for this button | |
) | |
# Extracting the advice content from the response | |
advice_content = response.choices[0].message['content'] | |
# Display the advice to the user | |
st.subheader("Sustainability Report") | |
st.write(advice_content) | |
st.download_button( | |
label="Download Sustainability advice", | |
data=advice_content, | |
file_name='sustainability_advice.txt', | |
mime='text/txt', | |
key="download_advice_button", # Unique key for this button | |
) | |
# Extracting the strategies content from the response | |
strategies_content = response_strategies.choices[0].message['content'] | |
# Display the advice to the user | |
st.subheader("Carbon Reduction Strategy") | |
st.write(strategies_content) | |
st.download_button( | |
label="Download Sustainability strategy", | |
data=strategies_content, | |
file_name='sustainability_strategy.txt', | |
mime='text/txt', | |
key="download_strategy_button", # Unique key for this button | |
) | |
# Display a disclaimer message | |
st.warning("Disclaimer: The carbon emission calculations provided here are based on certain assumptions and data sources. While we strive to provide accurate estimates, please be aware that the results should be considered as approximate. For the most accurate carbon emissions assessment, we recommend testing with globally accepted values and results.") | |
st.write(""" | |
--- | |
*Powered by Streamlit, CarbonInterface API, and OpenAI.* | |
""") | |
def page7(): | |
# Load and set OpenAI API key from file | |
os.environ["OPENAI_API_KEY"] = open("key.txt", "r").read().strip("\n") | |
# Define the DB_DIR variable at the top of your script, so it's available in the scope of the function | |
DB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "db") | |
# Make sure the directory exists, create if it does not | |
os.makedirs(DB_DIR, exist_ok=True) | |
# Function to process and store data once | |
#@st.cache_data() | |
def process_and_store_data(url): | |
# Initialize loader and load data from the URL | |
loader = WebBaseLoader(url) | |
data = loader.load() | |
# Initialize text splitter and split documents | |
text_splitter = CharacterTextSplitter(separator='\n', chunk_size=900, chunk_overlap=50) | |
docs = text_splitter.split_documents(data) | |
# Initialize OpenAI embeddings | |
openai_embeddings = OpenAIEmbeddings() | |
# Create or load Chroma vector database | |
vectordb = Chroma.from_documents(documents=docs, embedding=openai_embeddings, persist_directory=DB_DIR) | |
vectordb.persist() | |
# Return the retriever for later use | |
return vectordb.as_retriever(search_kwargs={"k": 3}) | |
# Main function to define the Streamlit application | |
st.write("<center><h1>π’ EcoPorts: Navigating Towards Sustainable Seaports π±</h1></center>", unsafe_allow_html=True) | |
st.title('') | |
st.image("page12.1.png", use_column_width=True) | |
st.subheader('Embark on a Voyage of Discovery in Port Sustainability') | |
st.write( | |
""" | |
Welcome to **EcoPorts**, your guide to sustainable practices in the world's seaports. | |
As critical hubs for global trade, ports play a key role but also pose environmental challenges. From pollution to ecosystem disruptions, the impact is significant. ππ | |
Seaports are now charting a course towards sustainability, adopting eco-friendly practices to protect our planet. ππ Dive into an exploration of port sustainability initiatives, ask questions, and discover how ports are becoming greener. Join us on a journey to sustainable port operations! π’π | |
""" | |
) | |
# Define a list of websites to choose from | |
websites = { | |
"Blue Economy Observatory News": "https://blue-economy-observatory.ec.europa.eu/news/antwerp-bruges-aims-become-worlds-greenest-port-2023-03-10_en", | |
"Euronews Green": "https://www.euronews.com/green/2023/02/28/port-behind-10-of-belgiums-co2-emissions-adopts-carbon-slashing-tech", | |
"Sustainable World Ports": "https://sustainableworldports.org/", | |
"Port of Gothenburg Green Connection": "https://www.portofgothenburg.com/green-connection/", | |
"Ship Technology Green Team Ports": "https://www.ship-technology.com/features/green-team-ports-leading-shipping-sustainability-drive/", | |
"AD Ports Group Sustainability": "https://www.adportsgroup.com/en/sustainability", | |
"World Shipping Council": "https://www.worldshipping.org/", | |
"International Association of Ports and Harbors": "https://www.iaphworldports.org/", | |
"GLA Family": "https://www.glafamily.com/", | |
"Strategia e Sviluppo": "https://strategiaesviluppo.com/supply-chain-sustainability" | |
} | |
sustainability_questions = [ | |
"What initiatives are in place to reduce carbon emissions in ports?", | |
"How are ports minimizing their environmental impact?", | |
"What actions are taken to protect local ecosystems?", | |
"How do ports manage waste and recycling?", | |
"What strategies are employed to improve energy efficiency in ports?", | |
"How do ports engage in community outreach and partnerships?", | |
"What measures are taken to ensure social responsibility in ports?", | |
"How are ports contributing to economic development in their communities?", | |
"What investments are being made in renewable energy sources in ports?", | |
"How are ports ensuring the well-being of future generations?", | |
"How do ports align their operations with the United Nations' Sustainable Development Goals (SDGs)?", | |
"What technologies are being adopted to promote sustainability in ports?", | |
"How do ports manage water resources responsibly?", | |
"What practices are implemented to promote sustainable supply chain practices in ports?", | |
"How do ports mitigate the impact of operations on local wildlife and habitats?", | |
"How is technology being utilized to enhance sustainable operations in ports?", | |
"What role do ports play in reducing the carbon footprint of the shipping industry?", | |
"How do ports safeguard marine life and biodiversity?", | |
"What is the impact of port operations on air quality, and how is it being mitigated?", | |
"How do ports plan to adapt to the challenges posed by climate change?", | |
"What initiatives are in place to promote green transportation within and around ports?", | |
"How are ports addressing noise pollution?", | |
"What measures are in place to handle hazardous materials safely and sustainably?", | |
"How are ports working towards reducing water pollution?", | |
"What collaborations or partnerships are ports forming to enhance sustainability?", | |
"How do ports facilitate and manage clean energy transition for vessels?", | |
"What are the strategies adopted by ports to ensure economic sustainability?", | |
"How are ports ensuring secure, transparent, and sustainable supply chains?", | |
"What frameworks are used to measure and report sustainability in ports?", | |
"How is sustainability integrated into the decision-making and operational processes of ports?", | |
"What is the role of port authorities in ensuring sustainability within port precincts?", | |
"What kind of training or awareness programs are in place for sustainability in ports?", | |
"How are the local communities involved in sustainability initiatives by ports?", | |
"What policies are in place to enhance social sustainability in port operations?", | |
] | |
# Select box for choosing a website to query | |
selected_website_name = st.selectbox("Select a website", options=list(websites.keys())) | |
url = websites[selected_website_name] | |
# Load and use the embeddings from the stored data | |
retriever = process_and_store_data(url) | |
# Input for user's question | |
question = st.selectbox("Choose a standard question:", [""] + sustainability_questions) | |
if question: | |
prompt = question | |
else: | |
prompt = st.text_input("Or ask your own question:") | |
#question = st.text_input("Ask your question about port sustainability:") | |
# Process button to handle queries | |
if st.button('Submit Query'): | |
if question: | |
with st.spinner('Fetching and Processing Data...'): | |
# Initialize the LLM and retrieval QA chain | |
llm = OpenAI(model_name='gpt-3.5-turbo') | |
qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever) | |
# Get the response using the QA chain | |
response = qa(question) | |
query = response.get("query") | |
result = response.get("result") | |
# Formatting and Displaying the response within the button pressed block | |
formatted_response = f"**Question:** {query}\n\n**Answer:** {result}" | |
st.markdown(formatted_response) | |
else: | |
st.warning("Please enter a question to proceed.") | |
with st.sidebar: | |
st.image("Logo.png") | |
selected = option_menu( | |
menu_title=None, | |
options=["π Home","βοΈ Energy Sustainability","π Sustainable Transportation", "β»οΈ Waste Assessment", | |
"π₯· Trash Ninja","π¨ Emission Assessment", "π£ Carbon Footprint", "π£οΈπ EcoPorts Query Engine", "βAbout"], | |
#icons = [ | |
#"home", "bus", "bolt", "cube", "ship", | |
#"cloud", "trash", "exclamation-triangle", | |
#"check-circle", "lightbulb-o", "eye", "paw", "β" | |
#], | |
styles=css_style | |
) | |
if selected == "π Home": | |
home_page() | |
elif selected == "βοΈ Energy Sustainability": | |
page1() | |
elif selected == "π Sustainable Transportation": | |
page2() | |
elif selected == "β»οΈ Waste Assessment": | |
page3() | |
elif selected == "π₯· Trash Ninja": | |
page4() | |
elif selected == "π¨ Emission Assessment": | |
page5() | |
elif selected == "π£ Carbon Footprint": | |
page6() | |
elif selected == "π£οΈπ EcoPorts Query Engine": | |
page7() | |
elif selected == "βAbout": | |
about_page() | |