import fitz
from transformers import pipeline
from langchain_core.documents import Document
from langchain_community.vectorstores import FAISS
from langchain_huggingface import (
HuggingFaceEmbeddings,
HuggingFacePipeline
)
from langchain_text_splitters import (
RecursiveCharacterTextSplitter
)
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 1. Define the PDF path
PDF_PATH = "document.pdf"
# 2. Extract text from the PDF
def extract_text_from_pdf(pdf_path):
pdf = fitz.open(pdf_path)
text = ""
for page in pdf:
text += page.get_text()
pdf.close()
return text
pdf_text = extract_text_from_pdf(
PDF_PATH
)
print("Total characters:", len(pdf_text))
# 3. Convert PDF text into a document
documents = [
Document(
page_content=pdf_text
)
]
# 4. Create a text splitter
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=100
)
# 5. Split the document into chunks
chunks = text_splitter.split_documents(
documents
)
print("Number of chunks:", len(chunks))
# 6. Load the embedding model
embeddings = HuggingFaceEmbeddings(
model_name="all-MiniLM-L6-v2"
)
# 7. Create the FAISS vector store
vector_store = FAISS.from_documents(
chunks,
embeddings
)
# 8. Create the retriever
retriever = vector_store.as_retriever(
search_kwargs={"k": 3}
)
# 9. Load the fine-tuned GPT-2 model
hf_pipeline = pipeline(
task="text-generation",
model="./finetuned_gpt2",
tokenizer="./finetuned_gpt2",
max_new_tokens=150,
do_sample=False
)
# 10. Convert the pipeline into a LangChain LLM
llm = HuggingFacePipeline(
pipeline=hf_pipeline
)
# 11. Create the prompt
prompt = PromptTemplate.from_template("""
Answer the question using only the provided context.
If the answer cannot be found in the context, say:
I could not find the answer in the knowledge base.
Context:
{context}
Question:
{question}
Answer:
""")
# 12. Create the output parser
output_parser = StrOutputParser()
# 13. Build the chain
chain = prompt | llm | output_parser
# 14. Ask a question
question = input(
"\nAsk a question about the PDF: "
)
# 15. Retrieve relevant chunks
retrieved_documents = retriever.invoke(
question
)
# 16. Display retrieved documents
print("\nRetrieved Documents:")
for rank, document in enumerate(
retrieved_documents,
start=1
):
print(f"\nRank {rank}")
print(document.page_content)
# 17. Combine chunks into context
context = "\n\n".join(
document.page_content
for document in retrieved_documents
)
# 18. Generate the answer
response = chain.invoke(
{
"context": context,
"question": question
}
)
# 19. Print the final answer
print("\nFinal Answer:")
print(response)