roshithindia commited on
Commit
80e67ff
·
verified ·
1 Parent(s): bbd8a3e

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +124 -0
  2. requirements.txt +13 -0
app.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LlamaCpp
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ from langchain.vectorstores import FAISS
8
+ from langchain.memory import ConversationBufferMemory
9
+ from langchain.document_loaders import PyPDFLoader
10
+ import os
11
+ import tempfile
12
+
13
+ def initialize_session_state():
14
+ if 'history' not in st.session_state:
15
+ st.session_state['history'] = []
16
+
17
+ if 'generated' not in st.session_state:
18
+ st.session_state['generated'] = ["Hello! Ask me anything about 🤗"]
19
+
20
+ if 'past' not in st.session_state:
21
+ st.session_state['past'] = ["Hey! 👋"]
22
+
23
+ def conversation_chat(query, chain, history):
24
+ result = chain({"question": query, "chat_history": history})
25
+ history.append((query, result["answer"]))
26
+ return result["answer"]
27
+
28
+ def display_chat_history(chain):
29
+ reply_container = st.container()
30
+ container = st.container()
31
+
32
+ with container:
33
+ with st.form(key='my_form', clear_on_submit=True):
34
+ user_input = st.text_input("Question:", placeholder="Ask about your PDF", key='input')
35
+ submit_button = st.form_submit_button(label='Send')
36
+
37
+ if submit_button and user_input:
38
+ with st.spinner('Generating response...'):
39
+ output = conversation_chat(user_input, chain, st.session_state['history'])
40
+
41
+ st.session_state['past'].append(user_input)
42
+ st.session_state['generated'].append(output)
43
+
44
+ if st.session_state['generated']:
45
+ with reply_container:
46
+ for i in range(len(st.session_state['generated'])):
47
+ message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="thumbs")
48
+ message(st.session_state["generated"][i], key=str(i), avatar_style="fun-emoji")
49
+
50
+ def create_conversational_chain(vector_store):
51
+ model_path = "E:/users/sriva/mistral_llm/mistral-7b-instruct-v0.1.Q4_K_M-001.gguf" # Updated model path
52
+
53
+ # Debugging output
54
+ print(f"Attempting to load model from: {model_path}")
55
+ print("Checking if model file exists...")
56
+ if not os.path.exists(model_path):
57
+ raise FileNotFoundError(f"The model file does not exist at: {model_path}")
58
+
59
+ # Initialize LlamaCpp
60
+ try:
61
+ llm = LlamaCpp(
62
+ streaming=True,
63
+ model_path=model_path,
64
+ temperature=0.75,
65
+ top_p=1,
66
+ verbose=True,
67
+ n_ctx=4096
68
+ )
69
+ print("Model loaded successfully.")
70
+ except Exception as e:
71
+ print(f"Error loading model: {e}")
72
+ raise
73
+
74
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
75
+
76
+ chain = ConversationalRetrievalChain.from_llm(
77
+ llm=llm,
78
+ chain_type='stuff',
79
+ retriever=vector_store.as_retriever(search_kwargs={"k": 2}),
80
+ memory=memory
81
+ )
82
+ return chain
83
+
84
+ def main():
85
+ # Initialize session state
86
+ initialize_session_state()
87
+ st.title("Multi-PDF ChatBot using Mistral-7B-Instruct :books:")
88
+ # Initialize Streamlit
89
+ st.sidebar.title("Document Processing")
90
+ uploaded_files = st.sidebar.file_uploader("Upload files", accept_multiple_files=True)
91
+
92
+ if uploaded_files:
93
+ text = []
94
+ for file in uploaded_files:
95
+ file_extension = os.path.splitext(file.name)[1]
96
+ with tempfile.NamedTemporaryFile(delete=False) as temp_file:
97
+ temp_file.write(file.read())
98
+ temp_file_path = temp_file.name
99
+
100
+ loader = None
101
+ if file_extension == ".pdf":
102
+ loader = PyPDFLoader(temp_file_path)
103
+
104
+ if loader:
105
+ text.extend(loader.load())
106
+ os.remove(temp_file_path)
107
+
108
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=20)
109
+ text_chunks = text_splitter.split_documents(text)
110
+
111
+ # Create embeddings
112
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",
113
+ model_kwargs={'device': 'cpu'})
114
+
115
+ # Create vector store
116
+ vector_store = FAISS.from_documents(text_chunks, embedding=embeddings)
117
+
118
+ # Create the chain object
119
+ chain = create_conversational_chain(vector_store)
120
+
121
+ display_chat_history(chain)
122
+
123
+ if __name__ == "__main__":
124
+ main()
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ torch
3
+ accelerate
4
+ sentence_transformers
5
+ streamlit_chat
6
+ streamlit
7
+ faiss-cpu
8
+ tiktoken
9
+ huggingface-hub
10
+ pypdf
11
+ llama-cpp-python
12
+
13
+