Spaces:
Sleeping
Sleeping
from dotenv import load_dotenv | |
import streamlit as st | |
from PyPDF2 import PdfReader | |
from langchain.text_splitter import CharacterTextSplitter | |
from langchain.embeddings.huggingface import HuggingFaceEmbeddings | |
from langchain.vectorstores import FAISS | |
from langchain.chains.question_answering import load_qa_chain | |
import os | |
from streamlit_chat import message | |
from langchain import HuggingFaceHub | |
def LLM_pdf(model_name = 'google/flan-t5-large'): | |
# st.header("Ask your PDF 💬") | |
# upload file | |
pdf = st.file_uploader("Upload your PDF", type="pdf") | |
# extract the text | |
if pdf is not None: | |
pdf_reader = PdfReader(pdf) | |
text = "" | |
for page in pdf_reader.pages: | |
text += page.extract_text() | |
# split into chunks | |
text_splitter = CharacterTextSplitter( | |
separator="\n", | |
chunk_size=1000, | |
chunk_overlap=200, | |
length_function=len | |
) | |
print(text_splitter) | |
chunks = text_splitter.split_text(text) | |
# create embeddings | |
embeddings = HuggingFaceEmbeddings() | |
knowledge_base = FAISS.from_texts(chunks, embeddings) | |
if 'generated' not in st.session_state: | |
st.session_state['generated'] = [] | |
if 'past' not in st.session_state: | |
st.session_state['past'] = [] | |
# print(st.session_state['generated'],st.session_state['past']) | |
chat_placeholder = st.empty() | |
# show user input | |
with st.container(): | |
input_placeholder = st.empty() | |
user_question = input_placeholder.text_input("Ask a question about your PDF:") | |
if user_question: | |
docs = knowledge_base.similarity_search(user_question) | |
llm = HuggingFaceHub(repo_id=model_name, model_kwargs={"temperature":5, | |
"max_length":64}) | |
chain = load_qa_chain(llm, chain_type="stuff") | |
response = chain.run(input_documents=docs,question=user_question) | |
#st.write(response) | |
# append user_input and output to state | |
st.session_state.past.append(user_question) | |
st.session_state.generated.append(response) | |
with chat_placeholder.container(): | |
# If responses have been generated by the model | |
if st.session_state['generated']: | |
# Reverse iteration through the list | |
for i in range(len(st.session_state['generated'])-1, -1, -1): | |
# message from streamlit_chat | |
message(st.session_state['past'][::-1][i], is_user=True, key=str(i) + '_user') | |
message(st.session_state['generated'][::-1][i], key=str(i)) | |