Spaces:
Runtime error
Runtime error
Download app.py from Pezh/Pdf: direct link, hf CLI and curl.
- Browser
- Download file 2.71 kB
-
https://huggingface.co/spaces/Pezh/Pdf/resolve/main/app.py
- Command line
-
hf download hf://spaces/Pezh/Pdf/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Pezh/Pdf/resolve/main/app.py
2.71 kB
| import streamlit as st | |
| from PyPDF2 import PdfReader | |
| from langchain.embeddings.openai import OpenAIEmbeddings | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| import pickle | |
| from langchain.chains import ConversationalRetrievalChain | |
| from langchain.chat_models import ChatOpenAI | |
| from langchain.vectorstores import FAISS | |
| # Function to read PDF content | |
| def read_pdf(): | |
| pdf_reader = PdfReader('hey.pdf') | |
| text = "" | |
| for page in pdf_reader.pages: | |
| text += page.extract_text() | |
| return text | |
| # Main Streamlit app | |
| def main(): | |
| st.title("Query your PDF") | |
| with st.sidebar: | |
| st.title('🤗💬 PDF Chat App') | |
| st.markdown(''' | |
| ## About | |
| Choose the desired PDF, then perform a query. | |
| ''') | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=1000, | |
| chunk_overlap=150, | |
| length_function=len | |
| ) | |
| # Process the PDF text and create the documents list | |
| documents = text_splitter.split_text(text=read_pdf()) | |
| # Vectorize the documents and create vectorstore | |
| embeddings = OpenAIEmbeddings(openai_api_key='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') | |
| vectorstore = FAISS.from_texts(documents, embedding=embeddings) | |
| st.session_state.processed_data = { | |
| "document_chunks": documents, | |
| "vectorstore": vectorstore, | |
| } | |
| # Load the Langchain chatbot | |
| llm = ChatOpenAI(temperature=0, max_tokens=1000, model_name="gpt-3.5-turbo") | |
| qa = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever()) | |
| # Initialize Streamlit chat UI | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| if prompt := st.chat_input("Ask your questions from PDF ?"): | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| result = qa({"question": prompt, "chat_history": [(message["role"], message["content"]) for message in st.session_state.messages]}) | |
| print(prompt) | |
| with st.chat_message("assistant"): | |
| message_placeholder = st.empty() | |
| full_response = result["answer"] | |
| message_placeholder.markdown(full_response + "|") | |
| message_placeholder.markdown(full_response) | |
| print(full_response) | |
| st.session_state.messages.append({"role": "assistant", "content": full_response}) | |
| main() |