Spaces:
Build error

File size: 3,113 Bytes
27805aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import streamlit as st
import faiss
import numpy as np
import pdfplumber
import tiktoken
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
from transformers import pipeline

# Load embedding model
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")

# Load text-generation model (Replace "gpt2" with "meta-llama/Llama-2-13b-chat-hf" for better results)
qa_model = pipeline("text-generation", model="gpt2")

# Tokenizer for chunking
tokenizer = tiktoken.get_encoding("cl100k_base")


# Function to extract text from PDF
def extract_text_from_pdf(pdf_file):
    text = ""
    with pdfplumber.open(pdf_file) as pdf:
        for page in pdf.pages:
            text += page.extract_text() + "\n"
    return text


# Function to chunk text
def chunk_text(text, chunk_size=1000, overlap=200):
    tokens = tokenizer.encode(text)
    chunks = []
    for i in range(0, len(tokens), chunk_size - overlap):
        chunks.append(tokenizer.decode(tokens[i:i+chunk_size]))
    return chunks


# Create FAISS Index
def create_faiss_index(chunks):
    embeddings = np.array([embedding_model.encode(chunk) for chunk in chunks], dtype="float32")
    index = faiss.IndexFlatL2(embeddings.shape[1])
    index.add(embeddings)
    return index


# FAISS Search
def search_faiss(query, index, chunks, top_k=5):
    query_embedding = np.array([embedding_model.encode(query)], dtype="float32")
    distances, indices = index.search(query_embedding, top_k)
    return [chunks[i] for i in indices[0]]


# Create BM25 Index
def create_bm25_index(chunks):
    tokenized_chunks = [chunk.split() for chunk in chunks]
    return BM25Okapi(tokenized_chunks), tokenized_chunks


# BM25 Search
def search_bm25(query, bm25, tokenized_chunks, top_k=5):
    return bm25.get_top_n(query.split(), tokenized_chunks, n=top_k)


# Generate Answer
def generate_answer(query, faiss_index, bm25, tokenized_chunks, chunks):
    faiss_results = search_faiss(query, faiss_index, chunks)
    bm25_results = search_bm25(query, bm25, tokenized_chunks)

    context = " ".join(faiss_results + bm25_results)[:4000]

    prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:"
    response = qa_model(prompt, max_length=200, do_sample=True)
    return response[0]["generated_text"]


# Streamlit UI
st.title("📜 AI-Powered PDF Q&A System")

uploaded_file = st.file_uploader("Upload a PDF file", type=["pdf"])

if uploaded_file:
    with st.spinner("Processing PDF..."):
        text = extract_text_from_pdf(uploaded_file)
        chunks = chunk_text(text)

        faiss_index = create_faiss_index(chunks)
        bm25, tokenized_chunks = create_bm25_index(chunks)

        st.success("PDF processed successfully!")

    query = st.text_input("Ask a question about the document:")

    if st.button("Get Answer"):
        if query:
            with st.spinner("Generating answer..."):
                answer = generate_answer(query, faiss_index, bm25, tokenized_chunks, chunks)
                st.subheader("Answer:")
                st.write(answer)
        else:
            st.warning("Please enter a question.")