File size: 2,066 Bytes
a0101e2
 
 
 
 
 
 
 
 
 
 
 
f1a6a61
a0101e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
591bd9e
a0101e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import streamlit as st
from PyPDF2 import PdfReader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain_groq import ChatGroq
from dotenv import load_dotenv

load_dotenv()

# Initialize the language model
llm = ChatGroq(model_name="llama-3.1-8b-instant", temperature=0.7)

# Function to read PDF
def read_pdf(pdf):
    raw_text = ""
    file = PdfReader(pdf)
    for page in file.pages:
        content = page.extract_text()
        if content:
            raw_text += content
    return raw_text

# Function to process text and create a FAISS index
def process_text(raw_text):
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=200,
        chunk_overlap=20,
        length_function=len,
        separators=["\n"]
    )
    texts = text_splitter.create_documents([raw_text])

    modelPath = "sentence-transformers/all-MiniLM-l6-v2"
    model_kwargs = {'device': 'cpu'}
    encode_kwargs = {'normalize_embeddings': False}

    embeddings = HuggingFaceEmbeddings(
        model_name=modelPath,
        model_kwargs=model_kwargs,
        encode_kwargs=encode_kwargs
    )

    db = FAISS.from_documents(texts, embeddings)
    return db

# Function to initialize the QA chain
def initialize_chain(db):
    chain = RetrievalQA.from_chain_type(
        llm=llm,
        chain_type="stuff",
        retriever=db.as_retriever()
    )
    return chain

# Main function to run the app
def main():
    st.title("PDF Question Answering")

    uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")

    if uploaded_file is not None:
        raw_text = read_pdf(uploaded_file)
        db = process_text(raw_text)
        chain = initialize_chain(db)
        
        question = st.text_input("Ask a question about the PDF")
        if question:
            answer = chain.invoke(question)
            st.write(f"Answer: {answer['result']}")

if __name__ == "__main__":
    main()