Spaces:
Sleeping
Sleeping
Upload 6 files
Browse filesFiles changed (6)
- __init__.cpython-312.pycAdded
- __init__.pyAdded+1
- app.pyAdded+95
- qabot.cpython-312.pycAdded
- qabot.pyAdded+244
- requirements.txtAdded+12
1# QueryVault source package1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""QueryVault - Gradio Web InterfaceRun this file to launch the QA bot in your browser.
Usage: python app.py"""
import gradio as grfrom dotenv import load_dotenvfrom src.qabot import process_pdf_and_query
# Load environment variables from .env fileload_dotenv()
# ---------------------------------------------------------------------------# Gradio Interface# ---------------------------------------------------------------------------
def answer_question(pdf_file, question: str) -> str: """ Wrapper called by Gradio on each user interaction.
Args: pdf_file: Gradio file object (has a .name attribute with the temp path). question: User's question string.
Returns: Answer string to display in the output box. """ if pdf_file is None: return "β οΈ Please upload a PDF document before asking a question."
file_path = pdf_file.name # Gradio stores uploaded files at a temp path return process_pdf_and_query(file_path, question)
# ---------------------------------------------------------------------------# UI Layout# ---------------------------------------------------------------------------
with gr.Blocks( title="QueryVault β PDF QA Bot") as demo:
gr.Markdown( """ # π QueryVault β PDF Question Answering Bot Upload a PDF document, ask any question about its content, and get an intelligent answer powered by **IBM Watsonx (Mixtral 8x7B)** and **LangChain RAG**. """ )
with gr.Row(): with gr.Column(scale=1): pdf_input = gr.File( label="π Upload PDF", file_types=[".pdf"], type="filepath", ) question_input = gr.Textbox( label="β Your Question", placeholder="e.g. What are the main findings of this document?", lines=3, ) submit_btn = gr.Button("π Get Answer", variant="primary")
with gr.Column(scale=1): answer_output = gr.Textbox( label="π‘ Answer", lines=12, interactive=False, )
submit_btn.click( fn=answer_question, inputs=[pdf_input, question_input], outputs=answer_output, )
gr.Markdown( """ --- **How it works:** 1. Your PDF is parsed and split into chunks. 2. Each chunk is converted to a semantic embedding via Watsonx. 3. The most relevant chunks are retrieved using ChromaDB. 4. Mixtral 8x7B reads the context and generates a precise answer. """ )
if __name__ == "__main__": demo.launch(share=True, theme=gr.themes.Soft())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""QueryVault - PDF Question Answering BotCore backend logic: document loading, embedding, retrieval, and LLM response generation."""
import osimport uuidfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import Chromafrom langchain_core.prompts import PromptTemplatefrom langchain_core.runnables import RunnablePassthroughfrom langchain_core.output_parsers import StrOutputParserfrom langchain_ibm import ChatWatsonx, WatsonxEmbeddingsfrom ibm_watsonx_ai.foundation_models.utils.enums import ModelTypes, EmbeddingTypesfrom ibm_watsonx_ai.metanames import GenTextParamsMetaNames as GenParamsfrom ibm_watsonx_ai.foundation_models.utils.enums import DecodingMethods
# ---------------------------------------------------------------------------# 1. LLM Initialization# ---------------------------------------------------------------------------
def init_llm() -> ChatWatsonx: """ Initialize the IBM Watsonx LLM (Mixtral 8x7B Instruct).
Reads credentials from environment variables: WATSONX_API_KEY β your IBM Cloud API key WATSONX_PROJECT_ID β your Watsonx project ID WATSONX_URL β IBM Cloud endpoint (default provided)
Returns: ChatWatsonx instance ready for inference. """ parameters = { "max_new_tokens": 500, "min_new_tokens": 1, }
llm = ChatWatsonx( model_id="meta-llama/llama-3-3-70b-instruct", url=os.getenv("WATSONX_URL", "https://us-south.ml.cloud.ibm.com"), project_id=os.getenv("WATSONX_PROJECT_ID"), apikey=os.getenv("WATSONX_API_KEY"), params=parameters, ) return llm
# ---------------------------------------------------------------------------# 2. Embedding Model# ---------------------------------------------------------------------------
def watsonx_embedding() -> WatsonxEmbeddings: """ Initialize IBM Watsonx Embeddings (Slate 125M English).
Returns: WatsonxEmbeddings instance. """ embeddings = WatsonxEmbeddings( model_id="ibm/slate-30m-english-rtrvr-v2", url=os.getenv("WATSONX_URL", "https://us-south.ml.cloud.ibm.com"), project_id=os.getenv("WATSONX_PROJECT_ID"), apikey=os.getenv("WATSONX_API_KEY"), ) return embeddings
# ---------------------------------------------------------------------------# 3. Document Loader# ---------------------------------------------------------------------------
def load_pdf(file_path: str) -> list: """ Load and parse a PDF file using PyPDFLoader.
Args: file_path: Absolute or relative path to the PDF file.
Returns: List of LangChain Document objects (one per page). """ loader = PyPDFLoader(file_path) documents = loader.load() return documents
# ---------------------------------------------------------------------------# 4. Text Splitter# ---------------------------------------------------------------------------
def split_documents(documents: list) -> list: """ Split loaded documents into smaller chunks for embedding.
Uses RecursiveCharacterTextSplitter with: chunk_size = 1000 characters chunk_overlap = 100 characters (preserves boundary context)
Args: documents: List of LangChain Document objects.
Returns: List of smaller Document chunks. """ splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50, ) chunks = splitter.split_documents(documents) return chunks
# ---------------------------------------------------------------------------# 5. Vector Store# ---------------------------------------------------------------------------
def create_vector_store(chunks: list) -> Chroma: """ Convert document chunks into embeddings and store in ChromaDB.
Args: chunks: List of Document chunks from the text splitter.
Returns: Chroma vector store instance. """ embedding_model = watsonx_embedding() vector_store = Chroma.from_documents( documents=chunks, embedding=embedding_model, collection_name=f"pdf_{uuid.uuid4().hex}" ) return vector_store
# ---------------------------------------------------------------------------# 6. Retriever# ---------------------------------------------------------------------------
def get_retriever(vector_store: Chroma): """ Create a retriever from the vector store using similarity search.
Args: vector_store: Chroma vector store instance.
Returns: LangChain BaseRetriever configured for top-3 similarity search. """ retriever = vector_store.as_retriever( search_type="similarity", search_kwargs={"k": 10}, ) return retriever
# ---------------------------------------------------------------------------# 7. QA Chain# ---------------------------------------------------------------------------
def build_qa_chain(retriever, llm: ChatWatsonx): """ Build a QA chain combining the retriever and LLM using LCEL.
Args: retriever: LangChain retriever from vector store. llm: Initialized ChatWatsonx instance.
Returns: Runnable chain ready to answer questions. """ template = """You are a helpful AI assistant answering questions based on a provided document.Use the following pieces of context from the document to answer the question. If the question is general (like "what is this document about"), summarize the provided context. If the context does not contain the answer, say "I don't have enough information from the document to answer that."
Context:{context}
Question: {question}
Helpful Answer:""" prompt = PromptTemplate.from_template(template)
def format_docs(docs): return "\\n\\n".join(doc.page_content for doc in docs)
qa_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | prompt | llm | StrOutputParser() ) return qa_chain
# ---------------------------------------------------------------------------# 8. Full Pipeline: process PDF and answer a question# ---------------------------------------------------------------------------
def process_pdf_and_query(file_path: str, question: str) -> str: """ End-to-end pipeline: load PDF β split β embed β retrieve β answer.
Args: file_path: Path to the uploaded PDF file. question: User's natural language question.
Returns: String answer generated by the LLM. """ if not file_path: return "Please upload a PDF file first." if not question.strip(): return "Please enter a question."
try: # Step 1 β Load documents = load_pdf(file_path)
# Step 2 β Split chunks = split_documents(documents)
# Step 3 & 4 β Embed + Store vector_store = create_vector_store(chunks)
# Step 5 β Retrieve retriever = get_retriever(vector_store)
# Step 6 β LLM llm = init_llm()
# Step 7 β QA Chain qa_chain = build_qa_chain(retriever, llm)
# Step 8 β Run answer = qa_chain.invoke(question) if not answer: answer = "No answer could be generated." return answer
except Exception as e: return f"Error processing your request: {str(e)}"123456789101112# QueryVault β Python dependencies# Install with: pip install -r requirements.txt
gradio>=4.0.0langchain>=0.2.0langchain-community>=0.2.0langchain-ibm>=0.1.0ibm-watsonx-ai>=0.2.6chromadb>=0.5.0pypdf>=4.0.0pydantic>=2.0.0python-dotenv>=1.0.0__init__.cpython-312.pycAdded
__init__.pyAdded+1
app.pyAdded+95
qabot.cpython-312.pycAdded
qabot.pyAdded+244
requirements.txtAdded+12