Spaces:
Build error
Build error
Upload 6 files
Browse filesFiles changed (6)
- .gitignoreAdded+160
- .python-versionAdded+1
- app.pyAdded+108
- htmlTemplates.pyAdded+44
- readme.mdAdded+65
- requirements.txtAdded+14
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/#use-with-ide.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder..idea13.9123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import osimport streamlit as stfrom dotenv import load_dotenvfrom PyPDF2 import PdfReaderfrom langchain.text_splitter import CharacterTextSplitterfrom langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddingsfrom langchain.vectorstores import FAISSfrom langchain.chat_models import ChatOpenAIfrom langchain.memory import ConversationBufferMemoryfrom langchain.chains import ConversationalRetrievalChainfrom htmlTemplates import css, bot_template, user_templatefrom langchain.llms import HuggingFaceHub
def get_pdf_text(pdf_docs): text = "" for pdf in pdf_docs: pdf_reader = PdfReader(pdf) for page in pdf_reader.pages: text += page.extract_text() return text
def get_text_chunks(text): text_splitter = CharacterTextSplitter( separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len ) chunks = text_splitter.split_text(text) return chunks
def get_vectorstore(text_chunks): embeddings = OpenAIEmbeddings()
#embeddings = HuggingFaceInstructEmbeddings(model_name="hkunlp/instructor-xl") vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings) return vectorstore
def get_conversation_chain(vectorstore): llm = ChatOpenAI() #llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature":0.5, "max_length":512})
memory = ConversationBufferMemory( memory_key='chat_history', return_messages=True) conversation_chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=vectorstore.as_retriever(), memory=memory ) return conversation_chain
def handle_userinput(user_question): response = st.session_state.conversation({'question': user_question}) st.session_state.chat_history = response['chat_history']
for i, message in enumerate(st.session_state.chat_history): if i % 2 == 0: st.write(user_template.replace( "{{MSG}}", message.content), unsafe_allow_html=True) else: st.write(bot_template.replace( "{{MSG}}", message.content), unsafe_allow_html=True)
def main(): load_dotenv() print(os.environ.get("OPENAI_API_KEY")) st.set_page_config(page_title="Chat with multiple PDFs", page_icon=":books:") st.write(css, unsafe_allow_html=True)
if "conversation" not in st.session_state: st.session_state.conversation = None if "chat_history" not in st.session_state: st.session_state.chat_history = None
st.header("Chat with multiple PDFs :books:") user_question = st.text_input("Ask a question about your documents:") if user_question: handle_userinput(user_question)
with st.sidebar: st.subheader("Your documents") pdf_docs = st.file_uploader( "Upload your PDFs here and click on 'Process'", accept_multiple_files=True) if st.button("Process"): with st.spinner("Processing"): # get pdf text raw_text = get_pdf_text(pdf_docs)
# get the text chunks text_chunks = get_text_chunks(raw_text)
# create vector store vectorstore = get_vectorstore(text_chunks)
# create conversation chain st.session_state.conversation = get_conversation_chain( vectorstore)
if __name__ == '__main__': main()1234567891011121314151617181920212223242526272829303132333435363738394041424344css = '''<style>.chat-message { padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex}.chat-message.user { background-color: #2b313e}.chat-message.bot { background-color: #475063}.chat-message .avatar { width: 20%;}.chat-message .avatar img { max-width: 78px; max-height: 78px; border-radius: 50%; object-fit: cover;}.chat-message .message { width: 80%; padding: 0 1.5rem; color: #fff;}'''
bot_template = '''<div class="chat-message bot"> <div class="avatar"> <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;"> </div> <div class="message">{{MSG}}</div></div>'''
user_template = '''<div class="chat-message user"> <div class="avatar"> <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png"> </div> <div class="message">{{MSG}}</div></div>'''1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# MultiPDF Chat App
> You can find the tutorial for this project on [YouTube](https://youtu.be/dXxQ0LR-3Hg).
## Introduction------------The MultiPDF Chat App is a Python application that allows you to chat with multiple PDF documents. You can ask questions about the PDFs using natural language, and the application will provide relevant responses based on the content of the documents. This app utilizes a language model to generate accurate answers to your queries. Please note that the app will only respond to questions related to the loaded PDFs.
## How It Works------------

The application follows these steps to provide responses to your questions:
1. PDF Loading: The app reads multiple PDF documents and extracts their text content.
2. Text Chunking: The extracted text is divided into smaller chunks that can be processed effectively.
3. Language Model: The application utilizes a language model to generate vector representations (embeddings) of the text chunks.
4. Similarity Matching: When you ask a question, the app compares it with the text chunks and identifies the most semantically similar ones.
5. Response Generation: The selected chunks are passed to the language model, which generates a response based on the relevant content of the PDFs.
## Dependencies and Installation----------------------------To install the MultiPDF Chat App, please follow these steps:
1. Clone the repository to your local machine.
2. Install the required dependencies by running the following command: ``` pip install -r requirements.txt ```
3. Obtain an API key from OpenAI and add it to the `.env` file in the project directory.```commandlineOPENAI_API_KEY=your_secrit_api_key```
## Usage-----To use the MultiPDF Chat App, follow these steps:
1. Ensure that you have installed the required dependencies and added the OpenAI API key to the `.env` file.
2. Run the `main.py` file using the Streamlit CLI. Execute the following command: ``` streamlit run app.py ```
3. The application will launch in your default web browser, displaying the user interface.
4. Load multiple PDF documents into the app by following the provided instructions.
5. Ask questions in natural language about the loaded PDFs using the chat interface.
## Contributing------------This repository is intended for educational purposes and does not accept further contributions. It serves as supporting material for a YouTube tutorial that demonstrates how to build this project. Feel free to utilize and enhance the app based on your own requirements.
## License-------The MultiPDF Chat App is released under the [MIT License](https://opensource.org/licenses/MIT).1234567891011121314langchain==0.0.184PyPDF2==3.0.1python-dotenv==1.0.0streamlit==1.18.1openai==0.27.6faiss-cpu==1.7.4altair==4tiktoken==0.4.0# uncomment to use huggingface llms# huggingface-hub==0.14.1
# uncomment to use instructor embeddings# InstructorEmbedding==1.0.1# sentence-transformers==2.2.2.gitignoreAdded+160
.python-versionAdded+1
app.pyAdded+108
htmlTemplates.pyAdded+44
readme.mdAdded+65
requirements.txtAdded+14