Chananchida/claude-chat-with-pdf
0
1import gradio as gr2import os3from getpass import getpass4from langchain_community.document_loaders import PyPDFLoader5from langchain.text_splitter import RecursiveCharacterTextSplitter6from langchain_community.vectorstores import Chroma7from langchain.chains import ConversationalRetrievalChain8from langchain_community.embeddings import HuggingFaceEmbeddings 9from langchain_community.llms import HuggingFacePipeline10from langchain.chains import ConversationChain11from langchain.memory import ConversationBufferMemory12from langchain_anthropic import ChatAnthropic13 14from pathlib import Path15import chromadb16from unidecode import unidecode17 18from transformers import AutoTokenizer19import transformers20import torch21import tqdm 22import accelerate23import re24 25# Load PDF document and create doc splits26def load_doc(list_file_path, chunk_size, chunk_overlap):27 # Processing for one document only28 loaders = [PyPDFLoader(x) for x in list_file_path]29 pages = []30 for loader in loaders:31 pages.extend(loader.load())32 # text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)33 text_splitter = RecursiveCharacterTextSplitter(34 chunk_size = chunk_size, 35 chunk_overlap = chunk_overlap)36 doc_splits = text_splitter.split_documents(pages)37 return doc_splits38 39# Create vector database40def 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 )49 return vectordb50 51 52# Load vector database53def load_db():54 embedding = HuggingFaceEmbeddings()55 vectordb = Chroma(56 embedding_function=embedding)57 return vectordb58 59 60# Initialize langchain LLM chain61def initialize_llmchain(key, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):62 progress(0.1, desc="Initializing...")63 64 llm = ChatAnthropic(model_name="claude-3-opus-20240229",65 temperature=temperature, 66 anthropic_api_key=key67 # max_new_tokens = max_tokens,68 # top_k = top_k,69 )70 71 progress(0.75, desc="Defining buffer memory...")72 memory = ConversationBufferMemory(73 memory_key="chat_history",74 output_key='answer',75 return_messages=True76 )77 # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})78 retriever=vector_db.as_retriever()79 progress(0.8, desc="Defining retrieval chain...")80 qa_chain = ConversationalRetrievalChain.from_llm(81 llm,82 retriever=retriever,83 chain_type="stuff", 84 memory=memory,85 # combine_docs_chain_kwargs={"prompt": your_prompt})86 return_source_documents=True,87 #return_generated_question=False,88 verbose=False,89 )90 progress(0.9, desc="Done!")91 return qa_chain92 93 94# Generate collection name for vector database95# - Use filepath as input, ensuring unicode text96def create_collection_name(filepath):97 # Extract filename without extension98 collection_name = Path(filepath).stem99 # Fix potential issues from naming convention100 ## Remove space101 collection_name = collection_name.replace(" ","-") 102 ## ASCII transliterations of Unicode text103 collection_name = unidecode(collection_name)104 ## Remove special characters105 #collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]106 collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)107 ## Limit length to 50 characters108 collection_name = collection_name[:50]109 ## Minimum length of 3 characters110 if len(collection_name) < 3:111 collection_name = collection_name + 'xyz'112 ## Enforce start and end as alphanumeric character113 if not collection_name[0].isalnum():114 collection_name = 'A' + collection_name[1:]115 if not collection_name[-1].isalnum():116 collection_name = collection_name[:-1] + 'Z'117 print('Filepath: ', filepath)118 print('Collection name: ', collection_name)119 return collection_name120 121 122# Initialize database123def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):124 # Create list of documents (when valid)125 list_file_path = [x.name for x in list_file_obj if x is not None]126 # Create collection_name for vector database127 progress(0.1, desc="Creating collection name...")128 collection_name = create_collection_name(list_file_path[0])129 progress(0.25, desc="Loading document...")130 # Load document and create splits131 doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)132 # Create or load vector database133 progress(0.5, desc="Generating vector database...")134 # global vector_db135 vector_db = create_db(doc_splits, collection_name)136 progress(0.9, desc="Done!")137 return vector_db, collection_name, "Complete!"138 139 140def initialize_LLM( key, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):141 qa_chain = initialize_llmchain( key, llm_temperature, max_tokens, top_k, vector_db, progress)142 return qa_chain, "Complete!"143 144 145def format_chat_history(message, chat_history):146 formatted_chat_history = []147 for user_message, bot_message in chat_history:148 formatted_chat_history.append(f"User: {user_message}")149 formatted_chat_history.append(f"Assistant: {bot_message}")150 return formatted_chat_history151 152 153def conversation(qa_chain, message, history):154 formatted_chat_history = format_chat_history(message, history)155 156 # Generate response using QA chain157 response = qa_chain({"question": message, "chat_history": formatted_chat_history})158 response_answer = response["answer"]159 if response_answer.find("Helpful Answer:") != -1:160 response_answer = response_answer.split("Helpful Answer:")[-1]161 response_sources = response["source_documents"]162 response_source1 = response_sources[0].page_content.strip()163 response_source2 = response_sources[1].page_content.strip()164 response_source3 = response_sources[2].page_content.strip()165 166 # Langchain sources are zero-based167 response_source1_page = response_sources[0].metadata["page"] + 1168 response_source2_page = response_sources[1].metadata["page"] + 1169 response_source3_page = response_sources[2].metadata["page"] + 1170 171 # Append user message and response to chat history172 new_history = history + [(message, response_answer)]173 return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page174 175 176def upload_file(file_obj):177 list_file_path = []178 for idx, file in enumerate(file_obj):179 file_path = file_obj.name180 list_file_path.append(file_path)181 return list_file_path182 183 184def demo():185 with gr.Blocks(theme="base") as demo:186 vector_db = gr.State()187 qa_chain = gr.State()188 collection_name = gr.State()189 190 gr.Markdown(191 """<center><h2>PDF-based chatbot (powered by LangChain and Anthropic Claude-3)</center></h2>192 <h3>Ask any questions about your PDF documents, along with follow-ups</h3>193 <b>Note:</b> This AI assistant performs retrieval-augmented generation from your PDF documents. \194 When generating answers, it takes past questions into account (via conversational memory), and includes document references for clarity purposes.</i>195 <br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate an output.<br>196 """)197 with gr.Tab("Step 1 - Document pre-processing"):198 with gr.Row():199 document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")200 # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)201 with gr.Row():202 db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")203 with gr.Accordion("Advanced options - Document text splitter", open=False):204 with gr.Row():205 slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)206 with gr.Row():207 slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)208 with gr.Row():209 db_progress = gr.Textbox(label="Vector database initialization", value="None")210 with gr.Row():211 db_btn = gr.Button("Generate vector database...")212 213 with gr.Tab("Step 2 - Claude QA chain initialization"):214 with gr.Row():215 gr.Markdown(216 """<h3>To use Anthropic models, you will need to set the ANTHROPIC_API_KEY environment variable. You can get an Anthropic API key <a href="https://console.anthropic.com/settings/keys">here</a></h3>""")217 with gr.Row():218 claude_key = gr.Textbox(placeholder="Enter your Anthropic API Key...", container=True,label="Anthropic API Key")219 with gr.Accordion("Advanced options - LLM model", open=False):220 with gr.Row():221 slider_temperature = gr.Slider(minimum = 0.0, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)222 with gr.Row():223 slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)224 with gr.Row():225 slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)226 with gr.Row():227 llm_progress = gr.Textbox(value="None",label="QA chain initialization")228 with gr.Row():229 qachain_btn = gr.Button("Initialize question-answering chain...")230 231 with gr.Tab("Step 3 - Conversation with chatbot"):232 chatbot = gr.Chatbot(height=300)233 with gr.Accordion("Advanced - Document references", open=False):234 with gr.Row():235 doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)236 source1_page = gr.Number(label="Page", scale=1)237 with gr.Row():238 doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)239 source2_page = gr.Number(label="Page", scale=1)240 with gr.Row():241 doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)242 source3_page = gr.Number(label="Page", scale=1)243 with gr.Row():244 msg = gr.Textbox(placeholder="Type message", container=True)245 with gr.Row():246 submit_btn = gr.Button("Submit")247 clear_btn = gr.ClearButton([msg, chatbot])248 249 # Preprocessing events250 #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])251 db_btn.click(initialize_database, \252 inputs=[document, slider_chunk_size, slider_chunk_overlap], \253 outputs=[vector_db, collection_name, db_progress])254 qachain_btn.click(initialize_LLM, \255 inputs=[ claude_key, slider_temperature, slider_maxtokens, slider_topk, vector_db], \256 outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \257 inputs=None, \258 outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \259 queue=False)260 261 # Chatbot events262 msg.submit(conversation, \263 inputs=[qa_chain, msg, chatbot], \264 outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \265 queue=False)266 submit_btn.click(conversation, \267 inputs=[qa_chain, msg, chatbot], \268 outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \269 queue=False)270 clear_btn.click(lambda:[None,"",0,"",0,"",0], \271 inputs=None, \272 outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \273 queue=False)274 demo.queue().launch(debug=True)275 276 277if __name__ == "__main__":278 demo()