Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from streamlit_chat import message
|
3 |
+
from langchain.chains import ConversationalRetrievalChain
|
4 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
5 |
+
from langchain.llms import Replicate
|
6 |
+
from langchain.text_splitter import CharacterTextSplitter
|
7 |
+
from langchain.vectorstores import FAISS
|
8 |
+
from langchain.memory import ConversationBufferMemory
|
9 |
+
from langchain.document_loaders import PyPDFLoader
|
10 |
+
from langchain.document_loaders import TextLoader
|
11 |
+
from langchain.document_loaders import Docx2txtLoader
|
12 |
+
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
13 |
+
import os
|
14 |
+
from dotenv import load_dotenv
|
15 |
+
import tempfile
|
16 |
+
|
17 |
+
load_dotenv()
|
18 |
+
|
19 |
+
def initialize_session_state():
|
20 |
+
if 'history' not in st.session_state:
|
21 |
+
st.session_state['history'] = []
|
22 |
+
|
23 |
+
if 'generated' not in st.session_state:
|
24 |
+
st.session_state['generated'] = ["Hello! Ask me about your file"]
|
25 |
+
|
26 |
+
if 'past' not in st.session_state:
|
27 |
+
st.session_state['past'] = ["Hey! 👋"]
|
28 |
+
|
29 |
+
def conversation_chat(query, chain, history):
|
30 |
+
result = chain({"question": query, "chat_history": history})
|
31 |
+
history.append((query, result["answer"]))
|
32 |
+
return result["answer"]
|
33 |
+
|
34 |
+
def display_chat_history(chain):
|
35 |
+
reply_container = st.container()
|
36 |
+
container = st.container()
|
37 |
+
|
38 |
+
with container:
|
39 |
+
col1, col2 = st.columns(2)
|
40 |
+
|
41 |
+
with col1:
|
42 |
+
with st.form(key='my_form', clear_on_submit=True):
|
43 |
+
user_input = st.text_input("Question:", placeholder="Ask about your Documents", key='input')
|
44 |
+
submit_button = st.form_submit_button(label='Send')
|
45 |
+
|
46 |
+
with col2:
|
47 |
+
if st.session_state['generated']:
|
48 |
+
for i in range(len(st.session_state['generated'])):
|
49 |
+
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="thumbs")
|
50 |
+
message(st.session_state["generated"][i], key=str(i), avatar_style="fun-emoji")
|
51 |
+
|
52 |
+
def create_conversational_chain(vector_store):
|
53 |
+
load_dotenv()
|
54 |
+
llm = Replicate(
|
55 |
+
streaming=True,
|
56 |
+
model="replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781",
|
57 |
+
callbacks=[StreamingStdOutCallbackHandler()],
|
58 |
+
input={"temperature": 0.01, "max_length": 500, "top_p": 1})
|
59 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
60 |
+
|
61 |
+
chain = ConversationalRetrievalChain.from_llm(llm=llm, chain_type='stuff',
|
62 |
+
retriever=vector_store.as_retriever(search_kwargs={"k": 2}),
|
63 |
+
memory=memory)
|
64 |
+
return chain
|
65 |
+
|
66 |
+
def main():
|
67 |
+
load_dotenv()
|
68 |
+
initialize_session_state()
|
69 |
+
st.title("ChatBot ")
|
70 |
+
st.sidebar.title("Document Processing")
|
71 |
+
uploaded_files = st.sidebar.file_uploader("Upload files", accept_multiple_files=True)
|
72 |
+
|
73 |
+
if uploaded_files:
|
74 |
+
text = []
|
75 |
+
for file in uploaded_files:
|
76 |
+
file_extension = os.path.splitext(file.name)[1]
|
77 |
+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
78 |
+
temp_file.write(file.read())
|
79 |
+
temp_file_path = temp_file.name
|
80 |
+
|
81 |
+
loader = None
|
82 |
+
if file_extension == ".pdf":
|
83 |
+
loader = PyPDFLoader(temp_file_path)
|
84 |
+
elif file_extension == ".docx" or file_extension == ".doc":
|
85 |
+
loader = Docx2txtLoader(temp_file_path)
|
86 |
+
elif file_extension == ".txt":
|
87 |
+
loader = TextLoader(temp_file_path)
|
88 |
+
|
89 |
+
if loader:
|
90 |
+
text.extend(loader.load())
|
91 |
+
os.remove(temp_file_path)
|
92 |
+
|
93 |
+
text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=100, length_function=len)
|
94 |
+
text_chunks = text_splitter.split_documents(text)
|
95 |
+
|
96 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
|
97 |
+
model_kwargs={'device': 'cpu'})
|
98 |
+
vector_store = FAISS.from_documents(text_chunks, embedding=embeddings)
|
99 |
+
chain = create_conversational_chain(vector_store)
|
100 |
+
display_chat_history(chain)
|
101 |
+
|
102 |
+
if __name__ == "__main__":
|
103 |
+
main()
|