Mjlehtim commited on
Commit
a2465fe
·
verified ·
1 Parent(s): 48ded57

Upload 24 files

Browse files

First app version

AM_Document_Analysis_v1.1.py ADDED
@@ -0,0 +1,1151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
8
+ import chromadb
9
+ from langchain_community.utilities import SerpAPIWrapper
10
+ from llama_index.core import VectorStoreIndex
11
+ from langchain_core.output_parsers import StrOutputParser
12
+ from langchain_core.runnables import RunnablePassthrough
13
+ from langchain_groq import ChatGroq
14
+ from langchain.chains import LLMChain
15
+ from langchain.agents import AgentType, Tool, initialize_agent, AgentExecutor
16
+ from llama_parse import LlamaParse
17
+ from langchain_community.document_loaders import UnstructuredMarkdownLoader
18
+ from langchain_huggingface import HuggingFaceEmbeddings
19
+ from llama_index.core import SimpleDirectoryReader
20
+ from dotenv import load_dotenv, find_dotenv
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
+ from dotenv import load_dotenv, find_dotenv
36
+ import uuid
37
+ from langchain_community.embeddings import HuggingFaceEmbeddings
38
+ from langchain_community.vectorstores import Chroma
39
+ from langchain.chat_models import ChatOpenAI
40
+ from langchain.embeddings import OpenAIEmbeddings
41
+ from langchain.prompts import PromptTemplate
42
+ from yachalk import chalk
43
+ from langchain.vectorstores import PGVector
44
+ from langchain.document_loaders import PyPDFLoader, UnstructuredPDFLoader, PyPDFium2Loader
45
+ from langchain.document_loaders import PyPDFDirectoryLoader
46
+ ## Import all the chains.
47
+ from chains_v2.create_questions import QuestionCreationChain
48
+ from chains_v2.most_pertinent_question import MostPertinentQuestion
49
+ from chains_v2.retrieval_qa import retrieval_qa
50
+ from chains_v2.research_compiler import research_compiler
51
+ from chains_v2.question_atomizer import QuestionAtomizer
52
+ from chains_v2.refine_answer import RefineAnswer
53
+ ## Import all the helpers.
54
+ from helpers.response_helpers import result2QuestionsList
55
+ from helpers.response_helpers import qStr2Dict
56
+ from helpers.questions_helper import getAnsweredQuestions
57
+ from helpers.questions_helper import getUnansweredQuestions
58
+ from helpers.questions_helper import getSubQuestions
59
+ from helpers.questions_helper import getHopQuestions
60
+ from helpers.questions_helper import getLastQuestionId
61
+ from helpers.questions_helper import markAnswered
62
+ from helpers.questions_helper import getQuestionById
63
+
64
+ import nest_asyncio # noqa: E402
65
+ nest_asyncio.apply()
66
+
67
+ load_dotenv()
68
+ load_dotenv(find_dotenv())
69
+
70
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
71
+ SERPAPI_API_KEY = os.environ["SERPAPI_API_KEY"]
72
+ GOOGLE_CSE_ID = os.environ["GOOGLE_CSE_ID"]
73
+ GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
74
+ LLAMA_PARSE_API_KEY = os.environ["LLAMA_PARSE_API_KEY"]
75
+ HUGGINGFACEHUB_API_TOKEN = os.environ["HUGGINGFACEHUB_API_TOKEN"]
76
+ LANGCHAIN_API_KEY = os.environ["LANGCHAIN_API_KEY"]
77
+ LANGCHAIN_ENDPOINT = os.environ["LANGCHAIN_ENDPOINT"]
78
+ LANGCHAIN_PROJECT = os.environ["LANGCHAIN_PROJECT"]
79
+ groq_api_key=os.getenv('GROQ_API_KEY')
80
+
81
+ st.set_page_config(layout="wide")
82
+
83
+ css = """
84
+ <style>
85
+ [data-testid="stAppViewContainer"] {
86
+ background-color: #f8f9fa; /* Very light grey */
87
+ }
88
+ [data-testid="stSidebar"] {
89
+ background-color: white;
90
+ color: black;
91
+ }
92
+ [data-testid="stAppViewContainer"] * {
93
+ color: black; /* Ensure all text is black */
94
+ }
95
+ button {
96
+ background-color: #add8e6; /* Light blue for primary buttons */
97
+ color: black;
98
+ border: 2px solid green; /* Green border */
99
+ }
100
+ button:hover {
101
+ background-color: #87ceeb; /* Slightly darker blue on hover */
102
+ }
103
+
104
+ button:active {
105
+ outline: 2px solid green; /* Green outline when the button is pressed */
106
+ outline-offset: 2px; /* Space between button and outline */
107
+ }
108
+
109
+ .stButton>button:first-child {
110
+ background-color: #add8e6; /* Light blue for primary buttons */
111
+ color: black;
112
+ }
113
+ .stButton>button:first-child:hover {
114
+ background-color: #87ceeb; /* Slightly darker blue on hover */
115
+ }
116
+ .stButton>button:nth-child(2) {
117
+ background-color: #b0e0e6; /* Even lighter blue for secondary buttons */
118
+ color: black;
119
+ }
120
+ .stButton>button:nth-child(2):hover {
121
+ background-color: #add8e6; /* Slightly darker blue on hover */
122
+ }
123
+ [data-testid="stFileUploadDropzone"] {
124
+ background-color: white; /* White background for file upload */
125
+ }
126
+ [data-testid="stFileUploadDropzone"] .stDropzone, [data-testid="stFileUploadDropzone"] .stDropzone input {
127
+ color: black; /* Ensure file upload text is black */
128
+ }
129
+
130
+ .stButton>button:active {
131
+ outline: 2px solid green; /* Green outline when the button is pressed */
132
+ outline-offset: 2px;
133
+ }
134
+ </style>
135
+ """
136
+ def load_credentials(filepath):
137
+ with open(filepath, 'r') as file:
138
+ return json.load(file)
139
+
140
+ # Load credentials from 'credentials.json'
141
+ credentials = load_credentials('Assets/credentials.json')
142
+
143
+ # Initialize session state if not already done
144
+ if 'logged_in' not in st.session_state:
145
+ st.session_state.logged_in = False
146
+ st.session_state.username = ''
147
+
148
+ # Function to handle login
149
+ def login(username, password):
150
+ if username in credentials and credentials[username] == password:
151
+ st.session_state.logged_in = True
152
+ st.session_state.username = username
153
+ st.rerun() # Rerun to reflect login state
154
+ else:
155
+ st.session_state.logged_in = False
156
+ st.session_state.username = ''
157
+ st.error("Invalid username or password.")
158
+
159
+ # Function to handle logout
160
+ def logout():
161
+ st.session_state.logged_in = False
162
+ st.session_state.username = ''
163
+ st.rerun() # Rerun to reflect logout state
164
+
165
+ #--------------
166
+ ## Define log printers
167
+
168
+ def print_iteration(current_iteration):
169
+ print(
170
+ chalk.bg_yellow_bright.black.bold(
171
+ f"\n Iteration - {current_iteration} ▷▶ \n"
172
+ )
173
+ )
174
+
175
+
176
+ def print_unanswered_questions(unanswered):
177
+ print(
178
+ chalk.cyan_bright("** Unanswered Questions **"),
179
+ chalk.cyan("".join([f"\n'{q['id']}. {q['question']}'" for q in unanswered])),
180
+ )
181
+
182
+
183
+ def print_next_question(current_question_id, current_question):
184
+ print(
185
+ chalk.magenta.bold("** 🤔 Next Questions I must ask: **\n"),
186
+ chalk.magenta(current_question_id),
187
+ chalk.magenta(current_question["question"]),
188
+ )
189
+
190
+
191
+ def print_answer(current_question):
192
+ print(
193
+ chalk.yellow_bright.bold("** Answer **\n"),
194
+ chalk.yellow_bright(current_question["answer"]),
195
+ )
196
+
197
+
198
+ def print_final_answer(answerpad):
199
+ print(
200
+ chalk.white("** Refined Answer **\n"),
201
+ chalk.white(answerpad[-1]),
202
+ )
203
+
204
+
205
+ def print_max_iterations():
206
+ print(
207
+ chalk.bg_yellow_bright.black.bold(
208
+ "\n ✔✔ Max Iterations Reached. Compiling the results ...\n"
209
+ )
210
+ )
211
+
212
+
213
+ def print_result(result):
214
+ print(chalk.italic.white_bright((result["text"])))
215
+
216
+
217
+ def print_sub_question(q):
218
+ print(chalk.magenta.bold(f"** Sub Question **\n{q['question']}\n{q['answer']}\n"))
219
+ #--------------
220
+ ## ---- The researcher ----- ##
221
+
222
+ class Agent:
223
+ ## Create chains
224
+ def __init__(self, agent_settings, scratchpad, store, verbose):
225
+ self.store = store
226
+ self.scratchpad = scratchpad
227
+ self.agent_settings = agent_settings
228
+ self.verbose = verbose
229
+ self.question_creation_chain = QuestionCreationChain.from_llm(
230
+ language_model(
231
+ temperature=self.agent_settings["question_creation_temperature"]
232
+ ),
233
+ verbose=self.verbose,
234
+ )
235
+ self.question_atomizer = QuestionAtomizer.from_llm(
236
+ llm=language_model(
237
+ temperature=self.agent_settings["question_atomizer_temperature"]
238
+ ),
239
+ verbose=self.verbose,
240
+ )
241
+ self.most_pertinent_question = MostPertinentQuestion.from_llm(
242
+ language_model(
243
+ temperature=self.agent_settings["question_creation_temperature"]
244
+ ),
245
+ verbose=self.verbose,
246
+ )
247
+ self.refine_answer = RefineAnswer.from_llm(
248
+ language_model(
249
+ temperature=self.agent_settings["refine_answer_temperature"]
250
+ ),
251
+ verbose=self.verbose,
252
+ )
253
+
254
+ def run(self, question):
255
+ ## Step 0. Prepare the initial set of questions
256
+ atomized_questions_response = self.question_atomizer.run(
257
+ question=question,
258
+ num_questions=self.agent_settings["num_atomistic_questions"],
259
+ )
260
+
261
+ self.scratchpad["questions"] += result2QuestionsList(
262
+ question_response=atomized_questions_response,
263
+ type="subquestion",
264
+ status="unanswered",
265
+ )
266
+
267
+ for q in self.scratchpad["questions"]:
268
+ q["answer"], q["documents"] = retrieval_qa(
269
+ llm=language_model(
270
+ temperature=self.agent_settings["qa_temperature"],
271
+ verbose=self.verbose,
272
+ ),
273
+ retriever=self.store.as_retriever(
274
+ search_type="mmr", search_kwargs={"k": 5, "fetch_k": 10}
275
+ ),
276
+ question=q["question"],
277
+ answer_length=self.agent_settings["intermediate_answers_length"],
278
+ verbose=self.verbose,
279
+ )
280
+ q["status"] = "answered"
281
+ print_sub_question(q)
282
+
283
+
284
+ current_context = "".join(
285
+ f"\n{q['id']}. {q['question']}\n{q['answer']}\n"
286
+ for q in self.scratchpad["questions"]
287
+ )
288
+
289
+ self.scratchpad["answerpad"] += [current_context]
290
+
291
+ current_iteration = 0
292
+
293
+ while True:
294
+ current_iteration += 1
295
+ print_iteration(current_iteration)
296
+
297
+ # STEP 1: create questions
298
+ start_id = getLastQuestionId(self.scratchpad["questions"]) + 1
299
+ questions_response = self.question_creation_chain.run(
300
+ question=question,
301
+ context=current_context,
302
+ previous_questions=[
303
+ "".join(f"\n{q['question']}") for q in self.scratchpad["questions"]
304
+ ],
305
+ num_questions=self.agent_settings["num_questions_per_iteration"],
306
+ start_id=start_id,
307
+ )
308
+ self.scratchpad["questions"] += result2QuestionsList(
309
+ question_response=questions_response,
310
+ type="hop",
311
+ status="unanswered",
312
+ )
313
+
314
+ # STEP 2: Choose question for current iteration
315
+ unanswered = getUnansweredQuestions(self.scratchpad["questions"])
316
+ unanswered_questions_prompt = self.unanswered_questions_prompt(unanswered)
317
+ print_unanswered_questions(unanswered)
318
+ response = self.most_pertinent_question.run(
319
+ original_question=question,
320
+ unanswered_questions=unanswered_questions_prompt,
321
+ )
322
+ current_question_dict = qStr2Dict(question=response)
323
+ current_question_id = current_question_dict["id"]
324
+ current_question = getQuestionById(
325
+ self.scratchpad["questions"], current_question_id
326
+ )
327
+ print_next_question(current_question_id, current_question)
328
+
329
+ # STEP 3: Answer the question
330
+ current_question["answer"], current_question["documents"] = retrieval_qa(
331
+ llm=language_model(
332
+ temperature=self.agent_settings["qa_temperature"],
333
+ verbose=self.verbose,
334
+ ),
335
+ retriever=self.store.as_retriever(
336
+ search_type="mmr", search_kwargs={"k": 5, "fetch_k": 10}
337
+ ),
338
+ question=current_question["question"],
339
+ answer_length=self.agent_settings["intermediate_answers_length"],
340
+ verbose=self.verbose,
341
+ )
342
+ markAnswered(self.scratchpad["questions"], current_question_id)
343
+ print_answer(current_question)
344
+ current_context = current_question["answer"]
345
+
346
+ ## STEP 4: refine the answer
347
+ refinement_context = current_question["question"] + "\n" + current_context
348
+ refine_answer = self.refine_answer.run(
349
+ question=question,
350
+ context=refinement_context,
351
+ answer=self.get_latest_answer(),
352
+ )
353
+ self.scratchpad["answerpad"] += [refine_answer]
354
+ print_final_answer(self.scratchpad["answerpad"])
355
+
356
+ if current_iteration > self.agent_settings["max_iterations"]:
357
+ print_max_iterations()
358
+ break
359
+
360
+ def unanswered_questions_prompt(self, unanswered):
361
+ return (
362
+ "[" + "".join([f"\n{q['id']}. {q['question']}" for q in unanswered]) + "]"
363
+ )
364
+
365
+ def notes_prompt(self, answered_questions):
366
+ return "".join(
367
+ [
368
+ f"{{ Question: {q['question']}, Answer: {q['answer']} }}"
369
+ for q in answered_questions
370
+ ]
371
+ )
372
+
373
+ def get_latest_answer(self):
374
+ answers = self.scratchpad["answerpad"]
375
+ answer = answers[-1] if answers else ""
376
+ return answer
377
+
378
+ #--------------
379
+ # If not logged in, show login form
380
+ if not st.session_state.logged_in:
381
+ st.sidebar.write("Login")
382
+ username = st.sidebar.text_input('Username')
383
+ password = st.sidebar.text_input('Password', type='password')
384
+ if st.sidebar.button('Login'):
385
+ login(username, password)
386
+ # Stop the script here if the user is not logged in
387
+ st.stop()
388
+
389
+
390
+ # If logged in, show logout button and main content
391
+ st.sidebar.image('StratXcel.png', width=150)
392
+ if st.session_state.logged_in:
393
+ st.sidebar.write(f"Welcome, {st.session_state.username}!")
394
+ if st.sidebar.button('Logout'):
395
+ logout()
396
+
397
+ st.write(css, unsafe_allow_html=True)
398
+
399
+ company_document = st.sidebar.toggle("Company document", False)
400
+ financial_document = st.sidebar.toggle("Financial document", False)
401
+ intercreditor_document = st.sidebar.toggle("Intercreditor document", False)
402
+
403
+ #-------------
404
+ llm=ChatGroq(groq_api_key=groq_api_key,
405
+ model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True)
406
+
407
+ Llama = "Llama-3.1-70b-Versatile"
408
+ def language_model(
409
+ model_name: str = Llama, temperature: float = 0, verbose: bool = False
410
+ ):
411
+ llm=ChatGroq(groq_api_key=groq_api_key, model_name=model_name, temperature=temperature, verbose=verbose)
412
+ return llm
413
+ #--------------
414
+ doc_retriever_company = None
415
+ doc_retriever_financials = None
416
+ doc_retriever_intercreditor = None
417
+
418
+ #--------------
419
+
420
+ #@st.cache_data
421
+ def load_or_parse_data_company():
422
+ data_file = "./data/parsed_data_company.pkl"
423
+
424
+ parsingInstructionUber10k = """The provided documents are company law documents of a company.
425
+ They contain detailed information about the rights and obligations of the company and its shareholders and contracting parties.
426
+ They also contain procedures for dispute resolution, voting, control priority and exit and sale situations.
427
+ You must never provide false legal or financial information. Use only the information included in the context documents.
428
+ Only refer to other sources if the context document refers to them or if necessary to provide additional understanding to company's own contracts."""
429
+
430
+ parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
431
+ result_type="markdown",
432
+ parsing_instruction=parsingInstructionUber10k,
433
+ max_timeout=5000,
434
+ gpt4o_mode=True,
435
+ )
436
+
437
+ file_extractor = {".pdf": parser}
438
+ reader = SimpleDirectoryReader("./Corporate_Documents", file_extractor=file_extractor)
439
+ documents = reader.load_data()
440
+
441
+ print("Saving the parse results in .pkl format ..........")
442
+ joblib.dump(documents, data_file)
443
+
444
+ # Set the parsed data to the variable
445
+ parsed_data_company = documents
446
+
447
+ return parsed_data_company
448
+
449
+ #@st.cache_data
450
+ def load_or_parse_data_financial():
451
+ data_file = "./data/parsed_data_financial.pkl"
452
+
453
+ parsingInstructionUber10k = """The provided documents are financial law documents of a company.
454
+ They contain detailed information about the rights and obligations of the company and its creditors.
455
+ They also contain procedures for acceleration of debt, sale of security, enforcement, use of creditor control, priority and distribution of assets.
456
+ You must never provide false legal or financial information. Use only the information included in the context documents.
457
+ Only refer to other sources if the context document refers to them or if necessary to provide additional understanding to company's own contracts."""
458
+
459
+ parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
460
+ result_type="markdown",
461
+ parsing_instruction=parsingInstructionUber10k,
462
+ max_timeout=5000,
463
+ gpt4o_mode=True,
464
+ )
465
+
466
+ file_extractor = {".pdf": parser}
467
+ reader = SimpleDirectoryReader("./Financial_Documents", file_extractor=file_extractor)
468
+ documents = reader.load_data()
469
+
470
+ print("Saving the parse results in .pkl format ..........")
471
+ joblib.dump(documents, data_file)
472
+
473
+ # Set the parsed data to the variable
474
+ parsed_data_financial = documents
475
+
476
+ return parsed_data_financial
477
+
478
+ #--------------
479
+
480
+ #@st.cache_data
481
+ def load_or_parse_data_intercreditor():
482
+ data_file = "./data/parsed_data_intercreditor.pkl"
483
+
484
+ parsingInstructionUber10k = """The provided documents are intercreditor agreements a company .
485
+ They contain detailed information about the rights and obligations of the company and its creditors and creditor groups.
486
+ They also contain procedures for acceleration of debt, sale of security, enforcement, use of creditor control, priority and distribution of assets.
487
+ You must never provide false legal or financial information. Use only the information included in the context documents.
488
+ Only refer to other sources if the context document refers to them or if necessary to provide additional understanding to company's own contracts."""
489
+
490
+ parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
491
+ result_type="markdown",
492
+ parsing_instruction=parsingInstructionUber10k,
493
+ max_timeout=5000,
494
+ gpt4o_mode=True,
495
+ )
496
+
497
+ file_extractor = {".pdf": parser}
498
+ reader = SimpleDirectoryReader("./Intercreditor_Documents", file_extractor=file_extractor)
499
+ documents = reader.load_data()
500
+
501
+ print("Saving the parse results in .pkl format ..........")
502
+ joblib.dump(documents, data_file)
503
+
504
+ # Set the parsed data to the variable
505
+ parsed_data_financial = documents
506
+
507
+ return parsed_data_financial
508
+ #--------------
509
+ # Create vector database
510
+
511
+ @st.cache_resource
512
+ def create_vector_database_company():
513
+ # Call the function to either load or parse the data
514
+ llama_parse_documents = load_or_parse_data_company()
515
+
516
+ with open('data/output_company.md', 'a') as f: # Open the file in append mode ('a')
517
+ for doc in llama_parse_documents:
518
+ f.write(doc.text + '\n')
519
+
520
+ markdown_path = "data/output_company.md"
521
+ loader = UnstructuredMarkdownLoader(markdown_path)
522
+ documents = loader.load()
523
+ # Split loaded documents into chunks
524
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=30)
525
+ docs = text_splitter.split_documents(documents)
526
+
527
+ #len(docs)
528
+ print(f"length of documents loaded: {len(documents)}")
529
+ print(f"total number of document chunks generated :{len(docs)}")
530
+ embed_model = HuggingFaceEmbeddings()
531
+ print('Vector DB not yet created !')
532
+
533
+ vs = Chroma.from_documents(
534
+ documents=docs,
535
+ embedding=embed_model,
536
+ collection_name="rag",
537
+ )
538
+
539
+ doc_retriever_company = vs
540
+ #doc_retriever_company = vs.as_retriever()
541
+
542
+ print('Vector DB created successfully !')
543
+ return doc_retriever_company
544
+
545
+ @st.cache_resource
546
+ def create_vector_database_financial():
547
+ # Call the function to either load or parse the data
548
+ llama_parse_documents = load_or_parse_data_financial()
549
+
550
+ with open('data/output_financials.md', 'a') as f: # Open the file in append mode ('a')
551
+ for doc in llama_parse_documents:
552
+ f.write(doc.text + '\n')
553
+
554
+ markdown_path = "data/output_financials.md"
555
+ loader = UnstructuredMarkdownLoader(markdown_path)
556
+ documents = loader.load()
557
+ # Split loaded documents into chunks
558
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
559
+ docs = text_splitter.split_documents(documents)
560
+
561
+ print(f"length of documents loaded: {len(documents)}")
562
+ print(f"total number of document chunks generated :{len(docs)}")
563
+ embed_model = HuggingFaceEmbeddings()
564
+
565
+ vs = Chroma.from_documents(
566
+ documents=docs,
567
+ embedding=embed_model,
568
+ collection_name="rag"
569
+ )
570
+ doc_retriever_financial = vs
571
+ #doc_retriever_financial = vs.as_retriever()
572
+
573
+ print('Vector DB created successfully !')
574
+ return doc_retriever_financial
575
+
576
+ #--------------
577
+
578
+ @st.cache_resource
579
+ def create_vector_database_intercreditor():
580
+ # Call the function to either load or parse the data
581
+ llama_parse_documents = load_or_parse_data_intercreditor()
582
+
583
+ with open('data/output_intercreditor.md', 'a') as f: # Open the file in append mode ('a')
584
+ for doc in llama_parse_documents:
585
+ f.write(doc.text + '\n')
586
+
587
+ markdown_path = "data/output_intercreditor.md"
588
+ loader = UnstructuredMarkdownLoader(markdown_path)
589
+ documents = loader.load()
590
+ # Split loaded documents into chunks
591
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
592
+ docs = text_splitter.split_documents(documents)
593
+
594
+ print(f"length of documents loaded: {len(documents)}")
595
+ print(f"total number of document chunks generated :{len(docs)}")
596
+ embed_model = HuggingFaceEmbeddings()
597
+
598
+ vs = Chroma.from_documents(
599
+ documents=docs,
600
+ embedding=embed_model,
601
+ collection_name="rag"
602
+ )
603
+ doc_retriever_intercreditor = vs
604
+ #doc_retriever_intercreditor = vs.as_retriever()
605
+
606
+ print('Vector DB created successfully !')
607
+ return doc_retriever_intercreditor
608
+
609
+ #--------------
610
+ legal_analysis_button_key = "legal_strategy_button"
611
+
612
+ #---------------
613
+ def delete_files_and_folders(folder_path):
614
+ for root, dirs, files in os.walk(folder_path, topdown=False):
615
+ for file in files:
616
+ try:
617
+ os.unlink(os.path.join(root, file))
618
+ except Exception as e:
619
+ st.error(f"Error deleting {os.path.join(root, file)}: {e}")
620
+ for dir in dirs:
621
+ try:
622
+ os.rmdir(os.path.join(root, dir))
623
+ except Exception as e:
624
+ st.error(f"Error deleting directory {os.path.join(root, dir)}: {e}")
625
+ #---------------
626
+
627
+ if company_document:
628
+ uploaded_files_ESG = st.sidebar.file_uploader("Choose company law documents", accept_multiple_files=True, key="company_files")
629
+ for uploaded_file in uploaded_files_ESG:
630
+ st.write("filename:", uploaded_file.name)
631
+ def save_uploadedfile(uploadedfile):
632
+ with open(os.path.join("Corporate_Documents",uploadedfile.name),"wb") as f:
633
+ f.write(uploadedfile.getbuffer())
634
+ return st.success("Saved File:{} to Company_Documents".format(uploadedfile.name))
635
+ save_uploadedfile(uploaded_file)
636
+
637
+ if financial_document:
638
+ uploaded_files_financials = st.sidebar.file_uploader("Choose financial law documents", accept_multiple_files=True, key="financial_files")
639
+ for uploaded_file in uploaded_files_financials:
640
+ st.write("filename:", uploaded_file.name)
641
+ def save_uploadedfile(uploadedfile):
642
+ with open(os.path.join("Financial_Documents",uploadedfile.name),"wb") as f:
643
+ f.write(uploadedfile.getbuffer())
644
+ return st.success("Saved File:{} to Financial_Documents".format(uploadedfile.name))
645
+ save_uploadedfile(uploaded_file)
646
+
647
+ if intercreditor_document:
648
+ uploaded_files_intercreditor = st.sidebar.file_uploader("Choose intercreditor documents", accept_multiple_files=True, key="intercreditor_files")
649
+ for uploaded_file in uploaded_files_intercreditor:
650
+ st.write("filename:", uploaded_file.name)
651
+ def save_uploadedfile(uploadedfile):
652
+ with open(os.path.join("Intercreditor_Documents",uploadedfile.name),"wb") as f:
653
+ f.write(uploadedfile.getbuffer())
654
+ return st.success("Saved File:{} to Intercreditor_Documents".format(uploadedfile.name))
655
+ save_uploadedfile(uploaded_file)
656
+ #---------------
657
+ def company_strategy():
658
+ doc_retriever_company = create_vector_database_company().as_retriever()
659
+ prompt_template = """<|system|>
660
+ You are a seasoned attorney specilizing in company and corporate law and legal analysis. You write expert analyses for institutional investors.
661
+ Output must have sub-headings in bold font and be fluent.<|end|>
662
+ <|user|>
663
+ Answer the {question} based on the information you find in context: {context} <|end|>
664
+ <|assistant|>"""
665
+
666
+ prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
667
+
668
+ qa = (
669
+ {
670
+ "context": doc_retriever_company,
671
+ "question": RunnablePassthrough(),
672
+ }
673
+ | prompt
674
+ | llm
675
+ | StrOutputParser()
676
+ )
677
+
678
+ Corporate_answer_1 = qa.invoke("What provisions govern the appointment and removal of directors in the company? Outline the procedures and any required shareholder involvement in these processes.")
679
+
680
+ Corporate_answer_2 = qa.invoke("Explain the company's share capital structure, including any provisions for different classes of shares and the rights attached to them. How are voting rights distributed among shareholders?")
681
+
682
+ Corporate_answer_3 = qa.invoke("What restrictions or conditions are placed on the transfer or sale of shares in the company's articles of association or shareholders' agreements? Include any pre-emption rights or lock-in provisions.")
683
+
684
+ Corporate_answer_4 = qa.invoke("Describe the rights and obligations of majority and minority shareholders as outlined in the company's shareholders' agreements. What protections are in place for minority shareholders?")
685
+
686
+ Corporate_answer_5 = qa.invoke("What are the provisions for issuing new shares or increasing the company's capital? Detail any existing shareholder approval requirements or pre-emptive rights outlined in the company's governing documents.")
687
+
688
+ Corporate_answer_6 = qa.invoke("Outline the procedures for decision-making in shareholder meetings, including quorum requirements and voting thresholds for ordinary and special resolutions. How are dissenting shareholders addressed in key decisions?")
689
+
690
+ Corporate_answer_7 = qa.invoke("What mechanisms are in place for resolving shareholder disputes? Provide details on any arbitration or mediation clauses found in the company's articles or shareholders' agreements.")
691
+
692
+ Corporate_answer_8 = qa.invoke("Describe the exit mechanisms available for shareholders, such as drag-along and tag-along rights, and the circumstances under which they can be triggered.")
693
+
694
+ Corporate_answer_9 = qa.invoke("What rights do shareholders have to appoint or remove members of the board? Outline any requirements for shareholder approval in relation to board appointments or dismissals.")
695
+
696
+ Corporate_answer_10 = qa.invoke("Explain any restrictions on the powers of the board as set out in the company's governing documents. Are there specific decisions that require shareholder approval or consultation?")
697
+
698
+ Corporate_answer_11 = qa.invoke("What provisions are in place regarding dividends and the distribution of profits? How are dividend rights structured among different classes of shares, if applicable?")
699
+
700
+
701
+ corporate_output = f"""**__Director Appointment and Removal:__** {Corporate_answer_1} \n\n
702
+ **__Share Capital Structure and Voting Rights:__** {Corporate_answer_2} \n\n
703
+ **__Restrictions on Share Transfer and Sale:__** {Corporate_answer_3} \n\n
704
+ **__Rights and Obligations of Shareholders:__** {Corporate_answer_4} \n\n
705
+ **__Issuing New Shares and Capital Increases:__** {Corporate_answer_5} \n\n
706
+ **__Decision-Making in Shareholder Meetings:__** {Corporate_answer_6} \n\n
707
+ **__Shareholder Dispute Resolution Mechanisms:__** {Corporate_answer_7} \n\n
708
+ **__Exit Mechanisms for Shareholders:__** {Corporate_answer_8} \n\n
709
+ **__Rights to Appoint or Remove Board Members:__** {Corporate_answer_9} \n\n
710
+ **__Restrictions on the Board's Powers:__** {Corporate_answer_10} \n\n
711
+ **__Dividend and Profit Distribution Provisions:__** {Corporate_answer_11}"""
712
+
713
+ financial_output = corporate_output
714
+
715
+ with open("company_analysis.txt", 'w') as file:
716
+ file.write(financial_output)
717
+
718
+ return financial_output
719
+
720
+ def financial_strategy():
721
+ doc_retriever_financial = create_vector_database_financial().as_retriever()
722
+ prompt_template = """<|system|>
723
+ You are a seasoned attorney specilizing in financial law and legal analysis. You write expert analyses for institutional investors.
724
+ Output must have sub-headings in bold font and be fluent.<|end|>
725
+ <|user|>
726
+ Answer the {question} based on the information you find in context: {context} <|end|>
727
+ <|assistant|>"""
728
+
729
+ prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
730
+
731
+ qa = (
732
+ {
733
+ "context": doc_retriever_financial,
734
+ "question": RunnablePassthrough(),
735
+ }
736
+ | prompt
737
+ | llm
738
+ | StrOutputParser()
739
+ )
740
+
741
+ Financial_answer_1 = qa.invoke("What are the parties of the agreements and key obligations of the borrower under the company's loan agreements? Describe any covenants or financial ratios the borrower must comply with.")
742
+
743
+ Financial_answer_3 = qa.invoke("What provisions govern the occurrence of events of default under the company's loan and bond agreements? Include any cross-default or material adverse change clauses.")
744
+
745
+ Financial_answer_4 = qa.invoke("Describe the rights of secured creditors under the company's security documents. What types of assets are secured, and how can creditors enforce their security in case of default?")
746
+
747
+ Financial_answer_5 = qa.invoke("What are the acceleration clauses in the company's financial agreements? Under what conditions can creditors demand early repayment or terminate financing arrangements?")
748
+
749
+ Financial_answer_6 = qa.invoke("Outline the procedures and requirements for enforcing security interests under the company's security documents. How do the rights of secured and unsecured creditors differ in this context?")
750
+
751
+ Financial_answer_7 = qa.invoke("How are decisions related to enforcement or restructuring prioritized among creditors?")
752
+
753
+ Financial_answer_8 = qa.invoke("Explain the company's obligations under any guarantees or indemnities provided to creditors. What are the limitations, if any, on the enforcement of these guarantees?")
754
+
755
+ Financial_answer_9 = qa.invoke("Describe the rights of bondholders or lenders in the company's bond issuance agreements or loans. What are the procedures for creditor meetings, and how can creditors exercise their rights in the event of default?")
756
+
757
+ Financial_answer_10 = qa.invoke("What protections are in place for junior creditors or subordinated debt holders in the company's financial agreements? How are their rights affected in the event of enforcement or restructuring?")
758
+
759
+ Financial_answer_11 = qa.invoke("What are the company's obligations to provide financial information to creditors under its loan or bond agreements? How frequently must the company report, and what information is typically required?")
760
+
761
+
762
+ financial_output = f"""**__Borrower Obligations and Covenants:__** {Financial_answer_1} \n\n
763
+ **__Events of Default and Cross-Default Provisions:__** {Financial_answer_3} \n\n
764
+ **__Rights of Secured Creditors and Enforcement of Security:__** {Financial_answer_4} \n\n
765
+ **__Acceleration Clauses and Early Repayment Triggers:__** {Financial_answer_5} \n\n
766
+ **__Enforcement of Security Interests:__** {Financial_answer_6} \n\n
767
+ **__Intercreditor Decision-Making and Control:__** {Financial_answer_7} \n\n
768
+ **__Guarantees and Indemnities Obligations:__** {Financial_answer_8} \n\n
769
+ **__Rights of Bondholders and Default Procedures:__** {Financial_answer_9} \n\n
770
+ **__Protections for Junior Creditors:__** {Financial_answer_10} \n\n
771
+ **__Financial Reporting Obligations to Creditors:__** {Financial_answer_11}"""
772
+
773
+ with open("financial_analysis.txt", 'w') as file:
774
+ file.write(financial_output)
775
+
776
+ return financial_output
777
+
778
+ def intercreditor_strategy():
779
+ doc_retriever_intercreditor = create_vector_database_intercreditor().as_retriever()
780
+ prompt_template = """<|system|>
781
+ You are a seasoned attorney specilizing in financial law and legal analysis. You write expert analyses for institutional investors.
782
+ Output must have sub-headings in bold font and be fluent.<|end|>
783
+ <|user|>
784
+ Answer the {question} based on the information you find in context: {context} <|end|>
785
+ <|assistant|>"""
786
+
787
+ prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
788
+
789
+ qa = (
790
+ {
791
+ "context": doc_retriever_intercreditor,
792
+ "question": RunnablePassthrough(),
793
+ }
794
+ | prompt
795
+ | llm
796
+ | StrOutputParser()
797
+ )
798
+
799
+ Intercreditor_answer_1 = qa.invoke("What are the parties involved in the intercreditor agreements, and what are their key roles and obligations?")
800
+
801
+ Intercreditor_answer_2 = qa.invoke("What provisions govern the ranking and priority of claims among creditors under the intercreditor agreements? Describe any subordination terms or waterfall clauses.")
802
+
803
+ Intercreditor_answer_3 = qa.invoke("How are enforcement actions handled under the intercreditor agreements? Are there specific procedures for appointing an enforcement agent or for coordinating enforcement between creditors?")
804
+
805
+ Intercreditor_answer_4 = qa.invoke("What are the standstill and turnover provisions in the intercreditor agreements? Under what circumstances can a creditor be prevented from taking enforcement actions?")
806
+
807
+ Intercreditor_answer_5 = qa.invoke("How are payment blockages or restrictions handled between senior and junior creditors? What are the limitations or conditions imposed on junior creditors under these provisions?")
808
+
809
+ Intercreditor_answer_6 = qa.invoke("What are the mechanisms for resolving disputes or conflicts between creditors in the intercreditor agreements?")
810
+
811
+ Intercreditor_answer_7 = qa.invoke("How do the intercreditor agreements handle the distribution of proceeds in the event of enforcement or restructuring? What are the priority rules for distributing recoveries among creditors?")
812
+
813
+ Intercreditor_answer_8 = qa.invoke("Describe the provisions related to amendments and waivers in the intercreditor agreements. How are decisions to amend the agreement or waive certain rights made among creditors?")
814
+
815
+ Intercreditor_answer_9 = qa.invoke("What restrictions or limitations exist in the intercreditor agreements concerning the ability of junior creditors to exercise rights in insolvency or restructuring proceedings?")
816
+
817
+ Intercreditor_answer_10 = qa.invoke("What reporting or information-sharing obligations exist under the intercreditor agreements? How frequently must creditors be updated, and what type of information is shared between creditor groups?")
818
+
819
+ intercreditor_output = f"""**__Parties and Obligations under Intercreditor Agreements:__** {Intercreditor_answer_1} \n\n
820
+ **__Ranking and Priority of Claims:__** {Intercreditor_answer_2} \n\n
821
+ **__Enforcement Actions and Coordination:__** {Intercreditor_answer_3} \n\n
822
+ **__Standstill and Turnover Provisions:__** {Intercreditor_answer_4} \n\n
823
+ **__Payment Blockages and Restrictions:__** {Intercreditor_answer_5} \n\n
824
+ **__Dispute Resolution Mechanisms:__** {Intercreditor_answer_6} \n\n
825
+ **__Distribution of Proceeds and Priority Rules:__** {Intercreditor_answer_7} \n\n
826
+ **__Amendments and Waivers:__** {Intercreditor_answer_8} \n\n
827
+ **__Restrictions on Junior Creditors in Insolvency:__** {Intercreditor_answer_9} \n\n
828
+ **__Information-Sharing Obligations:__** {Intercreditor_answer_10}"""
829
+
830
+ with open("intercreditor_analysis.txt", 'w') as file:
831
+ file.write(intercreditor_output)
832
+
833
+ return intercreditor_output
834
+
835
+ #-------------
836
+ @st.cache_data
837
+ def generate_strategy() -> str:
838
+ combined_output = ""
839
+
840
+ # Check if there are files in the Corporate_Documents folder
841
+ if company_document and os.path.exists("Corporate_Documents") and os.listdir("Corporate_Documents"):
842
+ company_output = company_strategy()
843
+ combined_output += company_output + '\n\n'
844
+
845
+ # Check if there are files in the Financial_Documents folder
846
+ if financial_document and os.path.exists("Financial_Documents") and os.listdir("Financial_Documents"):
847
+ financial_output = financial_strategy()
848
+ combined_output += financial_output + '\n\n'
849
+
850
+ # Check if there are files in the Intercreditor_Documents folder
851
+ if intercreditor_document and os.path.exists("Intercreditor_Documents") and os.listdir("Intercreditor_Documents"):
852
+ intercreditor_output = intercreditor_strategy()
853
+ combined_output += intercreditor_output + '\n\n'
854
+
855
+ # Set the combined result in a single session state key
856
+ st.session_state.results["legal_analysis_button_key"] = combined_output
857
+
858
+ return combined_output
859
+ #---------------
860
+ #@st.cache_data
861
+ def create_pdf():
862
+ company_content = ""
863
+ financial_content = ""
864
+ intercreditor_content = ""
865
+
866
+ # Check if 'company_analysis.txt' exists and open if it does
867
+ if os.path.exists('company_analysis.txt'):
868
+ with open('company_analysis.txt', 'r') as file1:
869
+ company_content = file1.read()
870
+
871
+ # Check if 'financial_analysis.txt' exists and open if it does
872
+ if os.path.exists('financial_analysis.txt'):
873
+ with open('financial_analysis.txt', 'r') as file2:
874
+ financial_content = file2.read()
875
+
876
+ # Check if 'intercreditor_analysis.txt' exists and open if it does
877
+ if os.path.exists('intercreditor_analysis.txt'):
878
+ with open('intercreditor_analysis.txt', 'r') as file3:
879
+ intercreditor_content = file3.read()
880
+
881
+ # Combine the contents of the available files
882
+ combined_content = ""
883
+
884
+ if company_content:
885
+ combined_content += company_content + '\n\n'
886
+
887
+ if financial_content:
888
+ combined_content += financial_content + '\n\n'
889
+
890
+ if intercreditor_content:
891
+ combined_content += intercreditor_content + '\n\n'
892
+
893
+ # Write the combined content to a new file only if any content exists
894
+ if combined_content:
895
+ with open('legal_analysis.txt', 'w') as outfile:
896
+ outfile.write(combined_content.strip())
897
+
898
+ text_file = "legal_analysis.txt"
899
+ pdf = FPDF('P', 'mm', 'A4')
900
+ pdf.add_page()
901
+ pdf.set_margins(10, 10, 10)
902
+ pdf.set_font("Arial", size=15)
903
+
904
+ pdf.cell(0, 10, txt="Structured Legal Analysis", ln=2, align='C')
905
+ pdf.ln(5)
906
+
907
+ pdf.set_font("Arial", size=11)
908
+ try:
909
+ with open(text_file, 'r', encoding='utf-8') as f:
910
+ for line in f:
911
+ pdf.multi_cell(0, 6, txt=line.encode('latin-1', 'replace').decode('latin-1'), align='L')
912
+ pdf.ln(5)
913
+ except UnicodeEncodeError:
914
+ print("UnicodeEncodeError: Some characters could not be encoded in Latin-1. Skipping...")
915
+ pass # Skip the lines causing UnicodeEncodeError
916
+
917
+ output_pdf_path = "ESG_analysis.pdf"
918
+ pdf.output(output_pdf_path)
919
+
920
+ #----------------
921
+ #llm = build_llm()
922
+
923
+ if 'results' not in st.session_state:
924
+ st.session_state.results = {
925
+ "legal_analysis_button_key": {}
926
+ }
927
+
928
+ loaders = {'.pdf': PyMuPDFLoader,
929
+ '.xml': UnstructuredXMLLoader,
930
+ '.csv': CSVLoader,
931
+ }
932
+
933
+ def create_directory_loader(file_type, directory_path):
934
+ return DirectoryLoader(
935
+ path=directory_path,
936
+ glob=f"**/*{file_type}",
937
+ loader_cls=loaders[file_type],
938
+ )
939
+
940
+
941
+ strategies_container = st.container()
942
+ with strategies_container:
943
+ mrow1_col1, mrow1_col2 = st.columns(2)
944
+
945
+ st.sidebar.info("To get started, please upload the documents from the company you would like to analyze.")
946
+ button_container = st.sidebar.container()
947
+ if os.path.exists("company_analysis.txt") and os.path.exists("financial_analysis.txt"):
948
+ create_pdf()
949
+ with open("ESG_analysis.pdf", "rb") as pdf_file:
950
+ PDFbyte = pdf_file.read()
951
+
952
+ st.sidebar.download_button(label="Download Analyses",
953
+ data=PDFbyte,
954
+ file_name="strategy_sheet.pdf",
955
+ mime='application/octet-stream',
956
+ )
957
+
958
+ if button_container.button("Clear All"):
959
+
960
+ st.session_state.button_states = {
961
+ "legal_analysis_button_key": False,
962
+ }
963
+ st.session_state.button_states = {
964
+ "financial_analysis_button_key": False,
965
+ }
966
+ st.session_state.results = {}
967
+
968
+ st.session_state['history'] = []
969
+ st.session_state['generated'] = ["Let's discuss the company documents 🤗"]
970
+ st.session_state['past'] = ["Hey ! 👋"]
971
+ st.cache_data.clear()
972
+ st.cache_resource.clear()
973
+
974
+ # Check if the subfolder exists
975
+ if os.path.exists("Corporate_Documents"):
976
+ for filename in os.listdir("Corporate_Documents"):
977
+ file_path = os.path.join("Corporate_Documents", filename)
978
+ try:
979
+ if os.path.isfile(file_path):
980
+ os.unlink(file_path)
981
+ except Exception as e:
982
+ st.error(f"Error deleting {file_path}: {e}")
983
+ else:
984
+ pass
985
+
986
+ if os.path.exists("Financial_Documents"):
987
+ # Iterate through files in the subfolder and delete them
988
+ for filename in os.listdir("Financial_Documents"):
989
+ file_path = os.path.join("Financial_Documents", filename)
990
+ try:
991
+ if os.path.isfile(file_path):
992
+ os.unlink(file_path)
993
+ except Exception as e:
994
+ st.error(f"Error deleting {file_path}: {e}")
995
+ else:
996
+ pass
997
+ # st.warning("No 'data' subfolder found.")
998
+
999
+ if os.path.exists("Intercreditor_Documents"):
1000
+ # Iterate through files in the subfolder and delete them
1001
+ for filename in os.listdir("Intercreditor_Documents"):
1002
+ file_path = os.path.join("Intercreditor_Documents", filename)
1003
+ try:
1004
+ if os.path.isfile(file_path):
1005
+ os.unlink(file_path)
1006
+ except Exception as e:
1007
+ st.error(f"Error deleting {file_path}: {e}")
1008
+ else:
1009
+ pass
1010
+ # st.warning("No 'data' subfolder found.")
1011
+
1012
+ folders_to_clean = ["data", "chroma_db_portfolio", "chroma_db_LT", "chroma_db_fin"]
1013
+
1014
+ for folder_path in folders_to_clean:
1015
+ if os.path.exists(folder_path):
1016
+ for item in os.listdir(folder_path):
1017
+ item_path = os.path.join(folder_path, item)
1018
+ try:
1019
+ if os.path.isfile(item_path) or os.path.islink(item_path):
1020
+ os.unlink(item_path) # Remove files or symbolic links
1021
+ elif os.path.isdir(item_path):
1022
+ shutil.rmtree(item_path) # Remove subfolders and all their contents
1023
+ except Exception as e:
1024
+ st.error(f"Error deleting {item_path}: {e}")
1025
+ else:
1026
+ pass
1027
+ # st.warning(f"No '{folder_path}' folder found.")
1028
+
1029
+ with mrow1_col1:
1030
+ st.subheader("Legal Document Analysis")
1031
+ st.info("This tool is designed to provide a legal analysis of the documentation for institutional investors.")
1032
+
1033
+ button_container2 = st.container()
1034
+ if "button_states" not in st.session_state:
1035
+ st.session_state.button_states = {
1036
+ "legal_analysis_button_key": False,
1037
+ }
1038
+
1039
+ if "results" not in st.session_state:
1040
+ st.session_state.results = {}
1041
+
1042
+ if button_container2.button("Legal Analysis", key=legal_analysis_button_key):
1043
+ st.session_state.button_states[legal_analysis_button_key] = True
1044
+ result_generator = generate_strategy() # Call the generator function
1045
+ st.session_state.results["legal_analysis_output"] = result_generator
1046
+
1047
+ if "legal_analysis_output" in st.session_state.results:
1048
+ st.write(st.session_state.results["legal_analysis_output"])
1049
+ st.divider()
1050
+
1051
+ with mrow1_col2:
1052
+ if "legal_analysis_button_key" in st.session_state.results and st.session_state.results["legal_analysis_button_key"]:
1053
+
1054
+ run_id = str(uuid.uuid4())
1055
+
1056
+ scratchpad = {
1057
+ "questions": [], # list of type Question
1058
+ "answerpad": [],
1059
+ }
1060
+
1061
+ if company_document:
1062
+ store = create_vector_database_company()
1063
+ if financial_document:
1064
+ store = create_vector_database_financial()
1065
+ if intercreditor_document:
1066
+ store = create_vector_database_intercreditor()
1067
+
1068
+ agent_settings = {
1069
+ "max_iterations": 3,
1070
+ "num_atomistic_questions": 2,
1071
+ "num_questions_per_iteration": 4,
1072
+ "question_atomizer_temperature": 0,
1073
+ "question_creation_temperature": 0.4,
1074
+ "question_prioritisation_temperature": 0,
1075
+ "refine_answer_temperature": 0,
1076
+ "qa_temperature": 0,
1077
+ "analyser_temperature": 0,
1078
+ "intermediate_answers_length": 200,
1079
+ "answer_length": 500,
1080
+ }
1081
+
1082
+ # Updated prompt templates to include chat history
1083
+ def format_chat_history(chat_history):
1084
+ """Format chat history as a single string for input to the chain."""
1085
+ formatted_history = "\n".join([f"User: {entry['input']}\nAI: {entry['output']}" for entry in chat_history])
1086
+ return formatted_history
1087
+
1088
+ # Initialize the agent with LCEL tools and memory
1089
+ memory = ConversationBufferMemory(memory_key="chat_history", k=3, return_messages=True)
1090
+ agent = Agent(agent_settings, scratchpad, store, True)
1091
+ def conversational_chat(query):
1092
+ # Get the result from the agent
1093
+ agent.run({"input": query, "chat_history": st.session_state['history']})
1094
+
1095
+ result = agent.get_latest_answer()
1096
+
1097
+ # Handle different response types
1098
+ if isinstance(result, dict):
1099
+ # Extract the main content if the result is a dictionary
1100
+ result = result.get("output", "") # Adjust the key as needed based on your agent's output
1101
+ elif isinstance(result, list):
1102
+ # If the result is a list, join it into a single string
1103
+ result = "\n".join(result)
1104
+ elif not isinstance(result, str):
1105
+ # Convert the result to a string if it is not already one
1106
+ result = str(result)
1107
+
1108
+ # Add the query and the result to the session state
1109
+ st.session_state['history'].append((query, result))
1110
+
1111
+ # Update memory with the conversation
1112
+ memory.save_context({"input": query}, {"output": result})
1113
+
1114
+ # Return the result
1115
+ return result
1116
+
1117
+ # Ensure session states are initialized
1118
+ if 'history' not in st.session_state:
1119
+ st.session_state['history'] = []
1120
+
1121
+ if 'generated' not in st.session_state:
1122
+ st.session_state['generated'] = ["Let's discuss the legal and financial matters 🤗"]
1123
+
1124
+ if 'past' not in st.session_state:
1125
+ st.session_state['past'] = ["Hey ! 👋"]
1126
+
1127
+ if 'input' not in st.session_state:
1128
+ st.session_state['input'] = ""
1129
+
1130
+ # Streamlit layout
1131
+ st.subheader("Discuss the documentation")
1132
+ st.info("This tool is designed to enable discussion about the company's corporate and financial documentation.")
1133
+ response_container = st.container()
1134
+ container = st.container()
1135
+
1136
+ with container:
1137
+ with st.form(key='my_form'):
1138
+ user_input = st.text_input("Query:", placeholder="What would you like to know about the documentation", key='input')
1139
+ submit_button = st.form_submit_button(label='Send')
1140
+ if submit_button and user_input:
1141
+ output = conversational_chat(user_input)
1142
+ st.session_state['past'].append(user_input)
1143
+ st.session_state['generated'].append(output)
1144
+ user_input = "Query:"
1145
+ #st.session_state['input'] = ""
1146
+ # Display generated responses
1147
+ if st.session_state['generated']:
1148
+ with response_container:
1149
+ for i in range(len(st.session_state['generated'])):
1150
+ message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="shapes")
1151
+ message(st.session_state["generated"][i], key=str(i), avatar_style="icons")
Assets/credentials.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "Mika": "password1",
3
+ "Maija": "MikaPassword",
4
+ "Sara": "password2",
5
+ "Teemu": "LT_334+DInv"
6
+ }
Corporate_Documents/.gitkeep ADDED
File without changes
Financial_Documents/.gitkeep ADDED
File without changes
Intercreditor_Documents/.gitkeep ADDED
File without changes
StratXcel.png ADDED
chains_v2/__init__.py ADDED
File without changes
chains_v2/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (215 Bytes). View file
 
chains_v2/__pycache__/create_questions.cpython-311.pyc ADDED
Binary file (2.24 kB). View file
 
chains_v2/__pycache__/most_pertinent_question.cpython-311.pyc ADDED
Binary file (1.84 kB). View file
 
chains_v2/__pycache__/question_atomizer.cpython-311.pyc ADDED
Binary file (2.12 kB). View file
 
chains_v2/__pycache__/refine_answer.cpython-311.pyc ADDED
Binary file (1.9 kB). View file
 
chains_v2/__pycache__/research_compiler.cpython-311.pyc ADDED
Binary file (1.8 kB). View file
 
chains_v2/__pycache__/retrieval_qa.cpython-311.pyc ADDED
Binary file (1.8 kB). View file
 
chains_v2/create_questions.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.llms import BaseLLM
2
+ from langchain.base_language import BaseLanguageModel
3
+ from langchain.chains import LLMChain
4
+ from langchain.prompts import PromptTemplate
5
+
6
+
7
+ class QuestionCreationChain(LLMChain):
8
+ """Chain to generates subsequent questions."""
9
+ # Check what the below code line means and what it in practice does
10
+ @classmethod
11
+ def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:
12
+ questions_creation_template = (
13
+ "You are a part of a team. The ultimate goal of your team is to"
14
+ " answer the following Question: '{question}'.\n"
15
+ "Your team has discovered some new text (delimited by ```) that may be relevant to your ultimate goal."
16
+ " text: \n ``` {context} ``` \n"
17
+ "Your task is to ask new questions that may help your team achieve the ultimate goal."
18
+ " If you think that the text is relevant to your ultimate goal, then ask new questions."
19
+ " New questions should be based only on the text and the goal Question and no other previous knowledge."
20
+ " The new questions should have no semantic overlap with questions in the following list:\n"
21
+ " {previous_questions}\n"
22
+ "You can ask up to {num_questions} new questions."
23
+ " Return the questions as a comma separated list. "
24
+ " Format your response as a numbered list of questions, like:\n"
25
+ "n. First question\n"
26
+ "n. Second question\n"
27
+ "Start the list with number {start_id}"
28
+ )
29
+
30
+ prompt = PromptTemplate(
31
+ template=questions_creation_template,
32
+ input_variables=[
33
+ "question",
34
+ "context",
35
+ "previous_questions",
36
+ "num_questions",
37
+ "start_id",
38
+ ],
39
+ )
40
+ return cls(prompt=prompt, llm=llm, verbose=verbose)
chains_v2/most_pertinent_question.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from langchain.llms import BaseLLM
3
+ from langchain.base_language import BaseLanguageModel
4
+ from langchain.chains import LLMChain
5
+ from langchain.prompts import PromptTemplate
6
+
7
+ class MostPertinentQuestion(LLMChain):
8
+ """
9
+ This chain picks one question out of a list of questions
10
+ most pertinent to the original question.
11
+ """
12
+
13
+ @classmethod
14
+ def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:
15
+ """Get the response parser."""
16
+ question_prioritization_template = (
17
+ "You are provided with the following list of questions:"
18
+ " {unanswered_questions} \n"
19
+ " Your task is to choose one question from the above list"
20
+ " that is the most pertinent to the following query:\n"
21
+ " '{original_question}' \n"
22
+ " Respond with one question out of the provided list of questions."
23
+ " Return the questions as it is without any edits."
24
+ " Format your response like:\n"
25
+ " #. question"
26
+ )
27
+ prompt = PromptTemplate(
28
+ template=question_prioritization_template,
29
+ input_variables=["unanswered_questions", "original_question"],
30
+ )
31
+ return cls(prompt=prompt, llm=llm, verbose=verbose)
chains_v2/question_atomizer.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from langchain.llms import BaseLLM
3
+ from langchain.base_language import BaseLanguageModel
4
+ from langchain.chains import LLMChain
5
+ from langchain.prompts import PromptTemplate
6
+
7
+
8
+ class QuestionAtomizer(LLMChain):
9
+ """
10
+ This chain splits the original question into a set of atomistic questions.
11
+ """
12
+
13
+ @classmethod
14
+ def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:
15
+ """Get the response parser."""
16
+ question_atomizer_template = (
17
+ " Your are provided with the following question:"
18
+ " '{question}' \n"
19
+ " Your task is to split the given question in at most {num_questions} very"
20
+ " simple, basic and atomist sub-questions (only if needed) using only the"
21
+ " information given in the question and no other prior knowledge."
22
+ " The sub-questions should be directly related to the intent of the original question."
23
+ " Consider the primary subject and the predicate of the question (if any) when creating sub questions.\n"
24
+ " Consider also the Characters, Ideas, Concepts, Entities, Actions, Or Events mentioned"
25
+ " in the question (if any) when creating the sub questions.\n"
26
+ " The sub questions should have no semantic overlap with each other."
27
+ " Format your response like: \n"
28
+ " n. question"
29
+ )
30
+ prompt = PromptTemplate(
31
+ template=question_atomizer_template,
32
+ input_variables=["question", "num_questions"],
33
+ )
34
+ return cls(prompt=prompt, llm=llm, verbose=verbose)
chains_v2/refine_answer.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.llms import BaseLLM
2
+ from langchain.base_language import BaseLanguageModel
3
+ from langchain.chains import LLMChain
4
+ from langchain.prompts import PromptTemplate
5
+
6
+
7
+ class RefineAnswer(LLMChain):
8
+ """
9
+ This refines the answer with every iteration.
10
+ """
11
+
12
+ @classmethod
13
+ def from_llm(cls, llm: BaseLanguageModel, verbose: bool = True) -> LLMChain:
14
+ """Get the response parser."""
15
+ prompt_template = (
16
+ "Your task is to answer the following question.\n"
17
+ " Question: '{question}'\n"
18
+ " You are provided with an existing Answer: \n---\n{answer}\n---\n\n"
19
+ " You are also provided with some additional context that may be relevant to the question.\n"
20
+ " New Context: \n---\n{context}\n---\n\n"
21
+ " You have the opportunity to rewrite and improve upon the existing answer."
22
+ " Use only the information from the existing answer and the given context to write better answer."
23
+ " Use a descriptive style and a business casual language."
24
+ " If the context isn't useful, return the existing answer."
25
+ )
26
+ prompt = PromptTemplate(
27
+ template=prompt_template,
28
+ input_variables=["question", "answer", "context"],
29
+ )
30
+ return cls(prompt=prompt, llm=llm, verbose=verbose)
chains_v2/research_compiler.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.chains import LLMChain
2
+ from langchain.prompts import PromptTemplate
3
+
4
+ def research_compiler(llm, question: str, notes: str, answer_length: int, verbose: bool = True):
5
+ # prompt_template = (
6
+ # "You are a researcher. Your task is to answer the following question\n"
7
+ # " Question: '{question}' \n"
8
+ # " You are provided with some notes (delimited between '___')"
9
+ # " ___\n{notes}\n ___\n"
10
+ # " The notes include answers to several questions that may be relevant to the original question."
11
+ # " Use only the information from the notes that is most pertinent to the question."
12
+ # " Write the answer solely based on the give notes and no other provious knowledge."
13
+ # " Answer should be clear, crisp and detailed."
14
+ # " Write your answer in less than {answer_length} words."
15
+ # " Answer :")
16
+ prompt_template = (
17
+ "You are a research agent who answers complex questions with clear, crisp and detailed answers."
18
+ " You are provided with a question and some research notes prepared by your team."
19
+ " Question: {question} \n"
20
+ " Notes: {notes} \n"
21
+ " Your task is to answer the question entirely based on the given notes."
22
+ " The notes contain a list of intermediate-questions and answers that may be helpful to you in writing an answer."
23
+ " Use only the most relevant information from the notes while writing your answer."
24
+ " Do not use any prior knowledge while writing your answer, Do not make up the answer."
25
+ " If the notes are not relevant to the question, just return 'Context is insufficient to answer the question'."
26
+ " Remember your goal is to answer the question as objectively as possible."
27
+ " Write your answer succinctly in less than {answer_length} words."
28
+ )
29
+
30
+ PROMPT = PromptTemplate(
31
+ template=prompt_template, input_variables=["notes", "question", "answer_length"]
32
+ )
33
+
34
+ chain = LLMChain(
35
+ llm=llm,
36
+ prompt=PROMPT,
37
+ verbose=verbose,
38
+ )
39
+
40
+ result = chain({"question": question, "notes": notes, "answer_length": answer_length})
41
+ return result
chains_v2/retrieval_qa.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from langchain.llms import BaseLLM
2
+ # from langchain.base_language import BaseLanguageModel
3
+ # from langchain.chains import LLMChain
4
+ from langchain.prompts import PromptTemplate
5
+ from langchain.vectorstores import PGVector
6
+ from langchain.chains import RetrievalQA
7
+
8
+ def retrieval_qa(llm, retriever: PGVector, question: str, answer_length: 250, verbose: bool = True):
9
+ """
10
+ This chain is used to answer the intermediate questions.
11
+ """
12
+ prompt_answer_length = f" Answer as succinctly as possible in less than {answer_length} words.\n"
13
+
14
+ prompt_template = \
15
+ "You are provided with a question and some helpful context to answer the question \n" \
16
+ " Question: {question}\n" \
17
+ " Context: {context}\n" \
18
+ "Your task is to answer the question based in the information given in the context" \
19
+ " Answer the question entirely based on the context and no other previous knowledge." \
20
+ " If the context provided is empty or irrelevant, just return 'Context not sufficient'"\
21
+ + prompt_answer_length
22
+
23
+ PROMPT = PromptTemplate(
24
+ template=prompt_template, input_variables=["context", "question"]
25
+ )
26
+
27
+ qa_chain = RetrievalQA.from_chain_type(
28
+ llm=llm,
29
+ chain_type="stuff",
30
+ retriever=retriever,
31
+ return_source_documents=True,
32
+ chain_type_kwargs={"prompt": PROMPT},
33
+ verbose = verbose,
34
+ )
35
+
36
+ result = qa_chain({"query": question})
37
+ return result['result'], result['source_documents']
helpers/__pycache__/questions_helper.cpython-311.pyc ADDED
Binary file (2.8 kB). View file
 
helpers/__pycache__/response_helpers.cpython-311.pyc ADDED
Binary file (2.55 kB). View file
 
helpers/questions_helper.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ getAnsweredQuestions = lambda questions: [
3
+ q for q in questions if q["status"] == "answered"
4
+ ]
5
+ getUnansweredQuestions = lambda questions: [
6
+ q for q in questions if q["status"] == "unanswered"
7
+ ]
8
+ getSubQuestions = lambda questions: [q for q in questions if q["type"] == "subquestion"]
9
+ getHopQuestions = lambda questions: [q for q in questions if q["type"] == "hop"]
10
+ getLastQuestionId = lambda questions: max([q["id"] for q in questions])
11
+
12
+
13
+ def markAnswered(questions, id: int):
14
+ for q in questions:
15
+ if q["id"] == id:
16
+ q["status"] = "answered"
17
+
18
+
19
+ def getQuestionById(questions, id: int):
20
+ q = [q for q in questions if q["id"] == id]
21
+ if len(q) == 0:
22
+ return None
23
+ return q[0]
helpers/response_helpers.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''def qStr2Dict(question: str) -> dict:
2
+ print('qStr2Dict :', question)
3
+ split = question.strip(" '\"").split(".", 1)
4
+ question_dict = {'id': int(split[0]), 'question': split[-1].strip()}
5
+ return question_dict
6
+
7
+
8
+ def result2QuestionsList(question_response: str, type: str, status: str) -> list:
9
+ response_splits = question_response.split("\n")
10
+ qlist = []
11
+ for q in response_splits:
12
+ question = {**qStr2Dict(q), 'type': type, 'status': status, 'answer': None}
13
+ qlist = qlist + [question]
14
+ return qlist
15
+ '''
16
+ def qStr2Dict(question: str) -> dict:
17
+ try:
18
+ print('qStr2Dict:', question)
19
+ split = question.strip(" '\"").split(".", 1)
20
+
21
+ # Check if id_part is 'Here are the sub-questions:', set it to integer 1
22
+ id_part = split[0].replace("#", "").strip()
23
+ if isinstance(id_part, str):
24
+ id_part = 1 # Convert any string to integer 1
25
+
26
+ # Convert id_part to integer, if not empty
27
+ id_part = int(id_part) if id_part else None
28
+
29
+ question_dict = {'id': id_part, 'question': split[-1].strip()}
30
+ return question_dict
31
+ except ValueError as e:
32
+ print("Error:", e)
33
+ return {'id': None, 'question': question.strip()}
34
+
35
+ def result2QuestionsList(question_response: str, type: str, status: str) -> list:
36
+ response_splits = question_response.split("\n")
37
+ qlist = []
38
+ for q in response_splits:
39
+ # Skip empty lines
40
+ if q.strip() == '':
41
+ continue
42
+ question = qStr2Dict(q)
43
+ question.update({'type': type, 'status': status, 'answer': None})
44
+ qlist.append(question)
45
+ return qlist