Download app.py from perfaction/pdf-question-answer: direct link, hf CLI and curl.
- Browser
- Download file 2.42 kB
-
https://huggingface.co/perfaction/pdf-question-answer/resolve/main/app.py
- Command line
-
hf download hf://perfaction/pdf-question-answer/app.py
-
curl -L -o app.py https://huggingface.co/perfaction/pdf-question-answer/resolve/main/app.py
2.42 kB
| import warnings | |
| from dotenv import load_dotenv | |
| import os | |
| load_dotenv() | |
| import streamlit as st | |
| from PyPDF2 import PdfReader | |
| import io | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| from langchain.vectorstores import Chroma | |
| from langchain.chains import RetrievalQA | |
| from langchain.prompts import PromptTemplate | |
| from langchain_openai import OpenAIEmbeddings | |
| from langchain_openai import ChatOpenAI | |
| # Suppress warnings | |
| warnings.filterwarnings("ignore") | |
| # Set up Streamlit interface | |
| st.title("PDF Question Answering App") | |
| # Initialize OpenAI model | |
| model = ChatOpenAI( | |
| model="gpt-3.5-turbo", | |
| openai_api_key=os.getenv("OPENAI_API_KEY"), | |
| temperature=0.2 | |
| ) | |
| # File uploader | |
| uploaded_file = st.file_uploader("Upload a PDF file", type="pdf") | |
| if uploaded_file is not None: | |
| # Read PDF content | |
| pdf_reader = PdfReader(io.BytesIO(uploaded_file.read())) | |
| context = "" | |
| for page_num in range(len(pdf_reader.pages)): | |
| context += pdf_reader.pages[page_num].extract_text() | |
| # Split text into chunks | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=10000, | |
| chunk_overlap=1000 | |
| ) | |
| texts = text_splitter.split_text(context) | |
| # Create embeddings using OpenAI | |
| embeddings = OpenAIEmbeddings( | |
| model="text-embedding-3-small", | |
| openai_api_key=os.getenv("OPENAI_API_KEY") | |
| ) | |
| # Create vector store and retriever | |
| vector_index = Chroma.from_texts( | |
| texts, | |
| embeddings | |
| ).as_retriever(search_kwargs={"k": 5}) | |
| # Define prompt template | |
| template = """Use the following pieces of context to answer the question at the end. | |
| If you don't know the answer, just say that you don't know, don't try to make up an answer. | |
| Keep the answer as concise as possible. | |
| Always say "thanks for asking!" at the end of the answer. | |
| {context} | |
| Question: {question} | |
| Helpful Answer:""" | |
| QA_CHAIN_PROMPT = PromptTemplate.from_template(template) | |
| # Create QA chain | |
| qa_chain = RetrievalQA.from_chain_type( | |
| model, | |
| retriever=vector_index, | |
| return_source_documents=True, | |
| chain_type_kwargs={"prompt": QA_CHAIN_PROMPT} | |
| ) | |
| # Question input | |
| question = st.text_input("Enter your question about the PDF:") | |
| if st.button("Get Answer"): | |
| result = qa_chain({"query": question}) | |
| st.write("AI Response:") | |
| st.write(result["result"]) |