Gainward777 commited on
Commit
5db687f
·
verified ·
1 Parent(s): 952d4f6

Upload 8 files

Browse files
Files changed (8) hide show
  1. ChatErector.py +30 -0
  2. CustomRetriever.py +47 -0
  3. README.md.txt +12 -0
  4. app.py +3 -0
  5. db/utils.py +44 -0
  6. llm/utils.py +74 -0
  7. requirements.txt +10 -0
  8. ui/gradio_ui.py +88 -0
ChatErector.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llm.utils import initialize_LLM, format_chat_history, postprocess
2
+ from db.utils import initialize_database
3
+ import gradio as gr
4
+ import spaces
5
+
6
+ def initializer(list_file_obj, llm_temperature, max_tokens, top_k, thold, progress=gr.Progress()):
7
+ vdb=initialize_database(list_file_obj)
8
+ qa_chain=initialize_LLM(llm_temperature, max_tokens, top_k, vdb, thold)#, progress)
9
+ return qa_chain, "Success."
10
+
11
+
12
+ @spaces.GPU
13
+ def conversation(qa_chain, message, history):
14
+ formatted_chat_history = format_chat_history(message, history)
15
+ # Generate response using QA chain
16
+ response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
17
+ response_answer = postprocess(response)#response["answer"]
18
+ #if response_answer.find("Helpful Answer:") != -1:
19
+ #response_answer = response_answer.split("Helpful Answer:")[-1]
20
+ #response_sources = response["source_documents"]
21
+ #response_source1 = response_sources[0].page_content.strip()
22
+ #response_source2 = response_sources[1].page_content.strip()
23
+ #response_source3 = response_sources[2].page_content.strip()
24
+ # Langchain sources are zero-based
25
+ #response_source1_page = response_sources[0].metadata["page"] + 1
26
+ #response_source2_page = response_sources[1].metadata["page"] + 1
27
+ #response_source3_page = response_sources[2].metadata["page"] + 1
28
+ # Append user message and response to chat history
29
+ new_history = history + [(message, response_answer)]
30
+ return qa_chain, gr.update(value=""), new_history #, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
CustomRetriever.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.schema.retriever import BaseRetriever
2
+ from langchain_core.documents import Document
3
+ from typing import List
4
+
5
+ from langchain.callbacks.manager import CallbackManagerForRetrieverRun
6
+
7
+ from langchain_core.documents import Document
8
+ from langchain_core.runnables import chain
9
+
10
+ class CustomRetriever():
11
+ def __init__(self, v_db, thold=0.7):
12
+
13
+
14
+ #self.retriever=RetrieverWithScores()
15
+
16
+ class RetrieverWithScores(BaseRetriever):
17
+ #def __init__(self, vdb):
18
+ #self.vdb=vdb
19
+ #def __init__(self, retriever: BaseRetriever): # Add an __init__ to store the existing retriever
20
+ #super().__init__(retriever=retriever)
21
+ def _get_relevant_documents(
22
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun)-> List[Document]:
23
+
24
+ @chain
25
+ def retr_func(query: str)-> List[Document]: #(vdb, query: str)-> List[Document]:
26
+ docs, scores = zip(*v_db.similarity_search_with_relevance_scores(query))#similarity_search_with_score(query))
27
+ result=[]
28
+ for doc, score in zip(docs, scores):
29
+ if score>thold:
30
+ doc.metadata["score"] = score
31
+ result.append(doc)
32
+ if len(result)==0:
33
+ result.append(Document(metadata={}, page_content='No data'))
34
+
35
+ return result #docs
36
+
37
+ return retr_func.invoke(query) #(self.vdb, query)
38
+
39
+ self.retriever=RetrieverWithScores()
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
README.md.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: RAG Test1
3
+ emoji: 🐢
4
+ colorFrom: yellow
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 4.31.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from ui.gradio_ui import ui
2
+
3
+ ui()
db/utils.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.document_loaders import PyPDFLoader
2
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
3
+ from langchain_community.embeddings import HuggingFaceEmbeddings
4
+ from langchain_community.vectorstores import FAISS
5
+ import gradio as gr
6
+
7
+
8
+ # Load and split PDF document
9
+ def load_doc(list_file_path):
10
+ # Processing for one document only
11
+ # loader = PyPDFLoader(file_path)
12
+ # pages = loader.load()
13
+ loaders = [PyPDFLoader(x) for x in list_file_path]
14
+ pages = []
15
+ for loader in loaders:
16
+ pages.extend(loader.load())
17
+ text_splitter = RecursiveCharacterTextSplitter(
18
+ chunk_size = 1024,
19
+ chunk_overlap = 64
20
+ )
21
+ doc_splits = text_splitter.split_documents(pages)
22
+ return doc_splits
23
+
24
+
25
+
26
+ def create_db(splits):
27
+ model_kwargs = {'device': 'cpu'}
28
+
29
+ embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en", model_kwargs =model_kwargs)
30
+ vectordb = FAISS.from_documents(splits, embeddings)
31
+ return vectordb
32
+
33
+
34
+ def initialize_database(list_file_obj, progress=gr.Progress()):
35
+ # Create a list of documents (when valid)
36
+ list_file_path = [x.name for x in list_file_obj if x is not None]
37
+ # Load document and create splits
38
+ doc_splits = load_doc(list_file_path)
39
+ # Create or load vector database
40
+ vector_db = create_db(doc_splits)
41
+ return vector_db #, "Database created!"
42
+
43
+
44
+
llm/utils.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.llms import HuggingFaceEndpoint
2
+ from langchain.memory import ConversationBufferMemory
3
+ from langchain.chains import ConversationalRetrievalChain
4
+ import gradio as gr
5
+ import os
6
+ from CustomRetriever import CustomRetriever
7
+
8
+
9
+ API_TOKEN=os.getenv("TOKEN")
10
+
11
+ # Initialize langchain LLM chain
12
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vdb,
13
+ thold=0.8, progress=gr.Progress()):
14
+ llm = HuggingFaceEndpoint(
15
+ huggingfacehub_api_token = API_TOKEN,
16
+ repo_id=llm_model,
17
+ temperature = temperature,
18
+ max_new_tokens = max_tokens,
19
+ top_k = top_k,
20
+ )
21
+
22
+ memory = ConversationBufferMemory(
23
+ memory_key="chat_history",
24
+ output_key='answer',
25
+ return_messages=True
26
+ )
27
+
28
+ retr=CustomRetriever(vdb, thold=thold)
29
+ retriever=retr.retriever #vector_db.as_retriever()
30
+ qa_chain = ConversationalRetrievalChain.from_llm(
31
+ llm,
32
+ retriever=retriever,
33
+ chain_type="stuff",
34
+ memory=memory,
35
+ return_source_documents=True,
36
+ verbose=False,
37
+ )
38
+ return qa_chain
39
+
40
+
41
+
42
+ # Initialize LLM
43
+ def initialize_LLM(llm_temperature, max_tokens, top_k, vector_db, thold, progress=gr.Progress()):
44
+ # print("llm_option",llm_option)
45
+ llm_name = "mistralai/Mistral-7B-Instruct-v0.2" #list_llm[llm_option]
46
+ #print("llm_name: ",llm_name)
47
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, thold)
48
+ return qa_chain #, "QA chain initialized. Chatbot is ready!"
49
+
50
+
51
+
52
+ def format_chat_history(chat_history):#message, chat_history): #no need message
53
+ formatted_chat_history = []
54
+ for user_message, bot_message in chat_history:
55
+ formatted_chat_history.append(f"User: {user_message}")
56
+ formatted_chat_history.append(f"Assistant: {bot_message}")
57
+ return formatted_chat_history
58
+
59
+
60
+
61
+ def postprocess(response):
62
+ try:
63
+ result=response["answer"]
64
+ for doc in response['source_documents']:
65
+ file_doc="\n\nFile: " + doc.metadata["source"]
66
+ page="\nPage: " + str(doc.metadata["page"])
67
+ content="\nFragment: " + doc.page_content.strip()
68
+ result+=file_doc+page+content
69
+ return result
70
+ except:
71
+ return response["answer"]
72
+
73
+
74
+
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ sentence-transformers
4
+ langchain
5
+ langchain-community
6
+ tqdm
7
+ accelerate
8
+ pypdf
9
+ faiss-cpu
10
+ #faiss-gpu
ui/gradio_ui.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from ChatErector import conversation, initializer
3
+
4
+ def ui():
5
+ # with gr.Blocks(theme=gr.themes.Default(primary_hue="sky")) as demo:
6
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue = "sky")) as ui:
7
+ #vector_db = gr.State()
8
+ qa_chain = gr.State()
9
+ gr.HTML("<center><h1>RAG PDF chatbot</h1><center>")
10
+ gr.Markdown("""<b>Query your PDF documents!</b> This AI agent is designed to perform retrieval augmented generation (RAG) on PDF documents. The app is hosted on Hugging Face Hub for the sole purpose of demonstration. \
11
+ <b>Please do not upload confidential documents.</b>
12
+ """)
13
+ with gr.Row():
14
+ with gr.Column(scale = 86):
15
+ gr.Markdown("<b>Step 1 - Upload PDF documents and Initialize RAG pipeline</b>")
16
+ with gr.Row():
17
+ document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
18
+ #with gr.Row():
19
+ #db_btn = gr.Button("Create vector database")
20
+ #with gr.Row():
21
+ #db_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Vector database status",
22
+ #gr.Markdown("<style>body { font-size: 16px; }</style><b>Advanced settings</b>")
23
+ #with gr.Row():
24
+ #llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value = list_llm_simple[0], type="index") # info="Select LLM", show_label=False
25
+ with gr.Row():
26
+ with gr.Accordion("Advanced settings", open=False):
27
+ with gr.Row():
28
+ slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.5, step=0.1, label="Temperature", info="Controls randomness in token generation", interactive=True)
29
+ with gr.Row():
30
+ slider_maxtokens = gr.Slider(minimum = 128, maximum = 9192, value=4096, step=128, label="Max New Tokens", info="Maximum number of tokens to be generated",interactive=True)
31
+ with gr.Row():
32
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k", info="Number of tokens to select the next token from", interactive=True)
33
+ with gr.Row():
34
+ thold = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.8, step=0.1, label="Treshold", info="Retrieved information relevance level", interactive=True)
35
+ with gr.Row():
36
+ qachain_btn = gr.Button("Initialize Question Answering Chatbot")
37
+ with gr.Row():
38
+ llm_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Chatbot status",
39
+
40
+ with gr.Column(scale = 200):
41
+ gr.Markdown("<b>Step 2 - Chat with your Document</b>")
42
+ chatbot = gr.Chatbot(height=505)
43
+ #with gr.Accordion("Relevent context from the source document", open=False):
44
+ #with gr.Row():
45
+ #doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
46
+ #source1_page = gr.Number(label="Page", scale=1)
47
+ #with gr.Row():
48
+ #doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
49
+ #source2_page = gr.Number(label="Page", scale=1)
50
+ #with gr.Row():
51
+ #doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
52
+ #source3_page = gr.Number(label="Page", scale=1)
53
+ with gr.Row():
54
+ msg = gr.Textbox(placeholder="Ask a question", container=True)
55
+ with gr.Row():
56
+ submit_btn = gr.Button("Submit")
57
+ clear_btn = gr.ClearButton([msg, chatbot], value="Clear")
58
+
59
+ # Preprocessing events
60
+ #db_btn.click(initialize_database, \
61
+ #inputs=[document], \
62
+ #outputs=[vector_db, db_progress])
63
+ qachain_btn.click(initializer, \
64
+ inputs=[document, slider_temperature, slider_maxtokens, slider_topk, thold], \
65
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
66
+ inputs=None, \
67
+ outputs=[chatbot] \
68
+ queue=False)
69
+
70
+ # Chatbot events
71
+ msg.submit(conversation, \
72
+ inputs=[qa_chain, msg, chatbot], \
73
+ outputs=[qa_chain, msg, chatbot], \
74
+ queue=False)
75
+ submit_btn.click(conversation, \
76
+ inputs=[qa_chain, msg, chatbot], \
77
+ outputs=[qa_chain, msg, chatbot], \
78
+ queue=False)
79
+ clear_btn.click(lambda:[None,"",0,"",0,"",0], \
80
+ inputs=None, \
81
+ outputs=[chatbot], \
82
+ queue=False)
83
+ ui.queue().launch(debug=True)
84
+
85
+
86
+
87
+
88
+