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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from annotated_text import annotated_text, annotation
|
| 3 |
+
import fitz
|
| 4 |
+
import os
|
| 5 |
+
import chromadb
|
| 6 |
+
import uuid
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import os
|
| 9 |
+
os.environ['OPENAI_API_KEY'] = os.environ['OPEN_API_KEY']
|
| 10 |
+
st.title("Contracts Multiple File Search ")
|
| 11 |
+
|
| 12 |
+
from langchain.retrievers import BM25Retriever, EnsembleRetriever
|
| 13 |
+
from langchain.schema import Document
|
| 14 |
+
from langchain.vectorstores import Chroma
|
| 15 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 16 |
+
embedding = HuggingFaceEmbeddings(model_name='BAAI/bge-base-en-v1.5')
|
| 17 |
+
|
| 18 |
+
import spacy
|
| 19 |
+
# Load the English model from SpaCy
|
| 20 |
+
nlp = spacy.load("en_core_web_md")
|
| 21 |
+
|
| 22 |
+
def util_upload_file_and_return_list_docs(uploaded_file):
|
| 23 |
+
#util_del_cwd()
|
| 24 |
+
save_path = Path(os.getcwd(), uploaded_file.name)
|
| 25 |
+
with open(save_path, mode='wb') as w:
|
| 26 |
+
w.write(uploaded_file.getvalue())
|
| 27 |
+
print('save_path:', save_path)
|
| 28 |
+
docs = fitz.open(save_path)
|
| 29 |
+
return(docs, save_path)
|
| 30 |
+
#### Helper Functions to Split using Rolling Window (recomm : use smaller rolling window )
|
| 31 |
+
def split_txt_file_synthetic_sentence_rolling(ctxt, sentence_size_in_chars, sliding_size_in_chars,debug=False):
|
| 32 |
+
sliding_size_in_chars = sentence_size_in_chars - sliding_size_in_chars
|
| 33 |
+
pos_start = 0
|
| 34 |
+
pos_end = len(ctxt)
|
| 35 |
+
final_return = []
|
| 36 |
+
if(debug):
|
| 37 |
+
print('pos_start : ',pos_start)
|
| 38 |
+
print('pos_end : ',pos_end)
|
| 39 |
+
if(pos_end<sentence_size_in_chars):
|
| 40 |
+
return([{'section_org_text':ctxt[pos_start:pos_end],'section_char_start':pos_start,'section_char_end':pos_end}])
|
| 41 |
+
if(sentence_size_in_chars<sliding_size_in_chars):
|
| 42 |
+
return(None)
|
| 43 |
+
stop_condition = False
|
| 44 |
+
start = pos_start
|
| 45 |
+
end = start + sentence_size_in_chars
|
| 46 |
+
mydict = {}
|
| 47 |
+
mydict['section_org_text'] = ctxt[start:end]
|
| 48 |
+
mydict['section_char_start'] = start
|
| 49 |
+
mydict['section_char_end'] = end
|
| 50 |
+
final_return.append(mydict)
|
| 51 |
+
#### First Time ENDS
|
| 52 |
+
while(stop_condition==False):
|
| 53 |
+
start = end - sliding_size_in_chars
|
| 54 |
+
end = start + sentence_size_in_chars
|
| 55 |
+
if(end>pos_end):
|
| 56 |
+
if(start<pos_end):
|
| 57 |
+
end = pos_end
|
| 58 |
+
mydict = {}
|
| 59 |
+
mydict['section_org_text'] = ctxt[start:end]
|
| 60 |
+
mydict['section_char_start'] = start
|
| 61 |
+
mydict['section_char_end'] = end
|
| 62 |
+
final_return.append(mydict)
|
| 63 |
+
stop_condition=True
|
| 64 |
+
else:
|
| 65 |
+
stop_condition=True
|
| 66 |
+
else:
|
| 67 |
+
mydict = {}
|
| 68 |
+
mydict['section_org_text'] = ctxt[start:end]
|
| 69 |
+
mydict['section_char_start'] = start
|
| 70 |
+
mydict['section_char_end'] = end
|
| 71 |
+
final_return.append(mydict)
|
| 72 |
+
if(debug):
|
| 73 |
+
print('start : ', start)
|
| 74 |
+
print('end : ', end)
|
| 75 |
+
return(final_return)
|
| 76 |
+
### helper to make string out of iw_status
|
| 77 |
+
# def util_get_list_page_and_passage(docs):
|
| 78 |
+
# page_documents = []
|
| 79 |
+
# passage_documents = []
|
| 80 |
+
# for txt_index, txt_page in enumerate(docs):
|
| 81 |
+
# page_document = txt_page.get_text()##.encode("utf8") # get plain text (is in UTF-8)
|
| 82 |
+
# page_documents.append(page_document)
|
| 83 |
+
# sections = split_txt_file_synthetic_sentence_rolling(page_document,700,200)
|
| 84 |
+
# for sub_sub_index, sub_sub_item in enumerate(sections):
|
| 85 |
+
# sub_text=sub_sub_item['section_org_text']
|
| 86 |
+
# passage_document = Document(page_content=sub_text, metadata={"page_index": txt_index})
|
| 87 |
+
# passage_documents.append(passage_document)
|
| 88 |
+
# return(page_documents,passage_documents)
|
| 89 |
+
|
| 90 |
+
def split_into_sentences_with_offsets(text):
|
| 91 |
+
"""
|
| 92 |
+
Splits a paragraph into sentences and returns them along with their start and end offsets.
|
| 93 |
+
:param text: The input text to be split into sentences.
|
| 94 |
+
:return: A list of tuples, each containing a sentence and its start and end offsets.
|
| 95 |
+
"""
|
| 96 |
+
doc = nlp(text)
|
| 97 |
+
return [(sent.text, sent.start_char, sent.end_char) for sent in doc.sents]
|
| 98 |
+
|
| 99 |
+
def util_get_list_page_and_passage(docs):
|
| 100 |
+
page_documents = []
|
| 101 |
+
passage_documents = []
|
| 102 |
+
for txt_index, txt_page in enumerate(docs):
|
| 103 |
+
page_document = txt_page.get_text()##.encode("utf8") # get plain text (is in UTF-8)
|
| 104 |
+
page_documents.append(page_document)
|
| 105 |
+
sections = split_into_sentences_with_offsets(page_document)
|
| 106 |
+
for sub_sub_index, sub_sub_item in enumerate(sections):
|
| 107 |
+
sub_text=sub_sub_item[0]
|
| 108 |
+
passage_document = Document(page_content=sub_text, metadata={"page_index": txt_index})
|
| 109 |
+
passage_documents.append(passage_document)
|
| 110 |
+
return(page_documents,passage_documents)
|
| 111 |
+
|
| 112 |
+
# def util_index_chromadb_passages():
|
| 113 |
+
# ##### PROCESSING
|
| 114 |
+
# # create client and a new collection
|
| 115 |
+
# collection_name = str(uuid.uuid4().hex)
|
| 116 |
+
# chroma_client = chromadb.EphemeralClient()
|
| 117 |
+
# chroma_collection = chroma_client.get_or_create_collection(collection_name)
|
| 118 |
+
# # define embedding function
|
| 119 |
+
# embed_model = LangchainEmbedding(HuggingFaceEmbeddings(model_name="BAAI/bge-small-en"))
|
| 120 |
+
# vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
| 121 |
+
# return(chroma_client,chroma_collection,collection_name,vector_store,embed_model)
|
| 122 |
+
|
| 123 |
+
def util_get_only_content_inside_loop(page_no,page_documents):
|
| 124 |
+
for index, item in enumerate(page_documents):
|
| 125 |
+
if(page_documents[index].metadata['txt_page_index']==page_no):
|
| 126 |
+
return(page_documents[index].get_content())
|
| 127 |
+
return(None)
|
| 128 |
+
# def util_get_list_pageno_and_contents(page_documents,passage_documents,passage_nodes):
|
| 129 |
+
# ''' page no starts with index 1 '''
|
| 130 |
+
# return_value = []
|
| 131 |
+
# for index, item in enumerate(passage_nodes):
|
| 132 |
+
# page_no = passage_nodes[index].metadata['txt_page_index']
|
| 133 |
+
# page_content = util_get_only_content_inside_loop(page_no,page_documents)
|
| 134 |
+
# return_value.append((page_no+1,page_content))
|
| 135 |
+
# return(return_value)
|
| 136 |
+
|
| 137 |
+
def util_get_list_pageno_and_contents(some_query_passage, page_documents,passage_documents,passage_nodes):
|
| 138 |
+
''' page no starts with index 1 '''
|
| 139 |
+
|
| 140 |
+
return_value = []
|
| 141 |
+
|
| 142 |
+
rescore = reranker.compute_score([[some_query_passage , x.page_content] for x in passage_nodes])
|
| 143 |
+
print('rescore ' , rescore)
|
| 144 |
+
print(rescore)
|
| 145 |
+
max_pos_index = rescore.index(max(rescore))
|
| 146 |
+
print("Maximum Index position: ",max_pos_index)
|
| 147 |
+
print(passage_nodes[max_pos_index].page_content)
|
| 148 |
+
|
| 149 |
+
#Document(page_content=sub_text, metadata={"page_index": txt_index})
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
for index, item in enumerate(passage_nodes):
|
| 153 |
+
page_no = passage_nodes[index].metadata['page_index']
|
| 154 |
+
page_content = page_documents[page_no]
|
| 155 |
+
if(index==max_pos_index):
|
| 156 |
+
return_value.append((page_no+1,page_content))
|
| 157 |
+
return(passage_nodes[max_pos_index].page_content, return_value)
|
| 158 |
+
|
| 159 |
+
# # def util_openai_extract_entity(example_passage, example_entity, page_content):
|
| 160 |
+
# # import openai
|
| 161 |
+
# # openai.api_key = os.environ['OPENAI_API_KEY']
|
| 162 |
+
|
| 163 |
+
# # content = """Find the Entity based on Text . Return empty string if Entity does not exists. Here is one example below
|
| 164 |
+
# # Text: """ + example_passage + """
|
| 165 |
+
# # Entity: """ + example_entity + """
|
| 166 |
+
|
| 167 |
+
# # Text: """ + page_content + """
|
| 168 |
+
# # Entity: """
|
| 169 |
+
|
| 170 |
+
# # return_value = openai.ChatCompletion.create(model="gpt-4",temperature=0.0001,messages=[{"role": "user", "content": content},])
|
| 171 |
+
# # return(str(return_value['choices'][0]['message']['content']))
|
| 172 |
+
def util_openai_extract_clause(example_prompt, page_content):
|
| 173 |
+
import openai
|
| 174 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
| 175 |
+
content = example_prompt
|
| 176 |
+
content = content + "\n Answer precisely; do not add anything extra, and try to locate the answer in the below context \n context: "
|
| 177 |
+
return_value = openai.ChatCompletion.create(model="gpt-3.5-turbo",temperature=0.0001,messages=[{"role": "user", "content": content + "\n" + page_content},])
|
| 178 |
+
return(str(return_value['choices'][0]['message']['content']))
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def util_openai_hyde(example_prompt):
|
| 182 |
+
import openai
|
| 183 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
| 184 |
+
content = example_prompt
|
| 185 |
+
return_value = openai.ChatCompletion.create(model="gpt-3.5-turbo",temperature=0.0001,messages=[
|
| 186 |
+
{"role": "system", "content": "You are a legal contract lawyer. generate a summary from below text " + "\n"},
|
| 187 |
+
{"role": "user", "content": example_prompt + "\n"},
|
| 188 |
+
|
| 189 |
+
]
|
| 190 |
+
)
|
| 191 |
+
return(str(return_value['choices'][0]['message']['content']))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def util_openai_format (example_passage, page_content):
|
| 195 |
+
'''
|
| 196 |
+
annotated_text(" ",annotation("ENTITY : ", str(page_no)),)
|
| 197 |
+
'''
|
| 198 |
+
if(True):
|
| 199 |
+
found_value = util_openai_extract_clause(example_passage, page_content)
|
| 200 |
+
if(len(found_value)>0):
|
| 201 |
+
found_value = found_value.strip()
|
| 202 |
+
first_index = page_content.find(found_value)
|
| 203 |
+
if(first_index!=-1):
|
| 204 |
+
print('first_index : ',first_index)
|
| 205 |
+
print('found_value : ',found_value)
|
| 206 |
+
return(annotated_text(page_content[0:first_index-1],annotation(found_value, " FOUND ENTITY "),page_content[first_index+len(found_value):]))
|
| 207 |
+
return(annotated_text(page_content))
|
| 208 |
+
def util_openai_modify_prompt(example_prompt, page_content):
|
| 209 |
+
import openai
|
| 210 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
| 211 |
+
my_prompt = """Expand the original Query to show exact resuls for extraction\n
|
| 212 |
+
Query: """ + example_prompt # + """\nDocument: """ + page_content + """ """
|
| 213 |
+
return_value = openai.ChatCompletion.create(model="gpt-4",temperature=0.0001,messages=[{"role": "user", "content": my_prompt},])
|
| 214 |
+
return(str(return_value['choices'][0]['message']['content']))
|
| 215 |
+
|
| 216 |
+
# def create_bm25_page_rank(page_list_retrieve, page_query):
|
| 217 |
+
# """ page_corpus : array of page text , page_query is user query """
|
| 218 |
+
# from operator import itemgetter
|
| 219 |
+
# from rank_bm25 import BM25Okapi
|
| 220 |
+
# tokenized_corpus = [doc.split(" ") for x, doc in page_list_retrieve]
|
| 221 |
+
# tokenized_query = page_query.split(" ")
|
| 222 |
+
# bm25 = BM25Okapi(tokenized_corpus)
|
| 223 |
+
# doc_scores = bm25.get_scores(tokenized_query).tolist()
|
| 224 |
+
# tmp_list = []
|
| 225 |
+
# for index, item in enumerate(page_list_retrieve):
|
| 226 |
+
# tmp_list.append((item[0], item[1],doc_scores[index]))
|
| 227 |
+
# tmp_list = sorted(tmp_list, key=itemgetter(2), reverse=True)
|
| 228 |
+
# return(tmp_list)
|
| 229 |
+
|
| 230 |
+
page_documents = []
|
| 231 |
+
passage_documents = []
|
| 232 |
+
|
| 233 |
+
with st.form("my_form"):
|
| 234 |
+
multi = '''1. Download and Upload Multiple contracts
|
| 235 |
+
|
| 236 |
+
e.g. https://www.barc.gov.in/tenders/GCC-LPS.pdf
|
| 237 |
+
|
| 238 |
+
e.g. https://www.montrosecounty.net/DocumentCenter/View/823/Sample-Construction-Contract
|
| 239 |
+
'''
|
| 240 |
+
st.markdown(multi)
|
| 241 |
+
multi = '''2. Insert Query to search or find similar language '''
|
| 242 |
+
st.markdown(multi)
|
| 243 |
+
multi = '''3. Press Index.'''
|
| 244 |
+
st.markdown(multi)
|
| 245 |
+
multi = '''
|
| 246 |
+
** Attempt is made for appropriate page and passage retrieval ** \n
|
| 247 |
+
'''
|
| 248 |
+
st.markdown(multi)
|
| 249 |
+
uploaded_file = st.file_uploader("Choose a file")
|
| 250 |
+
if uploaded_file is not None:
|
| 251 |
+
docs, save_path = util_upload_file_and_return_list_docs(uploaded_file)
|
| 252 |
+
page_documents , passage_documents = util_get_list_page_and_passage(docs)
|
| 253 |
+
print('len(page_documents) len(passage_documents ', len(page_documents), len(passage_documents))
|
| 254 |
+
single_example_passage = st.text_area('Enter Query Here',"What is Governing Law ")
|
| 255 |
+
#hyde_passage = util_openai_hyde(single_example_passage)
|
| 256 |
+
#print("HYDE :: ", hyde_passage)
|
| 257 |
+
|
| 258 |
+
submitted = st.form_submit_button("Index and Calculate")
|
| 259 |
+
if submitted and (uploaded_file is not None):
|
| 260 |
+
bm25_retriever = BM25Retriever.from_documents(passage_documents)
|
| 261 |
+
bm25_retriever.k = 2
|
| 262 |
+
chroma_vectorstore = Chroma.from_documents(passage_documents, embedding)
|
| 263 |
+
chroma_retriever = chroma_vectorstore.as_retriever(search_kwargs={"k": 2})
|
| 264 |
+
#initialize the ensemble retriever
|
| 265 |
+
ensemble_retriever = EnsembleRetriever(retrievers=[bm25_retriever, chroma_retriever],weights=[0.25, 0.75])
|
| 266 |
+
passage_nodes = ensemble_retriever.get_relevant_documents(single_example_passage)
|
| 267 |
+
print('len(passage_nodes):', len(passage_nodes))
|
| 268 |
+
### From Passage to PAGE
|
| 269 |
+
|
| 270 |
+
found_passage, page_list_retrieve = util_get_list_pageno_and_contents(single_example_passage, page_documents,passage_documents,passage_nodes)
|
| 271 |
+
print('len(page_list_retrieve):', len(page_list_retrieve))
|
| 272 |
+
if(len(page_list_retrieve)>0):
|
| 273 |
+
page_list_retrieve = list(set(page_list_retrieve))
|
| 274 |
+
for iindex in page_list_retrieve:
|
| 275 |
+
page_no = iindex[0]
|
| 276 |
+
page_content = iindex[1]
|
| 277 |
+
annotated_text(" ",annotation("RELEVANT PAGENO : ", str(page_no), font_family="Comic Sans MS", border="2px dashed red"),)
|
| 278 |
+
util_openai_format(single_example_passage, page_content)
|
| 279 |
+
#st.write('Modified Prompt :: ')
|
| 280 |
+
annotated_text(" ",annotation("RELEVANT PASSAGE : ", "", font_family="Comic Sans MS", border="2px dashed red"),)
|
| 281 |
+
st.write(found_passage)
|
| 282 |
+
# util_del_file(save_path)
|
| 283 |
+
# chroma_client.delete_collection(name=collection_name)
|
| 284 |
+
pchroma_client = chromadb.Client()
|
| 285 |
+
for citem in pchroma_client.list_collections():
|
| 286 |
+
print(citem.name)
|
| 287 |
+
|