Update app.py
Browse files
app.py
CHANGED
|
@@ -14,9 +14,148 @@ from langchain.llms import HuggingFaceHub
|
|
| 14 |
from pathlib import Path
|
| 15 |
import chromadb
|
| 16 |
|
| 17 |
-
from transformers import
|
| 18 |
import transformers
|
| 19 |
import torch
|
| 20 |
-
import tqdm
|
| 21 |
import accelerate
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
from pathlib import Path
|
| 15 |
import chromadb
|
| 16 |
|
| 17 |
+
from transformers import AutoTokenizer
|
| 18 |
import transformers
|
| 19 |
import torch
|
| 20 |
+
import tqdm
|
| 21 |
import accelerate
|
| 22 |
|
| 23 |
+
def load_doc(list_file_path, chunk_size, chunk_overlap):
|
| 24 |
+
# Processing for one document only
|
| 25 |
+
# loader = PyPDFLoader(file_path)
|
| 26 |
+
# pages = loader.load()
|
| 27 |
+
loaders = [PyPDFLoader(x) for x in list_file_path]
|
| 28 |
+
pages = []
|
| 29 |
+
for loader in loaders:
|
| 30 |
+
pages.extend(loader.load())
|
| 31 |
+
# text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
|
| 32 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 33 |
+
chunk_size = chunk_size,
|
| 34 |
+
chunk_overlap = chunk_overlap)
|
| 35 |
+
doc_splits = text_splitter.split_documents(pages)
|
| 36 |
+
return doc_splits
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Create vector database
|
| 40 |
+
def create_db(splits, collection_name):
|
| 41 |
+
embedding = HuggingFaceEmbeddings()
|
| 42 |
+
new_client = chromadb.EphemeralClient()
|
| 43 |
+
vectordb = Chroma.from_documents(
|
| 44 |
+
documents=splits,
|
| 45 |
+
embedding=embedding,
|
| 46 |
+
client=new_client,
|
| 47 |
+
collection_name=collection_name,
|
| 48 |
+
# persist_directory=default_persist_directory
|
| 49 |
+
)
|
| 50 |
+
return vectordb
|
| 51 |
+
|
| 52 |
+
# Load vector database
|
| 53 |
+
def load_db():
|
| 54 |
+
embedding = HuggingFaceEmbeddings()
|
| 55 |
+
vectordb = Chroma(
|
| 56 |
+
# persist_directory=default_persist_directory,
|
| 57 |
+
embedding_function=embedding)
|
| 58 |
+
return vectordb
|
| 59 |
+
|
| 60 |
+
def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
| 61 |
+
progress(0.1, desc="Initializing HF tokenizer...")
|
| 62 |
+
|
| 63 |
+
# HuggingFaceHub uses HF inference endpoints
|
| 64 |
+
progress(0.5, desc="Initializing HF Hub...")
|
| 65 |
+
# Use of trust_remote_code as model_kwargs
|
| 66 |
+
# Warning: langchain issue
|
| 67 |
+
# URL: https://github.com/langchain-ai/langchain/issues/6080
|
| 68 |
+
|
| 69 |
+
llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
| 70 |
+
llm = HuggingFaceHub(repo_id=llm_model, model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True})
|
| 71 |
+
progress(0.75, desc="Defining buffer memory...")
|
| 72 |
+
|
| 73 |
+
memory = ConversationBufferMemory(memory_key="chat_history",output_key='answer',return_messages=True )
|
| 74 |
+
|
| 75 |
+
# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
|
| 76 |
+
retriever=vector_db.as_retriever()
|
| 77 |
+
|
| 78 |
+
progress(0.8, desc="Defining retrieval chain...")
|
| 79 |
+
|
| 80 |
+
qa_chain = ConversationalRetrievalChain.from_llm(llm,retriever=retriever,chain_type="stuff", memory=memory,return_source_documents=True,verbose=False,)
|
| 81 |
+
progress(0.9, desc="Done!")
|
| 82 |
+
return qa_chain
|
| 83 |
+
|
| 84 |
+
# Initialize database
|
| 85 |
+
def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
|
| 86 |
+
|
| 87 |
+
# Create list of documents (when valid)
|
| 88 |
+
list_file_path = [x.name for x in list_file_obj if x is not None]
|
| 89 |
+
|
| 90 |
+
# Create collection_name for vector database
|
| 91 |
+
progress(0.1, desc="Creating collection name...")
|
| 92 |
+
collection_name = Path(list_file_path[0]).stem
|
| 93 |
+
|
| 94 |
+
# Fix potential issues from naming convention
|
| 95 |
+
## Remove space
|
| 96 |
+
collection_name = collection_name.replace(" ","-")
|
| 97 |
+
## Limit lenght to 50 characters
|
| 98 |
+
collection_name = collection_name[:50]
|
| 99 |
+
|
| 100 |
+
## Enforce start and end as alphanumeric character
|
| 101 |
+
if not collection_name[0].isalnum():
|
| 102 |
+
collection_name[0] = 'A'
|
| 103 |
+
if not collection_name[-1].isalnum():
|
| 104 |
+
collection_name[-1] = 'Z'
|
| 105 |
+
|
| 106 |
+
# print('list_file_path: ', list_file_path)
|
| 107 |
+
print('Collection name: ', collection_name)
|
| 108 |
+
progress(0.25, desc="Loading document...")
|
| 109 |
+
|
| 110 |
+
# Load document and create splits
|
| 111 |
+
doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
|
| 112 |
+
|
| 113 |
+
# Create or load vector database
|
| 114 |
+
progress(0.5, desc="Generating vector database...")
|
| 115 |
+
|
| 116 |
+
# global vector_db
|
| 117 |
+
vector_db = create_db(doc_splits, collection_name)
|
| 118 |
+
progress(0.9, desc="Done!")
|
| 119 |
+
return vector_db, collection_name, "Complete!"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
|
| 124 |
+
llm_name = list_llm[llm_option]
|
| 125 |
+
print("llm_name: ",llm_name)
|
| 126 |
+
qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
|
| 127 |
+
return qa_chain, "Complete!"
|
| 128 |
+
|
| 129 |
+
def format_chat_history(message, chat_history):
|
| 130 |
+
formatted_chat_history = []
|
| 131 |
+
for user_message, bot_message in chat_history:
|
| 132 |
+
formatted_chat_history.append(f"User: {user_message}")
|
| 133 |
+
formatted_chat_history.append(f"Assistant: {bot_message}")
|
| 134 |
+
return formatted_chat_history
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def conversation(qa_chain, message, history):
|
| 138 |
+
formatted_chat_history = format_chat_history(message, history)
|
| 139 |
+
#print("formatted_chat_history",formatted_chat_history)
|
| 140 |
+
|
| 141 |
+
# Generate response using QA chain
|
| 142 |
+
response = qa_chain({"question": message, "chat_history": formatted_chat_history})
|
| 143 |
+
response_answer = response["answer"]
|
| 144 |
+
if response_answer.find("Helpful Answer:") != -1:
|
| 145 |
+
response_answer = response_answer.split("Helpful Answer:")[-1]
|
| 146 |
+
response_sources = response["source_documents"]
|
| 147 |
+
response_source1 = response_sources[0].page_content.strip()
|
| 148 |
+
response_source2 = response_sources[1].page_content.strip()
|
| 149 |
+
response_source3 = response_sources[2].page_content.strip()
|
| 150 |
+
# Langchain sources are zero-based
|
| 151 |
+
response_source1_page = response_sources[0].metadata["page"] + 1
|
| 152 |
+
response_source2_page = response_sources[1].metadata["page"] + 1
|
| 153 |
+
response_source3_page = response_sources[2].metadata["page"] + 1
|
| 154 |
+
# print ('chat response: ', response_answer)
|
| 155 |
+
# print('DB source', response_sources)
|
| 156 |
+
|
| 157 |
+
# Append user message and response to chat history
|
| 158 |
+
new_history = history + [(message, response_answer)]
|
| 159 |
+
# return gr.update(value=""), new_history, response_sources[0], response_sources[1]
|
| 160 |
+
return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
|
| 161 |
+
|