Create semapdf1.1.py
Browse files- version/semapdf1.1.py +156 -0
version/semapdf1.1.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.text_splitter import CharacterTextSplitter
|
2 |
+
from langchain.embeddings import HuggingFaceBgeEmbeddings
|
3 |
+
from langchain.vectorstores import FAISS
|
4 |
+
from langchain.chat_models import ChatOpenAI
|
5 |
+
from langchain.memory import ConversationBufferMemory
|
6 |
+
from langchain.chains import ConversationalRetrievalChain
|
7 |
+
from langchain.llms import HuggingFaceHub
|
8 |
+
|
9 |
+
from htmlTemplates import css, bot_template, user_template
|
10 |
+
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
from PyPDF2 import PdfReader
|
13 |
+
import streamlit as st
|
14 |
+
import requests
|
15 |
+
import json
|
16 |
+
import os
|
17 |
+
|
18 |
+
# set this key as an environment variable
|
19 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets['huggingface_token']
|
20 |
+
|
21 |
+
# setup Mistral-7B for this question answering
|
22 |
+
#hf_token = os.environ['read'] # huggingface verification
|
23 |
+
|
24 |
+
# Sema Translator
|
25 |
+
#Public_Url = os.environ["sema_url"] #endpoint
|
26 |
+
|
27 |
+
def translate(userinput, target_lang, source_lang=None):
|
28 |
+
if source_lang:
|
29 |
+
url = "Public_Url/translate_enter/"
|
30 |
+
data = {
|
31 |
+
"userinput": userinput,
|
32 |
+
"source_lang": source_lang,
|
33 |
+
"target_lang": target_lang,
|
34 |
+
}
|
35 |
+
response = requests.post(url, json=data)
|
36 |
+
result = response.json()
|
37 |
+
print(type(result))
|
38 |
+
source_lange = source_lang
|
39 |
+
translation = result['translated_text']
|
40 |
+
return source_lange, translation
|
41 |
+
else:
|
42 |
+
url = "Public_Url/translate_detect/"
|
43 |
+
data = {
|
44 |
+
"userinput": userinput,
|
45 |
+
"target_lang": target_lang,
|
46 |
+
}
|
47 |
+
|
48 |
+
response = requests.post(url, json=data)
|
49 |
+
result = response.json()
|
50 |
+
source_lange = result['source_language']
|
51 |
+
translation = result['translated_text']
|
52 |
+
return source_lange, translation
|
53 |
+
|
54 |
+
|
55 |
+
def get_pdf_text(pdf_docs : list) -> str:
|
56 |
+
text = ""
|
57 |
+
for pdf in pdf_docs:
|
58 |
+
pdf_reader = PdfReader(pdf)
|
59 |
+
for page in pdf_reader.pages:
|
60 |
+
text += page.extract_text()
|
61 |
+
return text
|
62 |
+
|
63 |
+
|
64 |
+
def get_text_chunks(text:str) ->list:
|
65 |
+
text_splitter = CharacterTextSplitter(
|
66 |
+
separator="\n", chunk_size=1500, chunk_overlap=300, length_function=len
|
67 |
+
)
|
68 |
+
chunks = text_splitter.split_text(text)
|
69 |
+
return chunks
|
70 |
+
|
71 |
+
|
72 |
+
def get_vectorstore(text_chunks : list) -> FAISS:
|
73 |
+
model = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
74 |
+
encode_kwargs = {
|
75 |
+
"normalize_embeddings": True
|
76 |
+
} # set True to compute cosine similarity
|
77 |
+
embeddings = HuggingFaceBgeEmbeddings(
|
78 |
+
model_name=model, encode_kwargs=encode_kwargs, model_kwargs={"device": "cpu"}
|
79 |
+
)
|
80 |
+
vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
|
81 |
+
return vectorstore
|
82 |
+
|
83 |
+
|
84 |
+
def get_conversation_chain(vectorstore:FAISS) -> ConversationalRetrievalChain:
|
85 |
+
llm = HuggingFaceHub(
|
86 |
+
repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
|
87 |
+
#repo_id="TheBloke/Mixtral-8x7B-Instruct-v0.1-GGUF"
|
88 |
+
model_kwargs={"temperature": 0.5, "max_length": 1048},
|
89 |
+
)
|
90 |
+
|
91 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
92 |
+
conversation_chain = ConversationalRetrievalChain.from_llm(
|
93 |
+
llm=llm, retriever=vectorstore.as_retriever(), memory=memory
|
94 |
+
)
|
95 |
+
return conversation_chain
|
96 |
+
|
97 |
+
|
98 |
+
def handle_userinput(user_question:str):
|
99 |
+
response = st.session_state.conversation({"question": user_question})
|
100 |
+
st.session_state.chat_history = response["chat_history"]
|
101 |
+
|
102 |
+
for i, message in enumerate(st.session_state.chat_history):
|
103 |
+
if i % 2 == 0:
|
104 |
+
st.write("😎Usuer: " + message.content)
|
105 |
+
else:
|
106 |
+
st.write("🤖 ChatBot: " + message.content)
|
107 |
+
|
108 |
+
|
109 |
+
def main():
|
110 |
+
st.set_page_config(
|
111 |
+
page_title="Chat with a Bot that tries to answer questions about multiple PDFs",
|
112 |
+
page_icon=":books:",
|
113 |
+
)
|
114 |
+
|
115 |
+
st.markdown("# Chat with a Bot")
|
116 |
+
st.markdown("This bot tries to answer questions about multiple PDFs. Let the processing of the PDF finish before adding your question. 🙏🏾")
|
117 |
+
|
118 |
+
st.write(css, unsafe_allow_html=True)
|
119 |
+
|
120 |
+
|
121 |
+
if "conversation" not in st.session_state:
|
122 |
+
st.session_state.conversation = None
|
123 |
+
if "chat_history" not in st.session_state:
|
124 |
+
st.session_state.chat_history = None
|
125 |
+
|
126 |
+
|
127 |
+
st.header("Chat with a Bot 🤖🦾 that tries to answer questions about multiple PDFs :books:")
|
128 |
+
user_question = st.text_input("Ask a question about your documents:")
|
129 |
+
if user_question:
|
130 |
+
handle_userinput(user_question)
|
131 |
+
|
132 |
+
|
133 |
+
with st.sidebar:
|
134 |
+
st.subheader("Your documents")
|
135 |
+
pdf_docs = st.file_uploader(
|
136 |
+
"Upload your PDFs here and click on 'Process'", accept_multiple_files=True
|
137 |
+
)
|
138 |
+
if st.button("Process"):
|
139 |
+
with st.spinner("Processing"):
|
140 |
+
# get pdf text
|
141 |
+
raw_text = get_pdf_text(pdf_docs)
|
142 |
+
|
143 |
+
# get the text chunks
|
144 |
+
text_chunks = get_text_chunks(raw_text)
|
145 |
+
|
146 |
+
# create vector store
|
147 |
+
vectorstore = get_vectorstore(text_chunks)
|
148 |
+
|
149 |
+
# create conversation chain
|
150 |
+
st.session_state.conversation = get_conversation_chain(vectorstore)
|
151 |
+
|
152 |
+
st.info("DONE")
|
153 |
+
|
154 |
+
|
155 |
+
if __name__ == "__main__":
|
156 |
+
main()
|