Download app.py from datagpt/pdf2gpt: direct link, hf CLI and curl.
- Browser
- Download file 1.69 kB
-
https://huggingface.co/spaces/datagpt/pdf2gpt/resolve/main/app.py
- Command line
-
hf download hf://spaces/datagpt/pdf2gpt/app.py
-
curl -L -o app.py https://huggingface.co/spaces/datagpt/pdf2gpt/resolve/main/app.py
1.69 kB
| 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 | |
| def pdf_to_text(pdf_file, contraseña, query): | |
| os.environ["OPENAI_API_KEY"] = contraseña | |
| # Open the PDF file in binary mode | |
| with open(pdf_file.name, 'rb') as pdf_file: | |
| # Create a PDF reader object | |
| pdf_reader = PyPDF2.PdfReader(pdf_file) | |
| # Create an empty string to store the text | |
| text = "" | |
| # Loop through each page of the PDF | |
| for page_num in range(len(pdf_reader.pages)): | |
| # Get the page object | |
| page = pdf_reader.pages[page_num] | |
| # Extract the texst from the page and add it to the text variable | |
| text += page.extract_text() | |
| #embedding step | |
| text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0) | |
| texts = text_splitter.split_text(text) | |
| embeddings = OpenAIEmbeddings(openai_api_key=contraseña) | |
| #vector store | |
| vectorstore = FAISS.from_texts(texts, embeddings) | |
| #inference | |
| qa = VectorDBQA.from_chain_type(llm=OpenAI(), chain_type="stuff", vectorstore=vectorstore) | |
| return qa.run(query) | |
| # Define the Gradio interface | |
| 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, gr.Textbox(lines=1, placeholder="Enter your API-key here...", label="API-Key:", type="password"), query_input], outputs=outputs) | |
| # Run the interface | |
| interface.launch(debug = True) |