Update app.py
Browse files
app.py
CHANGED
|
@@ -1,119 +1,73 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import faiss
|
| 3 |
-
import
|
| 4 |
import os
|
| 5 |
-
|
| 6 |
-
from langchain_community.document_loaders import PyPDFLoader, UnstructuredPDFLoader
|
| 7 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
-
from sentence_transformers import SentenceTransformer
|
| 9 |
-
from rank_bm25 import BM25Okapi
|
| 10 |
-
from langchain_openai import ChatOpenAI
|
| 11 |
-
|
| 12 |
-
# --- Global Variables ---
|
| 13 |
-
pdf_texts = []
|
| 14 |
-
bm25, index, embed_model, document_embeddings = None, None, None, None
|
| 15 |
-
memory = ConversationBufferMemory()
|
| 16 |
-
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 17 |
-
|
| 18 |
-
# --- Load and split PDF with fallback to OCR ---
|
| 19 |
-
def load_pdf(uploaded_file, chunk_size=500, chunk_overlap=100):
|
| 20 |
-
"""Loads a PDF and splits it into chunks. Supports OCR."""
|
| 21 |
-
try:
|
| 22 |
-
loader = PyPDFLoader(str(uploaded_file))
|
| 23 |
-
pages = loader.load()
|
| 24 |
-
except Exception:
|
| 25 |
-
loader = UnstructuredPDFLoader(str(uploaded_file))
|
| 26 |
-
pages = loader.load()
|
| 27 |
-
|
| 28 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
|
| 29 |
-
doc_splits = text_splitter.split_documents(pages)
|
| 30 |
-
return [doc.page_content for doc in doc_splits]
|
| 31 |
-
|
| 32 |
-
# --- Initialize BM25 + FAISS index ---
|
| 33 |
-
def create_hybrid_index():
|
| 34 |
-
global bm25, index, embed_model, document_embeddings
|
| 35 |
-
|
| 36 |
-
if not pdf_texts:
|
| 37 |
-
raise ValueError("โ No PDF text to index!")
|
| 38 |
-
|
| 39 |
-
tokenized_corpus = [doc.split() for doc in pdf_texts]
|
| 40 |
-
bm25 = BM25Okapi(tokenized_corpus)
|
| 41 |
-
|
| 42 |
-
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 43 |
-
document_embeddings = embed_model.encode(pdf_texts)
|
| 44 |
-
|
| 45 |
-
index = faiss.IndexFlatL2(document_embeddings.shape[1])
|
| 46 |
-
index.add(np.array(document_embeddings).astype("float32"))
|
| 47 |
-
|
| 48 |
-
# --- Hybrid search: BM25 + FAISS ---
|
| 49 |
-
def hybrid_search(query, top_n=3):
|
| 50 |
-
if bm25 is None or index is None:
|
| 51 |
-
return ["โ Please upload and process a PDF first."]
|
| 52 |
-
|
| 53 |
-
bm25_scores = bm25.get_scores(query.split())
|
| 54 |
-
top_bm25_indices = np.argsort(bm25_scores)[-top_n:]
|
| 55 |
-
|
| 56 |
-
query_embedding = embed_model.encode([query])
|
| 57 |
-
selected_embeddings = np.array([document_embeddings[i] for i in top_bm25_indices]).astype("float32")
|
| 58 |
-
|
| 59 |
-
sub_index = faiss.IndexFlatL2(selected_embeddings.shape[1])
|
| 60 |
-
sub_index.add(selected_embeddings)
|
| 61 |
-
_, sub_ranked = sub_index.search(np.array(query_embedding).astype("float32"), top_n)
|
| 62 |
-
|
| 63 |
-
final_indices = [top_bm25_indices[i] for i in sub_ranked[0]]
|
| 64 |
-
return [pdf_texts[i] for i in final_indices]
|
| 65 |
-
|
| 66 |
-
# --- Generate GPT response based on hybrid search ---
|
| 67 |
-
def generate_response(query):
|
| 68 |
-
relevant_chunks = hybrid_search(query)
|
| 69 |
-
memory_context = memory.load_memory_variables({})
|
| 70 |
-
history = memory_context.get("history", "")
|
| 71 |
-
|
| 72 |
-
prompt = (
|
| 73 |
-
f"Conversation history:\n{history}\n\n"
|
| 74 |
-
f"Relevant text from document:\n{relevant_chunks}\n\n"
|
| 75 |
-
f"Answer the user's query: {query}"
|
| 76 |
-
)
|
| 77 |
-
|
| 78 |
-
llm = ChatOpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 79 |
-
response = llm.predict(prompt)
|
| 80 |
-
memory.save_context({"user": query}, {"AI": response})
|
| 81 |
-
return response
|
| 82 |
-
|
| 83 |
-
# --- Step 1: Upload PDF ---
|
| 84 |
-
def handle_pdf_upload(uploaded_file):
|
| 85 |
-
global pdf_texts
|
| 86 |
-
try:
|
| 87 |
-
pdf_texts = load_pdf(uploaded_file)
|
| 88 |
-
create_hybrid_index()
|
| 89 |
-
return "โ
PDF processed successfully. You may now ask a question."
|
| 90 |
-
except Exception as e:
|
| 91 |
-
return f"โ Failed to process PDF: {str(e)}"
|
| 92 |
-
|
| 93 |
-
# --- Step 2: Handle question ---
|
| 94 |
-
def handle_query(query):
|
| 95 |
-
if not pdf_texts:
|
| 96 |
-
return "โ No PDF uploaded. Please upload a PDF first."
|
| 97 |
-
return generate_response(query)
|
| 98 |
-
|
| 99 |
-
# --- Gradio UI ---
|
| 100 |
-
with gr.Blocks() as demo:
|
| 101 |
-
gr.Markdown("## ๐ค Chat with Your PDF (BM25 + FAISS + GPT-4)")
|
| 102 |
-
|
| 103 |
-
with gr.Row():
|
| 104 |
-
file_input = gr.File(label="Upload a PDF", file_types=[".pdf"])
|
| 105 |
-
upload_output = gr.Textbox(label="Upload Status", interactive=False)
|
| 106 |
-
|
| 107 |
-
with gr.Row():
|
| 108 |
-
query_input = gr.Textbox(label="Ask a Question", placeholder="What is this document about?", lines=2)
|
| 109 |
-
submit_btn = gr.Button("Submit")
|
| 110 |
-
|
| 111 |
-
response_output = gr.Textbox(label="Response", lines=6)
|
| 112 |
-
|
| 113 |
-
# Event Bindings
|
| 114 |
-
file_input.change(fn=handle_pdf_upload, inputs=file_input, outputs=upload_output)
|
| 115 |
-
submit_btn.click(fn=handle_query, inputs=query_input, outputs=response_output)
|
| 116 |
-
query_input.submit(fn=handle_query, inputs=query_input, outputs=response_output)
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ๐ RAG Book Summarizer (Hugging Face Spaces ready)
|
| 2 |
+
# This is a Streamlit app to summarize large books using RAG
|
| 3 |
+
# Dependencies: streamlit, sentence-transformers, faiss-cpu, transformers, PyPDF2, openai
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
from PyPDF2 import PdfReader
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
import faiss
|
| 9 |
+
import openai
|
| 10 |
import os
|
| 11 |
+
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# Load models
|
| 14 |
+
st.set_page_config(page_title="Book Summarizer RAG", layout="wide")
|
| 15 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 16 |
+
|
| 17 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
| 18 |
+
|
| 19 |
+
st.title("๐ Book Summarizer using RAG")
|
| 20 |
+
st.markdown("Upload a book in PDF format and get an AI-generated summary using Retrieval-Augmented Generation.")
|
| 21 |
+
|
| 22 |
+
# 1. Upload PDF
|
| 23 |
+
pdf_file = st.file_uploader("Upload a PDF book", type=["pdf"])
|
| 24 |
+
|
| 25 |
+
if pdf_file:
|
| 26 |
+
reader = PdfReader(pdf_file)
|
| 27 |
+
text = "\n".join(page.extract_text() for page in reader.pages if page.extract_text())
|
| 28 |
+
|
| 29 |
+
# 2. Chunk text
|
| 30 |
+
def split_text(text, chunk_size=500, overlap=50):
|
| 31 |
+
words = text.split()
|
| 32 |
+
chunks = []
|
| 33 |
+
for i in range(0, len(words), chunk_size - overlap):
|
| 34 |
+
chunk = " ".join(words[i:i+chunk_size])
|
| 35 |
+
chunks.append(chunk)
|
| 36 |
+
return chunks
|
| 37 |
+
|
| 38 |
+
chunks = split_text(text)
|
| 39 |
+
st.success(f"Document split into {len(chunks)} chunks")
|
| 40 |
+
|
| 41 |
+
# 3. Embed chunks
|
| 42 |
+
with st.spinner("Embedding chunks and creating vector index..."):
|
| 43 |
+
embeddings = embedder.encode(chunks, convert_to_numpy=True)
|
| 44 |
+
index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 45 |
+
index.add(np.array(embeddings))
|
| 46 |
+
|
| 47 |
+
# 4. Query-based summary
|
| 48 |
+
query = st.text_input("Ask a question or request a summary (e.g., 'Summarize the book')", value="Summarize the book")
|
| 49 |
+
if st.button("Generate Summary") and query:
|
| 50 |
+
query_vec = embedder.encode([query])
|
| 51 |
+
D, I = index.search(query_vec, k=5)
|
| 52 |
+
retrieved_chunks = [chunks[i] for i in I[0]]
|
| 53 |
+
|
| 54 |
+
context = "\n".join(retrieved_chunks)
|
| 55 |
+
prompt = f"""
|
| 56 |
+
You are an expert book summarizer.
|
| 57 |
+
Using the context below, answer the query: "{query}"
|
| 58 |
+
|
| 59 |
+
Context:
|
| 60 |
+
{context}
|
| 61 |
+
|
| 62 |
+
Answer:
|
| 63 |
+
"""
|
| 64 |
+
with st.spinner("Generating summary with OpenAI..."):
|
| 65 |
+
response = openai.ChatCompletion.create(
|
| 66 |
+
model="gpt-3.5-turbo",
|
| 67 |
+
messages=[{"role": "user", "content": prompt}],
|
| 68 |
+
temperature=0.7,
|
| 69 |
+
max_tokens=300
|
| 70 |
+
)
|
| 71 |
+
answer = response.choices[0].message.content
|
| 72 |
+
st.subheader("๐ Summary")
|
| 73 |
+
st.write(answer)
|