Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import faiss
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from langchain.memory import ConversationBufferMemory
|
| 5 |
from langchain.document_loaders import PyPDFLoader
|
| 6 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
@@ -8,14 +9,15 @@ from sentence_transformers import SentenceTransformer
|
|
| 8 |
from rank_bm25 import BM25Okapi
|
| 9 |
from langchain.llms import OpenAI
|
| 10 |
|
| 11 |
-
openai_api_key = "YOUR_OPENAI_API_KEY"
|
| 12 |
-
|
| 13 |
# Global variables for retrieval
|
| 14 |
pdf_texts = []
|
| 15 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
| 16 |
|
| 17 |
# Initialize conversational memory
|
| 18 |
-
memory = ConversationBufferMemory(
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
# Function to load PDF and split text
|
| 21 |
def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
|
|
@@ -29,10 +31,13 @@ def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
|
|
| 29 |
return [doc.page_content for doc in doc_splits]
|
| 30 |
|
| 31 |
# Function to initialize hybrid retrieval (BM25 + FAISS)
|
| 32 |
-
def create_hybrid_index(
|
| 33 |
"""Initializes BM25 and FAISS for hybrid retrieval."""
|
| 34 |
global bm25, index, embed_model, document_embeddings
|
| 35 |
|
|
|
|
|
|
|
|
|
|
| 36 |
# BM25 setup
|
| 37 |
tokenized_corpus = [doc.split(" ") for doc in pdf_texts]
|
| 38 |
bm25 = BM25Okapi(tokenized_corpus)
|
|
@@ -48,7 +53,7 @@ def create_hybrid_index(pdf_texts):
|
|
| 48 |
def hybrid_search(query, top_n=3):
|
| 49 |
"""Performs hybrid search using BM25 for filtering and FAISS for semantic ranking."""
|
| 50 |
if not bm25 or not index:
|
| 51 |
-
return ["Error: PDF not uploaded! Please upload a PDF first."]
|
| 52 |
|
| 53 |
# BM25 search
|
| 54 |
bm25_scores = bm25.get_scores(query.split(" "))
|
|
@@ -64,30 +69,29 @@ def hybrid_search(query, top_n=3):
|
|
| 64 |
final_ranked_indices = [top_docs_indices[i] for i in sub_ranked_indices[0]]
|
| 65 |
return [pdf_texts[i] for i in final_ranked_indices]
|
| 66 |
|
| 67 |
-
|
| 68 |
def generate_response(query):
|
| 69 |
"""Generates responses based on retrieved documents and conversation history."""
|
| 70 |
retrieved_docs = hybrid_search(query)
|
| 71 |
memory_context = memory.load_memory_variables({})
|
| 72 |
-
|
| 73 |
prompt = f"Conversation history: {memory_context}\nRelevant text: {retrieved_docs}\nGenerate a response:"
|
| 74 |
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 75 |
-
|
| 76 |
response = llm(prompt)
|
| 77 |
memory.save_context({"user": query}, {"AI": response})
|
| 78 |
return response
|
| 79 |
|
| 80 |
-
|
| 81 |
# Function to process uploaded PDF
|
| 82 |
def process_pdf(uploaded_file):
|
| 83 |
"""Handles PDF upload and initializes retrieval system."""
|
| 84 |
global pdf_texts
|
| 85 |
-
pdf_texts = load_pdf(uploaded_file
|
| 86 |
-
create_hybrid_index(
|
| 87 |
return "✅ PDF processed successfully! You can now ask questions."
|
| 88 |
|
| 89 |
# Gradio UI with PDF Upload + Conversational Chat
|
| 90 |
-
file_input = gr.File(label="Upload a PDF", type="
|
| 91 |
chat_box = gr.Textbox(label="Ask a question based on the uploaded PDF")
|
| 92 |
|
| 93 |
iface = gr.Interface(
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import faiss
|
| 3 |
import numpy as np
|
| 4 |
+
import os
|
| 5 |
from langchain.memory import ConversationBufferMemory
|
| 6 |
from langchain.document_loaders import PyPDFLoader
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 9 |
from rank_bm25 import BM25Okapi
|
| 10 |
from langchain.llms import OpenAI
|
| 11 |
|
|
|
|
|
|
|
| 12 |
# Global variables for retrieval
|
| 13 |
pdf_texts = []
|
| 14 |
bm25, index, embed_model, document_embeddings = None, None, None, None
|
| 15 |
|
| 16 |
# Initialize conversational memory
|
| 17 |
+
memory = ConversationBufferMemory()
|
| 18 |
+
|
| 19 |
+
# Load API key from Hugging Face Spaces Secrets
|
| 20 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 21 |
|
| 22 |
# Function to load PDF and split text
|
| 23 |
def load_pdf(pdf_path, chunk_size=500, chunk_overlap=100):
|
|
|
|
| 31 |
return [doc.page_content for doc in doc_splits]
|
| 32 |
|
| 33 |
# Function to initialize hybrid retrieval (BM25 + FAISS)
|
| 34 |
+
def create_hybrid_index():
|
| 35 |
"""Initializes BM25 and FAISS for hybrid retrieval."""
|
| 36 |
global bm25, index, embed_model, document_embeddings
|
| 37 |
|
| 38 |
+
if not pdf_texts:
|
| 39 |
+
return "❌ Error: No PDF data found!"
|
| 40 |
+
|
| 41 |
# BM25 setup
|
| 42 |
tokenized_corpus = [doc.split(" ") for doc in pdf_texts]
|
| 43 |
bm25 = BM25Okapi(tokenized_corpus)
|
|
|
|
| 53 |
def hybrid_search(query, top_n=3):
|
| 54 |
"""Performs hybrid search using BM25 for filtering and FAISS for semantic ranking."""
|
| 55 |
if not bm25 or not index:
|
| 56 |
+
return ["❌ Error: PDF not uploaded! Please upload a PDF first."]
|
| 57 |
|
| 58 |
# BM25 search
|
| 59 |
bm25_scores = bm25.get_scores(query.split(" "))
|
|
|
|
| 69 |
final_ranked_indices = [top_docs_indices[i] for i in sub_ranked_indices[0]]
|
| 70 |
return [pdf_texts[i] for i in final_ranked_indices]
|
| 71 |
|
| 72 |
+
# Function to generate response using OpenAI GPT-4
|
| 73 |
def generate_response(query):
|
| 74 |
"""Generates responses based on retrieved documents and conversation history."""
|
| 75 |
retrieved_docs = hybrid_search(query)
|
| 76 |
memory_context = memory.load_memory_variables({})
|
| 77 |
+
|
| 78 |
prompt = f"Conversation history: {memory_context}\nRelevant text: {retrieved_docs}\nGenerate a response:"
|
| 79 |
llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key)
|
| 80 |
+
|
| 81 |
response = llm(prompt)
|
| 82 |
memory.save_context({"user": query}, {"AI": response})
|
| 83 |
return response
|
| 84 |
|
|
|
|
| 85 |
# Function to process uploaded PDF
|
| 86 |
def process_pdf(uploaded_file):
|
| 87 |
"""Handles PDF upload and initializes retrieval system."""
|
| 88 |
global pdf_texts
|
| 89 |
+
pdf_texts = load_pdf(uploaded_file)
|
| 90 |
+
create_hybrid_index()
|
| 91 |
return "✅ PDF processed successfully! You can now ask questions."
|
| 92 |
|
| 93 |
# Gradio UI with PDF Upload + Conversational Chat
|
| 94 |
+
file_input = gr.File(label="Upload a PDF", type="filepath", interactive=True)
|
| 95 |
chat_box = gr.Textbox(label="Ask a question based on the uploaded PDF")
|
| 96 |
|
| 97 |
iface = gr.Interface(
|