SinhNguyen commited on
Commit
6f7a50b
1 Parent(s): 80ef0ef

initiate the space

Browse files
Files changed (5) hide show
  1. .gitignore +42 -0
  2. README.md +13 -12
  3. app.py +120 -0
  4. htmlTemplates.py +57 -0
  5. requirements.txt +15 -0
.gitignore ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ dist/
11
+ build/
12
+ *.egg-info/
13
+ *.egg
14
+
15
+ # Virtual environments
16
+ venv/
17
+ env/
18
+ .env
19
+
20
+ # IDE specific files
21
+ .idea/
22
+ .vscode/
23
+
24
+ # Jupyter Notebook specific files
25
+ .ipynb_checkpoints/
26
+
27
+ # Compiled Python files
28
+ *.pyc
29
+
30
+ # Logs and temporary files
31
+ *.log
32
+ *.bak
33
+ *.swp
34
+ *.tmp
35
+
36
+ # Coverage reports
37
+ htmlcov/
38
+ .coverage
39
+
40
+ # Dependency directories
41
+ lib/
42
+ lib64/
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Pdf Buddy
3
- emoji: 📉
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: streamlit
7
- sdk_version: 1.21.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
 
 
1
+ # Langchain Demo - PDF Text Chatbot
2
+
3
+ This repository contains a pet demo showcasing the use of Langchain, Hugging Face's Embedding & LLM, to build a chatbot for PDF documents. It is customized from [original repository](https://github.com/alejandro-ao/ask-multiple-pdfs). The chatbot is deployed as a Streamlit web application on Hugging Face Spaces using GitHub Actions.
4
+
5
+ ## Overview
6
+
7
+ The Langchain Demo allows you to extract text content from PDF documents and interact with them using a chatbot interface. The main steps involved in the process are as follows:
8
+
9
+ 1. **Extract PDF Text Content**: The demo extracts the text content from PDF documents.
10
+
11
+ 2. **Text Chunking and Embedding**: The extracted text is broken down into smaller chunks and processed using a powerful Hugging Face instruction-finetuned text embedding model and saved in a vector database.
12
+
13
+ 3. **Response Generation**: The selected chunks are then passed to a language model provided by Hugging Face. Conversational retrieval by leveraging the LLM for generating responses, the vector store for efficient similarity-based retrieval, and the conversation buffer memory to maintain the context of the conversation history.
app.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PyPDF2 import PdfReader
3
+ from langchain.text_splitter import CharacterTextSplitter
4
+ from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
5
+ from langchain.vectorstores import FAISS
6
+ from langchain.chat_models import ChatOpenAI
7
+ from langchain.memory import ConversationBufferMemory
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ from htmlTemplates import css, bot_template, user_template
10
+ from langchain.llms import HuggingFaceHub
11
+ import os
12
+ from dotenv import load_dotenv
13
+
14
+
15
+ def get_pdf_text(pdf_docs):
16
+ text = ""
17
+ for pdf in pdf_docs:
18
+ pdf_reader = PdfReader(pdf)
19
+ for page in pdf_reader.pages:
20
+ text += page.extract_text()
21
+ return text
22
+
23
+
24
+ def get_text_chunks(text):
25
+ text_splitter = CharacterTextSplitter(
26
+ separator="\n",
27
+ chunk_size=1000,
28
+ chunk_overlap=200,
29
+ length_function=len
30
+ )
31
+ chunks = text_splitter.split_text(text)
32
+ return chunks
33
+
34
+
35
+ def get_vectorstore(text_chunks):
36
+ # embeddings = OpenAIEmbeddings()
37
+ print("HAHA")
38
+ model_name = "hkunlp/instructor-xl"
39
+ model_kwargs = {'device': 'cpu'}
40
+ embeddings = HuggingFaceInstructEmbeddings(
41
+ model_name=model_name, model_kwargs=model_kwargs)
42
+ print("HAHA")
43
+ vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
44
+ return vectorstore
45
+
46
+
47
+ def get_conversation_chain(vectorstore):
48
+ # llm = ChatOpenAI()
49
+ llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":218})
50
+
51
+ memory = ConversationBufferMemory(
52
+ memory_key='chat_history', return_messages=True)
53
+ conversation_chain = ConversationalRetrievalChain.from_llm(
54
+ llm=llm,
55
+ retriever=vectorstore.as_retriever(),
56
+ memory=memory
57
+ )
58
+ return conversation_chain
59
+
60
+
61
+ def handle_userinput(user_question):
62
+ response = st.session_state.conversation({'question': user_question})
63
+ st.session_state.chat_history = response['chat_history']
64
+
65
+ for i, message in enumerate(st.session_state.chat_history):
66
+ if i % 2 == 0:
67
+ st.write(user_template.replace(
68
+ "{{MSG}}", message.content), unsafe_allow_html=True)
69
+ else:
70
+ st.write(bot_template.replace(
71
+ "{{MSG}}", message.content), unsafe_allow_html=True)
72
+
73
+
74
+ def main():
75
+ load_dotenv()
76
+ st.set_page_config(page_title="PDF Buddy", page_icon=":coffee:")
77
+ st.markdown(
78
+ """
79
+ <style>
80
+ body {
81
+ background-color: #fce6ef;
82
+ }
83
+ </style>
84
+ """,
85
+ unsafe_allow_html=True
86
+ )
87
+ st.write(css, unsafe_allow_html=True)
88
+
89
+ if "conversation" not in st.session_state:
90
+ st.session_state.conversation = None
91
+ if "chat_history" not in st.session_state:
92
+ st.session_state.chat_history = None
93
+
94
+ st.header("PDF Buddy :coffee:")
95
+ user_question = st.text_input("Ask a question about your documents:")
96
+ if user_question:
97
+ handle_userinput(user_question)
98
+
99
+ with st.sidebar:
100
+ st.subheader("Your documents")
101
+ pdf_docs = st.file_uploader(
102
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
103
+ if st.button("Process"):
104
+ with st.spinner("Processing"):
105
+ # get pdf text
106
+ raw_text = get_pdf_text(pdf_docs)
107
+
108
+ # get the text chunks
109
+ text_chunks = get_text_chunks(raw_text)
110
+
111
+ # create vector store
112
+ vectorstore = get_vectorstore(text_chunks)
113
+
114
+ # create conversation chain
115
+ st.session_state.conversation = get_conversation_chain(
116
+ vectorstore)
117
+
118
+
119
+ if __name__ == '__main__':
120
+ main()
htmlTemplates.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ css = '''
2
+ <style>
3
+ body {
4
+ background-color: #fce6ef;
5
+ }
6
+
7
+ .chat-message {
8
+ padding: 1.5rem;
9
+ border-radius: 0.5rem;
10
+ margin-bottom: 1rem;
11
+ display: flex;
12
+ }
13
+
14
+ .chat-message.user {
15
+ background-color: #fdeff2;
16
+ }
17
+
18
+ .chat-message.bot {
19
+ background-color: #fba5c0;
20
+ }
21
+
22
+ .chat-message .avatar {
23
+ width: 20%;
24
+ }
25
+
26
+ .chat-message .avatar img {
27
+ max-width: 78px;
28
+ max-height: 78px;
29
+ border-radius: 50%;
30
+ object-fit: cover;
31
+ }
32
+
33
+ .chat-message .message {
34
+ width: 80%;
35
+ padding: 0 1.5rem;
36
+ color: #fff;
37
+ }
38
+ </style>
39
+ '''
40
+
41
+ bot_template = '''
42
+ <div class="chat-message bot">
43
+ <div class="avatar">
44
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
45
+ </div>
46
+ <div class="message">{{MSG}}</div>
47
+ </div>
48
+ '''
49
+
50
+ user_template = '''
51
+ <div class="chat-message user">
52
+ <div class="avatar">
53
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
54
+ </div>
55
+ <div class="message">{{MSG}}</div>
56
+ </div>
57
+ '''
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ PyPDF2
3
+ python-dotenv
4
+ streamlit
5
+ openai
6
+ faiss-cpu
7
+ altair
8
+ tiktoken
9
+
10
+ # use huggingface llms
11
+ huggingface-hub
12
+
13
+ # Use instructor embeddings
14
+ InstructorEmbedding
15
+ sentence-transformers