File size: 1,996 Bytes
8ad2a6b
77725db
 
 
 
 
 
 
 
 
 
 
 
 
8ad2a6b
 
 
 
 
77725db
 
8ad2a6b
77725db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74e97fc
77725db
59f82c8
 
74e97fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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