import pdfplumber from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.schema import Document from langchain.document_loaders import TextLoader from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM # Load the tokenizer and model tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-large") model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-large", device_map="auto", torch_dtype="auto") pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, device_map="auto", torch_dtype="auto") # Function to extract text from a PDF using LangChain def extracted_text(file): with pdfplumber.open(file) as pdf: text = "" for page in pdf.pages: # text +=page.extract_text() +"\n" text = "\n".join(page.extract_text() for page in pdf.pages if page.extract_text()) return text # Function to chunk the extracted text def chunks(text): # Prepare the document for chunking using LangChain's RecursiveCharacterTextSplitter docs = [Document(page_content=text)] text_splitter = RecursiveCharacterTextSplitter(chunk_size=512, chunk_overlap=50) chunked_docs = text_splitter.split_documents(docs) # Split the document into chunks return chunked_docs # Function to answer a question based on the chunked documents def answer_question_from_chunk(chunks, question): # Combine chunk texts into one context context = "\n".join([chunk.page_content for chunk in chunks]) # Create the prompt prompt = f"Context: {context}\n\nQuestion: {question}\n\nAnswer:" # Use the pipeline to generate an answer result = pipe(prompt, max_length=200, temperature=0.7) # Return the answer part of the generated result answer = result[0]["generated_text"].split("Answer:")[-1].strip() # if not answer or answer .lower() in ["i don't know","not found","no answer"]: # return "No answer found from the document." return answer