Create semapdf1.4.py
Browse files- version/semapdf1.4.py +169 -0
version/semapdf1.4.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
creator: Lewis Kamau Kimaru
|
3 |
+
Function: chat with pdf documents in different languages
|
4 |
+
best version yet
|
5 |
+
"""
|
6 |
+
from langchain.text_splitter import CharacterTextSplitter
|
7 |
+
from langchain.embeddings import HuggingFaceBgeEmbeddings
|
8 |
+
from langchain.vectorstores import FAISS
|
9 |
+
from langchain.chat_models import ChatOpenAI
|
10 |
+
from langchain.memory import ConversationBufferMemory
|
11 |
+
from langchain.chains import ConversationalRetrievalChain
|
12 |
+
from langchain.llms import HuggingFaceHub
|
13 |
+
|
14 |
+
from typing import Union
|
15 |
+
|
16 |
+
from dotenv import load_dotenv
|
17 |
+
from PyPDF2 import PdfReader
|
18 |
+
import streamlit as st
|
19 |
+
import requests
|
20 |
+
import json
|
21 |
+
import os
|
22 |
+
|
23 |
+
# set this key as an environment variable
|
24 |
+
os.environ["HUGGINGFACEHUB_API_TOKEN"] = st.secrets['huggingface_token']
|
25 |
+
|
26 |
+
# Page configuration
|
27 |
+
st.set_page_config(page_title="SemaNaPDF", page_icon="📚",)
|
28 |
+
|
29 |
+
# Sema Translator
|
30 |
+
Public_Url = 'https://lewiskimaru-helloworld.hf.space' #endpoint
|
31 |
+
|
32 |
+
def translate(userinput, target_lang, source_lang=None):
|
33 |
+
if source_lang:
|
34 |
+
url = f"{Public_Url}/translate_enter/"
|
35 |
+
data = {
|
36 |
+
"userinput": userinput,
|
37 |
+
"source_lang": source_lang,
|
38 |
+
"target_lang": target_lang,
|
39 |
+
}
|
40 |
+
response = requests.post(url, json=data)
|
41 |
+
result = response.json()
|
42 |
+
print(type(result))
|
43 |
+
source_lange = source_lang
|
44 |
+
translation = result['translated_text']
|
45 |
+
|
46 |
+
else:
|
47 |
+
url = f"{Public_Url}/translate_detect/"
|
48 |
+
data = {
|
49 |
+
"userinput": userinput,
|
50 |
+
"target_lang": target_lang,
|
51 |
+
}
|
52 |
+
|
53 |
+
response = requests.post(url, json=data)
|
54 |
+
result = response.json()
|
55 |
+
source_lange = result['source_language']
|
56 |
+
translation = result['translated_text']
|
57 |
+
return source_lange, translation
|
58 |
+
|
59 |
+
def get_pdf_text(pdf : Union[str, bytes, bytearray]) -> str:
|
60 |
+
reader = PdfReader(pdf)
|
61 |
+
pdf_text = ''
|
62 |
+
for page in (reader.pages):
|
63 |
+
text = page.extract_text()
|
64 |
+
if text:
|
65 |
+
pdf_text += text
|
66 |
+
return text
|
67 |
+
|
68 |
+
|
69 |
+
def get_text_chunks(text:str) ->list:
|
70 |
+
text_splitter = CharacterTextSplitter(
|
71 |
+
separator="\n", chunk_size=1500, chunk_overlap=300, length_function=len
|
72 |
+
)
|
73 |
+
chunks = text_splitter.split_text(text)
|
74 |
+
return chunks
|
75 |
+
|
76 |
+
|
77 |
+
def get_vectorstore(text_chunks : list) -> FAISS:
|
78 |
+
model = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
|
79 |
+
encode_kwargs = {
|
80 |
+
"normalize_embeddings": True
|
81 |
+
} # set True to compute cosine similarity
|
82 |
+
embeddings = HuggingFaceBgeEmbeddings(
|
83 |
+
model_name=model, encode_kwargs=encode_kwargs, model_kwargs={"device": "cpu"}
|
84 |
+
)
|
85 |
+
vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
|
86 |
+
return vectorstore
|
87 |
+
|
88 |
+
|
89 |
+
def get_conversation_chain(vectorstore:FAISS) -> ConversationalRetrievalChain:
|
90 |
+
llm = HuggingFaceHub(
|
91 |
+
repo_id="mistralai/Mixtral-8x7B-Instruct-v0.1",
|
92 |
+
#repo_id="TheBloke/Mixtral-8x7B-Instruct-v0.1-GGUF"
|
93 |
+
model_kwargs={"temperature": 0.5, "max_length": 1048},
|
94 |
+
)
|
95 |
+
|
96 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
97 |
+
conversation_chain = ConversationalRetrievalChain.from_llm(
|
98 |
+
llm=llm, retriever=vectorstore.as_retriever(), memory=memory
|
99 |
+
)
|
100 |
+
return conversation_chain
|
101 |
+
|
102 |
+
|
103 |
+
st.markdown ("""
|
104 |
+
<style> div.stSpinner > div {
|
105 |
+
text-align:center;
|
106 |
+
text-align:center;
|
107 |
+
align-items: center;
|
108 |
+
justify-content: center;
|
109 |
+
}
|
110 |
+
</style>""", unsafe_allow_html=True)
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
def main():
|
115 |
+
st.title("SemaNaPDF📚")
|
116 |
+
# upload file
|
117 |
+
pdf = st.file_uploader("Upload a PDF Document", type="pdf")
|
118 |
+
if pdf is not None:
|
119 |
+
with st.spinner(""):
|
120 |
+
# get pdf text
|
121 |
+
raw_text = get_pdf_text(pdf)
|
122 |
+
|
123 |
+
# get the text chunks
|
124 |
+
text_chunks = get_text_chunks(raw_text)
|
125 |
+
|
126 |
+
# create vector store
|
127 |
+
vectorstore = get_vectorstore(text_chunks)
|
128 |
+
|
129 |
+
# create conversation chain
|
130 |
+
st.session_state.conversation = get_conversation_chain(vectorstore)
|
131 |
+
st.info("done")
|
132 |
+
|
133 |
+
#user_question = st.text_input("chat with your pdf ...")
|
134 |
+
# show user input
|
135 |
+
if "messages" not in st.session_state:
|
136 |
+
st.session_state.messages = []
|
137 |
+
|
138 |
+
for message in st.session_state.messages:
|
139 |
+
with st.chat_message(message["role"]):
|
140 |
+
st.markdown(message["content"])
|
141 |
+
|
142 |
+
if user_question := st.chat_input("Ask your document anything ......?"):
|
143 |
+
with st.chat_message("user"):
|
144 |
+
st.markdown(user_question)
|
145 |
+
|
146 |
+
user_langd, Queryd = translate(user_question, 'eng_Latn')
|
147 |
+
st.session_state.messages.append({"role": "user", "content": user_question})
|
148 |
+
response = st.session_state.conversation({"question": Queryd}) #Queryd
|
149 |
+
st.session_state.chat_history = response["chat_history"]
|
150 |
+
|
151 |
+
output = translate(response['answer'], user_langd, 'eng_Latn')[1] # translated response
|
152 |
+
with st.chat_message("assistant"):
|
153 |
+
#st.markdown(response['answer'])
|
154 |
+
st.markdown(output)
|
155 |
+
st.session_state.messages.append({"role": "assistant", "content": response['answer']})
|
156 |
+
|
157 |
+
# Signature
|
158 |
+
st.markdown(
|
159 |
+
"""
|
160 |
+
<div style="position: fixed; bottom: 0; right: 0; padding: 10px;">
|
161 |
+
<a href="https://kamaukimaru.vercel.app" target="_blank" style="font-size: 12px; color: #269129; text-decoration: none;">©2023 Lewis Kimaru. All rights reserved.</a>
|
162 |
+
</div>
|
163 |
+
""",
|
164 |
+
unsafe_allow_html=True
|
165 |
+
)
|
166 |
+
|
167 |
+
|
168 |
+
if __name__ == '__main__':
|
169 |
+
main()
|