Mjlehtim commited on
Commit
04f546c
1 Parent(s): 05cdb5c

Change of the base software

Browse files
Files changed (1) hide show
  1. LocalT_ESG_RAG_1.25.py +0 -821
LocalT_ESG_RAG_1.25.py DELETED
@@ -1,821 +0,0 @@
1
- import os
2
- import shutil
3
- import streamlit as st
4
- from fpdf import FPDF
5
- from chromadb import Client
6
- from chromadb.config import Settings
7
- import chromadb
8
- from langchain_community.utilities import SerpAPIWrapper
9
- from llama_index.core import VectorStoreIndex
10
- from langchain_core.output_parsers import StrOutputParser
11
- from langchain_core.runnables import RunnablePassthrough
12
- from langchain_groq import ChatGroq
13
- from langchain.chains import LLMChain
14
- from langchain.agents import AgentType, Tool, initialize_agent, AgentExecutor
15
- from llama_parse import LlamaParse
16
- from langchain_community.document_loaders import UnstructuredMarkdownLoader
17
- from langchain_huggingface import HuggingFaceEmbeddings
18
- from llama_index.core import SimpleDirectoryReader
19
- from dotenv import load_dotenv, find_dotenv
20
- import pandas as pd
21
- from streamlit_chat import message
22
- from langchain_community.vectorstores import Chroma
23
- from langchain_community.utilities import SerpAPIWrapper
24
- from langchain.chains import RetrievalQA
25
- from langchain_community.document_loaders import DirectoryLoader
26
- from langchain_community.document_loaders import PyMuPDFLoader
27
- from langchain_community.document_loaders import UnstructuredXMLLoader
28
- from langchain_community.document_loaders import CSVLoader
29
- from langchain.prompts import PromptTemplate
30
- from langchain.text_splitter import RecursiveCharacterTextSplitter
31
- from langchain.memory import ConversationBufferMemory
32
- from langchain.prompts import PromptTemplate
33
- import joblib
34
- import nltk
35
-
36
- import nest_asyncio # noqa: E402
37
- nest_asyncio.apply()
38
-
39
- load_dotenv()
40
- load_dotenv(find_dotenv())
41
-
42
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
43
- SERPAPI_API_KEY = os.environ["SERPAPI_API_KEY"]
44
- GOOGLE_CSE_ID = os.environ["GOOGLE_CSE_ID"]
45
- GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
46
- LLAMA_PARSE_API_KEY = os.environ["LLAMA_PARSE_API_KEY"]
47
- HUGGINGFACEHUB_API_TOKEN = os.environ["HUGGINGFACEHUB_API_TOKEN"]
48
- groq_api_key=os.getenv('GROQ_API_KEY')
49
-
50
- st.set_page_config(layout="wide")
51
-
52
- css = """
53
- <style>
54
- [data-testid="stAppViewContainer"] {
55
- background-color: #f8f9fa; /* Very light grey */
56
- }
57
- [data-testid="stSidebar"] {
58
- background-color: white;
59
- color: black;
60
- }
61
- [data-testid="stAppViewContainer"] * {
62
- color: black; /* Ensure all text is black */
63
- }
64
- button {
65
- background-color: #add8e6; /* Light blue for primary buttons */
66
- color: black;
67
- border: 2px solid green; /* Green border */
68
- }
69
- button:hover {
70
- background-color: #87ceeb; /* Slightly darker blue on hover */
71
- }
72
-
73
- button:active {
74
- outline: 2px solid green; /* Green outline when the button is pressed */
75
- outline-offset: 2px; /* Space between button and outline */
76
- }
77
-
78
- .stButton>button:first-child {
79
- background-color: #add8e6; /* Light blue for primary buttons */
80
- color: black;
81
- }
82
- .stButton>button:first-child:hover {
83
- background-color: #87ceeb; /* Slightly darker blue on hover */
84
- }
85
- .stButton>button:nth-child(2) {
86
- background-color: #b0e0e6; /* Even lighter blue for secondary buttons */
87
- color: black;
88
- }
89
- .stButton>button:nth-child(2):hover {
90
- background-color: #add8e6; /* Slightly darker blue on hover */
91
- }
92
- [data-testid="stFileUploadDropzone"] {
93
- background-color: white; /* White background for file upload */
94
- }
95
- [data-testid="stFileUploadDropzone"] .stDropzone, [data-testid="stFileUploadDropzone"] .stDropzone input {
96
- color: black; /* Ensure file upload text is black */
97
- }
98
-
99
- .stButton>button:active {
100
- outline: 2px solid green; /* Green outline when the button is pressed */
101
- outline-offset: 2px;
102
- }
103
- </style>
104
- """
105
-
106
- st.write(css, unsafe_allow_html=True)
107
- st.sidebar.image('lt.png', width=250)
108
- #-------------
109
- llm=ChatGroq(groq_api_key=groq_api_key,
110
- model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True)
111
- #--------------
112
- doc_retriever_ESG = None
113
- doc_retriever_financials = None
114
- #--------------
115
-
116
- #@st.cache_data
117
- def load_or_parse_data_ESG():
118
- data_file = "./data/parsed_data_ESG.pkl"
119
-
120
- parsingInstructionUber10k = """The provided document contain detailed information about the company's environmental, social and governance matters.
121
- It contains several tables, figures and statistical information. You must be precise while answering the questions and never provide false numeric or statistical data."""
122
-
123
- parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
124
- result_type="markdown",
125
- parsing_instruction=parsingInstructionUber10k,
126
- max_timeout=5000,
127
- gpt4o_mode=True,
128
- )
129
-
130
- file_extractor = {".pdf": parser}
131
- reader = SimpleDirectoryReader("./ESG_Documents", file_extractor=file_extractor)
132
- documents = reader.load_data()
133
-
134
- print("Saving the parse results in .pkl format ..........")
135
- joblib.dump(documents, data_file)
136
-
137
- # Set the parsed data to the variable
138
- parsed_data_ESG = documents
139
-
140
- return parsed_data_ESG
141
-
142
- #@st.cache_data
143
- def load_or_parse_data_financials():
144
- data_file = "./data/parsed_data_financials.pkl"
145
-
146
- parsingInstructionUber10k = """The provided document is the company's annual reports and includes financial statement, balance sheet, cash flow sheet and description of the company's business and operations.
147
- It contains several tabless, figures and statistical information. You must be precise while answering the questions and never provide false numeric or statistical data."""
148
-
149
- parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
150
- result_type="markdown",
151
- parsing_instruction=parsingInstructionUber10k,
152
- max_timeout=5000,
153
- gpt4o_mode=True,
154
- )
155
-
156
- file_extractor = {".pdf": parser}
157
- reader = SimpleDirectoryReader("./Financial_Documents", file_extractor=file_extractor)
158
- documents = reader.load_data()
159
-
160
- print("Saving the parse results in .pkl format ..........")
161
- joblib.dump(documents, data_file)
162
-
163
- # Set the parsed data to the variable
164
- parsed_data_financials = documents
165
-
166
- return parsed_data_financials
167
-
168
- #@st.cache_data
169
- def load_or_parse_data_portfolio():
170
- data_file = "./data/parsed_data_portfolio.pkl"
171
-
172
- parsingInstructionUber10k = """The provided document is the ESG and sustainability report of LocalTapiola (Lähitapiola) group including the funds it manages.
173
- It contains several tabless, figures and statistical information. You must be precise while answering the questions and never provide false numeric or statistical data."""
174
-
175
- parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
176
- result_type="markdown",
177
- parsing_instruction=parsingInstructionUber10k,
178
- max_timeout=5000,
179
- gpt4o_mode=True,
180
- )
181
-
182
- file_extractor = {".pdf": parser}
183
- reader = SimpleDirectoryReader("./ESG_Documents_Portfolio", file_extractor=file_extractor)
184
- documents = reader.load_data()
185
-
186
- print("Saving the parse results in .pkl format ..........")
187
- joblib.dump(documents, data_file)
188
-
189
- # Set the parsed data to the variable
190
- parsed_data_portfolio = documents
191
-
192
- return parsed_data_portfolio
193
- #--------------
194
- # Create vector database
195
-
196
- @st.cache_resource
197
- def create_vector_database_ESG():
198
- # Call the function to either load or parse the data
199
- llama_parse_documents = load_or_parse_data_ESG()
200
-
201
- with open('data/output_ESG.md', 'a') as f: # Open the file in append mode ('a')
202
- for doc in llama_parse_documents:
203
- f.write(doc.text + '\n')
204
-
205
- markdown_path = "data/output_ESG.md"
206
- loader = UnstructuredMarkdownLoader(markdown_path)
207
-
208
- #loader = DirectoryLoader('data/', glob="**/*.md", show_progress=True)
209
- documents = loader.load()
210
- # Split loaded documents into chunks
211
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
212
- docs = text_splitter.split_documents(documents)
213
-
214
- #len(docs)
215
- print(f"length of documents loaded: {len(documents)}")
216
- print(f"total number of document chunks generated :{len(docs)}")
217
- embed_model = HuggingFaceEmbeddings()
218
- #embed_model = OpenAIEmbeddings()
219
- # Create and persist a Chroma vector database from the chunked documents
220
- # Set up the Chroma client in local mode
221
- print('Vector DB not yet created !')
222
- persist_directory = os.path.join(os.getcwd(), "chroma_db_LT")
223
- if not os.path.exists(persist_directory):
224
- os.makedirs(persist_directory)
225
-
226
- vs = Chroma.from_documents(
227
- documents=docs,
228
- embedding=embed_model,
229
- persist_directory=persist_directory, # Local mode with in-memory storage only
230
- collection_name="rag",
231
- )
232
-
233
- doc_retriever_ESG = vs.as_retriever()
234
-
235
- print('Vector DB created successfully !')
236
- return doc_retriever_ESG
237
-
238
- @st.cache_resource
239
- def create_vector_database_financials():
240
- # Call the function to either load or parse the data
241
- llama_parse_documents = load_or_parse_data_financials()
242
- print(llama_parse_documents[0].text[:300])
243
-
244
- with open('data/output_financials.md', 'a') as f: # Open the file in append mode ('a')
245
- for doc in llama_parse_documents:
246
- f.write(doc.text + '\n')
247
-
248
- markdown_path = "data/output_financials.md"
249
- loader = UnstructuredMarkdownLoader(markdown_path)
250
-
251
- #loader = DirectoryLoader('data/', glob="**/*.md", show_progress=True)
252
- documents = loader.load()
253
- # Split loaded documents into chunks
254
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
255
- docs = text_splitter.split_documents(documents)
256
-
257
- #len(docs)
258
- print(f"length of documents loaded: {len(documents)}")
259
- print(f"total number of document chunks generated :{len(docs)}")
260
- embed_model = HuggingFaceEmbeddings()
261
- #embed_model = OpenAIEmbeddings()
262
- # Create and persist a Chroma vector database from the chunked documents
263
- persist_directory = os.path.join(os.getcwd(), "chroma_db_fin")
264
- if not os.path.exists(persist_directory):
265
- os.makedirs(persist_directory)
266
-
267
- vs = Chroma.from_documents(
268
- documents=docs,
269
- embedding=embed_model,
270
- persist_directory=persist_directory, # Local mode with in-memory storage only
271
- collection_name="rag"
272
- )
273
- doc_retriever_financials = vs.as_retriever()
274
-
275
- print('Vector DB created successfully !')
276
- return doc_retriever_financials
277
-
278
- @st.cache_resource
279
- def create_vector_database_portfolio():
280
- # Call the function to either load or parse the data
281
- llama_parse_documents = load_or_parse_data_portfolio()
282
- print(llama_parse_documents[0].text[:300])
283
-
284
- with open('data/output_portfolio.md', 'a') as f: # Open the file in append mode ('a')
285
- for doc in llama_parse_documents:
286
- f.write(doc.text + '\n')
287
-
288
- markdown_path = "data/output_portfolio.md"
289
- loader = UnstructuredMarkdownLoader(markdown_path)
290
-
291
- documents = loader.load()
292
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
293
- docs = text_splitter.split_documents(documents)
294
-
295
- print(f"length of documents loaded: {len(documents)}")
296
- print(f"total number of document chunks generated :{len(docs)}")
297
- embed_model = HuggingFaceEmbeddings()
298
-
299
- persist_directory = os.path.join(os.getcwd(), "chroma_db_portfolio")
300
- if not os.path.exists(persist_directory):
301
- os.makedirs(persist_directory)
302
-
303
- vs = Chroma.from_documents(
304
- documents=docs,
305
- embedding=embed_model,
306
- persist_directory=persist_directory, # Local mode with in-memory storage only
307
- collection_name="rag"
308
- )
309
- doc_retriever_portfolio = vs.as_retriever()
310
-
311
- print('Vector DB created successfully !')
312
- return doc_retriever_portfolio
313
- #--------------
314
- ESG_analysis_button_key = "ESG_strategy_button"
315
- portfolio_analysis_button_key = "portfolio_strategy_button"
316
-
317
- #---------------
318
- def delete_files_and_folders(folder_path):
319
- for root, dirs, files in os.walk(folder_path, topdown=False):
320
- for file in files:
321
- try:
322
- os.unlink(os.path.join(root, file))
323
- except Exception as e:
324
- st.error(f"Error deleting {os.path.join(root, file)}: {e}")
325
- for dir in dirs:
326
- try:
327
- os.rmdir(os.path.join(root, dir))
328
- except Exception as e:
329
- st.error(f"Error deleting directory {os.path.join(root, dir)}: {e}")
330
- #---------------
331
-
332
- uploaded_files_ESG = st.sidebar.file_uploader("Choose a Sustainability Report", accept_multiple_files=True, key="ESG_files")
333
- for uploaded_file in uploaded_files_ESG:
334
- #bytes_data = uploaded_file.read()
335
- st.write("filename:", uploaded_file.name)
336
- def save_uploadedfile(uploadedfile):
337
- with open(os.path.join("ESG_Documents",uploadedfile.name),"wb") as f:
338
- f.write(uploadedfile.getbuffer())
339
- return st.success("Saved File:{} to ESG_Documents".format(uploadedfile.name))
340
- save_uploadedfile(uploaded_file)
341
-
342
- uploaded_files_financials = st.sidebar.file_uploader("Choose an Annual Report", accept_multiple_files=True, key="financial_files")
343
- for uploaded_file in uploaded_files_financials:
344
- #bytes_data = uploaded_file.read()
345
- st.write("filename:", uploaded_file.name)
346
- def save_uploadedfile(uploadedfile):
347
- with open(os.path.join("Financial_Documents",uploadedfile.name),"wb") as f:
348
- f.write(uploadedfile.getbuffer())
349
- return st.success("Saved File:{} to Financial_Documents".format(uploadedfile.name))
350
- save_uploadedfile(uploaded_file)
351
-
352
- #---------------
353
- def ESG_strategy():
354
- doc_retriever_ESG = create_vector_database_ESG()
355
- prompt_template = """<|system|>
356
- 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|>
357
- <|user|>
358
- Answer the {question} based on the information you find in context: {context} <|end|>
359
- <|assistant|>"""
360
-
361
- prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
362
-
363
- qa = (
364
- {
365
- "context": doc_retriever_ESG,
366
- "question": RunnablePassthrough(),
367
- }
368
- | prompt
369
- | llm
370
- | StrOutputParser()
371
- )
372
-
373
- ESG_answer_1 = qa.invoke("Give a summary what ESG measures the company has taken and compare these to the best practices. Has the company issues green bonds or green loans.")
374
- ESG_answer_2 = qa.invoke("Do the company's main business fall under the European Union's taxonomy regulation? Is the company taxonomy compliant under European Union Taxonomy Regulation? Does the company follow the Paris Treaty's obligation to limit globabl warming to 1.5 celcius degrees? What are the measures to achieve this goal")
375
- ESG_answer_3 = qa.invoke("Explain what items of ESG information the company publishes. Describe what ESG transparency commitments the company has given?")
376
- ESG_answer_4 = qa.invoke("Does the company have carbon emissions reduction plan? Set out in a table the company's carbon footprint by location and its development over time. Set out carbon dioxide emissions in relation to turnover and whether the company has reached its carbod dioxide reduction objectives")
377
- ESG_answer_5 = qa.invoke("Describe and give a time series table of the company's carbon dioxide emissions (Scope 1), carbon dioxide emissions from purchased energy (Scope 2) and other indirect carbon dioxide emissions (Scope 3). Set out the company's objectives and material developments relating to these figures")
378
- ESG_answer_6 = qa.invoke("Set out in a table the company's energy and renewable energy usage for each activity coverning the last two or three years. Explain the energy efficiency measures taken by the company. Does the company have a plan to make its use of energy greemer?.")
379
- 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? Set out the measures taken to have the gender balance on the upper management of the company.")
380
- ESG_answer_8 = qa.invoke("List the environmental permits and certifications held by the company. Set out and explain any environmental procedures and investigations and decisions taken against the company. Answer whether the company's locations or operations are connected to areas sensitive in relation to biodiversity.")
381
- ESG_answer_9 = qa.invoke("Set out waste produces by the company and possible waste into the soil by real estate. Describe if the company's real estates have hazardous waste.")
382
- ESG_answer_10 = qa.invoke("What policies has the company implemented to counter money laundering and corruption? What percentage of women are represented in the board, executive directors and upper management?")
383
-
384
- 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 **__Money laundering and corruption:__** {ESG_answer_10}"
385
- financial_output = ESG_output
386
-
387
- with open("ESG_analysis.txt", 'w') as file:
388
- file.write(financial_output)
389
-
390
- return financial_output
391
-
392
- def portfolio_strategy():
393
- persist_directory_ESG = "chroma_db_LT"
394
- embeddings = HuggingFaceEmbeddings()
395
- doc_retriever_ESG = Chroma(persist_directory=persist_directory_ESG, embedding_function=embeddings).as_retriever()
396
-
397
- doc_retriever_portfolio = create_vector_database_portfolio()
398
- prompt_portfolio = PromptTemplate.from_template(
399
- template="""<|system|>
400
- You are a seasoned finance specialist and a specialist in environmental, social and governance matters. You write expert portofolion analyses fund management. Always use figures, numerical and statistical data when possible. Output must have sub-headings in bold font and be fluent.<|end|>
401
- <|user|> Based on the {context}, write a summary of LähiTapiola's investment policy. Set out also the most important ESG and sustainability aspects of the policy.<|end|>"\
402
- <|assistant|>""")
403
-
404
- prompt_strategy = PromptTemplate.from_template(
405
- template="""<|system|>
406
- You are a seasoned specialist in environmental, social and governance matters. You analyse companies' ESG matters. Always use figures, numerical and statistical data when possible. Output must have sub-headings in bold font and be fluent.<|end|>
407
- <|user|> Based on the {context}, give a summary of the target company's ESG policy. Set out also the most important ESG and sustainability aspects of the policy.<|end|>"\
408
- <|assistant|>""")
409
-
410
- prompt_analysis = PromptTemplate.from_template(
411
- template="""<|system|>
412
- You are a seasoned finance specialist and a specialist in environmental, social and governance matters. You write expert portofolio analyses fund management. Always use figures, numerical and statistical data when possible. Output must have sub-headings in bold font and be fluent.<|end|>
413
- <|user|> Answer the {question} based on {company_ESG} and {fund_policy}.<|end|>"\
414
- <|assistant|>""")
415
-
416
- portfolio_chain = (
417
- {
418
- "context": doc_retriever_portfolio,
419
- #"question": RunnablePassthrough(),
420
- }
421
- | prompt_portfolio
422
- | llm
423
- | StrOutputParser()
424
- )
425
- strategy_chain = (
426
- {
427
- "context": doc_retriever_ESG,
428
- #"question": RunnablePassthrough(),
429
- }
430
- | prompt_strategy
431
- | llm
432
- | StrOutputParser()
433
- )
434
-
435
- analysis_chain = (
436
- {
437
- "company_ESG": strategy_chain,
438
- "fund_policy": portfolio_chain,
439
- "question": RunnablePassthrough(),
440
- }
441
- | prompt_analysis
442
- | llm
443
- | StrOutputParser()
444
- )
445
-
446
- portfolio_answer = analysis_chain.invoke("is the company's ESG such that it fits within LähiTapiola's investment policy of: {fund_policy}? Give a policy rating")
447
- portfolio_output = f"**__Summary of fit with LähiTapiola's sustainability policy:__** {portfolio_answer} \n"
448
-
449
- with open("portfolio_analysis.txt", 'w') as file:
450
- file.write(portfolio_output)
451
-
452
- return portfolio_output
453
-
454
- #-------------
455
- @st.cache_data
456
- def generate_ESG_strategy() -> str:
457
- ESG_output = ESG_strategy()
458
- st.session_state.results["ESG_analysis_button_key"] = ESG_output
459
- return ESG_output
460
-
461
- @st.cache_data
462
- def generate_portfolio_analysis() -> str:
463
- portfolio_output = portfolio_strategy()
464
- st.session_state.results["portfolio_analysis_button_key"] = portfolio_output
465
- return portfolio_output
466
- #---------------
467
- #@st.cache_data
468
- def create_pdf():
469
- text_file = "ESG_analysis.txt"
470
- pdf = FPDF('P', 'mm', 'A4')
471
- pdf.add_page()
472
- pdf.set_margins(10, 10, 10)
473
- pdf.set_font("Arial", size=15)
474
- image = "lt.png"
475
- pdf.image(image, w = 40)
476
- # Add introductory lines
477
- #pdf.cell(0, 10, txt="Company name", ln=1, align='C')
478
- pdf.cell(0, 10, txt="Structured ESG Analysis", ln=2, align='C')
479
- pdf.ln(5)
480
-
481
- pdf.set_font("Arial", size=11)
482
- try:
483
- with open(text_file, 'r', encoding='utf-8') as f:
484
- for line in f:
485
- # Replace '\u2019' with a different character or string
486
- #line = line.replace('\u2019', "'") # For example, replace with apostrophe
487
- #line = line.replace('\u2265', "'") # For example, replace with apostrophe
488
- #pdf.multi_cell(0, 6, txt=line, align='L')
489
- pdf.multi_cell(0, 6, txt=line.encode('latin-1', 'replace').decode('latin-1'), align='L')
490
- pdf.ln(5)
491
- except UnicodeEncodeError:
492
- print("UnicodeEncodeError: Some characters could not be encoded in Latin-1. Skipping...")
493
- pass # Skip the lines causing UnicodeEncodeError
494
-
495
- output_pdf_path = "ESG_analysis.pdf"
496
- pdf.output(output_pdf_path)
497
-
498
- #----------------
499
- #llm = build_llm()
500
-
501
- if 'results' not in st.session_state:
502
- st.session_state.results = {
503
- "ESG_analysis_button_key": {}
504
- }
505
-
506
- loaders = {'.pdf': PyMuPDFLoader,
507
- '.xml': UnstructuredXMLLoader,
508
- '.csv': CSVLoader,
509
- }
510
-
511
- def create_directory_loader(file_type, directory_path):
512
- return DirectoryLoader(
513
- path=directory_path,
514
- glob=f"**/*{file_type}",
515
- loader_cls=loaders[file_type],
516
- )
517
-
518
-
519
- strategies_container = st.container()
520
- with strategies_container:
521
- mrow1_col1, mrow1_col2 = st.columns(2)
522
-
523
- st.sidebar.info("To get started, please upload the documents from the company you would like to analyze.")
524
- button_container = st.sidebar.container()
525
- if os.path.exists("ESG_analysis.txt"):
526
- create_pdf()
527
- with open("ESG_analysis.pdf", "rb") as pdf_file:
528
- PDFbyte = pdf_file.read()
529
-
530
- st.sidebar.download_button(label="Download Analyses",
531
- data=PDFbyte,
532
- file_name="strategy_sheet.pdf",
533
- mime='application/octet-stream',
534
- )
535
-
536
- if button_container.button("Clear All"):
537
-
538
- st.session_state.button_states = {
539
- "ESG_analysis_button_key": False,
540
- }
541
- st.session_state.button_states = {
542
- "portfolio_analysis_button_key": False,
543
- }
544
- st.session_state.results = {}
545
-
546
- st.session_state['history'] = []
547
- st.session_state['generated'] = ["Let's discuss the ESG issues of the company 🤗"]
548
- st.session_state['past'] = ["Hey ! 👋"]
549
- st.cache_data.clear()
550
- st.cache_resource.clear()
551
-
552
- # Check if the subfolder exists
553
- if os.path.exists("ESG_Documents"):
554
- for filename in os.listdir("ESG_Documents"):
555
- file_path = os.path.join("ESG_Documents", filename)
556
- try:
557
- if os.path.isfile(file_path):
558
- os.unlink(file_path)
559
- except Exception as e:
560
- st.error(f"Error deleting {file_path}: {e}")
561
- else:
562
- pass
563
-
564
- if os.path.exists("Financial_Documents"):
565
- # Iterate through files in the subfolder and delete them
566
- for filename in os.listdir("Financial_Documents"):
567
- file_path = os.path.join("Financial_Documents", filename)
568
- try:
569
- if os.path.isfile(file_path):
570
- os.unlink(file_path)
571
- except Exception as e:
572
- st.error(f"Error deleting {file_path}: {e}")
573
- else:
574
- pass
575
- # st.warning("No 'data' subfolder found.")
576
-
577
- folders_to_clean = ["data", "chroma_db_portfolio", "chroma_db_LT", "chroma_db_fin"]
578
-
579
- for folder_path in folders_to_clean:
580
- if os.path.exists(folder_path):
581
- for item in os.listdir(folder_path):
582
- item_path = os.path.join(folder_path, item)
583
- try:
584
- if os.path.isfile(item_path) or os.path.islink(item_path):
585
- os.unlink(item_path) # Remove files or symbolic links
586
- elif os.path.isdir(item_path):
587
- shutil.rmtree(item_path) # Remove subfolders and all their contents
588
- except Exception as e:
589
- st.error(f"Error deleting {item_path}: {e}")
590
- else:
591
- pass
592
- # st.warning(f"No '{folder_path}' folder found.")
593
-
594
- with mrow1_col1:
595
- st.subheader("Summary of the ESG Analysis")
596
- st.info("This tool is designed to provide a comprehensive ESG risk analysis for institutional investors.")
597
- button_container2 = st.container()
598
- if "button_states" not in st.session_state:
599
- st.session_state.button_states = {
600
- "ESG_analysis_button_key": False,
601
- }
602
-
603
- if "results" not in st.session_state:
604
- st.session_state.results = {}
605
-
606
- if button_container2.button("ESG Analysis", key=ESG_analysis_button_key):
607
- st.session_state.button_states[ESG_analysis_button_key] = True
608
- result_generator = generate_ESG_strategy() # Call the generator function
609
- st.session_state.results["ESG_analysis_output"] = result_generator
610
-
611
- if "ESG_analysis_output" in st.session_state.results:
612
- st.write(st.session_state.results["ESG_analysis_output"])
613
- st.divider()
614
-
615
- with mrow1_col2:
616
- st.subheader("Analyze the ESG summary and LähiTapiola's investment policy")
617
- st.info("This tool enables analysing the company's ESG policy with respect to the portfolio and investment policy.")
618
- uploaded_files_portfolio = st.file_uploader("Choose a pdf file", accept_multiple_files=True, key="portfolio_files")
619
- for uploaded_file in uploaded_files_portfolio:
620
- st.write("filename:", uploaded_file.name)
621
- def save_uploadedfile(uploadedfile):
622
- with open(os.path.join("ESG_Documents_Portfolio",uploadedfile.name),"wb") as f:
623
- f.write(uploadedfile.getbuffer())
624
- return st.success("Saved File:{} to ESG_Documents_Portfolio".format(uploadedfile.name))
625
- save_uploadedfile(uploaded_file)
626
- button_container3 = st.container()
627
- #st.button("Portfolio Analysis")
628
- if "button_states" not in st.session_state:
629
- st.session_state.button_states = {
630
- "portfolio_analysis_button_key": False,
631
- }
632
- if button_container3.button("Portfolio Analysis", key=portfolio_analysis_button_key):
633
- st.session_state.button_states[portfolio_analysis_button_key] = True
634
- portfolio_result_generator = generate_portfolio_analysis()
635
- st.session_state.results["portfolio_analysis_output"] = portfolio_result_generator
636
- st.write(portfolio_result_generator)
637
-
638
- if "portfolio_analysis_output" in st.session_state.results:
639
- st.write(st.session_state.results["portfolio_analysis_output"])
640
-
641
- st.divider()
642
-
643
- with mrow1_col2:
644
- if "ESG_analysis_button_key" in st.session_state.results and st.session_state.results["ESG_analysis_button_key"]:
645
- doc_retriever_ESG = create_vector_database_ESG()
646
- doc_retriever_financials = create_vector_database_financials()
647
-
648
- persist_directory = os.path.join(os.getcwd(), "chroma_db_portfolio")
649
- if not os.path.exists(persist_directory):
650
- os.makedirs(persist_directory)
651
-
652
- # Load the Chroma retriever from the persisted directory
653
- embeddings = HuggingFaceEmbeddings()
654
- doc_retriever_portfolio = Chroma(persist_directory=persist_directory, embedding_function=embeddings).as_retriever()
655
-
656
- memory = ConversationBufferMemory(memory_key="chat_history", k=3, return_messages=True)
657
- search = SerpAPIWrapper()
658
-
659
- # Updated prompt templates to include chat history
660
- def format_chat_history(chat_history):
661
- """Format chat history as a single string for input to the chain."""
662
- formatted_history = "\n".join([f"User: {entry['input']}\nAI: {entry['output']}" for entry in chat_history])
663
- return formatted_history
664
-
665
- prompt_portfolio = PromptTemplate.from_template(
666
- template="""
667
- You are a seasoned finance specialist and a specialist in environmental, social, and governance matters.
668
- Use figures, numerical, and statistical data when possible.
669
-
670
- Conversation history:
671
- {chat_history}
672
-
673
- Based on the context: {context}, write a summary of LähiTapiola's investment policy. Set out also the most important ESG and sustainability aspects of the policy.
674
- """
675
- )
676
-
677
- prompt_financials = PromptTemplate.from_template(
678
- template="""
679
- You are a seasoned corporate finance specialist.
680
- Use figures, numerical, and statistical data when possible.
681
-
682
- Conversation history:
683
- {chat_history}
684
-
685
- Based on the context: {context}, answer the following question: {question}.
686
- """
687
- )
688
-
689
- prompt_ESG = PromptTemplate.from_template(
690
- template="""
691
- You are a seasoned finance specialist and a specialist in environmental, social, and governance matters.
692
- Use figures, numerical, and statistical data when possible.
693
-
694
- Conversation history:
695
- {chat_history}
696
-
697
- Based on the context: {context}, write a summary of LähiTapiola's ESG policy. Set out also the most important sustainability aspects of the policy.
698
- """
699
- )
700
-
701
- # LCEL Chains with memory integration
702
- financials_chain = (
703
- {
704
- "context": doc_retriever_financials,
705
- # Lambda function now accepts one argument (even if unused)
706
- "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
707
- "question": RunnablePassthrough(),
708
- }
709
- | prompt_financials
710
- | llm
711
- | StrOutputParser()
712
- )
713
-
714
- portfolio_chain = (
715
- {
716
- "context": doc_retriever_portfolio,
717
- "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
718
- "question": RunnablePassthrough(),
719
- }
720
- | prompt_portfolio
721
- | llm
722
- | StrOutputParser()
723
- )
724
-
725
- ESG_chain = (
726
- {
727
- "context": doc_retriever_ESG,
728
- "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
729
- "question": RunnablePassthrough(),
730
- }
731
- | prompt_ESG
732
- | llm
733
- | StrOutputParser()
734
- )
735
-
736
- # Define the tools with LCEL expressions
737
- tools = [
738
- Tool(
739
- name="ESG QA System",
740
- func=ESG_chain.invoke,
741
- description="Useful for answering questions about environmental, social, and governance (ESG) matters related to the target company, but not LähiTapiola.",
742
- ),
743
- Tool(
744
- name="Financials QA System",
745
- func=financials_chain.invoke,
746
- description="Useful for answering questions about financial or operational information concerning the target company, but not LähiTapiola.",
747
- ),
748
- Tool(
749
- name="Policy QA System",
750
- func=portfolio_chain.invoke,
751
- description="Useful for answering questions about LähiTapiola's ESG policy and sustainability measures.",
752
- ),
753
- Tool(
754
- name="Search Tool",
755
- func=search.run,
756
- description="Useful when other tools do not provide the answer.",
757
- ),
758
- ]
759
-
760
- # Initialize the agent with LCEL tools and memory
761
- agent = initialize_agent(
762
- tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, handle_parsing_errors=True)
763
- def conversational_chat(query):
764
- # Get the result from the agent
765
- result = agent.invoke({"input": query, "chat_history": st.session_state['history']})
766
-
767
- # Handle different response types
768
- if isinstance(result, dict):
769
- # Extract the main content if the result is a dictionary
770
- result = result.get("output", "") # Adjust the key as needed based on your agent's output
771
- elif isinstance(result, list):
772
- # If the result is a list, join it into a single string
773
- result = "\n".join(result)
774
- elif not isinstance(result, str):
775
- # Convert the result to a string if it is not already one
776
- result = str(result)
777
-
778
- # Add the query and the result to the session state
779
- st.session_state['history'].append((query, result))
780
-
781
- # Update memory with the conversation
782
- memory.save_context({"input": query}, {"output": result})
783
-
784
- # Return the result
785
- return result
786
-
787
- # Ensure session states are initialized
788
- if 'history' not in st.session_state:
789
- st.session_state['history'] = []
790
-
791
- if 'generated' not in st.session_state:
792
- st.session_state['generated'] = ["Let's discuss the ESG matters and financial matters 🤗"]
793
-
794
- if 'past' not in st.session_state:
795
- st.session_state['past'] = ["Hey ! 👋"]
796
-
797
- if 'input' not in st.session_state:
798
- st.session_state['input'] = ""
799
-
800
- # Streamlit layout
801
- st.subheader("Discuss the ESG and financial matters")
802
- st.info("This tool is designed to enable discussion about the ESG and financial matters concerning the company and also LocalTapiola's own comprehensive sustainability policy and guidance.")
803
- response_container = st.container()
804
- container = st.container()
805
-
806
- with container:
807
- with st.form(key='my_form'):
808
- user_input = st.text_input("Query:", placeholder="What would you like to know about ESG and financial matters", key='input')
809
- submit_button = st.form_submit_button(label='Send')
810
- if submit_button and user_input:
811
- output = conversational_chat(user_input)
812
- st.session_state['past'].append(user_input)
813
- st.session_state['generated'].append(output)
814
- user_input = "Query:"
815
- #st.session_state['input'] = ""
816
- # Display generated responses
817
- if st.session_state['generated']:
818
- with response_container:
819
- for i in range(len(st.session_state['generated'])):
820
- message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="shapes")
821
- message(st.session_state["generated"][i], key=str(i), avatar_style="icons")