ArturG9 commited on
Commit
3c4de7d
1 Parent(s): 40273bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -40
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import streamlit as st
 
3
  from transformers import pipeline
4
  from langchain_community.embeddings import HuggingFaceEmbeddings
5
  from langchain_community.llms import llamacpp
@@ -14,6 +15,7 @@ from langchain.prompts import PromptTemplate
14
  from langchain.chains import create_history_aware_retriever, create_retrieval_chain
15
  from langchain.vectorstores import Chroma
16
  from utills import load_txt_documents , split_docs, load_uploaded_documents,retriever_from_chroma
 
17
 
18
 
19
  script_dir = os.path.dirname(os.path.abspath(__file__))
@@ -32,66 +34,93 @@ hf = HuggingFaceEmbeddings(
32
  model_kwargs=model_kwargs,
33
  encode_kwargs=encode_kwargs
34
  )
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
 
37
 
38
 
 
 
 
 
 
 
 
39
 
40
- documents = load_txt_documents(data_path)
41
- docs = split_docs(documents, 450, 20)
42
 
 
 
 
 
 
 
 
 
 
43
 
44
 
45
- retriever = retriever_from_chroma(docs, hf, "mmr", 6)
46
 
 
 
47
 
48
- callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
49
 
50
- llm = llamacpp.LlamaCpp(
51
- model_path="/kaggle/working/phi-2-layla-v1-chatml-Q8_0.gguf",
52
- n_gpu_layers=1,
53
- temperature=0.1,
54
- top_p = 0.9,
55
- n_ctx=22000,
56
- max_tokens=200,
57
- repeat_penalty=1.7,
58
- callback_manager = callback_manager,
59
- verbose=False,
60
  )
61
 
62
- contextualize_q_system_prompt = """Given a context, chat history and the latest user question
63
- which maybe reference context in the chat history, formulate a standalone question
64
- which can be understood without the chat history. Do NOT answer the question,
65
- just reformulate it if needed and otherwise return it as is."""
66
 
67
- ha_retriever = history_aware_retriever(llm, retriever, contextualize_q_system_prompt)
68
 
69
- qa_system_prompt = """You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Be as informative as possible, be polite and formal.\n{context}"""
70
 
71
- qa_prompt = ChatPromptTemplate.from_messages(
72
- [
73
- ("system", qa_system_prompt),
74
- MessagesPlaceholder("chat_history"),
75
- ("human", "{input}"),
76
- ]
77
- )
78
-
79
- question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
80
 
 
81
 
82
- rag_chain = create_retrieval_chain(ha_retriever, question_answer_chain)
83
- msgs = StreamlitChatMessageHistory(key="special_app_key")
84
 
85
- @st.cache_resource
86
- def create_conversational_rag_chain():
87
- return RunnableWithMessageHistory(
88
- rag_chain,
89
- lambda session_id: msgs,
90
- input_messages_key="input",
91
- history_messages_key="chat_history",
92
- output_messages_key="answer",
93
- )
94
 
 
95
  conversational_rag_chain = create_conversational_rag_chain()
96
 
97
  def display_chat_history(chat_history):
@@ -102,6 +131,7 @@ def display_chat_history(chat_history):
102
 
103
 
104
  def main_page(conversational_rag_chain):
 
105
  """Main page for the Streamlit app."""
106
  msgs = st.session_state.get("chat_history", StreamlitChatMessageHistory(key="special_app_key"))
107
  chain_with_history = conversational_rag_chain
 
1
  import os
2
  import streamlit as st
3
+ from dotenv import load_dotenv
4
  from transformers import pipeline
5
  from langchain_community.embeddings import HuggingFaceEmbeddings
6
  from langchain_community.llms import llamacpp
 
15
  from langchain.chains import create_history_aware_retriever, create_retrieval_chain
16
  from langchain.vectorstores import Chroma
17
  from utills import load_txt_documents , split_docs, load_uploaded_documents,retriever_from_chroma
18
+ from langchain.text_splitter import TokenTextSplitter,RecursiveCharacterTextSplitter
19
 
20
 
21
  script_dir = os.path.dirname(os.path.abspath(__file__))
 
34
  model_kwargs=model_kwargs,
35
  encode_kwargs=encode_kwargs
36
  )
37
+ def get_vectorstore(text_chunks):
38
+ model_name = "sentence-transformers/all-mpnet-base-v2"
39
+ model_kwargs = {'device': 'cpu'}
40
+ encode_kwargs = {'normalize_embeddings': True}
41
+ hf = HuggingFaceEmbeddings(
42
+ model_name=model_name,
43
+ model_kwargs=model_kwargs,
44
+ encode_kwargs=encode_kwargs
45
+ )
46
+
47
+ vectorstore = Chroma.from_documents(texts=text_chunks, embedding=hf,persist_directory="docs/chroma/")
48
+ return vectorstore
49
 
50
 
51
 
52
 
53
+ def get_pdf_text(pdf_docs):
54
+ text = ""
55
+ for pdf in pdf_docs:
56
+ pdf_reader = PdfReader(pdf)
57
+ for page in pdf_reader.pages:
58
+ text += page.extract_text()
59
+ return text
60
 
 
 
61
 
62
+ def get_text_chunks(text):
63
+ text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
64
+ separator="\n",
65
+ chunk_size=1000,
66
+ chunk_overlap=200,
67
+ length_function=len
68
+ )
69
+ chunks = text_splitter.split_text(text)
70
+ return chunks
71
 
72
 
 
73
 
74
+ def create_conversational_rag_chain(vectorstore):
75
+ retriever = retriever_from_chroma(docs, hf, "mmr", 6)
76
 
77
+ callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])
78
 
79
+ llm = LlamaCpp(
80
+ model_path="/kaggle/working/phi-2-layla-v1-chatml-Q8_0.gguf",
81
+ n_gpu_layers=1,
82
+ temperature=0.1,
83
+ top_p=0.9,
84
+ n_ctx=22000,
85
+ max_tokens=200,
86
+ repeat_penalty=1.7,
87
+ callback_manager=callback_manager,
88
+ verbose=False,
89
  )
90
 
91
+ contextualize_q_system_prompt = """Given a context, chat history and the latest user question
92
+ which maybe reference context in the chat history, formulate a standalone question
93
+ which can be understood without the chat history. Do NOT answer the question,
94
+ just reformulate it if needed and otherwise return it as is."""
95
 
96
+ ha_retriever = history_aware_retriever(llm, retriever, contextualize_q_system_prompt)
97
 
98
+ qa_system_prompt = """You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Be as informative as possible, be polite and formal.\n{context}"""
99
 
100
+ qa_prompt = ChatPromptTemplate.from_messages(
101
+ [
102
+ ("system", qa_system_prompt),
103
+ MessagesPlaceholder("chat_history"),
104
+ ("human", "{input}"),
105
+ ]
106
+ )
 
 
107
 
108
+ question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
109
 
110
+ rag_chain = create_retrieval_chain(ha_retriever, question_answer_chain)
111
+ msgs = StreamlitChatMessageHistory(key="special_app_key")
112
 
113
+ @st.cache_resource
114
+ def create_rag_chain():
115
+ return RunnableWithMessageHistory(
116
+ rag_chain,
117
+ lambda session_id: msgs,
118
+ input_messages_key="input",
119
+ history_messages_key="chat_history",
120
+ output_messages_key="answer",
121
+ )
122
 
123
+ return create_rag_chain()
124
  conversational_rag_chain = create_conversational_rag_chain()
125
 
126
  def display_chat_history(chat_history):
 
131
 
132
 
133
  def main_page(conversational_rag_chain):
134
+ load_dotenv()
135
  """Main page for the Streamlit app."""
136
  msgs = st.session_state.get("chat_history", StreamlitChatMessageHistory(key="special_app_key"))
137
  chain_with_history = conversational_rag_chain