Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,122 +1,132 @@
|
|
1 |
-
|
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
|
7 |
-
from langchain.vectorstores import
|
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
|
13 |
-
|
14 |
-
from
|
15 |
-
|
|
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
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 |
-
#
|
41 |
-
def
|
42 |
-
|
43 |
-
for
|
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
|
59 |
def get_vectorstore(chunks):
|
60 |
-
embeddings=OpenAIEmbeddings()
|
61 |
-
vectorstore=
|
62 |
return vectorstore
|
63 |
|
64 |
-
#
|
65 |
def get_conversationchain(vectorstore):
|
66 |
-
llm=ChatOpenAI(temperature=0.4,model_name='gpt-
|
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 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
|
|
75 |
return conversation_chain
|
76 |
|
77 |
-
#
|
78 |
-
def
|
79 |
-
|
80 |
-
|
81 |
-
for
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
|
|
|
|
|
|
|
|
87 |
|
|
|
88 |
def main():
|
89 |
-
|
90 |
-
st.
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
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()
|