import streamlit as st
import pandas as pd
import requests
import openai
from streamlit_option_menu import option_menu
import streamlit as st
import openai
import matplotlib.pyplot as plt
import collections
import requests
from bs4 import BeautifulSoup
import pandas as pd
# Load and set our key
openai.api_key = open("key.txt", "r").read().strip("\n")
st.set_page_config(page_title="Loan Eligibility and Repayment Strategy Advisor", page_icon="GH", initial_sidebar_state="expanded")
hide_streamlit_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(f"""# Sustainable Shipping and Logistics Advisor""", unsafe_allow_html=True)
#st.image("banner1.jpg", use_column_width=True)
st.write(f"""
The Challenge
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:
- Rising carbon emissions from global shipping operations.
- Waste management challenges in ports and logistics facilities.
- Operational inefficiencies leading to increased environmental footprint.
- Lack of integration of green technologies and renewable energy sources.
- Increasing regulatory and compliance pressures.
- Growing consumer demand for sustainable shipping options.
- Impact of shipping activities on marine biodiversity.
- Resource depletion and increasing waste generation.
- Addressing the socio-economic aspects of sustainability in shipping communities.
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.
""", unsafe_allow_html=True)
st.write(f"""Project Goals
The Sustainable Shipping and Logistics Advisor aims to champion sustainability in the shipping, port, and logistics domain by:
- Quantifying Carbon Emissions: Providing tools to measure and analyze carbon footprints of shipping operations.
- Offering Sustainability Insights: Generating personalized advice for businesses to optimize operations, reduce emissions, and implement green technologies.
- Promoting Green Practices: Educating stakeholders about best practices in sustainable shipping and logistics.
- Facilitating Sustainable Decisions: Empowering businesses with the information and tools they need to make sustainability-driven decisions in their operations.
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.
""", unsafe_allow_html=True)
def about_page():
st.write("""About Sustainable Shipping and Logistics Advisor
""", unsafe_allow_html=True)
#st.image("about.jpg", use_column_width=True)
st.write("""
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.
The focal objectives of the AI for Good 2023 Hackathon are:
- Empower with AI: The hackathon seeks to push the boundaries of AI, venturing beyond conventional realms, to address complex socio-economic challenges.
- Cultivate Technological Advancement: By fostering an environment of collaboration and innovation, the hackathon aspires to spur developments in AI that are both revolutionary and beneficial for society.
- Champion Sustainable Solutions: 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.
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.
""", unsafe_allow_html=True)
def page1():
st.write("Sustainable Logistics Strategy and Transportation
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
section_header("Commitment and Strategy")
st.write("
", 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("
", unsafe_allow_html=True)
sections = {
"Commitment and Strategy": [
("1. Environmental Management Commitment (0-10):", 'slider'),
("2. Progress in Reducing Environmental Impact (0-10):", 'slider'),
("3. Transparency in Environmental Reporting (0-10):", 'slider'),
("4. Commitment to Digital Transformation for Sustainability (0-10):", 'slider'),
("5. Integration of Sustainability Goals in Business Strategy (0-10):", 'slider'),
("6. Commitment to Increasing Energy Efficiency (0-10):", 'slider'),
("7. Commitment to Sustainable Packaging (0-10):", 'slider'),
("8. Commitment to Emission Reduction (0-10):", 'slider'),
("9. Commitment to Sustainable Waste Management (0-10):", 'slider'),
],
"Transport Method": [
("10. Type of Vehicle:\n\nSelect the primary type of vehicle used for transportation:", ["Truck", "Ship", "Train", "Airplane"],'multiselect'),
("11. Fuel Type:\n\nSelect the primary fuel type used in your vehicles:", ["Diesel", "Gasoline", "Natural Gas", "Electric"],'multiselect'),
("12. Average Vehicle Fuel Efficiency (MPG or L/Km):", 'text'),
("13. Frequency of Vehicle Trips (per month):", 'text'),
("14. Use of Alternative Transportation Methods:\n\nDo you incorporate alternative transportation methods, such as electric or hybrid vehicles, in your logistics operations?", 'text', ["Yes", "No"]),
("15. Describe any initiatives to reduce empty or partially filled vehicle trips to maximize efficiency:", 'text'),
("16. How does your company monitor and reduce idling time for vehicles to minimize fuel consumption and emissions?", 'text'),
("17. Equipped with fuel-efficient technologies, such as aerodynamic features or fuel-efficient tires? (Type 'yes' or 'no'):", 'text'),
("18. Describe any strategies or technologies used to track and manage vehicle emissions:", 'text'),
("19. Percentage of your vehicle fleet that meets the latest emission standards (e.g., Euro 6, EPA Tier 3):", 'number_input', {"min_value": 0, "max_value": 100}),
("20. How do you manage vehicle maintenance to ensure optimal fuel efficiency and emissions control? (Provide details):", 'text'),
("21. Average age of your vehicle fleet (in years):", 'number_input', {"min_value": 0}),
("22. How do you handle the disposal or recycling of end-of-life vehicles in an environmentally friendly manner? (Provide details):", 'text'),
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
#st.write(all_answers)
def calculate_Transport_score(answers):
score = 0
# Create concise textual contexts for each answer
contexts = [
(f"Primary vehicle: {answers.get('10', 'N/A')}.", 8), # vehicle type
(f"Fuel type: {answers.get('11', 'N/A')}.", 8), # fuel type
(f"Efficiency: {answers.get('12', '0')} mpg.", 7), # fuel efficiency
(f"Alternative transport: {answers.get('14', 'N/A')}.", 5), # alternative transportation
(f"Trip efficiency: {answers.get('15', 'N/A')}.", 5), # trip efficiency
(f"Anti-idling: {answers.get('16', 'N/A')}.", 4), # anti-idling
(f"Fuel-efficient tech: {answers.get('17', 'N/A')}.", 4), # fuel-efficient tech
(f"Emission standard: {answers.get('19', 'N/A')}%.", 9), # emission standards
(f"Vehicle age: {answers.get('21', 'N/A')} years.", 7), # vehicle age
(f"Vehicle disposal: {answers.get('22', 'N/A')}.", 5) # end-of-life vehicle handling
]
# Use get_binary_interpretations function
interpretations = get_binary_interpretations([context[0] for context in contexts])
# Adjust the score based on the binary interpretations
for interpretation, context in zip(interpretations, contexts):
if interpretation == 'yes':
score += context[1]
else:
score -= context[1] * 0.3 # Let's reduce the score but not as heavily as a positive increase
# Ensure the score remains between 0 and 100 after all calculations
score = max(0, min(100, score))
return score
def get_transport_report(all_answers):
"""Generates a Transport Method sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Transport Method questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Calculate score and consolidate data
score = calculate_Transport_score(all_answers)
# Consolidate data using list comprehension
data_keys = ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22']
data_labels = ["Type", "Fuel", "Avg. Efficiency", "Monthly Trips", "Alt. Transport Methods",
"Trip Efficiency", "Anti-Idling", "Fuel-Efficient Tech.", "Emission Mgmt.",
"Fleet Emission Std %", "Vehicle Maintenance", "Avg. Fleet Age", "Disposal/Recycling"]
consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(data_keys, data_labels)])
# Construct the prompt for the OpenAI API
prompt = f"""Based on the Transport Method Sustainability Report with a score of {score}/100, assess the details: "{consolidated_data}". Provide insights and recommendations."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Transport Method sustainability strategy advisor."},
{"role": "system", "content": "Evaluate the data and provide insights."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
evaluation_content = response.choices[0].message['content']
refined_report = f"**Transport Method Sustainability Report - Score: {score}/100**\n\n{consolidated_data}\n\n{evaluation_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_transport_sustainability_advice(all_answers, company_data):
"""Generates Transport Sustainability Strategy advice for a company based on its responses to a set of questions."""
# Simplify and consolidate answers and company data
consolidated_answers = ', '.join(f"{question}: {answer}" for question, answer in all_answers.items() if answer) # Exclude empty answers
country_of_operation = company_data.get('Country of Operation', 'N/A')
company_summary = company_data.get('Company Summary', 'N/A')
# Transportation themes summary
transport_themes_summary = """
**Transport Method Assessment Themes**:
- Vehicle type, fuel efficiency, and trip frequency.
- Adoption of alternative transport methods and load optimization strategies.
- Monitoring idling time, fuel-efficient tech, and emission management.
- Emission standards adherence, maintenance, fleet age, and eco-friendly vehicle disposal.
"""
# Form the prompt
prompt = f"""
Based on the provided company and transport assessment data, provide transportation sustainability advice:
**Company Info**:
- Country: {country_of_operation}
- Summary: {company_summary}
{transport_themes_summary}
**Assessment Data**: {consolidated_answers}
Offer actionable advice considering the company's specific context.
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a transportation sustainability strategy advisor."},
{"role": "user", "content": prompt}
],
max_tokens=800,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
def plot_histogram(data):
"""Plot a histogram of the responses."""
fig, ax = plt.subplots(figsize=(10,6))
# Plot histogram
data.hist(bins=11, range=(-0.5, 10.5), rwidth=0.8, ax=ax, color="#1f77b4", alpha=0.7)
# Plot mean
mean_val = data.mean()
ax.axvline(mean_val, color='red', linestyle='dashed', linewidth=1)
ax.text(mean_val+0.2, ax.get_ylim()[1]-1, f'Mean: {mean_val:.2f}', color = 'red')
# Set labels & title
ax.set_xlabel("Score")
ax.set_ylabel("Count")
ax.set_title("Distribution of Responses in 'Commitment and Strategy' Section")
# Improve appearance
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.get_yaxis().tick_left()
ax.yaxis.grid(True, linestyle='--', which='major', color='gray', alpha=.25)
plt.xticks(list(range(11))) # Setting x-ticks from 0 to 10
return fig
st.markdown("
"*3, unsafe_allow_html=True)
if st.button('Submit'):
section_key = "Commitment and Strategy"
questions = sections[section_key]
# Validate answers to avoid empty data
if not all_answers:
st.warning("No answers found!")
else:
# Create a DataFrame from the answers
df = pd.DataFrame.from_dict(all_answers, orient="index", columns=["Response"])
# Convert responses to numeric type
df["Response"] = pd.to_numeric(df["Response"], errors='coerce')
# Drop non-numeric rows if any
df = df.dropna(subset=["Response"])
# Ensure there's data to plot
if df.empty:
st.warning("No valid data to display!")
else:
# Check if there's variability in the data
if df["Response"].nunique() == 1:
st.warning("All responses are the same. Histogram would not be meaningful!")
else:
# Create and display the histogram
chart = plot_histogram(df["Response"])
st.pyplot(chart)
try:
# Use a spinner for generating advice
with st.spinner("Generating report and advice..."):
strategy = get_transport_sustainability_advice(all_answers, company_data)
report = get_transport_report(all_answers)
st.subheader("Transport Sustainability Strategy")
st.subheader("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
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=2f5m-jBf81Q"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page2():
st.write("Energizing Sustainability: Powering a Greener Future
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll evaluate your company's commitment to energy sustainability, progress in reducing energy-related impact, transparency in reporting energy performance to stakeholders, preparedness in managing energy efficiency and sustainability risks, and commitment to sustainable energy practices.")
st.write("
", unsafe_allow_html=True)
sections = {
"Energy Usage": [
("23. What is the primary source of energy used in your logistics operations?", 'selectbox', ["Electricity", "Diesel", "Natural Gas", "Other"]),
("24. Please specify the percentage of electricity consumption from renewable sources (e.g., solar, wind) in your logistics operations:", 'number_input', {"min_value": 0, "max_value": 100}),
("25. Average annual energy consumption for your logistics operations (in kWh or MMBtu):", 'number_input', {"min_value": 0}),
("26. Do you use energy-efficient technologies and practices (e.g., LED lighting, energy-efficient HVAC) in your facilities?", 'radio', ["Yes", "No"]),
("27. How do you manage energy consumption during non-operational hours to reduce energy waste? (Provide details):", 'text'),
("28. Describe any initiatives to optimize energy usage in transportation (e.g., route planning, load optimization):", 'text'),
("29. Are there any energy management systems or software in place to monitor and control energy usage? (Type 'yes' or 'no'):", 'text'),
("30. Energy Efficiency Measures:\n\nDescribe any specific energy efficiency measures or technologies you have implemented in your logistics operations:", 'text'),
("31. Renewable Energy Adoption:\n\nIf you are adopting renewable energy sources, please provide details about the types of renewable sources (e.g., solar panels, wind turbines) and their contribution to your energy supply:", 'text'),
("32. Energy Audits:\n\nHave you conducted energy audits or assessments to identify opportunities for energy savings and reduce energy consumption? (Type 'yes' or 'no'):", 'text'),
("33. Energy Reporting and Transparency:\n\nHow do you report and communicate your energy consumption and sustainability efforts to stakeholders, including clients and the public?", 'text'),
("34. Energy Goals and Targets:\n\nDo you have specific energy efficiency or renewable energy goals and targets in place for your logistics operations? If so, please provide details:", 'text'),
("35. Energy Monitoring and Data Analysis:\n\nHow frequently do you monitor and analyze energy usage data to identify trends and areas for improvement?", 'text'),
("36. Collaboration and Partnerships:\n\nAre you involved in any partnerships or collaborations to enhance energy efficiency and sustainability in the logistics and transportation sector?", 'text'),
("37. Challenges and Opportunities:\n\nDescribe any challenges you face in managing and reducing energy consumption, as well as any opportunities you see for further improvements:", 'text'),
("38. Future Energy Plans:\n\nWhat are your future plans or initiatives related to energy usage and sustainability within your logistics operations?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
# Initialize the summarization pipeline once
#summarizer = pipeline("summarization")
#summarizer = pipeline("summarization", model="facebook/bart-base")
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def calculate_energy_score(answers):
"""Calculate an energy sustainability score based on answers provided."""
score = 0
# Scoring based on primary source of energy used
primary_energy = answers.get("23", "").lower()
if "solar" in primary_energy or "wind" in primary_energy or "hydro" in primary_energy:
score += 10
elif "natural gas" in primary_energy:
score += 5
# Scoring based on renewable sources
renewable_percentage = answers.get("24", 0)
try:
renewable_percentage = float(renewable_percentage)
if renewable_percentage >= 80:
score += 10
elif 50 <= renewable_percentage < 80:
score += 7
elif 20 <= renewable_percentage < 50:
score += 3
except ValueError:
pass
# Check for energy-efficient technologies and practices
if "yes" in answers.get("26", "").lower():
score += 5
# Check for energy management during non-operational hours
if "yes" in answers.get("27", "").lower():
score += 5
# Scoring based on use of energy management systems or software
if "yes" in answers.get("29", "").lower():
score += 5
# Scoring based on renewable energy adoption
if "yes" in answers.get("31", "").lower():
score += 5
# Scoring based on conducting energy audits
if "yes" in answers.get("32", "").lower():
score += 5
# Scoring based on setting energy goals and targets
if "yes" in answers.get("34", "").lower():
score += 5
# Scoring based on energy monitoring and data analysis
if "yes" in answers.get("35", "").lower():
score += 5
# Scoring based on collaboration and partnerships for energy sustainability
if "yes" in answers.get("36", "").lower():
score += 5
return score
def get_energy_report(all_answers):
"""Generates an Energy Sustainability report based on responses to a questionnaire."""
score = calculate_energy_score(all_answers)
# Consolidate data
energy_source_info = f"Primary Energy Source: {all_answers.get('23', 'N/A')}, Renewable Source Percentage: {all_answers.get('24', 'N/A')}%, Avg. Annual Consumption: {all_answers.get('25', 'N/A')}"
efficiency_measures = f"Efficiency Tech.: {all_answers.get('26', 'N/A')}, Energy Management: {all_answers.get('29', 'N/A')}, Renewable Adoption: {all_answers.get('31', 'N/A')}"
consolidated_report = f"""
**Energy Usage Sustainability Report - Score: {score}/100**:
{energy_source_info}
{efficiency_measures}
"""
# Prompt for the OpenAI API
prompt = f"""
Based on the provided Energy Usage Sustainability Report and a score of {score} out of 100,
please provide insights, intuitions, and potential synergies derived from the given answers.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are an Energy sustainability strategy advisor."},
{"role": "system", "content": "Provide insights and actionable advice based on the given data."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.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):
"""Generates Energy Sustainability Strategy advice for a company based on its responses to a set of questions."""
formatted_answers = "\n".join(f"{question}: {answer}" for question, answer in all_answers.items())
# Consolidate company info
company_info = f"""
**Company Information:**
- Country: {company_data.get('Country of Operation', 'Vietnam')}
- Revenue: {company_data.get('Annual Revenue', '[Annual Revenue]')}
- Employees: {company_data.get('Number of Employees', '[Number of Employees]')}
- Operational Years: {company_data.get('Years in Operation', '[Years in Operation]')}
- Certifications: {', '.join(company_data.get('Selected Energy Certifications and Initiatives', ['[Certifications]']))}
"""
# Energy themes
energy_themes = """
**Energy Sustainability Assessment Themes**:
1. Primary energy source and renewable energy consumption.
2. Average annual energy consumption and efficiency measures.
3. Energy management practices and systems.
4. Renewable energy adoption and energy audits.
5. Reporting, collaboration, and energy challenges faced.
"""
prompt = f"""
To enhance energy sustainability within your company's operations, consider the following details:
{company_info}
{company_data.get('Company Summary', '[Company Summary]')}
{energy_themes}
Based on the above themes and the provided details:
'{formatted_answers}'
please provide actionable advice to enhance energy sustainability.
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are an energy sustainability strategy advisor."},
{"role": "user", "content": prompt}
],
max_tokens=900,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
st.markdown("
"*3, unsafe_allow_html=True)
if st.button('Submit'):
try:
# Use a spinner for generating advice
with st.spinner("Generating report and advice..."):
strategy = get_energy_sustainability_advice(all_answers, company_data)
report = get_energy_report(all_answers)
#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
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=olOjPWpYo4U"
st.video(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("Packaging Paradigm: Sustainable Solutions for a Greener Tomorrow
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll examine your company's sustainability practices related to packaging materials. We'll assess your commitment to sustainable packaging, reduction of packaging waste, and adoption of eco-friendly packaging solutions.")
st.write("
", unsafe_allow_html=True)
sections = {
"Packaging Materials": [
("39. Types of Packaging Materials Used:\n\nPlease select the types of packaging materials used in your logistics operations (select all that apply):", 'multiselect', ["Plastic", "Cardboard", "Wood", "Metal", "Paper", "Biodegradable", "Other"]),
("40. Percentage of Recyclable Packaging Materials:\n\nPlease specify the percentage of recyclable packaging materials used in your logistics operations (0-100%):", 'number_input', {"min_value": 0, "max_value": 100}),
("41. Use of Eco-Friendly Packaging:\n\nDo you use eco-friendly or sustainable packaging materials, such as biodegradable plastics or recycled materials? (Type 'yes' or 'no'):", 'text'),
("42. Packaging Design for Efficiency:\n\nDescribe any packaging design practices implemented to minimize material usage and reduce waste during transportation:", 'text'),
("43. Reusable Packaging:\n\nDo you utilize reusable packaging solutions to minimize single-use packaging materials? (Type 'yes' or 'no'):", 'text'),
("44. Packaging Waste Reduction Initiatives:\n\nDescribe any initiatives or strategies in place to reduce packaging waste and promote sustainability:", 'text'),
("45. Packaging Recycling Programs:\n\nDo you have recycling programs in place for used packaging materials within your logistics operations? (Type 'yes' or 'no'):", 'text'),
("46. Supplier Sustainability:\n\nDo you consider supplier sustainability practices and packaging choices in your procurement process? (Type 'yes' or 'no'):", 'text'),
("47. Life Cycle Analysis:\n\nHave you conducted a life cycle analysis of your packaging materials to assess their environmental impact? (Type 'yes' or 'no'):", 'text'),
("48. Compliance with Packaging Regulations:\n\nAre you compliant with local and international packaging regulations and standards related to sustainability and environmental impact? (Type 'yes' or 'no'):", 'text'),
("49. Packaging Transparency:\n\nHow transparent are you with customers and stakeholders about the sustainability and environmental impact of your packaging materials?", 'text'),
("50. Challenges and Opportunities:\n\nDescribe any challenges you face in implementing sustainable packaging practices and any opportunities you see for further improvements:", 'text'),
("51. Future Packaging Plans:\n\nWhat are your future plans or initiatives related to packaging materials and sustainability within your logistics operations?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
# Initialize the summarization pipeline once
#summarizer = pipeline("summarization")
#summarizer = pipeline("summarization", model="facebook/bart-base")
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
#st.write(all_answers)
def calculate_packaging_score(answers):
score = 0
# Handle special conditions:
if answers.get("39", "").lower() in ["paper", "cardboard", "glass", "bioplastic"]:
score += 10
if float(answers.get("40", "0")) > 75:
score += 10
# Questions to evaluate for binary responses (Yes/No based)
binary_questions = {
"41": 10,
"42": 10,
"43": 10,
"44": 10,
"45": 10,
"46": 5,
"47": 5,
"48": 5,
"49": 5,
"50": 5,
"51": 5
}
# Determine interpretations for the non-direct questions
texts_to_evaluate = [answers.get(q, "") for q in binary_questions.keys() if answers.get(q, "").lower() != 'yes']
interpretations = get_binary_interpretations(texts_to_evaluate)
# Score based on the determined interpretations
for q, interpretation in zip(binary_questions.keys(), interpretations):
if interpretation == 'yes':
score += binary_questions[q]
return min(score, 100)
def get_Packaging_Materials_report(all_answers):
"""Generates a Packaging Materials sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Packaging Materials questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Calculate score and consolidate data
score = calculate_packaging_score(all_answers)
# Consolidate data using list comprehension
data_keys = ["39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51"]
data_labels = ["Materials Used", "Recyclable %", "Eco-Friendly", "Design Efficiency",
"Reusable Practices", "Waste Reduction", "Recycling Programs",
"Supplier Considerations", "Life Cycle Analysis", "Regulation Compliance",
"Transparency", "Challenges/Opportunities", "Future Plans"]
consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(data_keys, data_labels)])
# Construct the prompt for the OpenAI API
prompt = f"""Based on the Packaging Materials Sustainability Report with a score of {score}/100, assess the details: "{consolidated_data}". Provide insights and recommendations."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Packaging Materials sustainability strategy advisor."},
{"role": "system", "content": "Evaluate the data and provide insights."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
evaluation_content = response.choices[0].message['content']
refined_report = f"**Packaging Materials Sustainability Report - Score: {score}/100**\n\n{consolidated_data}\n\n{evaluation_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_Packaging_Materials_advice(all_answers, company_data):
"""Generates Packaging Materials sustainability Strategy for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the Packaging Materials sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the Packaging Materials strategy advice.
"""
# Consolidate the data for Packaging Materials using list comprehension
data_keys = ["39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51"]
data_labels = ["Materials", "Recyclable %", "Eco-Friendly", "Design Efficiency",
"Reusable", "Waste Reduction", "Recycling",
"Supplier", "Life Cycle", "Regulations",
"Transparency", "Challenges", "Future Plans"]
consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(data_keys, data_labels)])
# Construct the prompt for the OpenAI API
prompt = f"""
To enhance packaging sustainability practices, consider this:
**Company Information:**
Country: {company_data.get('Country of Operation', 'N/A')}
Revenue: {company_data.get('Annual Revenue', 'N/A')}
Employees: {company_data.get('Number of Employees', 'N/A')}
Years: {company_data.get('Years in Operation', 'N/A')}
Certifications: {', '.join(company_data.get('Selected Cargo Certifications and Initiatives', ['N/A']))}
**Summary:**
{company_data.get('Company Summary', 'N/A')}
**Packaging Data:**
{consolidated_data}
Based on the above details, provide actionable advice to enhance packaging sustainability without speculation.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Packaging Materials sustainability strategy advisor."},
{"role": "system", "content": "Provide advice relevant to the company's packaging sustainability based on the details given."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
st.markdown("
"*3, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_Packaging_Materials_advice(all_answers, company_data)
report = get_Packaging_Materials_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Materials Sustainability Report")
st.write(report)
st.download_button(
label="Download Materials Sustainability Report",
data=report,
file_name='Materials_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Materials Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Materials Sustainability Strategy",
data=strategy,
file_name='Materials_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=IfF7QO7F_p0"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page4():
st.write("Cargo Consciousness: Navigating Sustainable Logistics
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll delve into your company's sustainability practices related to cargo handling. We'll assess your commitment to efficient cargo handling and the adoption of sustainable cargo handling technologies.")
st.write("
", unsafe_allow_html=True)
sections = {
"Cargo Handling": [
("52. What types of cargo do you typically handle in your logistics operations? (Select all that apply)", 'multiselect', ["Containerized Cargo", "Bulk Cargo", "Liquid Cargo", "Refrigerated Cargo", "Hazardous Cargo", "Other"]),
("53. Do you have specific processes or equipment in place to handle hazardous or environmentally sensitive cargo safely?", 'radio', ["Yes", "No"]),
("54. Describe any initiatives to reduce emissions and environmental impact during cargo handling operations:", 'text'),
("55. How do you manage and reduce the release of dust and particulate matter during bulk cargo handling?", 'text'),
("56. Are there any noise reduction measures or technologies implemented during cargo handling activities?", 'text'),
("57. Describe any efforts to minimize the impact on aquatic ecosystems during cargo handling near water bodies or ports:", 'text'),
("58. What methods or technologies do you use to minimize the risk of cargo spills or leaks during handling?", 'text'),
("59. Are there any practices or equipment used to optimize cargo storage and minimize space wastage?", 'text'),
("60. How do you handle cargo packaging to minimize waste and environmental impact?", 'text'),
("61. Cargo Handling Goals:\n\nDo you have specific goals or targets related to the sustainability of cargo handling operations? If so, please provide details:", 'text'),
("62. Communication and Transparency:\n\nHow do you communicate your efforts and progress in sustainable cargo handling to stakeholders, including customers and the public?", 'text'),
("63. Cargo Handling Audits:\n\nHave you conducted audits or assessments to evaluate the sustainability of your cargo handling practices and identify areas for improvement?", 'radio', ["Yes", "No"]),
("64. Future Sustainability Plans:\n\nWhat are your future plans or initiatives regarding the sustainability of cargo handling in logistics?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
# Initialize the summarization pipeline once
#summarizer = pipeline("summarization")
#summarizer = pipeline("summarization", model="facebook/bart-base")
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def cargo_sustainability_score(all_answers):
"""Compute a sustainability score for cargo handling based on the provided answers.
Args:
all_answers: A dictionary of answers to the Cargo Handling questions.
Returns:
A float sustainability score (0 to 100).
"""
total_score = 0
# Score allocation for each aspect of cargo handling sustainability
score_weights = {
"52": 5, # Types of Cargo Handled
"53": 15, # Processes for Hazardous Cargo
"54": 10, # Emission Reduction Initiatives
"55": 8, # Managing Dust and Particulate Release
"56": 7, # Noise Reduction Measures
"57": 10, # Impact Minimization on Aquatic Ecosystems
"58": 15, # Technologies to Minimize Spills/Leaks
"59": 5, # Optimized Cargo Storage Practices
"60": 10, # Eco-friendly Cargo Packaging
"61": 5, # Sustainability Goals for Cargo Handling
"62": 5, # Communication and Transparency Measures
"63": 3, # Cargo Handling Audits Conducted
"64": 2 # Future Sustainability Plans for Cargo
}
# Positive keywords which suggest a higher level of sustainability
positive_keywords = [
"eco-friendly", "green", "sustainable", "renewable", "low emission",
"efficient", "optimized", "minimized", "reduced", "audit", "goal",
"plan", "certified", "standard", "practice", "initiative", "measure",
"strategy"
]
# Analyze each answer and allocate score
for key, value in all_answers.items():
if key in score_weights:
# The presence of positive keywords will add to the score
for keyword in positive_keywords:
if keyword in value.lower():
total_score += score_weights[key] / len(positive_keywords)
return min(total_score, 100) # Cap the score at 100
def get_cargo_report(all_answers):
"""Generates a Cargo Handling sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Cargo Handling questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Calculate score and consolidate data
score = cargo_sustainability_score(all_answers)
# Consolidate data using list comprehension
data_keys = ['52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64']
data_labels = ["Types of Cargo", "Processes for Hazardous Cargo", "Emission Reduction", "Dust/Particulate Mgmt.",
"Noise Reduction", "Aquatic Ecosystem Impact", "Spill Prevention", "Cargo Storage",
"Eco-friendly Packaging", "Goals", "Communication", "Audits", "Future Plans"]
consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(data_keys, data_labels)])
# Construct the prompt for the OpenAI API
prompt = f"""Based on the Cargo Handling Sustainability Report with a score of {score}/100, assess the details: "{consolidated_data}". Provide insights and recommendations."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Cargo Handling sustainability strategy advisor."},
{"role": "system", "content": "Evaluate the data and provide insights."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
evaluation_content = response.choices[0].message['content']
refined_report = f"**Cargo Handling Sustainability Report - Score: {score}/100**\n\n{consolidated_data}\n\n{evaluation_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_cargo_sustainability_advice(all_answers, company_data):
"""Generates Cargo Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the cargo sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the cargo sustainability strategy advice.
"""
# Simplify and consolidate answers and company data
consolidated_answers = ', '.join(f"{question}: {answer}" for question, answer in all_answers.items() if answer) # Exclude empty answers
country_of_operation = company_data.get('Country of Operation', 'N/A')
company_summary = company_data.get('Company Summary', 'N/A')
certifications = ', '.join(company_data.get('Selected Cargo Certifications and Initiatives', ['N/A']))
# Form the prompt
prompt = f"""
Provide cargo sustainability advice based on the following data:
**Company Info**:
- Country: {country_of_operation}
- Certifications: {certifications}
- Summary: {company_summary}
**Cargo Sustainability Assessment Themes**:
1. Cargo Types & Safety
2. Environmental Initiatives
3. Operational Efficiency
4. Strategic Planning & Transparency
5. Risk Minimization of Cargo Spills or Leaks
6. Audits or Assessments of Sustainable Cargo Handling Practices
**Assessment Data**: {consolidated_answers}
Offer actionable advice considering the company's specific context.
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a cargo sustainability strategy advisor."},
{"role": "user", "content": prompt}
],
max_tokens=800,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
st.markdown("
"*3, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_cargo_sustainability_advice(all_answers, company_data)
report = get_cargo_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Cargo Sustainability Report")
st.write(report)
st.download_button(
label="Download Cargo Sustainability Report",
data=report,
file_name='Cargo_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Cargo Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Cargo Sustainability Strategy",
data=strategy,
file_name='Cargo_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=d5_U16FbpQs"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page5():
st.write("Emission Excellence: Paving the Way to Sustainability
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", 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("
", unsafe_allow_html=True)
sections = {
"Emission Reduction Initiatives": [
("65. What types of emissions are generated by your logistics operations? (Select all that apply)", 'multiselect', ["CO2", "NOx", "SOx", "Particulate Matter", "Volatile Organic Compounds (VOCs)", "Other"]),
("66. Do you have emissions reduction targets in place for your logistics operations?", 'radio', ["Yes", "No"]),
("67. Describe any technologies or strategies you have implemented to reduce CO2 emissions in your logistics operations:", 'text'),
("68. Are there measures in place to reduce NOx and SOx emissions from your transportation equipment or facilities?", 'text'),
("69. Describe initiatives to minimize particulate matter emissions during cargo handling or transportation:", 'text'),
("70. Have you adopted fuel-efficient technologies or alternative fuels to reduce emissions in your logistics fleet?", 'text'),
("71. How do you address emissions from refrigerated cargo containers, if applicable?", 'text'),
("72. Describe any efforts to reduce emissions from idling vehicles and equipment in your logistics operations:", 'text'),
("73. Do you have a strategy for reducing emissions from lighting, heating, and cooling systems in your facilities?", 'text'),
("74. Are there any renewable energy sources (e.g., solar panels) used to power your logistics facilities?", 'text'),
("75. How do you manage and reduce emissions from equipment maintenance and repair activities?", 'text'),
("76. Emission Reduction Goals:\n\nDo you have specific goals or targets related to emission reduction in logistics operations? If so, please provide details:", 'text'),
("77. Communication and Transparency:\n\nHow do you communicate your efforts and progress in emission reduction to stakeholders?", 'text'),
("78. Emission Reduction Audits:\n\nHave you conducted audits or assessments to evaluate emission reduction efforts and identify areas for improvement?", 'radio', ["Yes", "No"]),
("79. Future Emission Reduction Plans:\n\nWhat are your future plans or initiatives regarding emission reduction in logistics?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
# Initialize the summarization pipeline once
#summarizer = pipeline("summarization")
#summarizer = pipeline("summarization", model="facebook/bart-base")
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def calculate_emission_score(answers):
score = 0
# Directly scoreable answers using the get method to avoid KeyError:
if answers.get("66", "").lower() == "yes":
score += 10
if answers.get("70", "").lower() == "yes":
score += 10
if answers.get("74", "").lower() == "yes":
score += 10
if answers.get("77", "").lower() == "yes":
score += 5
if answers.get("78", "").lower() == "yes":
score += 5
# Questions to evaluate using get_binary_interpretations function:
questions_to_evaluate = {
"67": 10, # Strategies for CO2 Emissions Reduction
"68": 10, # Measures for NOx and SOx Emissions Reduction
"69": 10, # Initiatives to Reduce Particulate Matter Emissions
"71": 10, # Emissions Management from Refrigerated Cargo
"72": 10, # Efforts to Reduce Emissions from Idling Vehicles and Equipment
"73": 10, # Emissions Reduction Strategy for Facility Systems
"75": 5, # Management of Emissions from Equipment Maintenance
"76": 5, # Emission Reduction Goals
"79": 5 # Future Plans for Emission Reduction
}
# Use the get method to fetch values from the answers dictionary, and then use get_binary_interpretations function:
texts_to_evaluate = [answers.get(q, "") for q in questions_to_evaluate.keys()]
interpretations = get_binary_interpretations(texts_to_evaluate)
# Add scores based on the interpretations:
for q, interpretation in zip(questions_to_evaluate.keys(), interpretations):
if interpretation == 'yes':
score += questions_to_evaluate[q]
return min(score, 100)
def get_Emission_initiative_report(all_answers):
"""Generates an Emission Reduction Initiatives sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Emission Reduction Initiatives questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Calculate the score
score = calculate_emission_score(all_answers)
# Consolidate the most essential data points using the .get() method
data_keys = ['65', '66', '67', '68', '70', '71', '72', '74', '75', '76', '78', '79']
data_labels = ["Emissions Types", "Reduction Targets", "CO2 Strategy", "NOx/SOx Measures",
"Fuel-Efficient Tech.", "Refrigerated Cargo Management", "Idling Reduction",
"Renewable Energy", "Equipment Emission Management", "Reduction Goals",
"Audit Conduction", "Future Plans"]
consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(data_keys, data_labels)])
# Construct the prompt for OpenAI API
prompt = f"""Based on the Emission Reduction Initiatives Report with a score of {score}/100, assess the details: "{consolidated_data}". Provide insights and recommendations."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are an Emission Reduction Initiatives sustainability strategy advisor."},
{"role": "system", "content": "Evaluate the data and provide insights."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
evaluation_content = response.choices[0].message['content']
refined_report = f"**Emission Reduction Initiatives Report - Score: {score}/100**\n\n{consolidated_data}\n\n{evaluation_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_emission_sustainability_advice(all_answers, company_data):
"""Generates Emission Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the emission sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the emission sustainability strategy advice.
"""
# Consolidate the most essential data points for emissions using the .get() method
data_keys = ['65', '66', '67', '70', '71', '72', '74', '76', '78']
data_labels = ["Emissions Types", "Reduction Targets", "CO2 Strategy",
"Fuel-Efficient Tech.", "Refrigerated Cargo Management", "Idling Reduction",
"Renewable Energy", "Reduction Goals", "Audit Conduction"]
consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(data_keys, data_labels)])
# Construct the prompt for OpenAI API using the .get() method for company data
prompt = f"""For a company operating in {company_data.get('Country of Operation', 'Country')} with an annual revenue of {company_data.get('Annual Revenue', '[Annual Revenue]')} and employing {company_data.get('Number of Employees', '[Number of Employees]')} for {company_data.get('Years in Operation', '[Years in Operation]')} years, assess the emission sustainability details: "{consolidated_data}". Provide actionable advice considering the company's summary: {company_data.get('Company Summary', '[Company Summary]')}."""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are an emission sustainability strategy advisor."},
{"role": "system", "content": "Provide advice based on the company data and emission details provided."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
st.markdown("
"*2, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_emission_sustainability_advice(all_answers, company_data)
report = get_Emission_initiative_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Emission Reduction Initiatives Sustainability Report")
st.write(report)
st.download_button(
label="Download EmissionSustainability Report",
data=report,
file_name='Emission_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Emission Reduction Initiatives Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Emission Sustainability Strategy",
data=strategy,
file_name='Emission_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=RYzcE1OiwRE"
st.video(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("Waste Warriors: Navigating Sustainable Logistics
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", 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("
", 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. Describe your waste reduction and recycling initiatives for logistics operations:", 'text'),
("82. How do you segregate and dispose of different types of waste (e.g., hazardous, non-hazardous, recyclable) at your facilities?", 'text'),
("83. Are there measures to minimize waste generation in cargo handling or packaging processes?", 'text'),
("84. Describe any initiatives for reusing or repurposing materials and equipment to reduce waste:", 'text'),
("85. How do you ensure the proper disposal of hazardous materials and chemicals used in logistics operations?", 'text'),
("86. Are waste reduction and recycling efforts communicated to logistics employees? (Type 'yes' or 'no'):", 'text'),
("87. What is the percentage of waste that is recycled or diverted from landfills in your logistics operations?", 'number_input', {"min_value": 0, "max_value": 100}),
("88. Describe any waste audits or assessments conducted to evaluate waste management practices:", 'text'),
("89. Are there plans to improve waste management and recycling efforts in the future?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def calculate_waste_management_score(answers):
score = 0
# Direct scoring using the .get() method for safeguarding
if answers.get("80", "").lower() == "yes":
score += 15
# For percentage-based scoring:
try:
recycling_percentage = float(answers.get("87", "0"))
score += min(10, 0.10 * recycling_percentage)
except ValueError:
pass
# Interpretive scoring using the .get() method
questions_for_interpretation = ["81", "82", "83", "84", "85", "86", "88", "89"]
weightages = [15, 10, 10, 10, 10, 10, 5, 5]
texts_to_evaluate = [answers.get(q, "") for q in questions_for_interpretation] # Safeguarding with .get()
interpretations = get_binary_interpretations(texts_to_evaluate)
for interpretation, weight in zip(interpretations, weightages):
if interpretation == 'yes':
score += weight
return min(score, 100) # Ensure the score does not exceed 100
def get_Waste_Management_report(all_answers):
"""Generates a Waste Management sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Waste Management questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Calculate sustainability score
score = calculate_waste_management_score(all_answers)
# Create a brief version of the report for the prompt using the .get() method
brief_report = f"""
**Waste Management Sustainability Score**: {score}/100
Key Highlights:
- Presence of a Waste Management Plan: {all_answers.get("80", "N/A")}
- Waste Reduction and Recycling Initiatives: {all_answers.get("81", "N/A")}
- Management of Hazardous Materials Disposal: {all_answers.get("85", "N/A")}
- Percentage of Waste Recycled or Diverted: {all_answers.get("87", "N/A")}%
- Future Plans for Waste Management: {all_answers.get("89", "N/A")}
"""
# Construct the prompt for the OpenAI API
prompt = f"""
Given the Waste Management Sustainability Score and key highlights, please provide insights, intuitions, and potential synergies derived from the answers. Also, suggest areas of improvement based on the presented information:
{brief_report}
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Waste Management sustainability strategy advisor."},
{"role": "system", "content": "Provide insights and areas of improvement based on the presented score and highlights."},
{"role": "user", "content": prompt}
],
max_tokens=500, # Lower the token limit to save costs
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
evaluation_content = response.choices[0].message['content']
# Combine the full report and the evaluation for the final report
refined_report = f"{brief_report}\n\n{evaluation_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_waste_management_sustainability_advice(all_answers, company_data):
"""Generates Waste Management Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the waste management sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the waste management sustainability strategy advice.
"""
# Consolidate the key highlights for the prompt using the .get() method
key_highlights = f"""
Key Waste Management Highlights:
- Presence of a Waste Management Plan: {all_answers.get("80", "N/A")}
- Waste Reduction and Recycling Initiatives: {all_answers.get("81", "N/A")}
- Percentage of Waste Recycled/Diverted: {all_answers.get("87", "N/A")}%
- Waste Audits/Assessments: {all_answers.get("88", "N/A")}
- Future Plans for Waste Management: {all_answers.get("89", "N/A")}
"""
# Consolidate the company info for the prompt using the .get() method
company_info = f"""
**Company Info**:
Country: {company_data.get('Country of Operation', 'Country')}
Employees: {company_data.get('Number of Employees', '[Number of Employees]')}
Certifications: {', '.join(company_data.get('Selected Waste Management Certifications and Initiatives', ['[Certifications]']))}
Summary: {company_data.get('Company Summary', '[Company Summary]')}
"""
# Construct the prompt for the OpenAI API
prompt = f"""
Given the company details and key waste management highlights, provide actionable advice to enhance waste management sustainability while avoiding speculative or unfounded recommendations:
{company_info}
{key_highlights}
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a waste management sustainability strategy advisor."},
{"role": "system", "content": "Make the response relevant to the company information and key highlights provided."},
{"role": "user", "content": prompt}
],
max_tokens=700, # Lower the token limit to save costs
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
st.markdown("
"*2, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_waste_management_sustainability_advice(all_answers, company_data)
report = get_Waste_Management_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Waste Management Sustainability Report")
st.write(report)
st.download_button(
label="Download Waste Management Sustainability Report",
data=report,
file_name='Waste_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Waste Management Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Waste Sustainability Strategy",
data=strategy,
file_name='Waste_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=DmFGsxLcT6k"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page7():
st.write("Navigating Environmental Risks: A Sustainable Approach
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll explore your company's risk management practices in the context of environmental sustainability. We'll assess your preparedness to manage climate change risks and other sustainability-related risks to ensure a resilient and sustainable future.")
st.write("
", unsafe_allow_html=True)
sections = {
"Risk Management": [
("90. Have you identified environmental risks associated with your logistics operations? (Type 'yes' or 'no'):", 'text'),
("91. Please describe the key environmental risks identified and their potential impacts:", 'text'),
("92. Do you have a risk assessment and management plan in place to address environmental risks?", 'radio', ["Yes", "No"]),
("93. Provide details on your risk assessment and management plan for environmental risks:", 'text'),
("94. How frequently is the risk assessment and management plan reviewed and updated?", 'text'),
("95. Have you established protocols for responding to environmental incidents and emergencies?", 'radio', ["Yes", "No"]),
("96. Describe the protocols for responding to environmental incidents and emergencies:", 'text'),
("97. What measures are in place to minimize the likelihood of environmental incidents?", 'text'),
("98. How do you monitor and report environmental incidents or near-misses?", 'text'),
("99. Are employees trained in environmental risk management and incident response?", 'radio', ["Yes", "No"]),
("100. Describe any external audits or assessments conducted related to environmental risk management:", 'text'),
("101. Are there plans to enhance environmental risk management in the future?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def calculate_risk_management_score(answers):
score = 0
# Handle special conditions using the .get() method:
if answers.get("90", "").lower() == 'yes':
score += 5
if answers.get("92", "").lower() == 'yes':
score += 10
if answers.get("95", "").lower() == 'yes':
score += 10
if answers.get("98", "").lower() == 'yes':
score += 10
if answers.get("99", "").lower() == 'yes':
score += 5
if answers.get("100", "").lower() == 'yes':
score += 5
# Questions to evaluate for textual response quality:
textual_responses = {
"91": 10, # Key environmental risks and potential impacts
"93": 10, # Details on the risk assessment and management plan
"96": 10, # Description of protocols for environmental incidents
"97": 10, # Measures to minimize environmental incidents
"101": 10 # Future plans for enhancing risk management
}
# Determine interpretations for the non-direct questions using .get() method:
texts_to_evaluate = [answers.get(q, "") for q in textual_responses.keys()]
interpretations = get_binary_interpretations(texts_to_evaluate)
# Score based on the determined interpretations
for q, interpretation in zip(textual_responses.keys(), interpretations):
if interpretation == 'yes':
score += textual_responses[q]
# For Frequency of Review and Update of the Risk Plan:
frequency = answers.get("94", "").lower()
if frequency in ["annually", "yearly"]:
score += 5
elif frequency in ["quarterly", "monthly"]:
score += 10
elif frequency == "bi-annually":
score += 3
elif frequency == "weekly":
score += 15
return min(score, 100)
def get_risk_management_report(all_answers):
"""Generates a Risk Management sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Risk Management questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Consolidate the report details using the .get() method
report = f"""
**Risk Management Sustainability Report**:
- **Environmental Risks Identified**: {all_answers.get("90", "N/A")}
- **Key Risks and Their Impacts**: {all_answers.get("91", "N/A")}
- **Risk Assessment and Management Plan**: {all_answers.get("92", "N/A")}
- **Review Frequency of the Risk Plan**: {all_answers.get("94", "N/A")}
- **Protocols for Environmental Incidents**: {all_answers.get("95", "N/A")}
- **Measures to Minimize Incidents**: {all_answers.get("97", "N/A")}
- **Monitoring of Incidents/Near-misses**: {all_answers.get("98", "N/A")}
- **Employee Training on Risk Management**: {all_answers.get("99", "N/A")}
- **External Risk Management Audits**: {all_answers.get("100", "N/A")}
- **Future Plans for Risk Management**: {all_answers.get("101", "N/A")}
"""
# Assuming a separate function calculate_risk_management_score() exists
risk_management_score = calculate_risk_management_score(all_answers)
# Construct the prompt for OpenAI API
insights_prompt = f"""
Based on the provided answers, the sustainability score for Risk Management is {risk_management_score}/100.
Please provide insights, intuitions, and potential recommendations based on the given answers:
{report}
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Risk Management sustainability strategy advisor."},
{"role": "system", "content": "Provide insights based on the calculated risk management score and the details from the report."},
{"role": "user", "content": insights_prompt}
],
max_tokens=800,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
insights_content = response.choices[0].message['content']
refined_report = f"{report}\n\n**Risk Management Score**: {risk_management_score}/100\n\n{insights_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_risk_management_sustainability_advice(all_answers, company_data):
"""Generates Risk Management Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the risk management sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the risk management sustainability strategy advice.
"""
# Consolidate answers for the prompt using .get() method
formatted_answers = "\n".join(f"{question}: {all_answers.get(question, 'N/A')}" for question in all_answers.keys())
# Construct the prompt for the OpenAI API
prompt = f"""
Given the risk management sustainability assessment of a company operating in {company_data.get('Country of Operation', 'Country')} with {company_data.get('Number of Employees', '[Number of Employees]')} employees and the following certifications {', '.join(company_data.get('Selected Risk Management Certifications and Initiatives', ['[Certifications]']))}, provide actionable advice:
{formatted_answers}
**Key Thematic Areas:**
1. Identification and Assessment of Environmental Risks
2. Development and Review of Risk Management Plan
3. Protocols for Addressing Environmental Incidents
4. Employee Training and Awareness on Risk Management
Ensure the advice is specific and avoids speculative recommendations.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a risk management sustainability strategy advisor focusing on key thematic areas."},
{"role": "system", "content": "Tailor the response to the company's information and assessment answers."},
{"role": "user", "content": prompt}
],
max_tokens=600, # Further reduced to save tokens
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
st.markdown("
"*2, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_risk_management_sustainability_advice(all_answers, company_data)
report = get_risk_management_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Risk Management Sustainability Report")
st.write(report)
st.download_button(
label="Download Risk Management Sustainability Report",
data=report,
file_name='Risk_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Risk Management Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Risk Management Sustainability Strategy",
data=strategy,
file_name='Risk_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=CjF0sPYBiPk"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page8():
st.write("Green Compliance: Meeting Environmental Standards
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll evaluate your company's compliance with environmental sustainability regulations, standards, and best practices. We'll assess your adherence to legal and industry requirements to ensure a sustainable and responsible approach to logistics operations.")
st.write("
", unsafe_allow_html=True)
sections = {
"Compliance": [
("102. Are you aware of the environmental regulations and standards relevant to your logistics operations? (Type 'yes' or 'no'):", 'text'),
("103. Provide details on the specific environmental regulations and standards that apply to your operations:", 'text'),
("104. Have you conducted an environmental compliance assessment to ensure adherence to regulations?", 'radio', ["Yes", "No"]),
("105. Describe the process and findings of the environmental compliance assessment:", 'text'),
("106. Are there designated personnel responsible for ensuring environmental compliance?", 'radio', ["Yes", "No"]),
("107. Provide details on the roles and responsibilities of personnel responsible for compliance:", 'text'),
("108. How do you monitor and document compliance with environmental regulations and standards?", 'text'),
("109. Have there been any instances of non-compliance with environmental regulations in the past year?", 'radio', ["Yes", "No"]),
("110. Describe actions taken to address instances of non-compliance and prevent recurrence:", 'text'),
("111. Are there plans to improve environmental compliance in the future?", 'text'),
("112. How do you engage with regulatory authorities and stay informed about changing regulations?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def calculate_compliance_score(all_answers):
"""Calculate a compliance score based on questionnaire answers."""
def is_positive_response(response):
"""Check if the given response is positive."""
return response.lower() in ["yes", "true", "positive"]
def calculate_compliance_score(all_answers):
"""Calculate a compliance score based on questionnaire answers."""
# Initial score
score = 0
# Scoring based on awareness of regulations
if is_positive_response(all_answers.get("102", "N/A")):
score += 15
# Scoring based on assessment conduct
if is_positive_response(all_answers.get("104", "N/A")):
score += 10
# Scoring for having dedicated compliance personnel
if is_positive_response(all_answers.get("106", "N/A")):
score += 10
# Scoring based on monitoring and documentation
if is_positive_response(all_answers.get("108", "N/A")):
score += 10
# Penalizing for non-compliance instances. Assuming the response is numerical.
try:
non_compliance_instances = int(all_answers.get("109", 0))
score -= non_compliance_instances * 2 # assuming a 2-point penalty for each instance
except ValueError: # in case of non-numeric input
pass
# Scoring for future plans for environmental compliance
if is_positive_response(all_answers.get("111", "N/A")):
score += 10
# Scoring for engagement with regulatory authorities
if is_positive_response(all_answers.get("112", "N/A")):
score += 10
# Ensure the score remains between 0 and 100
score = max(0, min(score, 100))
return score
def get_compliance_report(all_answers):
"""Generates a Compliance Sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Compliance questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Calculate compliance score
compliance_score = calculate_compliance_score(all_answers)
# Consolidate report details
compliance_details = {
"102": "Awareness of Relevant Environmental Regulations",
"103": "Specific Environmental Regulations and Standards",
"104": "Compliance Assessment Conduct",
"105": "Findings from Compliance Assessment",
"106": "Designated Compliance Personnel",
"107": "Roles of Compliance Personnel",
"108": "Compliance Monitoring and Documentation",
"109": "Instances of Non-compliance (Past Year)",
"110": "Actions for Non-compliance",
"111": "Future Plans for Compliance",
"112": "Engagement with Regulatory Authorities"
}
consolidated_data = "\n".join([f"- **{desc}**: {all_answers.get(key, 'N/A')}" for key, desc in compliance_details.items()])
# Construct the prompt for OpenAI API
prompt = f"""
Based on the Environmental Compliance Sustainability Report with a score of {compliance_score}/100, assess the details:
{consolidated_data}
Provide insights, recommendations, and areas of improvement.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a Compliance Sustainability strategy advisor."},
{"role": "system", "content": "Evaluate the data and provide insights, recommendations, and areas of improvement."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
insights_content = response.choices[0].message['content']
# Construct the refined report
refined_report = f"**Environmental Compliance Sustainability Report - Score: {compliance_score}/100**\n\n{consolidated_data}\n\n{insights_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_compliance_sustainability_advice(all_answers, company_data):
"""Generates Compliance Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the compliance sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the compliance sustainability strategy advice.
"""
# Consolidate key compliance data points
key_points = {
"102": "Awareness of Regulations",
"103": "Specific Regulations & Standards",
"104": "Compliance Assessment Conduct",
"106": "Dedicated Compliance Personnel",
"108": "Compliance Monitoring & Documentation",
"109": "Non-compliance Instances (Past Year)",
"111": "Engagement with Regulatory Authorities"
}
compliance_highlights = ', '.join([f"{desc}: {all_answers.get(key, 'N/A')}" for key, desc in key_points.items()])
# Construct the prompt for the OpenAI API
prompt = f"""For a company operating in {company_data.get('Country of Operation', 'Country')} with {company_data.get('Number of Employees', '[Number of Employees]')} employees, and having certifications {', '.join(company_data.get('Selected Compliance Certifications and Initiatives', ['[Certifications]']))}, assess the compliance details: "{compliance_highlights}". Provide actionable advice considering the company's operations and the specific compliance challenges in its industry."""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a compliance sustainability strategy advisor."},
{"role": "system", "content": "Provide actionable advice tailored to the company's data and compliance details."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
st.markdown("
"*2, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_compliance_sustainability_advice(all_answers, company_data)
report = get_compliance_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Compliance Sustainability Report")
st.write(report)
st.download_button(
label="Download Compliance Sustainability Report",
data=report,
file_name='Compliance_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Compliance Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Compliance Sustainability Strategy",
data=strategy,
file_name='Compliance_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=lK3DPZHYc3w"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page9():
st.write("Eco-Evolution: Innovations in Environmental Sustainability
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll explore your company's dedication to innovation and continuous improvement in environmental sustainability. We'll assess your efforts to stay at the forefront of sustainable logistics practices, adopt cutting-edge technologies, and continuously refine your processes for a greener and more efficient future.")
st.write("
", unsafe_allow_html=True)
sections = {
"Innovation and Continuous Improvement": [
("113. Does your organization have a dedicated team or department focused on innovation and sustainability?", 'radio', ["Yes", "No"]),
("114. Describe the role and responsibilities of the innovation and sustainability team or department:", 'text'),
("115. Have you implemented innovative technologies or practices to reduce the environmental impact of your logistics operations?", 'radio', ["Yes", "No"]),
("116. Please provide examples of innovative technologies or practices implemented:", 'text'),
("117. Are you continuously monitoring and evaluating the effectiveness of your environmental initiatives?", 'radio', ["Yes", "No"]),
("118. Describe the methods and metrics used for monitoring and evaluating environmental initiatives:", 'text'),
("119. Have you set specific targets and goals for reducing your environmental footprint?", 'radio', ["Yes", "No"]),
("120. Please specify your environmental targets and goals:", 'text'),
("121. How do you engage with employees and stakeholders to gather ideas and feedback for sustainability and innovation?", 'text'),
("122. Are you investing in research and development related to sustainable logistics practices?", 'radio', ["Yes", "No"]),
("123. Describe any ongoing research and development projects related to sustainability and logistics:", 'text'),
("124. Do you collaborate with external partners, research institutions, or industry associations to drive innovation in sustainability?", 'radio', ["Yes", "No"]),
("125. Please provide details of any collaborative efforts to drive sustainability innovation:", 'text'),
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def is_positive_response(response):
"""Check if the given response is positive."""
return response.lower() in ["yes", "true", "positive"]
def calculate_innovation_score(all_answers):
"""Calculates a sustainability score for Innovation and Continuous Improvement based on the answers provided.
Args:
all_answers: A dictionary of answers to the Innovation and Continuous Improvement questions.
Returns:
A score out of 100 indicating the sustainability score for innovation.
"""
score = 0
# Scoring based on presence of a dedicated team for innovation
if is_positive_response(all_answers.get("113", "N/A")):
score += 15
# Scoring based on implementation of new technologies
if is_positive_response(all_answers.get("115", "N/A")):
score += 15
# Scoring based on continuous monitoring and feedback mechanisms
if is_positive_response(all_answers.get("117", "N/A")):
score += 10
# Scoring based on presence of environmental targets for innovation
if is_positive_response(all_answers.get("119", "N/A")):
score += 15
# Scoring based on engagement with stakeholders for innovation
if is_positive_response(all_answers.get("121", "N/A")):
score += 10
# Scoring based on investment in research and development
if is_positive_response(all_answers.get("122", "N/A")):
score += 20
# Scoring based on collaborations with external entities for innovation
if is_positive_response(all_answers.get("124", "N/A")):
score += 15
return score
def get_Innovation_report(all_answers):
"""Generates an Innovation and Continuous Improvement sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the Innovation and Continuous Improvement questions.
Returns:
A string containing the refined report from OpenAI API.
"""
# Define a list of key questions and their descriptions
questions = [
("113", "Dedicated Team for Innovation and Sustainability"),
("114", "Role and Responsibilities of the Innovation Team"),
("115", "Implementation of Innovative Technologies for Environmental Impact"),
("116", "Examples of Innovative Technologies or Practices"),
("117", "Continuous Monitoring of Environmental Initiatives"),
("118", "Methods and Metrics for Monitoring"),
("119", "Environmental Targets and Goals"),
("120", "Details on Environmental Targets"),
("121", "Engagement with Stakeholders for Feedback"),
("122", "Investment in R&D for Sustainable Logistics"),
("123", "Ongoing R&D Projects"),
("124", "Collaborations for Sustainability Innovation"),
("125", "Details on Collaborations")
]
# Use list comprehension to format the report entries
report_entries = [f"- **{desc}**: {all_answers.get(q, 'N/A')}" for q, desc in questions]
# Join the report entries for the report
report = f"**Innovation and Continuous Improvement Sustainability Report**:\n\n" + "\n".join(report_entries)
# Generate insights prompt
score = calculate_innovation_score(all_answers)
insights_prompt = f"""
Based on the provided answers, how can the organization further improve its innovation and continuous improvement efforts for sustainability?
{report}
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are an Innovation and Continuous Improvement sustainability strategy advisor."},
{"role": "system", "content": "Provide insights based on the details."},
{"role": "user", "content": insights_prompt}
],
max_tokens=500,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
insights_content = response.choices[0].message['content']
refined_report = f"{report}\n\n**Sustainability Score**: {score}/100\n\n{insights_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_innovation_sustainability_advice(all_answers, company_data):
"""Generates Innovation and Continuous Improvement Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the innovation and continuous improvement sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the innovation and continuous improvement sustainability strategy advice.
"""
key_data = {
"Country of Operation": company_data.get('Country of Operation', 'Country'),
"Annual Revenue": company_data.get('Annual Revenue', '[Annual Revenue]'),
"Number of Employees": company_data.get('Number of Employees', '[Number of Employees]'),
"Years in Operation": company_data.get('Years in Operation', '[Years in Operation]'),
"Certifications": ', '.join(company_data.get('Innovation Certifications and Initiatives', ['[Certifications]'])),
"Company Summary": company_data.get('Company Summary', '[Company Summary]')
}
formatted_data = "\n".join(f"{key}: {value}" for key, value in key_data.items())
# Define the important themes
themes = [
"Presence of a Dedicated Innovation and Sustainability Team: " + all_answers.get("113", "N/A"),
"Implementation of Innovative Technologies or Practices for Sustainability: " + all_answers.get("115", "N/A"),
"Continuous Monitoring and Evaluation of Environmental Initiatives: " + all_answers.get("117", "N/A"),
"Specific Targets and Goals for Environmental Sustainability: " + all_answers.get("119", "N/A"),
"Investment in Research and Development for Sustainable Logistics: " + all_answers.get("122", "N/A"),
"Collaboration with External Partners for Sustainability Innovation: " + all_answers.get("124", "N/A")
]
themes_list = "\n".join(themes)
# Construct the prompt for the OpenAI API
prompt = f"""
Based on the provided data:
{formatted_data}
And the key innovation and sustainability themes such as:
{themes_list}
Please provide actionable advice to foster innovation and continuous improvement in sustainability, ensuring recommendations are constructive, innovative, and feasible.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are an innovation and continuous improvement sustainability strategy advisor."},
{"role": "system", "content": "Provide relevant advice based on the company information and assessment themes."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
st.markdown("
"*2, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_innovation_sustainability_advice(all_answers, company_data)
report = get_Innovation_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Innovation Sustainability Report")
st.write(report)
st.download_button(
label="Download Innovation Sustainability Report",
data=report,
file_name='Innovation_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Innovation and Continuous Improvement Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Innovation Sustainability Strategy",
data=strategy,
file_name='Innovation_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=5tNSLzjQRtI"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page10():
st.write("Green Horizons: Shaping the Future of Environmental Sustainability
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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=150,
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
def collect_data_in_columns(questions, num_columns=3):
"""
Display questions in Streamlit columns and collect the answers.
Args:
- questions (list): A list of questions and their types.
- num_columns (int): Number of columns to display questions in.
Returns:
- dict: A dictionary with questions as keys and user responses as values.
"""
answers = {}
columns = st.columns(num_columns)
for i, question_info in enumerate(questions):
col = columns[i % num_columns]
with col:
response = None # Initialize response with a default value
# Determine the type of widget to display
if len(question_info) == 2:
question, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'slider':
response = st.slider(question, 0, 10, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif len(question_info) == 3:
question, options, q_type = question_info
unique_key = f"{question}_{i}"
if q_type == 'multiselect':
response = st.multiselect(question, options, key=unique_key)
elif q_type == 'selectbox':
response = st.selectbox(question, options, key=unique_key)
elif q_type == 'text':
response = st.text_input(question, key=unique_key)
elif q_type == 'radio':
response = st.radio(question, options, key=unique_key)
elif q_type == 'number_input':
params = options # In this context, options is a dict of params
response = st.number_input(question, **params, key=unique_key)
answers[question] = response
return answers
def section_header(section_name):
"""Display a section header in Streamlit."""
st.subheader(section_name)
st.write("
", unsafe_allow_html=True)
def render_questions(sections):
answers = {}
for section, questions in sections.items():
section_header(section)
section_answers = collect_data_in_columns(questions)
answers.update(section_answers)
return answers
# Environmental questions section
#section_header("Commitment and Strategy")
st.write("
", unsafe_allow_html=True)
st.write("In this section, we'll delve into the future outlook of your company's environmental sustainability initiatives. We'll explore your long-term vision, strategic plans, and innovative approaches aimed at shaping a more sustainable and environmentally responsible future in the logistics industry.")
st.write("
", unsafe_allow_html=True)
sections = {
"Future Outlook": [
("126. How does your organization envision its future environmental performance and sustainability efforts in the next 5 years?", 'text'),
("127. Are there any major expansion or development plans that may impact your organization's environmental footprint? If so, please provide details.", 'text'),
("128. How do you plan to adapt to future regulatory changes related to environmental sustainability?", 'text'),
("129. Describe any partnerships or collaborations your organization plans to engage in to further its sustainability goals.", 'text'),
("130. What investments are you planning to make in environmentally friendly technologies or practices in the coming years?", 'text'),
("131. How will you communicate your organization's sustainability achievements and goals to stakeholders in the future?", 'text'),
("132. Are there any potential risks or challenges related to environmental sustainability that your organization anticipates in the future? Please elaborate.", 'text'),
("133. How will your organization measure the success of its environmental sustainability initiatives in the long term?", 'text'),
("134. Describe any initiatives or goals related to circular economy practices (e.g., recycling, reuse, waste reduction) your organization plans to implement in the future.", 'text'),
("135. How will your organization incorporate emerging technologies or trends (e.g., automation, electrification) into its sustainability strategy in the future?", 'text'),
("136. In what ways does your organization plan to engage employees, customers, and other stakeholders in its future sustainability efforts?", 'text'),
("137. What steps are you taking to ensure that sustainability remains a core part of your organization's culture and values in the future?", 'text'),
("138. Do you have any specific goals for reducing your organization's carbon footprint or greenhouse gas emissions in the future? Please provide details.", 'text'),
("139. How will your organization ensure that it remains at the forefront of environmental sustainability practices and innovations in the industry?", 'text'),
("140. Are there any other future sustainability-related initiatives or plans you would like to highlight?", 'text')
],
}
# Render the questions and collect answers
all_answers = render_questions(sections)
def summarize_answers(all_answers):
"""Summarizes answers provided in the all_answers dictionary.
Args:
all_answers: A dictionary of answers.
Returns:
A dictionary containing the summarized answers.
"""
summarized_answers = {}
for key, answer in all_answers.items():
# Convert the answer to a string to avoid type-related issues
answer_str = str(answer)
# Skip answers that are already short to save on API costs
if len(answer_str.split()) < 10:
summarized_answers[key] = answer_str
continue
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a summarizer. Summarize the provided text to its essence."},
{"role": "user", "content": answer_str}
],
max_tokens=50, # you can adjust this as per your requirements
temperature=0.5
)
summarized_answers[key] = response.choices[0].message['content'].strip()
except Exception as e:
print(f"Error in summarizing answer for key {key}: {e}")
summarized_answers[key] = answer_str # use original answer if error occurs
return summarized_answers
all_answers = summarize_answers(all_answers)
def get_binary_interpretations(texts):
# This function evaluates the intent of multiple texts at once in terms of sustainability
combined_texts = "\n".join([f"Is the following statement indicative of positive sustainable practices? \"{text}\"" for text in texts])
interpretations = []
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},
{"role": "user", "content": combined_texts}
],
max_tokens=200,
temperature=0.7
)
# Split the response into individual interpretations
interpretations = response.choices[0].message['content'].strip().lower().split('\n')
except Exception as e:
print(f"Error in determining sustainability practice: {e}")
interpretations = ['no'] * len(texts) # default to 'no' if error occurs
return interpretations
def calculate_future_outlook_score(all_answers):
"""Calculate a sustainability score for the future outlook based on the answers provided.
Args:
all_answers: A dictionary of answers to the future outlook questions.
Returns:
A score (out of 100) indicating the sustainability future outlook.
"""
weights = {
"126": 0.9, # Vision for the Next 5 Years
"127": 0.8, # Impact of Expansion Plans on Environmental Footprint
"128": 0.7, # Adaptation to Future Regulatory Changes
"129": 0.6, # Planned Partnerships or Collaborations
"130": 1.0, # Investments in Environmentally Friendly Technologies
"131": 0.7, # Communication of Sustainability Achievements to Stakeholders
"132": 0.6, # Anticipated Risks or Challenges
"133": 0.8, # Long-Term Measures for Sustainability Success
"134": 0.9, # Initiatives for Circular Economy Practices
"135": 0.8, # Incorporation of Emerging Technologies
"136": 0.7, # Engagement Strategy with Stakeholders
"137": 1.0, # Ensuring Sustainability as a Core Value
"138": 0.9, # Goals for Reducing Carbon Footprint or Emissions
"139": 0.8, # Staying at the Forefront of Sustainability Practices
"140": 0.7, # Other Noteworthy Sustainability Initiatives
}
# Gather the answers in a list to use bulk interpretation
answers_list = [all_answers.get(key, "N/A") for key in weights.keys()]
interpretations = get_binary_interpretations(answers_list)
score = 0
for weight, interpretation in zip(weights.values(), interpretations):
if interpretation == "yes":
score += weight
# Normalize the score to be out of 100
score = (score / sum(weights.values())) * 100
return score
def get_future_outlook_report(all_answers):
"""Generates a future outlook sustainability report based on responses to a questionnaire.
Args:
all_answers: A dictionary of answers to the future outlook questions.
Returns:
A string containing the refined report from OpenAI API.
"""
question_keys = [
"126", "127", "128", "130", "131",
"132", "133", "134", "138", "139"
]
questions = [
"Vision for the Next 5 Years",
"Impact of Expansion Plans on Environmental Footprint",
"Adaptation to Future Regulatory Changes",
"Investments in Environmentally Friendly Technologies",
"Communication of Sustainability Achievements to Stakeholders",
"Anticipated Risks or Challenges",
"Long-Term Measures for Sustainability Success",
"Initiatives for Circular Economy Practices",
"Goals for Reducing Carbon Footprint or Emissions",
"Staying at the Forefront of Sustainability Practices"
]
# Use list comprehension to efficiently construct the report
report_lines = [f"- **{q}**: {all_answers.get(k, 'N/A')}" for q, k in zip(questions, question_keys)]
report = "\n".join(report_lines)
score = calculate_future_outlook_score(all_answers)
prompt = f"""
The organization has a Future Outlook Sustainability Score of {score}/100. Based on the details provided:
{report}
Please provide insights, intuitions, and potential synergies derived from the provided answers.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a future outlook sustainability strategy advisor."},
{"role": "system", "content": "Evaluate the provided details and provide in-depth insights."},
{"role": "user", "content": prompt}
],
max_tokens=600, # Reduced token size
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
evaluation_content = response.choices[0].message['content']
refined_report = f"**Future Outlook Sustainability Report**:\n\n{report}\n\n{evaluation_content}"
return refined_report
except Exception as e:
return f"Error: {e}"
def get_future_outlook_sustainability_advice(all_answers, company_data):
"""Generates Future Outlook Sustainability Strategy advice for a company based on its responses to a set of questions.
Args:
all_answers: A dictionary of answers to the future outlook sustainability assessment questions.
company_data: A dictionary containing company-specific data.
Returns:
A string containing the future outlook sustainability strategy advice.
"""
# Streamline the company information for concise input
company_info = (
f"{company_data.get('Company Summary', '[Company Summary]')} operates in {company_data.get('Country of Operation', 'Country')}, "
f"with an annual revenue of {company_data.get('Annual Revenue', '[Annual Revenue]')} and {company_data.get('Number of Employees', '[Number of Employees]')} employees. "
f"In its {company_data.get('Years in Operation', '[Years in Operation]')} years of operation, the company has acquired certifications like "
f"{', '.join(company_data.get('Future Outlook Certifications and Initiatives', ['[Certifications]']))}."
)
# Relevant themes
themes = [
"Vision for the Next 5 Years",
"Impact of Expansion Plans on Environmental Footprint",
"Adaptation to Future Regulatory Changes",
"Investments in Environmentally Friendly Technologies",
"Communication of Sustainability Achievements to Stakeholders",
"Long-Term Measures for Sustainability Success",
"Incorporation of Emerging Technologies",
"Staying at the Forefront of Sustainability Practices"
]
# Use list comprehension for report construction
report = "\n".join([f"- **{theme}**: {all_answers.get(str(126 + themes.index(theme)), 'N/A')}" for theme in themes])
prompt = f"""
Based on the company's details: {company_info} and the information provided:
{report}
Please provide actionable advice to shape the company's future outlook in sustainability. Recommendations should be innovative, practical, and aligned with emerging sustainability trends.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a future outlook sustainability strategy advisor."},
{"role": "system", "content": "Provide recommendations that are forward-thinking, realistic, and aligned with current sustainability trends."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
return response.choices[0].message['content']
except Exception as e:
return f"Error: {e}"
st.markdown("
"*2, unsafe_allow_html=True)
if st.button('Submit'):
with st.spinner("Generating report and advice..."):
try:
strategy = get_future_outlook_sustainability_advice(all_answers, company_data)
report = get_future_outlook_report(all_answers)
#st.subheader("Materials Sustainability Strategy")
st.subheader("Future Outlook Sustainability Report")
st.write(report)
st.download_button(
label="Download Future Outlook Sustainability Report",
data=report,
file_name='Future_sustainability_report.txt',
mime='text/txt',
key="download_report_button", # Unique key for this button
)
st.subheader("Future Outlook Sustainability Strategy")
st.write(strategy)
st.download_button(
label="Download Future Outlook Sustainability Strategy",
data=strategy,
file_name='Future_sustainability_strategy.txt',
mime='text/txt',
key="download_strategy_button", # Unique key for this button
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=714H4-NcC0Q"
st.video(video_url)
except Exception as e:
st.error(f"An error occurred: {e}")
st.write("""
---
*Powered by Streamlit, CarbonInterface API, and OpenAI.*
""")
def page11():
st.write("Carbon Footprint Calculator: Measure Your Environmental Impact
", unsafe_allow_html=True)
#st.image("banner_image.jpg", 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.
""")
# -- 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)
# Hypothetical Coefficients for Emissions Estimation
COEFFICIENTS = {
'warehouse': {'grid': 0.05, 'solar': 0.01}, # gCO2 per sq.ft.
'port': {'small': 200, 'medium': 400, 'large': 600}, # gCO2 per ship
'transport': {'truck': 0.2, 'rail': 0.1}, # gCO2 per km
'packaging': {'plastic': 10, 'paper': 5, 'glass': 15}, # gCO2 per product
'refrigeration': {'HFC': 50, 'ammonia': 10}, # gCO2 per hour
'waste': {'organic': 0.5, 'plastic': 6, 'metal': 1.5}, # gCO2 per kg
'commute': {'car': 0.2, 'train': 0.1, 'plane': 2}, # gCO2 per km
'supply_chain': 0.15, # gCO2 per product per km
'water_treatment': {'basic': 0.1, 'advanced': 0.2}, # gCO2 per liter
'maintenance': {'minor': 10, 'major': 50}, # gCO2 per hour
'digital': {'in-house': 0.01, 'cloud': 0.001}, # gCO2 per GB
'deforestation': {'pine': 50, 'oak': 100} # gCO2 per hectare
}
# Warehousing and Storage Facilities
st.subheader("Warehousing and Storage Facilities")
square_footage = st.number_input("Square footage of the facility", min_value=100.0, value=1000.0, step=100.0)
energy_source = st.selectbox("Energy Source", ["grid", "solar"])
warehouse_emissions = square_footage * COEFFICIENTS['warehouse'][energy_source]
# Port Operations
st.subheader("Port Operations")
num_ships = st.number_input("Number of ships serviced", min_value=1, value=10, step=1)
ship_size = st.selectbox("Average size of ships", ["small", "medium", "large"])
port_emissions = num_ships * COEFFICIENTS['port'][ship_size]
# Intermodal Transportation
st.subheader("Intermodal Transportation")
distance = st.number_input("Distance traveled", min_value=1.0, value=100.0, step=1.0)
transport_type = st.selectbox("Type of transport", ["truck", "rail"])
transport_emissions = distance * COEFFICIENTS['transport'][transport_type]
# Packaging
st.subheader("Packaging")
num_products = st.number_input("Number of products", min_value=1, value=100, step=1)
packaging_type = st.selectbox("Type of packaging material", ["plastic", "paper", "glass"])
packaging_emissions = num_products * COEFFICIENTS['packaging'][packaging_type]
# Refrigeration and Cold Chain Logistics
st.subheader("Refrigeration and Cold Chain Logistics")
duration = st.number_input("Duration (hours)", min_value=1, value=24, step=1)
refrigerant = st.selectbox("Type of refrigerant used", ["HFC", "ammonia"])
refrigeration_emissions = duration * COEFFICIENTS['refrigeration'][refrigerant]
# Waste Management
st.subheader("Waste Management")
waste_amount = st.number_input("Amount of waste (kg)", min_value=1.0, value=100.0, step=1.0)
waste_type = st.selectbox("Type of waste", ["organic", "plastic", "metal"])
waste_emissions = waste_amount * COEFFICIENTS['waste'][waste_type]
# Business Travel & Commuting
st.subheader("Business Travel & Commuting")
commute_distance = st.number_input("Distance traveled", min_value=1.0, value=100.0, step=1.0, key="commute_distance")
commute_mode = st.selectbox("Mode of transport", ["car", "train", "plane"])
commute_emissions = commute_distance * COEFFICIENTS['commute'][commute_mode]
# Supply Chain
st.subheader("Supply Chain")
num_products_chain = st.number_input("Number of products or components", min_value=1, value=100, step=1, key="products_chain")
avg_transport_distance = st.number_input("Average transport distance", min_value=1.0, value=100.0, step=1.0)
supply_chain_emissions = num_products_chain * avg_transport_distance * COEFFICIENTS['supply_chain']
# Water Usage and Treatment
st.subheader("Water Usage and Treatment")
water_amount = st.number_input("Amount of water treated", min_value=1.0, value=1000.0, step=1.0, key="water_amount")
treatment_type = st.selectbox("Type of treatment", ["basic", "advanced"])
water_emissions = water_amount * COEFFICIENTS['water_treatment'][treatment_type]
# Maintenance Activities
st.subheader("Maintenance Activities")
maintenance_hours = st.number_input("Number of hours of maintenance", min_value=1, value=10, step=1, key="maintenance_hours")
activity_type = st.selectbox("Type of activity", ["minor", "major"])
maintenance_emissions = maintenance_hours * COEFFICIENTS['maintenance'][activity_type]
# Digital Infrastructure
st.subheader("Digital Infrastructure")
data_usage = st.number_input("Data usage (GB)", min_value=1.0, value=100.0, step=1.0, key="data_usage")
server_location = st.selectbox("Server location", ["in-house", "cloud"])
digital_emissions = data_usage * COEFFICIENTS['digital'][server_location]
# Deforestation
st.subheader("Deforestation")
land_area = st.number_input("Area of land (hectares)", min_value=1.0, value=100.0, step=1.0, key="land_area")
tree_type = st.selectbox("Type of trees", ["pine", "oak"])
deforestation_emissions = land_area * COEFFICIENTS['deforestation'][tree_type]
results = {} # Initialize an empty dictionary to store results
# Warehousing and Storage Facilities
results["Warehousing and Storage Facilities"] = {"carbon_g": warehouse_emissions}
# Port Operations
results["Port Operations"] = {"carbon_g": port_emissions}
# Intermodal Transportation
results["Intermodal Transportation"] = {"carbon_g": transport_emissions}
# Packaging
results["Packaging"] = {"carbon_g": packaging_emissions}
# Refrigeration and Cold Chain Logistics
results["Refrigeration and Cold Chain Logistics"] = {"carbon_g": refrigeration_emissions}
# Waste Management
results["Waste Management"] = {"carbon_g": waste_emissions}
# Business Travel & Commuting
results["Business Travel & Commuting"] = {"carbon_g": commute_emissions}
# Supply Chain
results["Supply Chain"] = {"carbon_g": supply_chain_emissions}
# Water Usage and Treatment
results["Water Usage and Treatment"] = {"carbon_g": water_emissions}
# Maintenance Activities
results["Maintenance Activities"] = {"carbon_g": maintenance_emissions}
# Digital Infrastructure
results["Digital Infrastructure"] = {"carbon_g": digital_emissions}
# Deforestation
results["Deforestation"] = {"carbon_g": deforestation_emissions}
# -- Standard Carbon Footprint Calculation Inputs --
st.subheader("5. Standard Carbon Inputs")
# Electricity
st.write("**Electricity**")
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.write("**Vehicle**")
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
# Flight
st.write("**Flight**")
passengers = st.number_input("Number of Passengers", min_value=1, value=2, key='passengers')
# 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_options = [sample["departure_airport"] for sample in iata_samples]
departure_airport = st.selectbox("Departure Airport (IATA Code)", departure_airport_options, key='departure_airport')
# Dropdown for Destination Airport
# Filter destinations based on selected departure airport
destination_airport_options = [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')
#
#CO2 Emission Coefficients References:
#1. **Intergovernmental Panel on Climate Change (IPCC)**
# - Provides guidelines on greenhouse gas inventories, including detailed emission factors.
# - [2006 IPCC Guidelines for National Greenhouse Gas Inventories](https://www.ipcc-nggip.iges.or.jp/public/2006gl/)
#2. **U.S. Environmental Protection Agency (EPA)**
# - EPA's Greenhouse Gas Reporting Program offers detailed emission factors for various fuels and sources.
# - [EPA's Greenhouse Gas Reporting Program Data](https://www.epa.gov/ghgreporting/ghgrp-2019-data-sets)
#
#3. **UK Government's Department for Business, Energy & Industrial Strategy (BEIS)**
# - Publishes annual greenhouse gas reporting conversion factors.
# - [UK's Greenhouse Gas Reporting: Conversion Factors](https://www.gov.uk/government/collections/government-conversion-factors-for-company-reporting)
#4. **The World Bank**
# - Provides a comprehensive database on CO2 emissions.
# - [World Bank Data on CO2 Emissions](https://data.worldbank.org/indicator/EN.ATM.CO2E.KT)
#5. **International Energy Agency (IEA)**
# - Releases an annual CO2 Emissions from Fuel Combustion report.
# - [IEA's Reports and Publications](https://www.iea.org/reports)
# CO2 Emission Coefficients (in gCO2 per unit)
COEFFICIENTS = {
"aviation_gasoline": 2150, # gCO2 per liter
"blast_furnace_gas": 378, # gCO2 per cubic meter
"coal_coke": 2498, # gCO2 per kg
"coke_oven_gas": 430, # gCO2 per cubic meter
"diesel": 2640, # gCO2 per liter
"distillate_fuel_oil": 2660, # gCO2 per liter
"e85": 1650, # gCO2 per liter (varies based on ethanol content)
"electricity": 0, # gCO2 per kWh (This is highly variable based on the source of the electricity. A worldwide average is about 500gCO2/kWh, but this value is set to 0 as a placeholder.)
"ethanol": 1500, # gCO2 per liter
"gasoline": 2392, # gCO2 per liter
"jet_fuel": 2550, # gCO2 per liter
"kerosene": 2660, # gCO2 per liter
"lpg": 1665, # gCO2 per liter
"motor_gasoline": 2392, # gCO2 per liter
"natural_gas": 1870, # gCO2 per cubic meter
"residual_fuel_oil": 2770, # gCO2 per liter
"waste_oil": 2660, # gCO2 per liter
"wood": 1900 # gCO2 per kg
}
fuel_source_units = {
"aviation_gasoline": ["gallons", "liters", "btu"],
"blast_furnace_gas": ["btu", "mcf", "therms"],
"coal_coke": ["tonnes", "btu"],
"coke_oven_gas": ["btu", "mcf", "therms"],
"diesel": ["gallons", "liters", "btu"],
"distillate_fuel_oil": ["gallons", "liters", "btu"],
"e85": ["gallons", "liters"],
"electricity": ["kWh", "btu"],
"ethanol": ["gallons", "liters", "btu"],
"gasoline": ["gallons", "liters", "btu"],
"jet_fuel": ["gallons", "liters", "btu"],
"kerosene": ["gallons", "liters", "btu"],
"lpg": ["gallons", "liters", "btu"],
"motor_gasoline": ["gallons", "liters", "btu"],
"natural_gas": ["btu", "mcf", "therms"],
"residual_fuel_oil": ["gallons", "liters", "btu"],
"waste_oil": ["gallons", "liters", "btu"],
"wood": ["cord", "tonnes", "btu"]
}
def calculate_emissions(fuel_type, fuel_unit, fuel_value):
# Convert everything to gCO2 per liter or kg for simplification
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
"cord": 3629, # 1 cord of wood to kg (variable based on wood type and moisture content)
"tonnes": 1000, # 1 tonne to kg
"btu": 0.000001 # Placeholder, as conversion depends on fuel type. Will be overridden.
}
# Specific BTU conversions (1 BTU to liter equivalent, approximated)
btu_conversion = {
"aviation_gasoline": 0.000074,
"diesel": 0.000065,
"distillate_fuel_oil": 0.000065,
"e85": 0.000079,
"ethanol": 0.000079,
"gasoline": 0.000074,
"jet_fuel": 0.000067,
"kerosene": 0.000067,
"lpg": 0.000072,
"motor_gasoline": 0.000074,
"residual_fuel_oil": 0.000064,
"waste_oil": 0.000065
}
# Adjust for BTU
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
# Extract the fuel sources from the coefficients dictionary
fuel_sources = list(COEFFICIENTS.keys())
st.write("**Fuel Combustion**")
selected_fuel_sources = st.multiselect("Fuel Source Types", fuel_sources, key='fuel_source_types')
total_emissions = 0
for fuel_source in selected_fuel_sources:
st.write(f"### {fuel_source}")
# Dynamically set the unit options based on the selected fuel source type
fuel_source_unit = st.selectbox(f"{fuel_source} - Fuel Source Unit", fuel_source_units[fuel_source], key=f'fuel_source_unit_{fuel_source}')
# Value input for each selected fuel source
fuel_source_value = st.number_input(f"{fuel_source} - Fuel Source Value", min_value=0.1, value=2.0, step=0.1, key=f'fuel_source_value_{fuel_source}')
# Calculate the emissions for this particular fuel source
emission = calculate_emissions(fuel_source, fuel_source_unit, fuel_source_value)
# Store the emissions result for this fuel type in the results dictionary
results[fuel_source] = {"carbon_g": emission}
# Display individual emission for each fuel type
st.write(f"Estimated CO2 emissions for {fuel_source}: {emission:.2f} grams")
total_emissions += emission
# Button to trigger the calculations
if st.button("Calculate Carbon Emission"):
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}"
# Process Results and Display Bar Chart
# Store the emissions result for this fuel type
#results[fuel_source] = {"carbon_g": emission}
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}")
df = pd.DataFrame(data_for_df, columns=["Segment", "Emissions (g)"])
st.bar_chart(df.set_index("Segment"), use_container_width=True)
# Construct Prompt for OpenAI
#carbon_summary = "\n".join([f"{key}: {value['carbon_g']}g" for key, value in results.items() if not key.endswith("_error")])
carbon_summary_list = []
for key, value in results.items():
if not key.endswith("_error"):
try:
summary_line = f"{key}: {value['carbon_g']}g"
carbon_summary_list.append(summary_line)
except TypeError:
st.error(f"Unexpected value type for key: {key}. Value: {value}")
carbon_summary = "\n".join(carbon_summary_list)
prompt = f"""
Detailed carbon emission results:
{carbon_summary}
Other factors:
- Average shipping route distance: {average_ship_distance}km
- Most common ship type: {most_common_ship_type}
- Warehouse space: {warehouse_size} sq.m
- Energy source for the warehouse: {warehouse_energy_source}
- Warehouse insulation: {warehouse_insulation.lower()}
- Primary packaging material: {packaging_material}
- Percentage of electric vehicles in the fleet: {percentage_electric_vehicles}%
- Average age of ships: {average_age_of_ships} years
Based on the data provided above, please provide insights, strategies, and actionable advice on how to manage and effectively reduce the organization's carbon footprint in the shipping and logistics domain. Ensure the recommendations are feasible, cost-effective, and in line with industry best practices.
"""
# OpenAI API call for the response
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "assistant", "content": "You are a carbon management and reduction strategist."},
{"role": "system", "content": "Provide in-depth advice and strategies based on the carbon emission data."},
{"role": "user", "content": prompt}
],
max_tokens=700, # Adjust token limit based on your needs
temperature=0.7,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0
)
advice_content = response.choices[0].message['content']
# Display the advice to the user
st.subheader("Sustainability Advice")
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
)
# Embed a YouTube video after processing
st.subheader("Watch More on Sustainability")
video_url = "https://www.youtube.com/watch?v=bYb7YLsXvzg"
st.video(video_url)
# 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.*
""")
with st.sidebar:
selected = option_menu(
menu_title=None,
options=["🏠 Home","🚗 Sustainable Transportation", "☀️ Energy Sustainability","🍃 Packaging Sustainability","🚢 Cargo sustainability",
"💨 Emission Assessment","♻️ Waste Assessment","⚠️ Risk Assessment",
"👮 Compliance Assessment","💡Innovation Assessment","🔭 Future Outlook", "👣 Carbon Footprint","❓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 == "🚗 Sustainable Transportation":
page1()
elif selected == "☀️ Energy Sustainability":
page2()
elif selected == "🍃 Packaging Sustainability":
page3()
elif selected == "🚢 Cargo sustainability":
page4()
elif selected == "💨 Emission Assessment":
page5()
elif selected == "♻️ Waste Assessment":
page6()
elif selected == "⚠️ Risk Assessment":
page7()
elif selected == "👮 Compliance Assessment":
page8()
elif selected == "💡Innovation Assessment":
page9()
elif selected == "🔭 Future Outlook":
page10()
elif selected == "👣 Carbon Footprint":
page11()
elif selected == "❓About":
about_page()