Spaces:
Sleeping
Sleeping
import os | |
import shutil | |
import streamlit as st | |
from fpdf import FPDF | |
from chromadb import Client | |
from chromadb.config import Settings | |
import chromadb | |
import json | |
from langchain_community.utilities import SerpAPIWrapper | |
from llama_index.core import VectorStoreIndex | |
from langchain_core.output_parsers import StrOutputParser | |
from langchain_core.runnables import RunnablePassthrough | |
from langchain_groq import ChatGroq | |
from langchain.chains import LLMChain | |
from langchain.agents import AgentType, Tool, initialize_agent, AgentExecutor | |
from llama_parse import LlamaParse | |
from langchain_community.document_loaders import UnstructuredMarkdownLoader | |
from langchain_huggingface import HuggingFaceEmbeddings | |
from llama_index.core import SimpleDirectoryReader | |
from dotenv import load_dotenv, find_dotenv | |
import pandas as pd | |
from streamlit_chat import message | |
from langchain_community.vectorstores import Chroma | |
from langchain_community.utilities import SerpAPIWrapper | |
from langchain.chains import RetrievalQA | |
from langchain_community.document_loaders import DirectoryLoader | |
from langchain_community.document_loaders import PyMuPDFLoader | |
from langchain_community.document_loaders import UnstructuredXMLLoader | |
from langchain_community.document_loaders import CSVLoader | |
from langchain.prompts import PromptTemplate | |
from langchain.text_splitter import RecursiveCharacterTextSplitter | |
from langchain.memory import ConversationBufferMemory | |
from langchain.prompts import PromptTemplate | |
import joblib | |
import nltk | |
import nest_asyncio # noqa: E402 | |
nest_asyncio.apply() | |
load_dotenv() | |
load_dotenv(find_dotenv()) | |
nltk.download('averaged_perceptron_tagger_eng') | |
os.environ["TOKENIZERS_PARALLELISM"] = "false" | |
SERPAPI_API_KEY = os.environ["SERPAPI_API_KEY"] | |
GOOGLE_CSE_ID = os.environ["GOOGLE_CSE_ID"] | |
GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"] | |
LLAMA_PARSE_API_KEY = os.environ["LLAMA_PARSE_API_KEY"] | |
HUGGINGFACEHUB_API_TOKEN = os.environ["HUGGINGFACEHUB_API_TOKEN"] | |
groq_api_key=os.getenv('GROQ_API_KEY') | |
st.set_page_config(layout="wide") | |
css = """ | |
<style> | |
[data-testid="stAppViewContainer"] { | |
background-color: #f8f9fa; /* Very light grey */ | |
} | |
[data-testid="stSidebar"] { | |
background-color: white; | |
color: black; | |
} | |
[data-testid="stAppViewContainer"] * { | |
color: black; /* Ensure all text is black */ | |
} | |
button { | |
background-color: #add8e6; /* Light blue for primary buttons */ | |
color: black; | |
border: 2px solid green; /* Green border */ | |
} | |
button:hover { | |
background-color: #87ceeb; /* Slightly darker blue on hover */ | |
} | |
button:active { | |
outline: 2px solid green; /* Green outline when the button is pressed */ | |
outline-offset: 2px; /* Space between button and outline */ | |
} | |
.stButton>button:first-child { | |
background-color: #add8e6; /* Light blue for primary buttons */ | |
color: black; | |
} | |
.stButton>button:first-child:hover { | |
background-color: #87ceeb; /* Slightly darker blue on hover */ | |
} | |
.stButton>button:nth-child(2) { | |
background-color: #b0e0e6; /* Even lighter blue for secondary buttons */ | |
color: black; | |
} | |
.stButton>button:nth-child(2):hover { | |
background-color: #add8e6; /* Slightly darker blue on hover */ | |
} | |
[data-testid="stFileUploadDropzone"] { | |
background-color: white; /* White background for file upload */ | |
} | |
[data-testid="stFileUploadDropzone"] .stDropzone, [data-testid="stFileUploadDropzone"] .stDropzone input { | |
color: black; /* Ensure file upload text is black */ | |
} | |
.stButton>button:active { | |
outline: 2px solid green; /* Green outline when the button is pressed */ | |
outline-offset: 2px; | |
} | |
</style> | |
""" | |
st.write(css, unsafe_allow_html=True) | |
st.sidebar.image('StratXcel.png', width=150) | |
#-------------- | |
def load_credentials(filepath): | |
with open(filepath, 'r') as file: | |
return json.load(file) | |
# Load credentials from 'credentials.json' | |
credentials = load_credentials('credentials.json') | |
# Initialize session state if not already done | |
if 'logged_in' not in st.session_state: | |
st.session_state.logged_in = False | |
st.session_state.username = '' | |
# Function to handle login | |
def login(username, password): | |
if username in credentials and credentials[username] == password: | |
st.session_state.logged_in = True | |
st.session_state.username = username | |
st.rerun() # Rerun to reflect login state | |
else: | |
st.session_state.logged_in = False | |
st.session_state.username = '' | |
st.error("Invalid username or password.") | |
# Function to handle logout | |
def logout(): | |
st.session_state.logged_in = False | |
st.session_state.username = '' | |
st.rerun() # Rerun to reflect logout state | |
# If not logged in, show login form | |
if not st.session_state.logged_in: | |
st.sidebar.write("Login") | |
username = st.sidebar.text_input('Username') | |
password = st.sidebar.text_input('Password', type='password') | |
if st.sidebar.button('Login'): | |
login(username, password) | |
# Stop the script here if the user is not logged in | |
st.stop() | |
# If logged in, show logout button and main content | |
if st.session_state.logged_in: | |
st.sidebar.write(f"Welcome, {st.session_state.username}!") | |
if st.sidebar.button('Logout'): | |
logout() | |
#------------- | |
llm=ChatGroq(groq_api_key=groq_api_key, | |
model_name="Llama-3.2-90b-text-preview", temperature = 0.0, streaming=True) | |
#model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True) | |
llm_tool=ChatGroq(groq_api_key=groq_api_key, | |
model_name="llama3-groq-70b-8192-tool-use-preview", temperature = 0.0, streaming=True) | |
#model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True) | |
#-------------- | |
doc_retriever_ESG = None | |
#-------------- | |
#@st.cache_data | |
def load_or_parse_data_ESG(): | |
data_file = "./data/parsed_data_ESG.pkl" | |
parsingInstructionUber10k = """The provided document contains detailed information about the company's environmental, social, and governance matters. | |
It contains several tables, figures, and statistical information about CO2 emissions and energy consumption. | |
Give only precise CO2 and energy consumption levels from the context documents. | |
You must never provide false numeric or statistical data not included in the context document. | |
Include tables and numeric data always when possible. Only refer to other sources if the context document refers to them or if necessary to provide additional understanding to the company's own data.""" | |
parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY, | |
result_type="markdown", | |
parsing_instruction=parsingInstructionUber10k, | |
max_timeout=5000, | |
gpt4o_mode=True, | |
) | |
file_extractor = {".pdf": parser} | |
reader = SimpleDirectoryReader("./ESG_Documents", file_extractor=file_extractor) | |
documents = reader.load_data() | |
print("Saving the parse results in .pkl format ..........") | |
joblib.dump(documents, data_file) | |
# Set the parsed data to the variable | |
parsed_data_ESG = documents | |
return parsed_data_ESG | |
#-------------- | |
# Create vector database | |
def create_vector_database_ESG(): | |
# Call the function to either load or parse the data | |
llama_parse_documents = load_or_parse_data_ESG() | |
with open('data/output_ESG.md', 'a') as f: # Open the file in append mode ('a') | |
for doc in llama_parse_documents: | |
f.write(doc.text + '\n') | |
markdown_path = "data/output_ESG.md" | |
loader = UnstructuredMarkdownLoader(markdown_path) | |
documents = loader.load() | |
# Split loaded documents into chunks | |
text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=30) | |
docs = text_splitter.split_documents(documents) | |
#len(docs) | |
print(f"length of documents loaded: {len(documents)}") | |
print(f"total number of document chunks generated :{len(docs)}") | |
persist_directory = "./chroma_db_LT" # Specify directory for Chroma persistence | |
embed_model = HuggingFaceEmbeddings() | |
vs = Chroma.from_documents( | |
documents=docs, | |
embedding=embed_model, | |
collection_name="rag_ESG", | |
persist_directory=persist_directory # Ensure persistence | |
) | |
doc_retriever_ESG = vs.as_retriever() | |
index = VectorStoreIndex.from_documents(llama_parse_documents) | |
query_engine = index.as_query_engine() | |
return doc_retriever_ESG, query_engine | |
#-------------- | |
ESG_analysis_button_key = "ESG_strategy_button" | |
#--------------- | |
def delete_files_and_folders(folder_path): | |
for root, dirs, files in os.walk(folder_path, topdown=False): | |
for file in files: | |
try: | |
os.unlink(os.path.join(root, file)) | |
except Exception as e: | |
st.error(f"Error deleting {os.path.join(root, file)}: {e}") | |
for dir in dirs: | |
try: | |
os.rmdir(os.path.join(root, dir)) | |
except Exception as e: | |
st.error(f"Error deleting directory {os.path.join(root, dir)}: {e}") | |
#--------------- | |
uploaded_files_ESG = st.sidebar.file_uploader("Choose a Sustainability Report", accept_multiple_files=True, key="ESG_files") | |
for uploaded_file in uploaded_files_ESG: | |
st.write("filename:", uploaded_file.name) | |
def save_uploadedfile(uploadedfile): | |
with open(os.path.join("ESG_Documents",uploadedfile.name),"wb") as f: | |
f.write(uploadedfile.getbuffer()) | |
return st.success("Saved File:{} to ESG_Documents".format(uploadedfile.name)) | |
save_uploadedfile(uploaded_file) | |
#--------------- | |
def ESG_strategy(): | |
doc_retriever_ESG, _ = create_vector_database_ESG() | |
prompt_template = """<|system|> | |
You are a seasoned specialist in environmental, social and governance matters. You write expert analyses for institutional investors. Always use figures, nemerical and statistical data when possible. Output must have sub-headings in bold font and be fluent.<|end|> | |
<|user|> | |
Answer the {question} based on the information you find in context: {context} <|end|> | |
<|assistant|>""" | |
prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"]) | |
qa = ( | |
{ | |
"context": doc_retriever_ESG, | |
"question": RunnablePassthrough(), | |
} | |
| prompt | |
| llm | |
| StrOutputParser() | |
) | |
ESG_answer_1 = qa.invoke("Give a summary what specific ESG measures the company has taken recently and compare these to the best practices.") | |
ESG_answer_2 = qa.invoke("Does the company's main business fall under the European Union's taxonomy regulation? Answer whether the company is taxonomy compliant under European Union Taxonomy Regulation?") | |
ESG_answer_3 = qa.invoke("Describe what specific ESG transparency commitments the company has given. Give details how the company has followed the Paris Treaty's obligation to limit globabl warming to 1.5 celcius degrees.") | |
ESG_answer_4 = qa.invoke("Does the company have carbon emissions reduction plan? Has the company reached its carbon dioxide reduction objectives? Set the company's carbon footprint by location and its development or equivalent figures in a table. List carbon dioxide emissions compared to turnover.") | |
ESG_answer_5 = qa.invoke("Describe and set out in a table the following specific information: (i) Scope 1 CO2 emissions, (ii) Scope 2 CO2 emissions, and (iii) Scope 3 CO2 emissions of the company for 2021, 2022 and 2023. List the material changes relating to these figures.") | |
ESG_answer_6 = qa.invoke("List in a table the company's energy and renewable energy usage for each material activity. Explain the main energy efficiency measures taken by the company.") | |
ESG_answer_7 = qa.invoke("Does the company follow UN Guiding Principles on Business and Human Rights, ILO Declaration on Fundamental Principles and Rights at Work or OECD Guidelines for Multinational Enterprises that involve affected communities?") | |
ESG_answer_8 = qa.invoke("List the environmental permits and certifications held by the company. Set out and explain any environmental procedures, investigations, and decisions taken against the company. Answer whether the company's locations or operations are connected to areas sensitive in relation to biodiversity.") | |
ESG_answer_9 = qa.invoke("Set out waste management produces by the company and possible waste into the soil. Describe if the company's real estates have hazardous waste.") | |
ESG_answer_10 = qa.invoke("What percentage of women are represented in the (i) board, (ii) executive directors, and (iii) upper management? Set out the measures taken to have the gender balance on the upper management of the company.") | |
ESG_answer_11 = qa.invoke("What policies has the company implemented to counter money laundering and corruption?") | |
ESG_output = f"**__Summary of ESG reporting and obligations:__** {ESG_answer_1} \n\n **__Compliance with taxonomy:__** \n\n {ESG_answer_2} \n\n **__Disclosure transparency:__** \n\n {ESG_answer_3} \n\n **__Carbon footprint:__** \n\n {ESG_answer_4} \n\n **__Carbon dioxide emissions:__** \n\n {ESG_answer_5} \n\n **__Renewable energy:__** \n\n {ESG_answer_6} \n\n **__Human rights compliance:__** \n\n {ESG_answer_7} \n\n **__Management and gender balance:__** \n\n {ESG_answer_8} \n\n **__Waste and other emissions:__** {ESG_answer_9} \n\n **__Gender equality:__** {ESG_answer_10} \n\n **__Anti-money laundering:__** {ESG_answer_11}" | |
with open("ESG_analysis.txt", 'w') as file: | |
file.write(ESG_output) | |
return ESG_output | |
#------------- | |
def generate_ESG_strategy() -> str: | |
ESG_output = ESG_strategy() | |
st.session_state.results["ESG_analysis_button_key"] = ESG_output | |
return ESG_output | |
#--------------- | |
#@st.cache_data | |
def create_pdf(): | |
text_file = "ESG_analysis.txt" | |
pdf = FPDF('P', 'mm', 'A4') | |
pdf.add_page() | |
pdf.set_margins(10, 10, 10) | |
pdf.set_font("Arial", size=15) | |
#image = "lt.png" | |
#pdf.image(image, w = 40) | |
# Add introductory lines | |
#pdf.cell(0, 10, txt="Company name", ln=1, align='C') | |
pdf.cell(0, 10, txt="Structured ESG Analysis", ln=2, align='C') | |
pdf.ln(5) | |
pdf.set_font("Arial", size=11) | |
try: | |
with open(text_file, 'r', encoding='utf-8') as f: | |
for line in f: | |
# Replace '\u2019' with a different character or string | |
#line = line.replace('\u2019', "'") # For example, replace with apostrophe | |
#line = line.replace('\u2265', "'") # For example, replace with apostrophe | |
#pdf.multi_cell(0, 6, txt=line, align='L') | |
pdf.multi_cell(0, 6, txt=line.encode('latin-1', 'replace').decode('latin-1'), align='L') | |
pdf.ln(5) | |
except UnicodeEncodeError: | |
print("UnicodeEncodeError: Some characters could not be encoded in Latin-1. Skipping...") | |
pass # Skip the lines causing UnicodeEncodeError | |
output_pdf_path = "ESG_analysis.pdf" | |
pdf.output(output_pdf_path) | |
#---------------- | |
#llm = build_llm() | |
if 'results' not in st.session_state: | |
st.session_state.results = { | |
"ESG_analysis_button_key": {} | |
} | |
loaders = {'.pdf': PyMuPDFLoader, | |
'.xml': UnstructuredXMLLoader, | |
'.csv': CSVLoader, | |
} | |
def create_directory_loader(file_type, directory_path): | |
return DirectoryLoader( | |
path=directory_path, | |
glob=f"**/*{file_type}", | |
loader_cls=loaders[file_type], | |
) | |
strategies_container = st.container() | |
with strategies_container: | |
mrow1_col1, mrow1_col2 = st.columns(2) | |
st.sidebar.info("To get started, please upload the documents from the company you would like to analyze.") | |
button_container = st.sidebar.container() | |
if os.path.exists("ESG_analysis.txt"): | |
create_pdf() | |
with open("ESG_analysis.pdf", "rb") as pdf_file: | |
PDFbyte = pdf_file.read() | |
st.sidebar.download_button(label="Download Analyses", | |
data=PDFbyte, | |
file_name="strategy_sheet.pdf", | |
mime='application/octet-stream', | |
) | |
if button_container.button("Clear All"): | |
st.session_state.button_states = { | |
"ESG_analysis_button_key": False, | |
} | |
st.session_state.results = {} | |
st.session_state['history'] = [] | |
st.session_state['generated'] = ["Let's discuss the ESG issues of the company π€"] | |
st.session_state['past'] = ["Hey ! π"] | |
st.cache_data.clear() | |
st.cache_resource.clear() | |
# Check if the subfolder exists | |
if os.path.exists("ESG_Documents"): | |
for filename in os.listdir("ESG_Documents"): | |
file_path = os.path.join("ESG_Documents", filename) | |
try: | |
if os.path.isfile(file_path): | |
os.unlink(file_path) | |
except Exception as e: | |
st.error(f"Error deleting {file_path}: {e}") | |
else: | |
pass | |
with mrow1_col1: | |
st.subheader("Summary of the ESG Analysis") | |
st.info("This tool is designed to provide a comprehensive ESG risk analysis for institutional investors.") | |
button_container2 = st.container() | |
if "button_states" not in st.session_state: | |
st.session_state.button_states = { | |
"ESG_analysis_button_key": False, | |
} | |
if "results" not in st.session_state: | |
st.session_state.results = {} | |
if button_container2.button("ESG Analysis", key=ESG_analysis_button_key): | |
st.session_state.button_states[ESG_analysis_button_key] = True | |
result_generator = generate_ESG_strategy() # Call the generator function | |
st.session_state.results["ESG_analysis_output"] = result_generator | |
if "ESG_analysis_output" in st.session_state.results: | |
st.write(st.session_state.results["ESG_analysis_output"]) | |
st.divider() | |
with mrow1_col2: | |
if "ESG_analysis_button_key" in st.session_state.results and st.session_state.results["ESG_analysis_button_key"]: | |
doc_retriever_ESG, query_engine = create_vector_database_ESG() | |
memory = ConversationBufferMemory(memory_key="chat_history", k=3, return_messages=True) | |
search = SerpAPIWrapper() | |
# Updated prompt templates to include chat history | |
def format_chat_history(chat_history): | |
"""Format chat history as a single string for input to the chain.""" | |
formatted_history = "\n".join([f"User: {entry['input']}\nAI: {entry['output']}" for entry in chat_history]) | |
return formatted_history | |
prompt_ESG = PromptTemplate.from_template( | |
template=""" | |
You are a seasoned finance specialist and a specialist in environmental, social, and governance matters. | |
Use figures, and numerical, and statistical data when possible. Never give false information, numbers or data. | |
Conversation history: | |
{chat_history} | |
Based on the context: {context}, answer the following question: {question}. | |
""" | |
) | |
ESG_chain = ( | |
{ | |
"context": doc_retriever_ESG, | |
"chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]), | |
"question": RunnablePassthrough(), | |
} | |
| prompt_ESG | |
| llm_tool | |
| StrOutputParser() | |
) | |
# Define the vector query engine tool | |
vector_query_tool_ESG = Tool( | |
name="Vector Query Engine ESG", | |
func=lambda query: query_engine.query(query), # Use query_engine to query the vector database | |
description="Useful for answering questions about specific ESG figures, data and specific statistics.", | |
) | |
tools = [ | |
Tool( | |
name="ESG QA System", | |
func=ESG_chain.invoke, | |
description="Useful for answering general ESG questions related to the company. ", | |
), | |
Tool( | |
name="Search Tool", | |
func=search.run, | |
description="Useful for answering financial, or general questions, but not ESG or sustainability questions.", | |
), | |
vector_query_tool_ESG, | |
] | |
# Initialize the agent with LCEL tools and memory | |
agent = initialize_agent( | |
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, handle_parsing_errors=True) | |
def conversational_chat(query): | |
# Get the result from the agent | |
result = agent.invoke({"input": query, "chat_history": st.session_state['history']}) | |
# Handle different response types | |
if isinstance(result, dict): | |
# Extract the main content if the result is a dictionary | |
result = result.get("output", "") # Adjust the key as needed based on your agent's output | |
elif isinstance(result, list): | |
# If the result is a list, join it into a single string | |
result = "\n".join(result) | |
elif not isinstance(result, str): | |
# Convert the result to a string if it is not already one | |
result = str(result) | |
# Add the query and the result to the session state | |
st.session_state['history'].append((query, result)) | |
# Update memory with the conversation | |
memory.save_context({"input": query}, {"output": result}) | |
# Return the result | |
return result | |
# Ensure session states are initialized | |
if 'history' not in st.session_state: | |
st.session_state['history'] = [] | |
if 'generated' not in st.session_state: | |
st.session_state['generated'] = ["Let's discuss the ESG matters and financial matters π€"] | |
if 'past' not in st.session_state: | |
st.session_state['past'] = ["Hey ! π"] | |
if 'input' not in st.session_state: | |
st.session_state['input'] = "" | |
# Streamlit layout | |
st.subheader("Discuss the ESG and financial matters") | |
st.info("This tool is designed to enable discussion about the ESG and financial matters concerning the company.") | |
response_container = st.container() | |
container = st.container() | |
with container: | |
with st.form(key='my_form'): | |
user_input = st.text_input("Query:", placeholder="What would you like to know about ESG and financial matters", key='input') | |
submit_button = st.form_submit_button(label='Send') | |
if submit_button and user_input: | |
output = conversational_chat(user_input) | |
st.session_state['past'].append(user_input) | |
st.session_state['generated'].append(output) | |
user_input = "Query:" | |
#st.session_state['input'] = "" | |
# Display generated responses | |
if st.session_state['generated']: | |
with response_container: | |
for i in range(len(st.session_state['generated'])): | |
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="shapes") | |
message(st.session_state["generated"][i], key=str(i), avatar_style="icons") |