ChatBot / app.py
chatbytes's picture
Update app.py
3e36891 verified
raw
history blame
2.39 kB
import gradio as gr
from langchain_community.llms import GooglePalm
from langchain_community.embeddings import HuggingFaceInstructEmbeddings
from langchain_community.text_splitter import CharacterTextSplitter
from langchain_community.embeddings import GooglePalmEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.chains import RetrievalQA
from secret1 import GOOGLE_API as google_api
import PyPDF2
def chatbot_response(user_input, history):
# This is a placeholder function. Replace with your actual chatbot logic.
bot_response = "You said: " + user_input
history.append((user_input, bot_response))
return history, history
def text_splitter_function(text):
text_splitter = CharacterTextSplitter(
separator = '\n',
chunk_size = 1000,
chunk_overlap = 40,
length_function = len,
)
texts = text_splitter.split_text(text)
return texts;
def text_extract(file):
pdf_reader = PyPDF2.PdfReader(file.name)
# Get the number of pages
num_pages = len(pdf_reader.pages)
# Extract text from each page
text = ""
for page_num in range(num_pages):
page = pdf_reader.pages[page_num]
text += page.extract_text()
text_splitter=text_splitter_function(text);
db = FAISS.from_texts(text_splitter, embeddings);
retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 2})
llm=GooglePalm(google_api_key=google_api)
qa = RetrievalQA.from_chain_type(
llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True
)
print(db)
return text
with gr.Blocks() as demo:
gr.Markdown("# Chat with ChatGPT-like Interface")
chatbot = gr.Chatbot()
state = gr.State([])
with gr.Row():
with gr.Column():
user_input = gr.Textbox(show_label=False, placeholder="Type your message here...")
send_btn = gr.Button("Send")
with gr.Column():
input_file=gr.File(label="Upload PDF", file_count="single")
submit_btn=gr.Button("Submit")
submit_btn.click(text_extract, [input_file], [user_input])
send_btn.click(chatbot_response,[user_input,state],[chatbot, state])
if __name__ == "__main__":
embeddings=GooglePalmEmbeddings(google_api_key=google_api)
demo.launch()