rashid01 commited on
Commit
6bee77b
·
verified ·
1 Parent(s): 8c182d3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -0
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import tempfile
15
+
16
+ # Initialize session state
17
+ def initialize_session_state():
18
+ if 'history' not in st.session_state:
19
+ st.session_state['history'] = []
20
+
21
+ if 'generated' not in st.session_state:
22
+ st.session_state['generated'] = ["Hello! What you want to know about your file"]
23
+
24
+ if 'past' not in st.session_state:
25
+ st.session_state['past'] = ["Hey! 👋"]
26
+
27
+ # Conversation chat function
28
+ def conversation_chat(query, chain, history):
29
+ result = chain({"question": query, "chat_history": history})
30
+ history.append((query, result["answer"]))
31
+ return result["answer"]
32
+
33
+ # Display chat history
34
+ def display_chat_history(chain):
35
+ reply_container = st.container()
36
+ container = st.container()
37
+
38
+ with container:
39
+ with st.form(key='my_form', clear_on_submit=True):
40
+ user_input = st.text_input("Question:", placeholder="Ask about your Documents", key='input')
41
+ submit_button = st.form_submit_button(label='Send')
42
+
43
+ if submit_button and user_input:
44
+ with st.spinner('Generating response...'):
45
+ output = conversation_chat(user_input, chain, st.session_state['history'])
46
+
47
+ st.session_state['past'].append(user_input)
48
+ st.session_state['generated'].append(output)
49
+
50
+ if st.session_state['generated']:
51
+ with reply_container:
52
+ for i in range(len(st.session_state['generated'])):
53
+ message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="thumbs")
54
+ message(st.session_state["generated"][i], key=str(i), avatar_style="fun-emoji")
55
+
56
+ # Create conversational chain
57
+ def create_conversational_chain(vector_store):
58
+ replicate_api_token = "r8_MgTUrfPJIluDoXUhG7JXuPAYr6PonOW4BJCj0"
59
+ os.environ["REPLICATE_API_TOKEN"] = replicate_api_token
60
+
61
+ llm = Replicate(
62
+ streaming=True,
63
+ model="replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781",
64
+ callbacks=[StreamingStdOutCallbackHandler()],
65
+ input={"temperature": 0.01, "max_length": 500, "top_p": 1},
66
+ replicate_api_token=replicate_api_token
67
+ )
68
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
69
+
70
+ chain = ConversationalRetrievalChain.from_llm(llm=llm, chain_type='stuff',
71
+ retriever=vector_store.as_retriever(search_kwargs={"k": 2}),
72
+ memory=memory)
73
+ return chain
74
+
75
+ # Main function
76
+ def main():
77
+ initialize_session_state()
78
+ st.title("Chat With Your Doc")
79
+ st.sidebar.title("Document Processing")
80
+ uploaded_files = st.sidebar.file_uploader("Upload files", accept_multiple_files=True)
81
+
82
+ if uploaded_files:
83
+ text = []
84
+ for file in uploaded_files:
85
+ file_extension = os.path.splitext(file.name)[1]
86
+ with tempfile.NamedTemporaryFile(delete=False) as temp_file:
87
+ temp_file.write(file.read())
88
+ temp_file_path = temp_file.name
89
+
90
+ loader = None
91
+ if file_extension == ".pdf":
92
+ loader = PyPDFLoader(temp_file_path)
93
+ elif file_extension == ".docx" or file_extension == ".doc":
94
+ loader = Docx2txtLoader(temp_file_path)
95
+ elif file_extension == ".txt":
96
+ loader = TextLoader(temp_file_path)
97
+
98
+ if loader:
99
+ text.extend(loader.load())
100
+ os.remove(temp_file_path)
101
+
102
+ text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=100, length_function=len)
103
+ text_chunks = text_splitter.split_documents(text)
104
+
105
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
106
+ model_kwargs={'device': 'cpu'})
107
+ vector_store = FAISS.from_documents(text_chunks, embedding=embeddings)
108
+ chain = create_conversational_chain(vector_store)
109
+ display_chat_history(chain)
110
+
111
+ if __name__ == "__main__":
112
+ main()