import langchain from langchain.embeddings import SentenceTransformerEmbeddings from langchain.chains.question_answering import load_qa_chain from langchain.document_loaders import UnstructuredPDFLoader,UnstructuredWordDocumentLoader from langchain.indexes import VectorstoreIndexCreator from langchain.vectorstores import FAISS from langchain import HuggingFaceHub from langchain import PromptTemplate from langchain.chat_models import ChatOpenAI from zipfile import ZipFile import gradio as gr import openpyxl import os import shutil from langchain.schema import Document from langchain.text_splitter import RecursiveCharacterTextSplitter import tiktoken import secrets import openai import time from duckduckgo_search import DDGS import requests import tempfile tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo") # create the length function def tiktoken_len(text): tokens = tokenizer.encode( text, disallowed_special=() ) return len(tokens) text_splitter = RecursiveCharacterTextSplitter( chunk_size=600, chunk_overlap=200, length_function=tiktoken_len, separators=["\n\n", "\n", " ", ""] ) embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2") foo = Document(page_content='foo is fou!',metadata={"source":'foo source'}) def reset_database(ui_session_id): session_id = f"PDFAISS-{ui_session_id}" if 'drive' in session_id: print("RESET DATABASE: session_id contains 'drive' !!") return None try: shutil.rmtree(session_id) except: print(f'no {session_id} directory present') try: os.remove(f"{session_id}.zip") except: print("no {session_id}.zip present") return None def is_duplicate(split_docs,db): epsilon=0.0 print(f"DUPLICATE: Treating: {split_docs[0].metadata['source'].split('/')[-1]}") for i in range(min(3,len(split_docs))): query = split_docs[i].page_content docs = db.similarity_search_with_score(query,k=1) _ , score = docs[0] epsilon += score print(f"DUPLICATE: epsilon: {epsilon}") return epsilon < 0.1 def merge_split_docs_to_db(split_docs,db,progress,progress_step=0.1): progress(progress_step,desc="merging docs") if len(split_docs)==0: print("MERGE to db: NO docs!!") return filename = split_docs[0].metadata['source'] if is_duplicate(split_docs,db): print(f"MERGE: Document is duplicated: {filename}") return print(f"MERGE: number of split docs: {len(split_docs)}") batch = 10 for i in range(0, len(split_docs), batch): progress(i/len(split_docs),desc=f"added {i} chunks of {len(split_docs)} chunks") db1 = FAISS.from_documents(split_docs[i:i+batch], embeddings) db.merge_from(db1) return db def merge_pdf_to_db(filename,db,progress,progress_step=0.1): progress_step+=0.05 progress(progress_step,'unpacking pdf') doc = UnstructuredPDFLoader(filename).load() doc[0].metadata['source'] = filename.split('/')[-1] split_docs = text_splitter.split_documents(doc) progress_step+=0.3 progress(progress_step,'docx unpacked') return merge_split_docs_to_db(split_docs,db,progress,progress_step) def merge_docx_to_db(filename,db,progress,progress_step=0.1): progress_step+=0.05 progress(progress_step,'unpacking docx') doc = UnstructuredWordDocumentLoader(filename).load() doc[0].metadata['source'] = filename.split('/')[-1] split_docs = text_splitter.split_documents(doc) progress_step+=0.3 progress(progress_step,'docx unpacked') return merge_split_docs_to_db(split_docs,db,progress,progress_step) def merge_txt_to_db(filename,db,progress,progress_step=0.1): progress_step+=0.05 progress(progress_step,'unpacking txt') with open(filename) as f: docs = text_splitter.split_text(f.read()) split_docs = [Document(page_content=doc,metadata={'source':filename.split('/')[-1]}) for doc in docs] progress_step+=0.3 progress(progress_step,'txt unpacked') return merge_split_docs_to_db(split_docs,db,progress,progress_step) def unpack_zip_file(filename,db,progress): with ZipFile(filename, 'r') as zipObj: contents = zipObj.namelist() print(f"unpack zip: contents: {contents}") tmp_directory = filename.split('/')[-1].split('.')[-2] shutil.unpack_archive(filename, tmp_directory) if 'index.faiss' in [item.lower() for item in contents]: db2 = FAISS.load_local(tmp_directory, embeddings) db.merge_from(db2) return db for file in contents: if file.lower().endswith('.docx'): db = merge_docx_to_db(f"{tmp_directory}/{file}",db,progress) if file.lower().endswith('.pdf'): db = merge_pdf_to_db(f"{tmp_directory}/{file}",db,progress) if file.lower().endswith('.txt'): db = merge_txt_to_db(f"{tmp_directory}/{file}",db,progress) return db def add_files_to_zip(session_id): zip_file_name = f"{session_id}.zip" with ZipFile(zip_file_name, "w") as zipObj: for root, dirs, files in os.walk(session_id): for file_name in files: file_path = os.path.join(root, file_name) arcname = os.path.relpath(file_path, session_id) zipObj.write(file_path, arcname) ## Search files functions ## def search_docs(topic, max_references): print(f"SEARCH PDF : {topic}") doc_list = [] with DDGS() as ddgs: i=0 for r in ddgs.text('{} filetype:pdf'.format(topic), region='wt-wt', safesearch='On', timelimit='n'): #doc_list.append(str(r)) if i>=max_references: break doc_list.append("TITLE : " + r['title'] + " -- BODY : " + r['body'] + " -- URL : " + r['href']) i+=1 return doc_list def store_files(references, ret_names=False): url_list=[] temp_files = [] for ref in references: url_list.append(ref.split(" ")[-1]) for url in url_list: response = requests.get(url) if response.status_code == 200: filename = url.split('/')[-1] if filename.split('.')[-1] == 'pdf': filename = filename[:-4] print('File name.pdf :', filename) temp_file = tempfile.NamedTemporaryFile(delete=False,prefix=filename, suffix='.pdf') else: print('File name :', filename) temp_file = tempfile.NamedTemporaryFile(delete=False,prefix=filename, suffix='.pdf') temp_file.write(response.content) temp_file.close() if ret_names: temp_files.append(temp_file.name) else: temp_files.append(temp_file) return temp_files ## Summary functions ## ## Load each doc from the vector store def load_docs(ui_session_id): session_id_global_db = f"PDFAISS-{ui_session_id}" try: db = FAISS.load_local(session_id_global_db,embeddings) print("load_docs after loading global db:",session_id_global_db,len(db.index_to_docstore_id)) except: return f"SESSION: {session_id_global_db} database does not exist","","" docs = [] for i in range(1,len(db.index_to_docstore_id)): docs.append(db.docstore.search(db.index_to_docstore_id[i])) return docs # summarize with gpt 3.5 turbo def summarize_gpt(doc,system='provide a summary of the following document: ', first_tokens=600): doc = doc.replace('\n\n\n', '').replace('---', '').replace('...', '').replace('___', '') encoded = tokenizer.encode(doc) print("/n TOKENIZED : ", encoded) decoded = tokenizer.decode(encoded[:min(first_tokens, len(encoded))]) print("/n DOC SHORTEN", min(first_tokens, len(encoded)), " : ", decoded) completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": system}, {"role": "user", "content": decoded} ] ) return completion.choices[0].message["content"] def summarize_docs_generator(apikey_input, session_id): openai.api_key = apikey_input docs=load_docs(session_id) print("################# DOCS LOADED ##################", "docs type : ", type(docs[0])) try: fail = docs[0].page_content except: return docs[0] source = "" summaries = "" i = 0 while i