|
import gradio as gr |
|
import PyPDF2 |
|
from langchain.embeddings.openai import OpenAIEmbeddings |
|
from langchain.vectorstores.faiss import FAISS |
|
from langchain.text_splitter import RecursiveCharacterTextSplitter |
|
from langchain import OpenAI, VectorDBQA |
|
|
|
import os |
|
openai_api_key = os.environ["OPENAI_API_KEY"] |
|
|
|
|
|
def pdf_to_text(pdf_file, query): |
|
|
|
with open(pdf_file.name, 'rb') as pdf_file: |
|
|
|
pdf_reader = PyPDF2.PdfReader(pdf_file) |
|
|
|
|
|
text = "" |
|
|
|
|
|
for page_num in range(len(pdf_reader.pages)): |
|
|
|
page = pdf_reader.pages[page_num] |
|
|
|
text += page.extract_text() |
|
|
|
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0) |
|
texts = text_splitter.split_text(text) |
|
|
|
embeddings = OpenAIEmbeddings() |
|
|
|
vectorstore = FAISS.from_texts(texts, embeddings) |
|
|
|
|
|
qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type="stuff", vectorstore=vectorstore) |
|
return qa.run(query) |
|
|
|
|
|
|
|
|
|
|
|
|
|
pdf_input = gr.inputs.File(label="PDF File") |
|
query_input = gr.inputs.Textbox(label="Query") |
|
outputs = gr.outputs.Textbox(label="Chatbot Response") |
|
interface = gr.Interface(fn=pdf_to_text, inputs=[pdf_input, query_input], outputs=outputs) |
|
|
|
|
|
interface.launch(debug = True) |