annas4421 commited on
Commit
0dff71c
·
verified ·
1 Parent(s): 5df6164

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -92
app.py CHANGED
@@ -1,122 +1,132 @@
1
- # importing dependencies
2
  from dotenv import load_dotenv
3
  import streamlit as st
4
- from PyPDF2 import PdfReader
5
  from langchain.text_splitter import CharacterTextSplitter
6
- from langchain.embeddings import HuggingFaceEmbeddings
7
- from langchain.vectorstores import faiss
8
  from langchain.prompts import PromptTemplate
9
  from langchain.memory import ConversationBufferMemory
10
  from langchain.chains import ConversationalRetrievalChain
11
  from langchain.chat_models import ChatOpenAI
12
- from htmlTemplates import css, bot_template, user_template
13
- from langchain.embeddings import openai
14
- from langchain.embeddings.openai import OpenAIEmbeddings
15
- import os
 
16
 
17
-
18
- from openai import OpenAI
19
- api_key = os.getenv("OPENAI_API_KEY")
20
- client = OpenAI(api_key=api_key)
21
-
22
-
23
- # creating custom template to guide llm model
24
- custom_template ="""<s>[INST]You will start the conversation by greeting the user and introducing yourself as qanoon-bot,\
25
- stating your availability for legal assistance. Your next step will depend on the user's response.\
26
- If the user expresses a need for legal assistance in Pakistan, you will ask them to describe their case or problem.\
27
- After receiving the case or problem details from the user, you will provide the solutions and procedures according to the knowledge base and also give related penal codes and procedures. \
28
- However, if the user does not require legal assistance in Pakistan, you will immediately thank them and\
29
- say goodbye, ending the conversation. Remember to base your responses on the user's needs, providing accurate and\
30
- concise information regarding the Pakistan legal law and rights where applicable. Your interactions should be professional and\
31
- focused, ensuring the user's queries are addressed efficiently without deviating from the set flows.\
32
  CHAT HISTORY: {chat_history}
33
  QUESTION: {question}
34
  ANSWER:
35
  </s>[INST]
36
  """
37
-
38
  CUSTOM_QUESTION_PROMPT = PromptTemplate.from_template(custom_template)
39
 
40
- # extracting text from pdf
41
- def get_pdf_text(docs):
42
- text=""
43
- for pdf in docs:
44
- pdf_reader=PdfReader(pdf)
45
- for page in pdf_reader.pages:
46
- text+=page.extract_text()
47
- return text
48
-
49
- # converting text to chunks
50
- def get_chunks(raw_text):
51
- text_splitter=CharacterTextSplitter(separator="\n",
52
- chunk_size=1000,
53
- chunk_overlap=200,
54
- length_function=len)
55
- chunks=text_splitter.split_text(raw_text)
56
  return chunks
57
 
58
- # using all-MiniLm embeddings model and faiss to get vectorstore
59
  def get_vectorstore(chunks):
60
- embeddings=OpenAIEmbeddings()
61
- vectorstore=faiss.FAISS.from_texts(texts=chunks,embedding=embeddings)
62
  return vectorstore
63
 
64
- # generating conversation chain
65
  def get_conversationchain(vectorstore):
66
- llm=ChatOpenAI(temperature=0.4,model_name='gpt-4o-mini')
67
- memory = ConversationBufferMemory(memory_key='chat_history',
68
- return_messages=True,
69
- output_key='answer') # using conversation buffer memory to hold past information
70
  conversation_chain = ConversationalRetrievalChain.from_llm(
71
- llm=llm,
72
- retriever=vectorstore.as_retriever(),
73
- condense_question_prompt=CUSTOM_QUESTION_PROMPT,
74
- memory=memory)
 
75
  return conversation_chain
76
 
77
- # generating response from user queries and displaying them accordingly
78
- def handle_question(question):
79
- response=st.session_state.conversation({'question': question})
80
- st.session_state.chat_history=response["chat_history"]
81
- for i,msg in enumerate(st.session_state.chat_history):
82
- if i%2==0:
83
- st.write(user_template.replace("{{MSG}}",msg.content,),unsafe_allow_html=True)
84
- else:
85
- st.write(bot_template.replace("{{MSG}}",msg.content),unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
86
 
 
 
 
 
87
 
 
88
  def main():
89
- load_dotenv()
90
- st.set_page_config(page_title="Chat with multiple PDFs",page_icon=":books:")
91
- st.write(css,unsafe_allow_html=True)
92
- if "conversation" not in st.session_state:
93
- st.session_state.conversation=None
94
-
95
- if "chat_history" not in st.session_state:
96
- st.session_state.chat_history=None
97
-
98
- st.header("Chat with multiple PDFs :books:")
99
- question=st.text_input("Ask question from your document:")
100
- if question:
101
- handle_question(question)
102
- with st.sidebar:
103
- st.subheader("Your documents")
104
- docs=st.file_uploader("Upload your PDF here and click on 'Process'",accept_multiple_files=True)
105
- if st.button("Process"):
106
- with st.spinner("Processing"):
107
-
108
- #get the pdf
109
- raw_text=get_pdf_text(docs)
110
-
111
- #get the text chunks
112
- text_chunks=get_chunks(raw_text)
113
-
114
- #create vectorstore
115
- vectorstore=get_vectorstore(text_chunks)
116
-
117
- #create conversation chain
118
- st.session_state.conversation=get_conversationchain(vectorstore)
 
 
 
 
 
 
119
 
 
 
 
 
 
 
 
120
 
121
  if __name__ == '__main__':
122
- main()
 
1
+ import os
2
  from dotenv import load_dotenv
3
  import streamlit as st
 
4
  from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.vectorstores import FAISS
7
  from langchain.prompts import PromptTemplate
8
  from langchain.memory import ConversationBufferMemory
9
  from langchain.chains import ConversationalRetrievalChain
10
  from langchain.chat_models import ChatOpenAI
11
+ from langchain.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader, CSVLoader
12
+
13
+ # Load environment variables from .env
14
+ load_dotenv()
15
+ os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
16
 
17
+ # Custom template to guide the LLM
18
+ custom_template = """
19
+ <s>[INST]You will start the conversation by greeting the user and introducing yourself as an Expert PDF documents analyzer and assistant,
20
+ stating your availability for assistance. Your next step will depend on the user's response.
21
+ If the user expresses a need for assistance in pdf or document, you will ask them to describe their question.
22
+ However, if the user asks questions out of context from the knowledge base, you will immediately thank them and
23
+ say goodbye, ending the conversation. Remember to base your responses on the user's needs, providing accurate and
24
+ concise information regarding the data within the knowledge base. Your interactions should be professional and
25
+ focused, ensuring the user's queries are addressed efficiently without deviating from the set flows.
 
 
 
 
 
 
26
  CHAT HISTORY: {chat_history}
27
  QUESTION: {question}
28
  ANSWER:
29
  </s>[INST]
30
  """
 
31
  CUSTOM_QUESTION_PROMPT = PromptTemplate.from_template(custom_template)
32
 
33
+ # Convert text to chunks
34
+ def get_chunks(documents):
35
+ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
36
+ chunks = [chunk for doc in documents for chunk in text_splitter.split_text(doc.page_content)]
 
 
 
 
 
 
 
 
 
 
 
 
37
  return chunks
38
 
39
+ # Create vectorstore using OpenAI embeddings and FAISS
40
  def get_vectorstore(chunks):
41
+ embeddings = OpenAIEmbeddings()
42
+ vectorstore = FAISS.from_texts(texts=chunks, embedding=embeddings)
43
  return vectorstore
44
 
45
+ # Create conversation chain for LLM interaction
46
  def get_conversationchain(vectorstore):
47
+ llm = ChatOpenAI(temperature=0.4, model_name='gpt-4')
48
+ memory = ConversationBufferMemory(memory_key='chat_history', return_messages=True)
 
 
49
  conversation_chain = ConversationalRetrievalChain.from_llm(
50
+ llm=llm,
51
+ retriever=vectorstore.as_retriever(),
52
+ condense_question_prompt=CUSTOM_QUESTION_PROMPT,
53
+ memory=memory
54
+ )
55
  return conversation_chain
56
 
57
+ # Extract text from various document types including PDFs, TXT, DOCX, and CSV.
58
+ def get_document_text(uploaded_files):
59
+ documents = []
60
+
61
+ for uploaded_file in uploaded_files:
62
+ file_extension = os.path.splitext(uploaded_file.name)[1].lower()
63
+
64
+ if file_extension == ".pdf":
65
+ loader = PyPDFLoader(uploaded_file)
66
+ documents.extend(loader.load())
67
+ elif file_extension in [".docx", ".doc"]:
68
+ loader = Docx2txtLoader(uploaded_file)
69
+ documents.extend(loader.load())
70
+ elif file_extension == ".txt":
71
+ loader = TextLoader(uploaded_file)
72
+ documents.extend(loader.load())
73
+ elif file_extension == ".csv":
74
+ loader = CSVLoader(uploaded_file)
75
+ documents.extend(loader.load())
76
+
77
+ return documents
78
 
79
+ # Function to process and handle a user's query
80
+ def handle_question(conversation_chain, question):
81
+ response = conversation_chain({'question': question})
82
+ return response['answer']
83
 
84
+ # Streamlit app
85
  def main():
86
+ st.set_page_config(page_title="Chat with Documents", page_icon=":books:")
87
+ st.title("Chat with Your Documents :books:")
88
+
89
+ # Session state for conversation and chat history
90
+ if "conversation_chain" not in st.session_state:
91
+ st.session_state.conversation_chain = None
92
+
93
+ st.sidebar.header("Upload Your Documents")
94
+ uploaded_files = st.sidebar.file_uploader(
95
+ "Upload your documents here (PDF, TXT, DOCX, CSV):",
96
+ type=["pdf", "txt", "docx", "csv"],
97
+ accept_multiple_files=True
98
+ )
99
+
100
+ if st.sidebar.button("Process"):
101
+ if uploaded_files:
102
+ with st.spinner("Processing your documents..."):
103
+ # Extract text from uploaded documents
104
+ raw_documents = get_document_text(uploaded_files)
105
+
106
+ if not raw_documents:
107
+ st.error("No text could be extracted from the documents. Please check the files.")
108
+ return
109
+
110
+ # Convert text to chunks
111
+ text_chunks = get_chunks(raw_documents)
112
+
113
+ # Create vectorstore
114
+ vectorstore = get_vectorstore(text_chunks)
115
+
116
+ # Create conversation chain
117
+ st.session_state.conversation_chain = get_conversationchain(vectorstore)
118
+
119
+ st.success("Documents processed successfully! You can now ask questions.")
120
+ else:
121
+ st.error("Please upload at least one document.")
122
 
123
+ # Chat interface
124
+ if st.session_state.conversation_chain:
125
+ question = st.text_input("Ask a question about your documents:")
126
+ if question:
127
+ with st.spinner("Generating response..."):
128
+ answer = handle_question(st.session_state.conversation_chain, question)
129
+ st.markdown(f"**Answer:** {answer}")
130
 
131
  if __name__ == '__main__':
132
+ main()