# Standard library imports  
import collections  
import os  
 
# Third -party imports  
import matplotlib.pyplot as plt  
import openai  
import pandas as pd  
import requests  
import streamlit as st  
from bs 4 import BeautifulSoup  
from dotenv import load_dotenv  
from streamlit_option_menu import option_menu  
 
# Local/application -specific imports  
from langchain.chains import RetrievalQA  
from langchain.chains.summarize import load_summarize_chain  
from langchain.chat_models import ChatOpenAI  
from langchain.document_loaders import WebBaseLoader, YoutubeLoader  
from langchain.embeddings import OpenAIEmbeddings  
from langchain.prompts.chat impor t ( 
    ChatPromptTemplate,  
    HumanMessagePromptTemplate,  
    SystemMessagePromptTemplate  
) 
from langchain.text_splitter import TokenTextSplitter, CharacterTextSplitter  
from langchain.vectorstores import Chroma  
 
 # Load and set our key  
openai.api_key = o pen("key.txt", "r").read().strip(" \n")

openai.api_key = o pen("key.txt", "r").read().strip(" \n") 
 
st.set_page_config(page_title="Sustainable Shipping and Logistics Advisor", page_icon="GH", 
initial_sidebar_state="expanded")  
 
hide_streamlit_style = """  
            <style>  
            #MainMenu {visibility: hidden; } 
            footer {visibility: hidden;}  
            </style>  
            """ 
st.markdown(hide_streamlit_style, unsafe_allow_html=True)  
 
css_style = {  
    "icon": {"color": "white"},  
    "nav -link": {" --hover -color": "grey"},  
    "nav -link-selected": {"background -color": "#FF 4C1B"}, 
} 
 
def home_page():  
 
    st.write(f"""# Sustainable Shipping and Logistics Advisor""", unsafe_allow_html=True)  
 
    #st.image("banner 1.jpg", use_column_width=True)  
 
    st.write(f"""<h2>The Challeng e</h 2> 
    <p>The shipping, port, and logistics industry faces growing sustainability challenges in the face of

st.write(f"""<h2>The Challeng e</h 2> 
    <p>The shipping, port, and logistics industry faces growing sustainability challenges in the face of 
increasing global trade and environmental awareness. Key factors and challenges include:</p>      <ul>  
        <li>Rising carbon emissions from g lobal shipping operations.</li>  
        <li>Waste management challenges in ports and logistics facilities.</li>  
        <li>Operational inefficiencies leading to increased environmental footprint.</li>  
        <li>Lack of integration of green technologies and renewable energy sources.</li>  
        <li>Increasing regulatory and compliance pressures.</li>  
        <li>Growing consumer demand for sustainable shipping options.</li>  
        <li>Impact of shipping activities on marine biodiversity.</li>  
        <li>Resource depletion and increasing waste generation.</li>  
        <li>Addressing the socio -economic aspects of sustainability in shipping communities.</li>  
    </ul>

<li>Resource depletion and increasing waste generation.</li>  
    </ul>  
    <p>To navigate these challenges, the industry requires comprehensive strategies and t ools that can 
assess, manage, and mitigate its environmental and social impact, while also ensuring operational 
efficiency and profitability.</p>  
    """, unsafe_allow_html=True)  
 
    st.write(f"""<h 2>Project Goals</h 2> 
    <p>The Sustainable Shipping and Logistics Advisor aims to champion sustainability in the shipping, 
port, and logistics domain by:</p>  
    <ul>  
        <li>Quantifying Carbon Emissions: Providing tools to measure and analyze carbon footprints of 
shipping operations.</li>  
        <li>Offering Sustainability Insights: Generating personalized advice for businesses to optimize 
operations, reduce emissions, and implement green technologies.</li>

<li>Offering Sustainability Insights: Generating personalized advice for businesses to optimize 
operations, reduce emissions, and implement green technologies.</li>  
        <li>Promoting Green Practices: Educating stakeholders about best practices in sustainable shipping 
and logistics.</li>  
        <li>Facilitating Sustainable Decisions: Empowering businesses with the information and tools they 
need to make sustainability -driven decisions in their operations.</li>  
    </ul>  
    <p>By achieving these  goals, the Sustainable Shipping and Logistics Advisor aims to transform the 
industry towards a more sustainable future, fostering environmental responsibility and economic 
growth.</p>      """, unsafe_allow_html=True)  
 
def about_page():  
    st.write("""<h1 >About Sustainable Shipping and Logistics Advisor</h 1>""", unsafe_allow_html=True)  
    #st.image("about.jpg", use_column_width=True)  
    st.write("""

    st.write("""  
    <p>The Sustainable Shipping and Logistics Advisor is an ambitious project stemming from the AI for 
Goo d 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 commi tment to AI -driven solutions is 
underpinned by a belief that such technology can significantly propel the maritime sector towards a 
sustainable trajectory.</p>  
 
    <p>The focal objectives of the AI for Good 2023  Hackathon are:</p>  
 
    <ul>  
        <li><s trong>Empower with AI:</strong> The hackathon seeks to push the boundaries of AI,

<p>The focal objectives of the AI for Good 2023  Hackathon are:</p>  
 
    <ul>  
        <li><s trong>Empower with AI:</strong> The hackathon seeks to push the boundaries of AI, 
venturing beyond conventional realms, to address complex socio -economic challenges.</li>  
        <li><strong>Cultivate Technological Advancement:</strong> By fostering an env ironment of 
collaboration and innovation, the hackathon aspires to spur developments in AI that are both 
revolutionary and beneficial for society.</li>  
        <li><strong>Champion Sustainable Solutions:</strong> With an eye on the broader horizon, the 
hackathon emphasizes AI solutions that are sustainable, ethical, and poised to make a long -lasting 
positive impact.</li>  
    </ul>  
 
    <p>In this backdrop, the Sustainable Shipping and Logistics Advisor emerges as a pioneering solution 
navigating the intrica te landscape of maritime sustainability. Conceived and crafted by the dedicated duo

navigating the intrica te 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. I t's more than just an application; it's a 
beacon calling the maritime industry towards eco -friendly practices, carbon footprint reduction, and a 
sustainable future.</p>  
""", unsafe_allow_html=True)  
 def page 1(): 
 
    st.write("<center><h1>Sustainable Logis tics Strategy and Transportation</h 1></center>", 
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"])

st.header("Company Information")  
 
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']  
 
        exce pt requests.exceptions.RequestException as e:  
            return f"Error: Unable to connect to the website ({e})"          except Exception as e:

exce pt 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 = ope nai.ChatCompletion.create(  
                model="gpt -3.5-turbo",  
                messages=[  
                    {"role": "system", "content": "You are an excellent sustainability assessment tool for

model="gpt -3.5-turbo",  
                    {"role": "system", "content": "You are an excellent sustainability assessment tool for 
logistics."},  
                    {"role": "user", "cont ent": prompt}  
                ], 
                max_tokens= 150, 
                temperature= 0 
            ) 
            company_summary = response.choices[ 0].message['content']   
            return company_summary  
        except Exception as 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"

if input_option == "Enter logistics company's website URL":  
        example_url = "https://quangninhport.com.vn/en/home"  
        website_url = st.text_input("Please enter t he 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_s ummary)  
 
    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

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 pac kaging waste.",

such as using electric vehicles, optimizing routes to reduce emissions, and minimizing pac kaging 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 lo gistics 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]}")

if sustainability_level in sustainability_info:  
        st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")  
 
    # Additi onal 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 ini tiatives 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.",

"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 c ertification 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 enviro nmental 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 area s.", 
    }

"Zero Emission Zones Participation": "Participating in Zero Emission Zones demonstrates a 
    } 
 
    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 Sustaina bility Level": sustainability_level,  
        "Annual Carbon Emissions (in metric tons)": carbon_emissions,  
        "Utilize Renewable Energy Sources": renewable_energy,  
        "Selected Logistics Certifications and Initiatives": selected_certifications  
    }

"Utilize Renewable Energy Sources": renewable_energy,  
    } 
 
    # 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:

answers = {}  
 
            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  
                    if q_type == 'multiselect':

question, options, q_type = question_info  
                    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 == '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] = respons e 
 
        return answers   
 
    def section_header(section_name):

answers[question] = respons e 
 
    def section_header(section_name):  
        """Display a section header in Streamlit."""  
        st.subheader(section_name)  
        st.write("<hr>", 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("<hr>", unsafe_allow_html=True)  
    st.write("In this section, we'll assess your company's commitment to environmental management, 
progress in reducing its environmental impact, transparency in reporting environmental performance to 
stakeholders, preparedness in managing climate change r isks, and commitment to protecting

stakeholders, preparedness in managing climate change r isks, and commitment to protecting 
biodiversity.")  
 
    sections = {  
        "Commitment and Strategy": [  
            ("1. Environmental Management Commitment ( 0-10):", 'slider'),  
            ("2. Progress in Re ducing 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 Sus tainability 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 R eduction ( 0-10):", 'slider'),

("7. Commitment to Sustainable Packaging ( 0-10):", 'slider'),  
            ("8. Commitment to Emission R eduction ( 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:", ["Tr uck", 
"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 (MP G 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"]),

"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 vehic les 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 tech nologies 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'),

("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

""" 
 
            # Convert the answer to a string to avoid type -related issues  
            answer_str = str(answer)  
 
            # Skip answers that are already short t o 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 posi tive sustainable practices? 
\"{text} \"" for text in texts])  
        interpretations = []  
 
        try: 
            response = openai.ChatCompletion.create(

        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().s plit(' \n') 
            print(f"Error in determining sustainability practice: {e}")  
            interpretations = ['no'] * len(texts)  # default to 'no' if error occurs  
 
        return interpretations

print(f"Error in determining sustainability practice: {e}")  
 
        return interpretations  
 
    #st.write(all_answer s) 
 
    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: {a nswers.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"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 ve hicle 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 interpretati on, 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 -= 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 respons es 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",

data_labels = ["Type", "Fuel", "Avg. Efficiency", "Monthly Trips", "Alt. Transport Methods",  
                       "Trip Efficiency", "Anti -Idling", "Fuel -Efficient Tech.", "Emission Mgmt.",  
                       "Fleet Emission Std %", "Vehicle Ma intenance", "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"""Bas ed on the Transport Method Sustainability Report with a score of {score}/ 100, 
assess the details: "{consolidated_data}". Provide insights and recommendations."""  
 
        try: 
                    {"role": "assistant", "content": "You are a Transport Method sustainability strategy advisor."},

                    {"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  
 
    def get_transport_sustainability_advice(all_answers, company_data):

return refined_report  
 
    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('C ountry 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 e fficiency, and trip frequency.  
        - Adoption of alternative transport methods and load optimization strategies.

- Vehicle type, fuel e fficiency, 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  
        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=[

""" 
 
            messages=[  
                {"role": "assistant", "content": "You are a transportation sustainability strategy advisor."},  
                {"role": "user", "co ntent": 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)

# Plot 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_xlab el("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("<br>"* 3, unsafe_allow_html=True)  
 
    if st.button('Submit'):  
 
        section_key = "Commitment and Strategy"  
        questions = sections[section_key]

st.markdown("<br>"* 3, unsafe_allow_html=True)  
 
        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["Re sponse"] = 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 d ata to display!")  
            else:  
                # Check if there's variability in the data                  if df["Response"].nunique() == 1:

st.warning("No valid d ata 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("T ransport Sustainability Strategy")  
                    st.subheader("Sustainability Report")  
                    st.write(report)  
                    st.download_button(

st.subheader("Sustainability 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)  
                        label="Download Sustainability Strategy",  
                        data=strategy,  
                        file_name='sustainability_strategy.txt',  
                        mime='text/txt',                          key="download_strategy_button",  # Unique key for this button  
                    )

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=BawgdP 1jmPo"  
            st.video(video_url)  
            st.subheader("Youtube Summarizer")  
 
            # Load Transcript  
            loader = YoutubeLoader.from_youtube_url(video_url, language=["en", "en -US"])  
            transcript = loader.load()  
            # Split Transcript  
            splitter = TokenTextSplitter(model_name="gpt -3.5-turbo -16k", chunk_size=10000, 
chunk_ overlap= 100) 
            chunks = splitter.split_documents(transcript)  
            llm = ChatOpenAI(openai_api_key=openai.api_key, model="gpt -3.5-turbo -16k", temperature= 0.3) 
            # Summarize

chunks = splitter.split_documents(transcript)  
            # Summarize  
            summarize_chain = load_summarize_chain(llm=ll m, chain_type="refine", verbose=True)  
            Ysummary = summarize_chain.run(chunks)  
            st.write(Ysummary)  
            st.download_button(  
                label="Download Youtube Summary",  
                data=strategy,  
                file_na me='Youtube.txt',  
                mime='text/txt',  
                key="download_Youtube_summary",  # Unique key for this button  
                ) 
            st.error(f"An error occurred: {e}")   
    --- 
    *Powered by Streamlit, CarbonInterface API, and OpenAI.*  
    """) 
 
def page 2(): 
    st.write("<center><h 1>Energizing Sustainability: Powering a Greener Future</h 1></center>",

--- 
    """) 
 
    st.write("<center><h 1>Energizing Sustainability: Powering a Greener Future</h 1></center>", 
 
company description manual ly"]) 
 
        try: 
 
            soup = BeautifulSoup(response.text, 'html.parser')

# Parse the HTML content of the page  
 
            company_description = soup.find('meta', attrs={'na me': 'description'})              if company_description:  
 
        except requests.exceptions.RequestException as e:  
            return f"Error: Unable to connect to the website ({e})"  
        except Exc eption as e:  
 
        Description:

- Core logistics services offered  
 
        """ 
        try: 
                    {"role": " system", "content": "You are an excellent sustainability assessment tool for 
                    {"role": "user", "content": prompt}                  ], 
            ) 
            company_summary = response.choices[ 0].message['content']  
 
    st.title("Logistics Information Extractor")

return company_summary  
 
    if input_option == "Enter logistics compan y's website URL":  
        website_url = st.text_input("Please enter the logistics company's website URL:", example_url)  
 
            if logistics_info:

                company_su mmary = summarize_logistics_info(logistics_info)  
                #st.write("Company Summary:")                  #st.write(company_summary)  
 
            Please provide a  description of the logistics company, focusing on the following:  
            - Core logistics services offered  
        """) 
        company_description = st.text_area("Please provi de the company description:", "")  
 
            company_summary = summarize_logistics_info(company_description)  
 
    st.header("Logistics Sustainability Information")

#st.write("Company Summary:")  
 
        "Green Logistics": "Green logistics refers to environmental ly friendly practices in logistics operations, 
such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.",  
        "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 sus tainability_info:  
 
    # Additional sustainability -related information  
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric ton s) (if available)", 
operations?")  
 
    st.subheader("Certifications and Sustainability Initiatives" ) 
 
    logistics_certification_info = {

st.subheader("Certifications and Sustainability Initiatives" ) 
 
        "None": "No certifications or initiatives related to logistics.",  
        "SmartWay Certification": "SmartWay certification by the EPA recognize s logistics companies that 
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.",

"Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of 
commitment to using zero -emission vehicles and reducing emissions in specific areas.",  
    } 
 
    # Display explanations for selected certifications      for certification in selected_certifications:  
            st.write(f"**Explanation of {certification}:** {logistics_certification_info[certi fication]}")  
 
    # Define the company_data dictionary  
    company_data = {  
        "Logistics Sustainability Level": sustainability_level,  
        "Annual Carbon Emissions (in metric tons)": carbon_emissions,

company_data = {  
        "Utilize Renewable Energy Sources": re newable_energy,  
    } 
 
    def collect_data_in_columns(questions, num_columns= 3): 
        """ 
 
        Args:  
 
        Returns:  
        """ 
         answers = {}

Returns:  
        """ 
         answers = {}  
 
            col = columns[i % num_columns]  
            with col:  
 
                    question, options, q_type = question_info

response = st.text_input(question, key=unique_key)  
 
                        params = options  # In this context, options is a dict of params                          response = st.number_input(question, **params, key=unique_key)

params = options  # In this context, options is a dict of params                          response = st.number_input(question, **params, key=unique_key)  
 
                answers[question] = response  
 
        st.subhe ader(section_name)  
 
    #section_header("Commitment and Strategy")  
 
    st.write("<hr>", unsafe_allow_htm l=True)  
    st.write("In this section, we'll evaluate your company's commitment to energy sustainability, progress

st.write("<hr>", unsafe_allow_htm l=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 a nd sustainability risks, and commitment to sustainable 
energy practices.")  
     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_val ue": 100}), 
            ("25. Average annual energy consumption for your logistics operations (in kWh or MMBtu):", 
'number_input', {"min_value": 0}),

("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 -effic ient 
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 energ y 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 Effi ciency Measures: \n\nDescribe any specific energy efficiency measures or 
technologies you have implemented in your logistics operations:", 'text'),

("30. Energy Effi ciency 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 
provid e 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 en ergy 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

("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 M onitoring 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 opportun ities 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')          ],

("38. Future Energy Plans: \n\nWhat are your future plans or initiatives related to energy usage 
and sustainability within your logistics operations?", 'text')          ], 
 
        } 
 
    # Initialize the summarization pipeline once  
    #summarizer = pipeline("summarization")  
    #summarizer = pipeline("summarization", model="facebook/bart -base" ) 
 
        Args:  
 
        Returns:  
        """ 
 
            answer_str = str(answer)

for key, answer in all_answers.items():  
 
            # Skip answers that are already short to save on API costs  
            if len(answer_str.split()) < 10:                 summarized_answers[key] = answer_str  
                continue  
 
            try: 
                    model="gpt -3.5-turbo",  
                    messages=[  
                    ], 
                ) 
 
                summarized_answers[key] = response.choices[ 0].message['content'].strip()

temperature= 0.5 
                ) 
 
        # 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 posi tive sustainable practices? 
 
        try: 
                messages=[

interpretations = []  
 
        try: 
                ], 
            ) 
 
    def calculate_energy _score(answers):

interpretations = ['no'] * len(texts)  # default to 'no' if error occurs  
 
    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 prim ary_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

score += 10 
                score += 7 
                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

score += 5 
 
            score += 5 
 
        # Scoring based on setting energy goals and targets  
        if "yes" in answers.get(" 34", "").lower():  
            score += 5 
 
        # Scoring based on energy monitoring a nd 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 
 
    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_i nfo = f"Primary Energy Source: {all_answers.get(' 23', 'N/A')}, Renewable Source

score = calculate_energy_score(all_answers)  
        energy_source_i nfo = 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  
        Based on the provided Energy Usage Sustainability Report and a score of {score} out of 100, 
        please provide insights, intuitions, and potenti al synergies derived from the given answers.  
        """ 
 
        try:

please provide insights, intuitions, and potenti al synergies derived from the given answers.  
        """ 
 
        try: 
                    {"role": "assistant", "content": "You are an Energy sustainability strategy advisor."},  
                    {"role": "system", "content": "Provide insights and actionable advice based on the given 
data."},  
                ], 
                max_ tokens= 700, 
                temperature= 0.7,                 top_p= 1.0, 
            ) 
 
            refined_report = f"{consolidated_report} \n\n{evaluation_content}"  
 
        except Exception as e:

refined_report = f"{consolidated_report} \n\n{evaluation_content}"  
 
    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]')}

- 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 practic es and systems.  
    4. Renewable energy adoption and energy audits.  
    5. Reporting, collaboration, and energy challenges faced.  
    """ 
 
    To enhance energy sustainability within your company's operations, consider the following details:  
 
    {company_info}  
 
    {company_data.get('Company Summary', '[Company Summary]')}  
 
    {energy_themes}

{company_info}  
 
    {energy_themes}  
 
    Based on the above themes and the provided details:  
    '{formatted_answers}'  
    please provide actionable advice to enhance energy sustainability.  
    """ 
 
                {"role": "assistan t", "content": "You are an energy sustainability strategy advisor."},                  {"role": "user", "content": prompt}  
                ], 
            max_tokens= 900, 
            frequency_penalty= 0.5, 
            presence_penalty= 0.0 
        ) 
 
        try: 
            # Use a spinner for generating advice

        try: 
                strategy = get_energy_sustainability_advice(all_answers, company_data)  
                report = get_energy_report(all_answers)  
                #st.subheader("Energy Sustainabil ity 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.write(strategy)  
                    label="Download Energy Sustainability Strategy",  
                        file_name='Energy_sustainability_strategy.txt',  
                        mime='text/txt',  
                        key="download_strategy_button",  # Unique key for this button  
                        ) 
            st.subheader("Watch More on Sustainability ") 
            video_url = "https://www.youtube.com/watch?v=olOjPWpYo 4U" 
 
            loader = YoutubeLoader.from_youtube_url(video_url, language=[ "en", "en -US"])  
            # Split Transcript

# Load Transcript  
            splitter = TokenTextSplitter(model_name="gpt -3.5-turbo -16k", chunk_size= 10000 , 
chunk_overlap= 100) 
            summarize_chain = load_summarize_chain(llm=llm, chain_type="refine", verbose=True)  
            Ysummary = summarize_ch ain.run(chunks)  
            st.write(Ysummary)              st.download_button(  
                file_name='Youtube.txt',  
                key="d ownload_Youtube_summary",  # Unique key for this button  
                )

file_name='Youtube.txt',  
                ) 
 
            st.error(f"An error occurred: {e}")  
 
    --- 
    """) 
 
def page 3(): 
    st.write("<center><h 1>Packaging Paradigm: Sustainable Solutions for a Greener 
Tomorrow</h 1></center>", unsafe_allow_html=True)  
 
    # Function to extract logistics information fr om a website URL  
    def extract_logistics_info_from_website(url):

        try:             response = requests.get(url)  
 
    # Function to summarize logistics information using OpenAI's GPT -3 model

except Exception as e:  
 
        Please extract the following information from the logistics company's descripti on: 
 
        Please provide responses while avoiding speculative or unfounded information.          """ 
        try: 
logistics ."}, 
                ], 
                max_tokens= 150,

                ], 
            ) 
 
        if website_url:              # Ensure the URL starts with http/https

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://" + 
 
                #st.write("Company Summa ry:")  
                #st.write(company_summary)  
 
            Please provide a description of the logistics company, focusing on the following:  
        """)

        """) 
 
    # Definitions for logistics sustainabi lity levels  
        "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

"Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical labor 
        "Circul ar Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing 
    } 
 
    sustainability_level = st.selectbox("Logistics Sustain ability Level", list(sustainability_info.keys()))  
 
        st.write(f"**Definition of {sustainability_level}:** {sustainability_in fo[sustainability_level]}")  
 
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", 
min_value= 0)

# Additional sustainability -related information  
    renewable_energy = st.checkbox("Does the company utilize Ren ewable Energy Sources in its 
 
        "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that 
reduce fuel use and emissions through efficient transportation practices.",

"SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that 
        "C-TPAT Certification": "C -TPAT (Customs -Trade Partnership Against Terr orism) certification ensures 
secure and sustainable supply chain practices in logistics.",          "Green Freight Programs": "Green Freight Programs focus on reducing the environmental impact of 
    } 
 
    selected_certifications = st.multiselect("Select Logistics Certi fications and Initiatives", 
 
    for certification in selected_certifications:

            st.write (f"**Explanation of {certification}:** {logistics_certification_info[certification]}")  
 
        "Annual Carbon Emissions (in metri c tons)": carbon_emissions,  
    } 
 
        """

company_data["Company Summary"] = company_summary  
 
        """ 
        Display questions in Streamlit columns and co llect the answers.   
        Args:  
 
        Returns:  
        - dict: A dictionary with questions as keys and user respon ses as values.  
        """ 
 
            with col:  
                response = None  # Initialize  response with a default value  
                    unique_key = f"{question}_{i}"

if len(question_info) == 2: 
 
                    if q_type == 'multiselect':                          response = st.multiselect (question, options, key=unique_key)  
                        response = st.text_inp ut(question, key=unique_key)

elif q_type == 'text':  
                        response = st.text_inp ut(question, key=unique_key)  
                        params = options  # In this c ontext, options is a dict of params  
 
        """Display a se ction header in Streamlit."""  
 
            section_answers = collect_data_in_columns(questions)

     # Environmental questions section  
 
    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 
adopti on of eco -friendly packaging solutions.")  
 
        "Packaging Materials": [  
            ("39. Types of Packaging Materials Used: \n\nPlease select the types of packaging materials used 
in your lo gistics operations (select all that apply):", 'multiselect', ["Plastic", "Cardboard", "Wood",

in your lo gistics 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 packa ging 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'),

("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 t o 
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 analysi s of your packaging materials 
to assess their environmental impact? (Type 'yes' or 'no'):", 'text'),

("47. Life Cycle Analysis: \n\nHave you conducted a life cycle analysi s 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 s ustainability 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

("51. Future Packaging Plans: \n\nWhat are your future plans or initiatives related to packaging 
materials and sustainability within your logistics operations?", 'text')  
        ], 
 
        } 
 
    #summarizer = pipeline("summarization", model="facebook/bart -base")  
 
        Args:  
 
        Returns:  
        """ 
 
        for key, answer in all_answers.items():              # Convert the answer to a string to avoid type -related issues  

for key, answer in all_answers.items():              # Convert the answer to a string to avoid type -related issues  
 
                continue  
 
            try: 
                        {"role": "user", "content": answer_str}  
                    ], 
                    max_token s=50,  # you can adjust this as per your requirements  
                ) 
 
                ) 
 
                print( f"Error in summarizing answer for key {key}: {e}")  
 
     all_answers = summarize_answers(all_answers)  
 
    def get_binary_interpr etations(texts):  
        combined_texts = " \n".join([f"Is the following statement indicative of positive sustainable practices? 
\"{text} \"" for text in texts] ) 
 
        try: 

        try: 
                ], 
            ) 
 
    #st.write(all_answer s)

    #st.write(all_answer s)  
    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 = [ans wers.get(q, "") for q in binary_questions.keys() if answers.get(q, "").lower()

} 
 
        texts_to_evaluate = [ans wers.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(b inary_questions.keys(), interpretations):  
                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:  
        """ 
 
        # Calculate score and consolidate data

Returns:  
        """ 
 
        score = calculate_packaging_score(all_answers)  
 
        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",  
                       "Suppl ier 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(d ata_keys, 
data_labels)])   
        # Construct the prompt for the OpenAI API

consolidated_data = ', '.join([f"{label}: {all_answers.get(key, 'N/A')}" for key, label in zip(d ata_keys, 
        prompt = f"""Based on the Packaging Materials Sustainability Report with a score of {score}/100, 
assess the details: "{consolidated_data}". Provide insights and recommendati ons."""  
 
        try: 
                    {"role": "assistant", "content": "You are a Packaging Materials sustainability strategy 
adviso r."}, 
                ], 
                max_tokens= 500, 
                temperature= 0.7, 
                presence_penalty= 0.0

], 
            ) 
 
            refined_report = f"**Packaging Materials Sustainabilit y Report - Score: 
 
    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:

        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"]  
data_label s)]) 
 
        To enhance packaging sustainability practices, consider this:  
 
        **Company Information:**

# Construct the prompt for the OpenAI API  
 
        **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 Cer tifications 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: 

        """ 
 
        try: 
advisor."},  
                    {"role": "system", "content": "Provide advice relevant to the company's packaging 
sustainability based on the detail s given."},  
                ], 
                max_tokens= 700, 
            ) 
 
            return response.choices[ 0].message['content']   
 
        with st.spinner("Generating rep ort and advice..."):

return f"Error: {e}"  
 
        with st.spinner("Generating rep ort 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")  
                    label="Download Materials Sustainability Report",  
                    file_name='Materials_sustainability_report.txt',  
                    mime='text/txt',  
                    key="download_report_button",  # Unique key for this button  
                    ) 
 
                st.subheader("Materials Sustain ability Strategy")

key="download_report_button",  # Unique key for this button  
                    ) 
 
                st.subheader("Materials Sustain ability Strategy")  
                    label="Download Materials Sustainability Strategy",  
                    data=strategy,  
                    file_name='Materials_sustainability_str ategy.txt',  
                    mime='text/txt',                      key="download_strategy_button",  # Unique key for this button  
                ) 
                st.subheader("Watch More on Sustainability ") 
                video_url = "https://www.youtube.com/watch?v=IfF 7QO7F_p0" 
                st.video(video_url)  
                st.subheader("Youtube Summarizer")  
 
                # Load Transcript  
                loader = YoutubeLoader.from_youtube_url(v ideo_url, language=["en", "en -US"])

st.subheader("Youtube Summarizer")  
 
                loader = YoutubeLoader.from_youtube_url(v ideo_url, language=["en", "en -US"])  
                transcript = loader.load()  
                # Split Transcript  
                splitter = TokenTextSplitter(model_name="gpt -3.5-turbo -16k", chunk_size= 10000 , 
                chunks = spl itter.split_documents(transcript)  
                llm = ChatOpenAI(openai_api_key=openai.api_key, model="gpt -3.5-turbo -16k", 
temperature= 0.3) 
                # Summarize  
                summarize_chain = load_summarize_chain(llm=llm, chain_type="refine", verbose=True)  
                Ysummary = summarize_chain.run(chunks)  
                st.write(Ysummary)  
                    label="Down load Youtube Summary",  
                    file_name='Youtube.txt',

st.download_button(  
                    file_name='Youtube.txt',  
                    key="download_Youtube_summary",  # Unique key for this button  
                    ) 
             except Exception as e:  
                st.error(f"An error occurred: {e}")  
    --- 
    """) 
 
def page 4(): 
    st.write("<center><h1>Cargo Consciousness: Navigating Sustainable L ogistics</h 1></center>", 
 
    input_option = st.radio( "Choose an input option:", ["Enter logistics company's website URL", "Provide 

        try: 
 
            if company_description:                  return company_description['content']  
 
        except requests.e xceptions.RequestException as e:  

except requests.e xceptions.RequestException as e:  
 
        - Sustainability practices or initi atives related to logistics  
 
        """ 
        try: 

                ],                 max_tokens= 150, 
            ) 
 
    #website_url = st.text_input("Enter the logistics company's  website URL:")  
 
                #st.write( company_summary)   
            - Core logistics services offered

        """) 
 
            company_summary = summarize_logistics_info (company_description)  
 
such as using electric vehicles, optimizing routes to reduce emissions, and minimizing packaging waste.",

        "Sustainable Supply Chain": "A sustainable supply chain involves respons ible sourcing, ethical labor 
waste in packaging and materials, leading to  a more sustainable and resource -efficient approach.",  
    } 
 
        st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")   
    # Additional sustainability -related information

st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")   
    carbon_emissions = st.number_input("Annu al Carbon Emissions (in metric tons) (if available)", 
 
    st.subheader("Certificatio ns and Sustainability Initiatives")  
 
        "ISO 14001 for Logistics": "ISO 14001 for Lo gistics is an international standard that sets 
        "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics companies that

reduce fuel use and emiss ions through efficient transportation practices.",  
        "Green Freight Programs": " Green Freight Programs focus on reducing the environmental impact of 
commitment to using zero -emissi on vehicles and reducing emissions in specific areas.",  
    } 
 
list(logistics_certification_info.keys()))

} 
 
    # Display explanations for selected certification s 
            st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}")   
        "Utilize Renewable Energy Sources": renewable_energy , 
    } 
 
    if 'company_summary' in locals() or 'company_summary' in globals():

} 
 
        company_d ata["Company Summary"] = company_summary  
 
        """ 
 
        Args:  
        - questions (list): A list of questions and the ir types.  
 
        Returns:  
        """ 
 
        columns = st.columns(num_columns ) 
         for i, question_info in enumerate(questions):  
            with col:  
                # Determine the type of widget to display

with col:  
                        response = st.slider(question, 0, 10, key =unique_key)  
 
                    elif q_type == 'selectbox':

if q_type == 'multiselect':  
                        response = st.se lectbox(question, options, key=unique_key)  
                        response = st.radio(questio n, options, key=unique_key)  
 
                answers[question] = response   
 
        st.subheader(section_name)

return answers  
 
    def r ender_questions(sections):  
 
    st.write("In this section, we'll delve into your company's sustainability practices related to cargo 
handlin g. We'll assess your commitment to efficient cargo handling and the adoption of sustainable 
cargo handling technologies.")  
 
    sections = {

        "Cargo Handling": [              ("52. What types of cargo do y ou 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 equipme nt 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' ),

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 duri ng 
            ("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 communica te your efforts and progress

            ("62. Communication and Transparency: \n\nHow do you communica te 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 han dling 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')  
        ], 
 
        } 
 
     # Initialize the summarization pipeline once  
    #summarizer = pipeline("summarization", model="facebook/b art-base")  
 
    def summarize_answers(all_answers):

#summarizer = pipeline("summarization")  
 
        Args:  
 
        Returns:  
        """ 
 
            answer_str = str (answer)  
 
                continue  
 
            try: 
                response = openai. ChatCompletion.create(  
                    model="gpt -3.5-turbo",

continue  
 
            try: 
                    messages=[                          {"role": "system", "content": "You are a summarizer. Summarize the provided text to its 
                        {"role": "u ser", "content": answer_str}  
                    ], 
                ) 
 
                summarized_answers[key] = response.choices[0].mess age['content'].strip()  
 
    def get_binary_interpretations(texts):

return summarized_answers  
 
        try: 
                messages=[                      {"role": "system", "content": "You are an evaluator of sustainability practices. Respond with 
                    {"role": "user", "content": combined_texts}  
                ], 
            ) 
 
            # Split the response into individual interpretations

], 
            ) 
 
            interpretations = response.choices[0].message['content '].strip().lower().split(' \n') 
 
    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 = {

""" 
 
        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 Hand ling 
            "62": 5,   # Communication and Transparency Measures  
            "63": 3,   # Cargo Handling Audits Conducted  
            "64": 2    # Future Sustainability Plans for Cargo  
        }

"63": 3,   # Cargo Handling Audits Conducted  
        } 
 
        # 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

if keyword in value.lower():  
 
        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:  
 
        Returns:  
        """ 
 
        score = cargo_sustainability_score(all_answers)  
 
        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/Par ticulate Mgmt.",

data_labels = ["Types of Cargo", "Processes for Hazardous Cargo", "Emission Reduction", 
"Dust/Par ticulate Mgmt.",  
                       "Noise Reduction", "Aquatic Ecosystem Impact", "Spill Prevention", "Cargo Storage",  
                       "Eco -friendly Packaging", "Goals", "Communication", "Audits", "Future Plans"]  
 
        # 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: 
                    {"role": "assistant", "con tent": "You are a Cargo Handling sustainability strategy advisor."},

                    {"role": "assistant", "con tent": "You are a Cargo Handling sustainability strategy advisor."},  
                ], 
            ) 
 
            refined_report = f"**Cargo Handling Sustainability Report - Score: 
 
    def get_car go_sustainability_advice(all_answers, company_data):

    def get_car go_sustainability_advice(all_answers, company_data):  
        """Generates Cargo Sustainability Strategy advice for a company based on its responses to a set of 
         Args:  
            all_answers: A dictionary of answers to the cargo sustaina bility assessment questions.  
 
        Returns:  
            A string containing the cargo sustainability strategy advice.  
        """ 
 
        # Simplify and consolidate answers and co mpany data  
        country_of_operation = company_data.get('Country of Operation', 'N/A')  
        company_summa ry = company_data.get('Company Summary', 'N/A')

        company_summa ry = company_data.get('Company Summary', 'N/A')  
        certifications = ', '.join(company_data.get('Selected Cargo Certifications and Initiatives', ['N/A']))  
 
        Provide cargo sustainability advice base d on the following data:  
 
        - Certifications: {certifications}  
 
        **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}

6. Audits or Assessments of Sustainable Cargo Handling Practices  
 
        """ 
 
                {"role": "assistant", "content": "You are a cargo sustainability strategy advisor."},  
                {"role": "user", "content": prompt}  
            ], 
            top_p =1.0, 
        ) 
 
        with st.spinner("Generating report and advice..."):  
            try:                 strategy = get_cargo_sustainability_advice(all_answers, company_data)

if st.button('Submit'):  
            try:                 strategy = get_cargo_sustainability_advice(all_answers, company_data)  
                report = get_cargo_report(all_answers)  
                #st.subheader("Materia ls Sustainability Strategy")  
                st.subheader("Cargo Sustainability Report")  
                    label="Download Cargo Sustainability Report",  
                    file_name='Cargo_sustainability_report.txt',  
            ) 
 
                st.subheader("Cargo Sustainability Strateg y") 
                    label="Download Cargo Sustainability Strategy",

st.write(strategy)  
                    label="Download Cargo Sustainability Strategy",  
                    file_name='Cargo_sustainability_strategy.txt',  
                    key="download_strategy_button",  # Unique key for this button  
                    ) 
                st.subheader("Watch More on Sustainability")  
                video_url = "https://www.youtube.com/watch?v=d 5_U16FbpQs"  
 
                # Load Transcript                  loader = YoutubeLoader.from_youtube_url(video_url , language=["en", "en -US"])  
                splitter = TokenTextSplitter(model_name="gpt -3.5-turbo -16k", chunk_size= 10000 ,

transcript = loader.load()  
                chunks = splitter.sp lit_documents(transcript)  
                summarize_chain = load_summarize_chain(llm=llm, chain_type="refine", verbose=T rue) 
                    label="Download Youtube Summary",  
                    file_name='Youtu be.txt',  
                    ) 
 
            except Exception as e:

mime='text/txt',  
                    ) 
 
    --- 
    """) 
 
def page 5():     st.write("<center><h 1>Emission Excellence: Paving the Way to Sustainability</h 1></center>", 
    #st.image("banner_image.jpg", use_column _width=True)  
 
company descrip tion manually"])  
 
        try: 
            response = requests.get(url)

# Function to extract logistics information from a website URL  
        try: 
            response.raise_for_status()  # Raise an exception for H TTP errors (e.g., 404) 
 
            company_description = soup.find('meta',  attrs={'name': 'description'})  
 
        return None   
    def summarize_logistics_info(logistics_info):

        Please extrac t the following information from the logistics company's description:  
 
        Please provide re sponses while avoiding speculative or unfounded information.  
        """ 
        try: 
                    {"role": "system", "content": " You are an excellent sustainability assessment tool for 
                ], 
                temperature= 0

                ], 
            ) 
 
            return f"Error: {e}"   
    st.write("Extra ct logistics information from a logistics company's website URL.")  
 
            # Ensure the URL starts with http/https

            websit e_url = website_url if website_url.startswith(("http://", "https://")) else "https://" + 
 
                company_summary = summarize_l ogistics_info(logistics_info)  
 
            Please provide a description of the  logistics company, focusing on the following:  
        """)

        """) 
        company_description = st.text_area("Please provide the company description:", "")   
 
        "Green Logistics": "Green logistic s refers to environmentally friendly practices in logistics operations, 
        "Sustainable Supply Chain": "A sustainable supply chain involves respo nsible sourcing, ethical labor

"Sustainable Supply Chain": "A sustainable supply chain involves respo nsible sourcing, ethical labor 
    } 
 
    carbon_emissions = st.number_input("Annual Carbon  Emissions (in metric tons) (if available)", 

operations?")   
 
        "ISO 14001 for  Logistics": "ISO 14001  for Logistics is an international standard that sets 

    } 
 
    # Display explanati ons for selected certifications  

    # De fine the company_data dictionary  
        "Annual Carbon Emissions (in metric tons)": carbon_emissions,          "Utilize Renewable Energy Sources": renewable_energy,  
    } 
 
        """

        """ 
 
        Args:  
 
        Returns:  
        """ 
 
        columns = st.co lumns(num_columns)  
 
            with col:  
                # Determine the type of w idget to display                  if len(question_info) == 2: 

question, q_type = question_info  
 
                    elif q_typ e == 'radio':

                    elif q_typ e == 'radio':  
 
    def section_header(section_name):          """Display a section header in Streamlit."""  
        st.subheader(section_ name)  
 
    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 sustain ability goal.")  
 
        "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)",

'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 o r strategies you have implemented to reduce CO 2 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'),

            ("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 
            ("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

            ("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 yo ur future plans or initiatives regarding 
emission reduction in logistics?", 'text')  
        ], 
 
        } 
 
    #summarizer = pipeline("summarization", model="facebook/bart -base")   
        """Summarizes answers provided in the all_answers dictionary.

#summarizer = pipeline("summarization", model="facebook/bart -base")   
 
        Args:  
            all_answe rs: A dictionary of answers.  
 
        Returns:  
        """ 
 
            # Convert the answer to a string to avoid t ype-related issues  
 
                continue  
 
            try: 
                    messages=[

continue  
 
            try: 
                        {"role": "user", "content": answer_str}                      ], 
                ) 
 
                summarized_answers[key] = answer_str  # use original answ er if error occurs  
 
        try: 
                    {"role": "user", "content": combined_texts}                  ], 
            ) 
 
max_tokens= 200, 
            ) 
 
            interpretations = respons e.choices[ 0].message['content'].strip().lower().split(' \n') 
 
    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 += 10 
            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 CO 2 Emissions Reduction  
            "68": 10,  # Measures for NO x 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 Eq uipment  
            "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 Emiss ion Reduction  
        }

"76": 5,   # Emission Reduction Goals  
        } 
 
        # 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()]  
        interpretati ons = get_binary_interpretations(texts_to_evaluate)  
 
        # Add scores based on the interpretations:  
        for q, interpretation in zip(questions_to_evaluate.keys(), interpretations):  
                score += questions_to_evaluate[q]  
 
    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.

        Args:              all_answers: A dictionary of answers to the Emission Reduction Initiatives questions.  
 
        Returns:  
        """ 
 
        # Calculate the score  
        score = ca lculate_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", "Reducti on Targets", "CO 2 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,

"Audit Conduction", "Future Plans"]  
 
        # Construct the prompt for OpenAI API  
        prompt = f"""Based on t he Emission Reduction Initiatives Report with a score of {score}/ 100, assess 
 
        try: 
                    {"role": "assistant", "content": "You are an Emission Reduction Initiatives sustainability 
strategy advisor."},  
                    {"role": "system", "content": "Evaluat e the data and provide insights."},                      {"role": "user", "content": prompt}  
                ], 
                top_p= 1.0,

], 
            ) 
 
            refined_report = f"**Emission Reduction Initiatives Report - Score: 
 
    def get_emission_sustainability_advice(all_answers, company_data):  
        """Generates Emission Sustainability Strategy advice for a company based on its r esponses to a set 
of questions.  
 
        Args:  
            all_answers: A dictionary of answers to the emission sustainability assessment questions.  
 
        Returns:

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", "CO 2 Strategy",  
                       "Renewable Energy", "Reduction Goals", "Audit Conducti on"]  
 
        # Construct the prompt for OpenAI API using the .get() method for company data  
        prompt = f"""For a compan y operating in {company_data.get('Country of Operation', 'Country')}

# Construct the prompt for OpenAI API using the .get() method for company data  
        prompt = f"""For a compan y 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: 
                    {"role": "assistant", "content": "You are an emission sustainability strategy advisor."},

                    {"role": "assistant", "content": "You are an emission sustainability strategy advisor."},  
                    {"rol e": "system", "content": "Provide advice based on the company data and emission details 
provided."},  
                ], 
                presence_penalty= 0.0             ) 
 
            return response.choices[ 0].message['content']  
 
    st.markdown("<br>"* 2, unsafe_allow_html=True)  
 
            try: 
                strategy = get_emission_sustainability_advice(all_answers, company_data)

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")  
                    label="Download EmissionSustainability Report",  
                    file_name='Emission_sustainability_report.txt',  
                    key="do wnload_report_button",  # Unique key for this button  
            ) 
                st.subheader("Emission Reduction Initiatives Sustainability Strategy")  
                st.download_button(

) 
                    label="Down load Emission Sustainability Strategy",  
                    data=strategy,                      file_name='Emission_sustainability_strategy.txt',  
                    ) 
                video_url = "https://www.y outube.com/watch?v=RYzcE 1OiwRE"  
 
                loader = YoutubeLoader.from_youtube_url(video_url, language=["en", "en -US"])  
                transcript = loader.load()

                chunks = splitter.split_documents(transcript)  
                Ysummary = summ arize_chain.run(chunks)  

                    mime='t ext/txt',                      key="download_Youtube_summary",  # Unique key for this button  
                    ) 
 
    --- 
    """) 
 
def page 6(): 
    st.write("<center><h 1>Waste Warriors: Navigating Sustainable Logistics</h 1></center>", 
 
company description manually "])

company description manually "]) 
 
        try: 
            response.raise_for_status()  # Raise an exception for HTTP errors (e .g., 404) 
 
            soup = BeautifulSoup(response.text, 'html.parser')   
            company_description = soup.find('meta', attrs={'name ': 'description'})  
 
except requests.exceptions.RequestException as e:  
 
        """ 
        try: 
                messages=[                      {"role": "system", "content": " You are an excellent sustainability assessment tool for

                messages=[                      {"role": "system", "content": " You are an excellent sustainability assessment tool for 
                ], 
            ) 
 
            logistics_info = extract_logistics_info_from_website(website_url)              if logistics_info:  
 
        """) 
 
        "Sustainable Supply Chain": "A sustainable supply chain involves responsible sourcing, ethical lab or 
waste in packaging and materials, leading to a more sustainable and re source -efficient approach.",  
    }  
 
    if sustainability_level in sustai nability_info:  
 
st.write(f"**Definition of {sustainability_level}:** {sustainability_info[sustainability_level]}")  
 
        "ISO 14001 for Logistics": "ISO 14001 for Logistics is an international standard that sets 

reduce fuel use and emissions through efficient transportation  practices.",  
        "Green Freight Programs": "Green Freight Programs focus on reduc ing the environmental impact of 
commitment to using zero -emission vehicles and reducing emissions in  specific areas.",  
    } 
     selected_certifications = st.multiselect("Select Logistics Certifications and Initiatives", 

} 
 
    for certification in selected_c ertifications:  
 
        "Logi stics Sustainability Level": sustainability_level,  
        "Selected Logistics Certifications and Initiatives": selected_cer tifications  
    } 
 
} 
 
        """ 
 
        Args:  
        - num_columns (int): Numb er of columns to display questions in.  
         Returns:  
        """ 
 
        for i, question_info in enumerat e(questions):  
            with col:  

with col:  
                if len(question_info) == 2:  
 
                    unique_ke y = f"{question}_{i}"  

                        response = st.selectbox(questi on, options, key=unique_key)  
                        response = st.text_input(question, key=unique_key)                      elif q_type == 'radio':  
                        response = st.radio(question, options, k ey=unique_key)  
 
    st.write("<hr>", unsafe_allow_html=True)      st.write("In this section, we'll delve into your company's waste management practices and 
sustainab ility efforts. We'll examine how you handle waste, reduce single -use items, and manage waste 
in an environmentally friendly manner.")  
 
        "Waste Management": [

        "Waste Management": [  
            ("80. Do you have  a waste management plan in place for your logistics operations?", 'radio', 
            ("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 initi atives 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'),

logistics operations?", 'text'),  
            ("86. Are waste reducti on 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, "m ax_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')  
        ], 
 
        } 
 
     def summarize_answers(all_answers):  
 
        Args:

all_answers = render_questions(sections)  
 
        Args:  
 
        Returns:  
        """ 
 
            # Convert the answer t o a string to avoid type -related issues  
 
                continue  
 
            try: 

continue  
 
            try: 
                    ],                     max_tokens=50,  # you can  adjust this as per your requirements  
                ) 
 
                print(f"Error in summa rizing answer for key {key}: {e}")  
 
        interpr etations = []  
 
        try: 
                ], 
                max_tokens= 200,                 temperature= 0.7 
            ) 
 
], 
            ) 
 
            interpretations = response.choices[ 0].message['content'].strip().lower().split(' \n') 
            print(f"Error in determining sustainability practic e: {e}")  
 
    def calculate_waste_management_score(answers):  
        score = 0 
 
        # Direct scoring using the .get() method for safegu arding  
        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_percentag e) 
            pass

try: 
            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, weightage s): 
                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 re port based on responses to a questionnaire.  
 
        Args:

def get_Waste_Management_report(all_answers):  
 
        Args:  
            all_answers: A dictionary of answers to the Waste Management questions.  
 
        Returns:  
        """ 
 
        # Calc ulate 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")}

- 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")}  
        """ 
 
        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: 
                    {"role": "assis tant", "content": "You are a Waste Management sustainability strategy 
                    {"role": "system", "content": "Provide insights and areas of improvement based on the

                    {"role": "system", "content": "Provide insights and areas of improvement based on the 
presented score and highlights."},  
                    {"role": "use r", "content": prompt}  
                ], 
                max_tokens= 500,  # Lower the token limit to save costs  
 
            # Combine the full report and the evaluation for the final report  
            refined_report = f"{brief_report} \n\n{evaluation_content}"  
 
    def get_waste_management_sustainability_advice(all_answers, company_data):  
        """Generates Waste Management Sustainability Strategy advice for a co mpany based on its

def get_waste_management_sustainability_advice(all_answers, company_data):  
        """Generates Waste Management Sustainability Strategy advice for a co mpany based on its 
responses to a set of questions.  
 
        Args:  
            all_answers: A dictionary of answers to the waste management sustainability assessment 
 
        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 Highlig hts: 
        - 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 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")}  
        """ 
 
        # Consolidate the company info for the prompt using the .get() method  
        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 Manag ement Certifications and 
Initiatives', ['[Certifications]']))}  
        Summary: {company_data.get('Company Summary', '[Company Summary]')}  
        """ 
 
        prompt = f"""

Summary: {company_data.get('Company Summary', '[Company Summary]')}  
        """ 
 
        Given the company detail s and key waste management highlights, provide actionable advice to 
enhance waste management sustainability while avoiding speculative or unfounded recommendations:  
 
        {company_info}  
        {key_highlights}  
        """ 
 
        try: 
            resp onse = openai.ChatCompletion.create(  
                    {"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."},  
                ], 
                max_tokens= 700,  # Lower the token limit to save costs

                ], 
                max_tokens= 700,  # Lower the token limit to save costs  
            ) 
 
            try: 
                strategy = get_waste_management_sustainability_ad vice(all_answers, company_data)  
                report = get_Waste_Management_report(all_answers)  
                st.subheader("Waste Management Sustainability Report")  
                st.write(report)

#st.subheader("Materials Sustainability Strategy")  
                    label="Download Waste Management Sustainability Report",                      data=report,  
                    file_name='Waste_sustainability_report.txt',  
                    mime='text/t xt', 
            ) 
                st.subheader("Waste Management Sustainability Strategy")  
                    label="Download Waste Sustainability Strategy",  
                    file_name='Waste_sustainability_strategy.txt',  
                    key="download_strategy_button ",  # Unique key for this button

file_name='Waste_sustainability_strategy.txt',  
                    key="download_strategy_button ",  # Unique key for this button  
                    ) 
 
                video_url = "https://www.youtube.com/watch?v= 0bOAhEPXJ 1M" 
 
                chunks = splitter.split_documents(transcript)                  llm = ChatOpenAI(openai_api_key=openai.api_ key, model="gpt -3.5-turbo -16k",

                chunks = splitter.split_documents(transcript)                  llm = ChatOpenAI(openai_api_key=openai.api_ key, model="gpt -3.5-turbo -16k", 
                st.write( Ysummary)  
                    ) 
 
    --- 
    *Powered by Streamlit, CarbonInter face API, and OpenAI.*  
    """) 
 
def page 7():

st.error(f"An error occurred: {e}")  
 
    --- 
    """) 
 
def page 7(): 
    st.write("<center><h 1>Navigating Environmental Risks: A Sustainable Approach</h 1></center>", 
    st.write("Assess and improve  the sustainability of your logistics operations.")  
     input_option = st.radio("Choose an input option:", ["Enter logistics company's website URL", "Provide 
 
    # Function to extract l ogistics information from a website URL  
        try: 
 
            # Parse t he HTML content of the page

response = requests.get(url)  
 
            # Parse t he HTML content of the page  
 
        Please extract the following information from the lo gistics company's description:

def summarize_logistics_info(logistics_info):  
        Please extract the following information from the lo gistics company's description:  
        - Core logistics services offered          - Sustainability practices or initiatives related to logistics  
 
        Please provide responses while avoiding speculative or u nfounded information.  
        """ 
        try: 
                    {"role": "system", "content": "You are an excellent sustainability ass essment tool for 
                ], 
            ) 
 
            return company_summary

max_tokens= 150, 
            ) 
 
    # User input field for the website URL      #website_url = st.text_input("Enter the logistics company's website URL:")  
 
website_url

# Ensure the URL starts with http/https  
 
        """) 
 
            company_summary = summarize_logistics_info(company_description)

if company_description:  
     st.header("Logistics Sustainability Information")  
 
        "Circul ar Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing

    } 
 
    carbon_emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)" , 
 
    # Certification and Sustainability Initiatives

    # Explanati ons for logistics -related certifications  
    logistics_certification_info = {          "None": "No certifications or initiatives related to logistics.",  
requi rements for an environmental management system in logistics operations.",  
secure and sustainable supply chain practices in logistics.",

"C-TPAT Certification": "C -TPAT (Customs -Trade Partnership Against Terrorism) certification ensures 
        "Green Freight Programs": "Green Freight Programs focus on reducing the environ mental impact of 
commitment to using zero -emission vehicles and reducing emissions in specific areas .", 
    } 
 
            st.write(f"**Explanation of {certification}:** {logistics_certification_info[certification]}")

if certification in logistics_certification_info:  
 
        "Logistics Sustainab ility Level": sustainability_level,  
    } 
 
    if 'company_summary' in locals() or 'company_summary' in globals():          company_data["Company Summary"] = company_summary  
 
    def collect_data_in_columns(questions, n um_columns= 3): 
        """ 
 
        Args:  
        - questions (list): A list of questions and their types.

""" 
 
        Args:  
 
        Returns:  
        """ 
 
            with col:  
                        response = st.slider(question, 0, 10, key=unique_key)

unique_key = f"{question}_{i}"  
                    elif q_type  == 'text':                          response = st.text_input(question, key=unique_key)  
 
                        response = st.radio(question, options, key=unique_key)

elif q_type == 'radio':  
 
        for section, questions in sections.items():              section_header(section)  
 
    # Environm ental questions section

section_answers = collect_data_in_columns(questions)  
 
    # Environm ental questions section  
 
    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.")  
 
        "Risk Management": [  
            ("90. Ha ve you identified environmental risks associated with your logistics operations? (Type 'yes' 
            ("91. Please describe the key environmental risks identified and their potential impacts:", '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 re sponding 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'),

("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 ex ternal 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 an swers  
 
        Args:  
 
        Returns:  
        """ 
 
        for key, answer in all_answers.items():

Returns:  
        """ 
 
                continue   
            try: 
                    ], 
                    max_tokens= 50,  # you can adjust this as per your requirements

                    ], 
                ) 
 
                summarized_answe rs[key] = response.choices[ 0].message['content'].strip()  
 
                summarized_answers[key] = answer_str  # use original answer if error occur s 
 
         try:

combined_texts = " \n".join([f"Is the following statement indicative of positive sustainable practices? 
         try: 
                    {"role": " user", "content": combined_texts}  
                ], 
            ) 
 
            interpretations = response.choices[0].message[' content'].strip().lower().split(' \n') 
            print(f"Error in determining sustainability practice: {e}")

        return interpretation s 
 
    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 = {

if answers.get(" 100", "").lower() == 'yes':  
            score += 5 
 
        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 enhanci ng 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(text s_to_evaluate)  
 
        for q, interpretation in zip(textual_responses.keys(), interpretations):  
            if interpretation == 'yes':

# Score based on the determined interpretations  
                score += textual_responses[q]  
 
        # For Fr equency 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 
 
    def get_risk_management_report(all_answers):  
        """Generates a Risk Management sustainabi lity report based on responses to a questionnaire.  
 
        Args:  
            all_answers: A dictionary of answers to the Risk Management questions.  
 
        Returns:

Args:  
 
        Returns:  
        """ 
 
        # 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")}

- **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_man agement_score = calculate_risk_management_score(all_answers)  
 
        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: 

{report}  
        """ 
 
        try: 
                    {"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 fr om the report."},  
                    {"role": "user", "content": insights_prompt}  
                ], 
                max_tokens= 800,                 temperature= 0.7, 
                presenc e_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}"  
 
refined_report = f"{report} \n\n**Risk Management Score**: 
 
    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.  
 
        Returns:  
            A string conta ining 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 ())

# Consolidate answers for the prompt using .get() method  
all_answers.keys ())  
        Given the risk management sustainability assessment of a company operating in 
{company_data.get('Country of Operation', 'Country')} with {company_data.get('Number of Emplo yees', 
'[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

2. Development and Review of Risk Management Plan  
        4. Employee Training and Awareness  on Risk Management  
 
        Ensure the advice is specific and avoids speculative recommendations.  
        """ 
 
        try: 
                    {"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 answer s."}, 
                ], 
                max_tokens= 600,  # Further reduced to save tokens                  temperature= 0.7, 

top_p= 1.0, 
            ) 
 
            try: 
                strategy = get_risk_management_sustainability_advice(all_answers, company_data)  
                report = get_risk_management_report(all_answers)  
                st.subheader("Risk Management Sustainability Report")  
                    label="Download Risk Management Sustainability R eport",  
                    file_name='Risk_sustainability_report.txt',

label="Download Risk Management Sustainability R eport",  
                    file_name='Risk_sustainability_report.txt',  
            )  
                st.subheader("Risk Management Sustainability Strategy")  
                    label="Download Risk Management Sustainability Strategy",  
                    file_name='Risk_sustainability_strategy.txt',  
                    ) 
                video_url = "https://www.youtube.com/watch?v= 7o7adoJF 0kk"

# Embed a YouTube video after processing  
                video_url = "https://www.youtube.com/watch?v= 7o7adoJF 0kk" 
 
                # Load Transcrip t 
                splitter = TokenTextSplitter(model_name="gpt -3.5-turbo -16k", chunk_ size= 10000 , 
                summarize_c hain = load_summarize_chain(llm=llm, chain_type="refine", verbose=True)

                summarize_c hain = load_summarize_chain(llm=llm, chain_type="refine", verbose=True)  
                Ysummary = summarize_chain.run(chunks)                  st.write(Ysummary)  
                    ) 
 
    --- 
    """) 
 
def page 8(): 
    st.write("<center><h 1>Green Compliance: Meeting Environmental Standards</h 1></center>", 
    #st.image("banner_image.jpg", use_column_width=True)

    def ext ract_logistics_info_from_website(url):  
 
            soup = Beau tifulSoup(response.text, 'html.parser')  
 
            # Example: Extract company description from the website

                return compa ny_description['content']  
 
        - Core l ogistics services offered  
 
- Core l ogistics services offered  
 
        try: 
                ], 
            ) 
 
    # User input field for the websit e URL  
 
        website_url = st.text_input("Please e nter the logistics company's website URL:", example_url)  
 
                #st.write(com pany_summary)  
 
        """) 
 
    # Definitions for logistics sustainabil ity levels  
        "Circula r Economy": "The circular economy in logistics focuses on recycling, reusing, and reducing 
    }

    } 
 
    sustainability_level = st.selectbox("Logistics Sustaina bility Level", list(sustainability_info.keys()))  
 
        st.write(f"**Definition of {sustainability_level}:** {sustainability_inf o[sustainability_level]}")  
 
    renewable_energy = st.checkbox("Does the company utilize Rene wable Energy Sources in its 
 
st.subheader("Certifications and Sustainability Initiatives")  
 
    } 
 
        "Utilize Renewable Energy Sources": renewable_energy,

"Annual Carbon Emissions (in metri c tons)": carbon_emissions,  
    } 
 
        """ 
        Display questions in Streamlit columns and collect the answers.   
        Args:  
 
        Returns:  
        """ 
 
        for i, question_info in enumerate(questions):

""" 
 
            with col:  
                        response = st.text_input(question,  key=unique_key)  
 
elif len(question_info) == 3: 
                    if q_type == 'multiselect':                          response = st.multiselect(question, options, key=unique_key)  
                    elif q_type == 'text ': 
 
        return answers

response = st.number_input(question, **params, key=unique_key)  
 
    def secti on_header(section_name):  
 
        for section, questions in se ctions.items():  
 
    # Environmental questions section      #section_header("Commitment and Strategy")  
 
    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

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.")  
 
        "Compliance": [  
            ("102. Are you aware of the env ironmental 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 
            ("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"]),

("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. Desc ribe 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 a nd stay informed about changing 
regulations?", 'text')  
        ], 
        } 
     # Render the questions and collect answers  
    all_answers = render_questions(sections)

        ], 
        } 
 
        Args:  
 
        Returns:  
        """ 
 
        summarized_answers = { } 
 
            if len(ans wer_str.split()) < 10: 
                continue  
 
            try: 

continue  
 
            try: 
                    ], 
                ) 
 
            except Exception  as e:  
 
        try: 
                    {"role": "system", "content": "You are an ev aluator of sustainability practices. Respond with 
'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},                      {"role": "user", "content": combined_texts}  
                ], 
            ) 
 
], 
            ) 
 
    def calculate_compliance_score(all_answers):  
        """Calcul ate 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

def calculate_compliance_score(all _answers):  
 
        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 f or non -compliance instances. Assuming the response is numerical.  
        try: 
            non_compliance_instances = int(all_answers.get(" 109", 0))

# Penalizing f or 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 wit h 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)) 
 
    def get_compliance_report(all_answers):  
        """Generates a Compliance Sustainability report based on responses to a questionnaire.  
 
        Args:

return score  
 
        Args:  
            all_answers: A dictionary of answers to the Compliance questions.  
 
        Returns:  
        """ 
 
        # 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",

"106": "Designated Compliance Personnel",  
            "108": "Compliance Monitoring and Documentation",  
            "109": "Instances of Non -compliance (Past Year)",  
            "110": "Actions for Non -com pliance",              "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.ite ms()])  
 
    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: 
                model="gpt -3.5-turbo",

Provide insights, recommendations, and areas of improvement.  
    """ 
 
        try: 
                    {"role": "assistant", "content ": "You are a Compliance Sustainability strategy advisor."},  
                    {"role": "system", "content": "Evaluate the data and provide insights, recommendations, and 
areas of improvement."},  
                ], 
            )  
            insights_content = response.choices[0].messa ge['content']  
 
            # Construct the refined report  
            refined_report = f"**Environmental Compliance Sustainability Report - Score:

# Construct the refined report  
            refined_report = f"**Environmental Compliance Sustainability Report - Score: 
{compliance_score}/ 100**\n\n{consolidated_data} \n\n{insights_content}"  
 
    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 questi ons. 
 
        Args:  
            all_answers: A dictionary of answers to the compliance sustainability assessment questions.  
 
        Returns:  
            A string containing the compl iance sustainability strategy advice.  
        """ 
 
        # Consolidate key compliance data points  
        key_points = {  
            "102": "Awareness of Regulations",

""" 
 
            "102": "Awareness of Regulations",  
            "103": "Specific Regulations & Standards",  
            "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()])  
 
        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 {', '.join(company_data.get('Selected Compliance Certifications and Initiatives', 
['[Certifications]']))}, assess the co mpliance details: "{compliance_highlights}". Provide actionable advice 
considering the company's operations and the specific compliance challenges in its industry."""  
 
                {"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 ."}, 
            ], 
            max_tokens= 700, 
        )

], 
        ) 
 
        return response.c hoices[ 0].message['content']   
 
            try: 
                strategy = get_compliance_sustainability_advice(all_ answers, company_data)  
                report = get_compliance_report(all_answers)  
                st.subheader("Compliance Sustainability Report")  
                    label="Download Compliance Sustainability Report",  
                    file_name='Compliance_sustainability_report.txt',  
                    mime='text/txt',

data=report,  
            ) 
 
                st.subheader("Compliance Sustainability Strategy")  
                    label="Downl oad Compliance Sustainability Strategy",  
                    file_name='Compliance_sustainability_strategy.txt',  
                    key="download_strategy_button",  # Unique key for t his button                      ) 
                video_url = "https://www.youtube.com/watch?v=lK 3DPZHYc 3w" 
                st.video(video_url)

st.subheader("Watch More on Sustainability")  
 
                Ysumm ary = summarize_chain.run(chunks)  
                st.write(Ysummary)

summarize_chain = load_summarize_chain(llm=llm, chain_type="refine", verbose=True)  
                    ) 
 
            except Exception as e:                  st.error(f"An error occurred: {e}")  
 
    --- 
    *Powered by St reamlit, CarbonInterface API, and OpenAI.*  
    """) 
 
def page 9(): 
    st.write("<center><h 1>Eco -Evolution: Innovations in Environmental Sustainability</h 1></center>", 

st.write("<center><h 1>Eco -Evolution: Innovations in Environmental Sustainability</h 1></center>", 
 
        try: 
 
            company_description = soup.find('meta', attrs={'name': 'd escription'})  
 
        Please extract the following informati on from the logistics company's description:  
 
        """ 
        try: 
                    {"role ": "system", "content": "You are an excellent sustainability assessment tool for 
            ) 
 
    st.write("Extract logisti cs information from a logistics company's website URL.")  
 
                company_sum mary = summarize_logistics_info(logistics_info)  
                #st.write(company_summary)   
        """) 
        company_description = st.text_area("Please provid e the company description:", "")  
 
    st.header("Logistics Sustain ability Information")

    st.header("Logistics Sustain ability Information")  
 
    }

    } 
 
    # Display the definition when the use r selects a sustainability level      if sustainability_level in sustainability_info:  
 
    carbon_ emissions = st.number_input("Annual Carbon Emissions (in metric tons) (if available)", 
 
    # Certification and Sustainability Initiativ es 
 
        "ISO 14001 for Logistics": "ISO 14001  for Logistics is an international standard that sets 
        "SmartWay Certification": "SmartWay certification by the EPA recognizes logistics compani es that 

    } 
 
    for certification in selected_certifications:          if certification in logistics_certification_info:  
 
        "Utilize Renewable Energy Sources": r enewable_energy,  
    } 
 
        """ 
 
        Args:  
        - questions (list): A list of qu estions and their types.  
 
        Returns:  
        """

- num_columns (int): Number of columns to display questions in.  
 
        Returns:  
        """ 
 
        answers = {}          columns = st.columns(num_columns)  
 
            with col:  
 
                elif len(question_info) == 3:

                    question, options,  q_type = question_info  
                        params = options  # In this context, options is a dict of params

elif q_type == 'number_input':  
                        response = st.number_input(question, **params, key=unique_key)   
 
            section_answers = col lect_data_in_columns(questions)  
 
    st.write("<hr>", unsafe_allow_html=True)

    st.write("In this sec tion, 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.")  
 
        "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 
depart ment:", 'text'),

depart ment:", '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 a nd evaluating environmental 
initiatives:", 'text'),  
            ("119. Have you set specific targets and goals for reducing your environmental footprint?", 'radio', 
            ("120. Please specify your environmental targets and goals:", ' text'),

            ("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 practi ces?", 
            ("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 a ssociations 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  
 
], 
        } 
 
         Args:  
 
        Returns:  
        """ 
 
                continue  
 
            try: 

continue  
 
            try: 
                    ], 
                )  
                summarized_answers[key ] = response.choices[ 0].message['content'].strip()  
 
        try: 
                    {"role": "user", " content": combined_texts}  
                ], 
            ) 
             # Split the response into individual interpretations

], 
            ) 
             # Split the response into individual interpretations  
            interpretations = response.choices[0].message['content' ].strip().lower().split(' \n') 
 
    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:

        Args:  
 
        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

score += 10 
 
            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_respons e(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 
 
    def get_Innovation_report(all_answers):  
        """Generates an Innovation and Continuous Improvement sustainability report based on responses 
to a questionnaire.   
        Args:

def get_Innovation_report(all_answers):  
        Args:  
            all_answers: A dictionary of answers to the Innovation and Continuou s Improvement questions.  
 
        Returns:  
        """ 
 
        # Define a list of key questions and their descriptions  
        questions = [  
            ("113", "Dedicated Team for Innova tion 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"),

("117", "Continuous Monitoring of Environmental Initiatives"),  
            ("118", "Methods and Metrics for Monitoring"),  
            ("119", "Environmental Targets and Go als"),  
            ("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

        # Generate insights prompt  
        score = calculate_innovati on_score(all_answers)  
        Based on the provided answers, how can the organization further improve its innovation and 
continuous improvement efforts for sustainability?  
        {report}  
        """ 
 
        try: 
                    {"role": "assistant", "content": "You are an Innovation and Continuous Improvement 
sustainability strategy advisor."},  
                    {"role": "system", "content": "Provide insights based on the details."},  
                ], 

], 
            ) 
 
            refined_report = f"{report} \n\n**Sustainability Score**: {score}/100 \n\n{insights_content}"  
            return refined_report   
 
    def get_innovation_sustainability_advice(all_answers, company_data):  
        """Generates Innovation and Continuous Improvement Su stainability 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_d ata: A dictionary containing company -specific data.  
 
        Returns:

        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', '[Numb er 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())

"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 Evaluati on 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")  
        ]

"N/A"),  
"N/A")  
        ] 
 
        themes_list = " \n".join(themes)  
 
        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",  
                    {"role": "assistant", "content": "You are an innovation and continuous improvement 
sustainability strategy advisor."},

messages=[  
                    {"role": "system", "content": " Provide relevant advice based on the company information and 
assessment themes."},  
                ], 
            ) 
 
    st.markdown("<br>"*2, unsafe_allow_html=Tru e) 
 
            try: 
                strategy = get_innovation_sustainability_advice(all_answers, company_data)

            try: 
                strategy = get_innovation_sustainability_advice(all_answers, company_data)  
                report = get_Innovation_report(all_answers)  
                st.subheader("Innovation Sustainability Report")                  st.write(report)  
                st.download_butt on( 
                    label="Download Innovation Sustainability Report",  
                    file_name='Innovation_sustainability_report.txt',  
                    key="download_report _button",  # Unique key for this button  
            ) 
                st.subheader("Innovation and Continuous Improvement Sustainability Strategy")  

) 
                    label="Download I nnovation Sustainability Strategy",  
                    file_name='Innovation_sustainability_strategy.txt',  
                    key="download_strategy_button",  # Unique key for this b utton  
                    ) 
                video_url = "https://www.youtube.com/watch?v= 5tNSLzjQRtI"  
 
chunk_overlap= 100)                 chunks = splitter.split_documents(transcript)  

label="Download Youtube Summary",  
                    key="download_Youtube_summary",  # Uniq ue key for this button  
                    ) 
 
    --- 
    """) 
 
def page 10(): 
    st.write("<center><h 1>Green Horizons: Shaping the Future of Environmental 
Sustainability</h 1></center>", unsafe_allow_html=True)  
    st.write("Assess and improve the sustainability of your logisti cs operations.")  
    st.header("Company Information")   

st.header("Company Information")   
 
    # Function to extract logistics information from a websit e URL  
        try: 
 
        Please extract the following information from the logistics company's description:          - Core l ogistics services offered  
 
        """ 
        try: 

                ], 
            ) 
 
        except E xception as e:  
 
     # User input field for the website URL  
 
        """) 
 
            #st.write(company_summary)   
 
    } 
 
    # Additi onal sustainability -related information

    # Additi onal sustainability -related information  
 
    # Explanations for logistics -related certifications      logistics_certification_info = {  

    } 
 
} 
 
        "Annual Carbon Emissions (in m etric tons)": carbon_emissions,  
    } 
 
    # If company_summary is generated, add it to company_data dictiona ry     if 'company_summary' in locals() or 'company_summary' in globals():

} 
 
    # If company_summary is generated, add it to company_data dictiona ry     if 'company_summary' in locals() or 'company_summary' in globals():  
 
        """ 
 
        Args:  
 
        Returns:  
        """ 
 
            with col:  

with col:  
                        response = st.slider(question, 0, 10, key=unique_key)                      elif q_type == 'text':  
 
                        response = st.selectbox(question, options, key=unique_key)

elif q_type == 'selectbox':  
 
        answers = {}          for section, questions in se ctions.items():

st.write("<hr>", unsafe_allow_html=True)  
 
        answers = {}          for section, questions in se ctions.items():  
 
    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.")  
 
        "Future Outlook": [  
            ("126 . How does your organization envision its future environmental performance and

            ("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 fo otprint? 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 communica te your organization's sustainability achievements and goals to

            ("131. How will you communica te 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 pra ctices (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 sustainab ility strategy in the future?", 'text'),

("135. How will your organization incorporate emerging technologies or trends (e.g., automation, 
electrification) into its sustainab ility 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 ens ure 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? P lease 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 sust ainability -related initiatives or plans you would like to

            ("140. Are there any other future sust ainability -related initiatives or plans you would like to 
highlight?", 'text')  
        ], 
        } 
 
        Args:  
 
        Returns:  
        """ 
         summarized_answers = { } 
 
                summarized_answers[key] = answer_str

# Skip answers that are already short to save on API costs  
                continue  
 
            try: 
                    ], 
                ) 
 
                print(f"Error in summarizing answer for key {key}: {e}")

except Exception  as e:  
         return summarized_answers  
 
        try: 
'yes' if the statement suggests positive sustainable practices or 'no' otherwise."},

                ], 
            ) 
 
        return interpretations   
    def calculate_future_outlook_score(all_answers):  
        """Ca lculate 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:

Args:  
 
        Returns:  
            A score (out of 100) indicating the sustaina bility 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 Change s 
            "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

"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 Forefr ont 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":  
 
        # Norma lize the score to be out of 100

if interpretation == "yes":  
 
        # Norma lize the score to be out of 100 
        score = (score / sum(weights.values())) * 100 
 
    def get_future_outlook_report(all_answers):  
        """Generates a future outlook sustainability report based on responses to a questionnaire.  
 
        Args:  
 
        Returns:  
        """ 
 
        question_keys = [  
        "126", "127", "128", "130", "131", 
        "132", "133", "134", "138", "139" 
    ]  
        "Vision for the Next 5 Years",  
        "Impact of Expansion Plans on Environmental Footprint",  
        "Adaptation to Future Regulator y Changes",  
        "Investments in Environmentally Friendly Technologies",

"Impact of Expansion Plans on Environmental Footprint",  
        "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)  
 
        The organization has a Future Outlook Sustainability Score of {score}/ 100. Based on the details 
provided:

prompt = f"""  
provided:  
 
        {report}  
 
        Please provide insights, intuitions, and potential synergies derived from the provided answers.  
        """ 
         try: 
                    {"role": "assistant", "content": "You are a future outlook sustainability strategy advisor."},  
                    {"role": "system", "content": "Evaluate the provided details and provide in -depth insights."},  
                ], 
                max_tokens= 600,  # Reduced token size  
                temperature =0.7, 
            )

temperature =0.7, 
            ) 
 
            refined_report = f"**Future Outlook Sustainabil ity 
Report**: \n\n{report} \n\n{evaluation_content}"  
 
    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.  
 
        Returns:  
            A string containing the future outlook sustainability strategy advice.  
        """

        Returns:  
        """ 
 
        # Streamline the company information for concise input  
        comp any_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"{', '.joi n(company_data.get('Future Outlook Certifications and Initiatives', ['[Certifications]']))}."  
        ) 
 
        # Relevant themes  
        themes = [

f"{', '.joi n(company_data.get('Future Outlook Certifications and Initiatives', ['[Certifications]']))}."  
        ) 
 
        themes = [  
            "Vision for the Next 5 Years",  
            "Impact of Expansion Plans on Environmental Footpri nt", 
            "Adaptation to Future Regulatory Changes",  
            "Investments in Environmentally Friendly Technologies",  
            "Communication of Sustainability Achievements to Stakeholders",  
            "Long -Term Measures for Sustainability S uccess",  
            "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])  
 
report = " \n".join([f" - **{theme}**: {all_answers.get(str( 126 + themes.index(theme)), 'N/A')}" for 
 
        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.ChatComp letion.create(  
                    {"role": "system", "content": "Provide r ecommendations that are forward -thinking, realistic, 
and aligned with current sustainability trends."},  
                ],

                ], 
            ) 
 
            try: 
                strategy = get_future_outlook_sustainability_advice(all_answers, company_data)  
                report = get_future_outlook_report(all_answers)  
                st.subheader("Future Outlook Sustainability Report")  
                st.download_ button(

st.subheader("Future Outlook Sustainability Report")  
                st.download_ button(  
                    label="Download Future Outlook Sustainability Report",  
                    file_name='Future_sustainability_report.txt',  
                    key="download_rep ort_button",  # Unique key for this button  
            ) 
 
                st.subheader("Future Outlook Sustainability Strategy")  
                    label="Download Future Outlook Susta inability Strategy",  
                    file_name='Future_sustainability_strategy.txt',  
                    ) 
        # Embed a YouTube video after processing

mime='text/txt',                      key="download_strategy_button",  # Unique key for this button  
                    ) 
                video_url = "https://www.youtube.com/watch?v= 714H4-NcC0Q" 
 
                # Summarize

llm = ChatOpenAI(openai_api_key=openai.api_key, model="gpt -3.5-turbo -16k", 
                st.downl oad_button(  
                    key="download_Youtube_summary",  # Unique key for thi s button  
                    ) 
 
    --- 
    """) 
 
def page 11(): 
    st.write("<center><h 1>Carbon Footprint Calculator: Measure Your Environmental

--- 
    """) 
 
    st.write("<center><h 1>Carbon Footprint Calculator: Measure Your Environmental 
Impact</h 1></center>", unsafe_allow_html=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/v 1/estimates"  
    API_KEY = "XXtYmhThBssK 41ufq2JJOA"  
    # Define headers for the API call  
    headers = {  
        "Authorization": f"Bearer {A PI_KEY}",  
        "Content -Type": "application/json"  
    } 
 
    #st.title("Carbon Emission Estimate Calculator for Shipping & Logistics")  
 
    # Streamlined Subheader and Descriptions  

} 
 
    ### 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 Carr ier", "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",

# -- 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")  
    perc entage_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 = {

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 },  # gCO 2 per sq.ft.  
        'port': {'small': 200, 'medium': 400, 'large': 600},  # gCO 2 per ship  
        'transport': {'truck': 0.2, 'rail': 0.1},  # gCO 2 per km  
        'packaging': {'plastic': 10, 'paper': 5, 'glass': 15},  # gCO 2 per product  
        'refrigeration': {'HFC': 50, 'ammonia': 10},  # gCO 2 per hour  
        'waste': {'organic': 0.5, 'plastic': 6, 'metal': 1.5},  # gCO 2 per kg  
        'commute': {'car': 0.2, 'train': 0.1, 'plane': 2},  # gCO 2 per km  
        'supply_chain': 0.15 ,  # gCO 2 per product per km  
        'water_treatment': {'basic': 0.1, 'advanced': 0.2},  # gCO 2 per liter  
        'maintenance': {'minor': 10, 'major': 5 0},  # gCO 2 per hour  
        'digital': {'in -house': 0.01 , 'cloud': 0.001 },  # gCO 2 per GB

'maintenance': {'minor': 10, 'major': 5 0},  # gCO 2 per hour  
        'digital': {'in -house': 0.01 , 'cloud': 0.001 },  # gCO 2 per GB  
        'deforestation': {'pine': 50, 'oak': 100}  # gCO 2 per hectare  
    } 
 
    # Warehousing and Storage Facilities  
    st.subheader("Warehousing and Storage Facil ities")  
    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['warehous e'][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]

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.s electbox("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")

packaging_emissions = num_products * COEFFICIENTS['packaging'][packaging_type]  
 
    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 = durati on * 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", ["o rganic", "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")

st.subheader("Business Travel & Commuting")  
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")

st.subheader("Water Usage and Treatment")  
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.se lectbox("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")

# Digital Infrastructure  
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['defor estation'][tree_type]  
 
    results = {}  # Initialize an empty dictionary to store results  
 
    results["Warehousing and Storage Facilities"] = {"carbon_g": warehouse_emissions}  
 
    results["Port Operations"] = {"carbon_g": port_emissions}

results["Warehousing and Storage Facilities"] = {"carbon_g": warehouse_emissions}  
 
    results["Port Operations"] = {"carbon_g": port_emissions}  
 
    # Intermodal Transportation  
    results["Intermodal Transportation"] = {"carbon_g": transport_emissions}  
 
    results["Packaging"] = {"carbon_g": packaging_emissions}  
 
    results["Refrigeration and Cold Chain Logistics"] = {"carbon_g": refrigeration_emissions}  
 
    results["Waste Management"] = {"carbon_g": waste_emissions}   
    results["Business Travel & Commuting"] = {"carbon_g": commute_emissions}  
 
    results["Supply Chain"] = {"carbon_g": supply_chain_emissions}  
 
    results["Water Usage and Treatment"] = {"carbon_g": wa ter_emissions}  
 
    # Maintenance Activities

# Water Usage and Treatment  
 
    results["Maintenance Activities"] = {"carbon_g": maintenance_emissions}  
 
    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.sele ctbox("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"  
 
    # Veh icle 
    st.write("**Vehicle**")

#country = st.text_input("Country (ISO Code)", "US", key='country')      country = "US"  
 
    # Veh icle 
    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 = " 7268 a9b7-17e8-4c8d-acca -57059252 afe9" 
 
    # Flight  
    # Flight  
    st.write("**Flight**")  
    passengers = st.number_input("Number of Pas sengers", 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"  
        } 
    ]

"destination_airport": "YYZ"  
        }, 
        { 
        } 
    ] 
 
    # 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 Pane l on Climate Change (IPCC)**

    # 
 
    #1. **Intergovernmental Pane l 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/ 2006 gl/) 
 
    #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](http s://www.gov.uk/government/collections/government -conversion -factors -for-company -

#   - [UK's Greenhouse Gas Reporting: Conversion 
reporting)   
    #4. **The World Bank**  
    #   - Provides a comprehensive database on CO 2 emissions.  
    #   - [World Bank Data on CO2 Emissions](https://data.worldbank.org/ind icator/EN.ATM.CO 2E.KT)  
 
    #5. **International Energy Agency (IEA)**  
     #  - Releases an annual CO 2 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 ,  # gCO 2 per liter  
        "blast_furnace_gas": 378,  # gCO 2 per cubic meter  
        "coal_coke": 2498 ,  # gCO 2 per kg  
        "coke_oven_gas": 430,  # gCO 2 per cubic meter  
        "diesel":  2640 ,  # gCO 2 per liter  
        "distillate_fuel_oil": 2660 ,  # gCO 2 per liter

"coke_oven_gas": 430,  # gCO 2 per cubic meter  
        "distillate_fuel_oil": 2660 ,  # gCO 2 per liter  
        "e85": 1650 ,  # gCO 2 per liter (varies based on ethanol content)  
        "electricity": 0,  # gCO2 per kWh (This is highly variable based on the source of the electrici ty. A 
worldwide average is about 500gCO2/kWh, but this value is set to 0 as a placeholder.)  
        "ethanol": 1500 ,  # gCO 2 per liter  
        "gasoline": 2392 ,  # gCO 2 per liter  
        "jet_fuel": 2550 ,  # gCO 2 per liter  
        "kerosene": 2660 ,  # gCO 2 per liter  
        "lpg": 1665 ,  # gCO 2 per liter  
        "motor_gasoline": 2392 ,  # gCO 2 per liter  
        "natural_gas": 1870 ,  # gCO 2 per cubic meter  
        "residual_fuel_oil": 2770 ,  # gCO 2 per liter          "waste_oi l": 2660 ,  # gCO 2 per liter  
        "wood": 1900   # gCO 2 per kg  
    } 
 
    fuel_source_units = {

"residual_fuel_oil": 2770 ,  # gCO 2 per liter          "waste_oi l": 2660 ,  # gCO 2 per liter  
    } 
 
    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": ["gal lons", "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"],

"lpg": ["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 gCO 2 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  # Placeho lder, as conversion depends on fuel type. Will be overridden.  
        }

"tonnes": 1000 ,  # 1 tonne to kg  
        } 
 
        # 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_gas oline": 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)

if fuel_unit == "btu":  
 
        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 sel ected fuel source

        # Value input for each sel ected 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 CO 2 emissions for {fuel_source}: {emission:. 2f} grams")  
 
        total_emissions += emission  
 
    # Button to trigger the calculations  
    if st.button("Calculate Carbon Emission"):  
        st.spinn er("Calculating...")  
 
        #results = {}  # Initialize an empty dictionary to store results

if st.button("Calculate Carbon Emission"):  
 
        #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["Elect ricity"] = 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 = {

        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_v alue_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["V ehicle"] = 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": [

# Flight API Call  
            "legs": [  
                {"departure_airport": departure_airport, "destination_airport": destination_airport}  
                ] 
            } 
        response_flight = requ ests.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": emi ssion}   
        data_for_df = []  
        for key, value in results.items():  
            if not key.endswith("_error"):  
                try:

#results[fuel_source] = {"carbon_g": emi ssion}   
                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 OpenA I 
        #carbon_summary = " \n".join([f"{key}: {value['carbon_g']}g" for key, value in results.items() if not 
key.endswith("_error")])  
        carbon_summary_list = []  
                try: 
                    summary_line = f"{key}: {value['carbon_g']}g"

for key, value in results.items():  
                try: 
                    summary_line = f"{key}: {value['carbon_g']}g"  
                    carbon_summary_list.append(summary_line)  
                    st.error(f"Unexpected value type for key: {key}. Value:  {value}")  
 
        carbon_summary = " \n".join(carbon_summary_list)  
 
        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}

- Energy source for the warehouse: {warehouse_energy_source}  
        - 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  
                {"role": "assistant", "content": "You are a carbon management and reduction strategist." },

                {"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."},  
            ], 
            max_tokens=700,  # Adjust token limit based on you r needs  
            top_p= 1.0,             frequency_penalty= 0.5, 
        ) 
 
        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',

label="Download Sustainability advice",  
            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=bYb7YL sXvzg"  
        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 a ware 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("""      --- 
    """) 
 
def page 12():

    """) 
 
def page 12(): 
    # Load and set our key  
    api_key = open("key.txt", "r").read().strip(" \n") 
    openai.api_key = api_key  
    os.environ["OPENAI_API_KEY"] = api_key  
 
    system_templ ate = """Use the following pieces of context to answer the users question.  
    If you don't know the answer, just say that you don't know, don't try to make up an answer.  
    """ 
 
    messages = [  
        SystemMessagePromptTemplate.from_template(system_te mplate),  
        HumanMessagePromptTemplate.from_template("{question}"),  
    ] 
    prompt = ChatPromptTemplate.from_messages(messages)  
    chain_type_kwargs = {"prompt": prompt}  
 
    # Define a dictionary of websites  
    websites = {  
        "Blue Economy Observatory News": "https://blue -economy -

chain_type_kwargs = {"prompt": prompt}  
 
observatory.ec.europa.eu/news/antwerp -bruges -aims -become -worlds -greenest -port -2023 -03-10_en",  
        "Euronews Green": "https://www.euronews.com/green/2023/02/28/port -behind -10-of-belgiums -
co2-emissions -adopts -carb on-slashing -tech",  
        "Sustainable World Ports": "https://sustainableworldports.org/",          "Port of Gothenburg Green Connection": "https://www.portofgothenburg.com/green -connection/",  
        "Ship Technology Green Team Ports": "https://www.ship -technology.com/features/green -team -
ports -leading -shipping -sustainability -drive/",  
        "AD Ports Group Sustainability": "https://www.adportsgroup.com/en/sustainability",  
        "World Shipping Council": "https://www.worldshipping.org/",

"AD Ports Group Sustainability": "https://www.adportsgroup.com/en/sustainability",  
        "World Shipping Council": "https://www.worldshipping.org/",  
        "International Association of Ports and Harbors": "https://www.iaphworldports.org/",  
        "GLA Family": "https://www.glafamily.com/",  
        "Strategia e Sviluppo": "https://strategiaesviluppo.com/supply -chain -sustainability"  
        # Add more  websites as needed  
    } 
 
    sustainability_questions = [  
        "What initiatives are in place to reduce carbon emissions in ports?",  
        "How are ports minimizing their environmental impact?",  
        "What actions are taken to protect local ecosy stems?",  
        "How do ports manage waste and recycling?",  
        "What strategies are employed to improve energy efficiency in ports?",  
        "How do ports engage in community outreach and partnerships?",  
        "What measures are taken to ensure so cial responsibility in ports?",

"How do ports engage in community outreach and partnerships?",  
        "What measures are taken to ensure so cial responsibility in ports?",  
        "How are ports contributing to economic development in their communities?",  
        "What investments are being made in renewable energy sources in ports?",  
        "How are ports ensuring the well -being of future ge nerations?",  
        "How do ports align their operations with the United Nations' Sustainable Development Goals 
(SDGs)?",  
        "What technologies are being adopted to promote sustainability in ports?",  
        "How do ports manage water resources respo nsibly?",  
        "What practices are implemented to promote sustainable supply chain practices in ports?",  
        "How do ports mitigate the impact of operations on local wildlife and habitats?",

"What practices are implemented to promote sustainable supply chain practices in ports?",  
        "How do ports mitigate the impact of operations on local wildlife and habitats?",  
        "How is technology being utilized to enhance susta inable operations in ports?",          "What role do ports play in reducing the carbon footprint of the shipping industry?",  
        "How do ports safeguard marine life and biodiversity?",  
        "What is the impact of port operations on air quality, and h ow is it being mitigated?",  
        "How do ports plan to adapt to the challenges posed by climate change?",  
        "What initiatives are in place to promote green transportation within and around ports?",  
        "How are ports addressing noise pollution?",  
        "What measures are in place to handle hazardous materials safely and sustainably?",  
        "How are ports working towards reducing water pollution?",

"What measures are in place to handle hazardous materials safely and sustainably?",  
        "How are ports working towards reducing water pollution?",  
        "What collaborations or partnerships  are ports forming to enhance sustainability?",  
        "How do ports facilitate and manage clean energy transition for vessels?",  
        "What are the strategies adopted by ports to ensure economic sustainability?",  
        "How are ports ensuring secure , transparent, and sustainable supply chains?",  
        "What frameworks are used to measure and report sustainability in ports?",  
        "How is sustainability integrated into the decision -making and operational processes of ports?",  
        "What is the  role of port authorities in ensuring sustainability within port precincts?",  
        "What kind of training or awareness programs are in place for sustainability in ports?",

"What is the  role of port authorities in ensuring sustainability within port precincts?",  
        "What kind of training or awareness programs are in place for sustainability in ports?",  
        "How are the local communities involved in sustainability initiatives by ports?",  
        "What policies are in place to enhance social sustainability in port operations?",  
    ] 
 
    st.title('🚢 EcoPorts: Navigating Towards Sustainable Seaports 🌱') 
    st.subheader('Embark on a Voyage of Discovery in Port Sustainability')  
 
    # Additional explanation text  
    st.write(  
    """ 
    Welcome to **EcoPorts**, your compass to explore sustainability practices in seaports worldwide!  
     Seaports are pivotal junctions in global trade, connecting sea, and land, facilitating the tra nsit of goods 
across continents. However, the bustling activities at ports can harbor numerous environmental

across continents. However, the bustling activities at ports can harbor numerous environmental 
challenges, including air and water pollution, noise, and disruptions to local ecosystems. 🏭🔊🌊 
 
    In the quest for a more sustainable and gree n future, seaports around the globe are navigating toward 
eco-friendly practices. 🌎🍃 Here, you can delve into various websites dedicated to port sustainability 
and unearth the myriad strategies ports employ to steer towards a greener future.  
 
    🧐 Explore through predefined inquiries or ⚓ anchor your custom questions about sustainability 
practices, initiatives, technologies, and policies in port operations. Let ’s set sail towards sustainable port 
management and operations! 🚢💚 
    """) 
 
    selected_website_name = st.selectbox("Select a website", options=list(websites.keys()))  
    url = websites[selected_website_name]  
 
    selected_question = st.selectbox("Choose a standard question:", [""] + sustainability_questions)

url = websites[selected_website_name]  
 
    selected_question = st.selectbox("Choose a standard question:", [""] + sustainability_questions)  
 
    if selected_que stion:  
        prompt = selected_question  
    else:  
        prompt = st.text_input("Or ask your own question:")  
 
    if st.button("Submit Query", type="primary") and prompt:  
        with st.spinner('Fetching and Processing Data...'):  # spinner starts here  
            try: 
                ABS_PATH: str = os.path.dirname(os.path.abspath(__file__))  
                DB_DIR: str = os.path.join(ABS_PATH, "db")  
 
                loader = WebBaseLoader(url)  
                data = loader.load()   
                text_ splitter = CharacterTextSplitter(separator=' \n', 
                                                   chunk_size= 900, 
                                                   chunk_overlap= 50) 
 
                docs = text_splitter.split_documents(data)

chunk_overlap= 50) 
 
                docs = text_splitter.split_documents(data)  
 
                openai_embeddings = OpenAIEmbeddings()  
 
                vectordb = Chroma.from_documents(documents=docs,  
                                             embedding=openai_embeddings,  
                                             persist_directory=DB_DIR)  
 
                vectordb.persist()  
 
                retriever = vectordb.as_retriever(search_kwargs={"k": 3}) 
 
                llm = ChatOpenAI(model_name='gpt -3.5-turbo')  
 
                qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retr iever=retriever)  
 
                response = qa(prompt)  
 
                query = response.get("query")  
 
                result = response.get("result")  
 
                # Formatting and Displaying the response within the button pressed block

query = response.get("query")  
 
                # Formatting and Displaying the response within the button pressed block  
                formatted_response = f"**Question:** {query} \n\n**Answer:** {result}"   
                st.markdown(formatted_response)  
 
            except Exception as e:  # exception handling starts here  
                st.error(f"An error occurred: {str(e)}")  
 
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"," 🗣️🌐 EcoPorts Query Engine", " ❓About"],  
        #icons = [  
        #"home ", "bus", "bolt", "cube", "ship",

        #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 == " 🚗 Susta inable Transportation":  
    page 1() 
 
elif selected == " ☀️ Energy Sustainability":      page 2() 
 
elif selected == " 🍃 Packaging Sustainability":  
    page 3() 
 
elif selected == " 🚢 Cargo sustainability":  
    page 4() 
 
elif selected == " 💨 Emission Assessment":  
    page 5() 
 
elif selected == " ♻️ Waste Assessment":  
    page 6() 
 
elif selected == " ⚠️ Risk Assessment":  
    page 7() 
 
elif selected == " 👮 Compliance Assessment":  
    page 8() 
 
elif selected == " 💡Innovation Assessment":  
    page 9() 
 
elif selected == " 🔭 Future Outlook":  
    page 10()

page 7() 
 
    page 8() 
 
    page 9() 
 
    page 10() 
 
elif selected == " 👣 Carbon Footprint":  
    page 11()  
elif selected == " 🗣️🌐 EcoPorts Query Engine":  
    page 12() 
 
elif selected == " ❓About":  
    about_page()