Spaces:
Sleeping
Sleeping
SHAMIL SHAHBAZ AWAN
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,78 +2,106 @@ import os
|
|
| 2 |
import streamlit as st
|
| 3 |
import pdfplumber
|
| 4 |
from sentence_transformers import SentenceTransformer
|
| 5 |
-
from transformers import pipeline
|
| 6 |
import faiss
|
| 7 |
import numpy as np
|
| 8 |
-
from groq import Client
|
| 9 |
|
| 10 |
# Load Hugging Face Secrets
|
| 11 |
-
HUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY")
|
| 12 |
if not HUGGINGFACE_KEY:
|
| 13 |
st.error("Hugging Face API token not found. Please set it in the Hugging Face Secrets.")
|
| 14 |
|
| 15 |
# Initialize Groq client
|
| 16 |
groq_client = Client(api_key=HUGGINGFACE_KEY)
|
| 17 |
|
| 18 |
-
# Load
|
| 19 |
embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
file_path = "
|
| 23 |
VECTORSTORE_FOLDER = "vectorstore"
|
| 24 |
|
| 25 |
-
#
|
| 26 |
if not os.path.exists(VECTORSTORE_FOLDER):
|
| 27 |
os.makedirs(VECTORSTORE_FOLDER)
|
| 28 |
|
|
|
|
| 29 |
vectorstore_path = os.path.join(VECTORSTORE_FOLDER, "index.faiss")
|
|
|
|
|
|
|
| 30 |
if os.path.exists(vectorstore_path):
|
| 31 |
index = faiss.read_index(vectorstore_path)
|
| 32 |
else:
|
| 33 |
index = faiss.IndexFlatL2(embedder.get_sentence_embedding_dimension())
|
| 34 |
|
| 35 |
-
#
|
| 36 |
def load_pdf_text(file_path):
|
| 37 |
-
"""Extract text from
|
| 38 |
text = ""
|
| 39 |
with pdfplumber.open(file_path) as pdf:
|
| 40 |
for page in pdf.pages:
|
| 41 |
text += page.extract_text()
|
| 42 |
return text
|
| 43 |
|
|
|
|
| 44 |
def chunk_text(text, chunk_size=500, overlap=100):
|
| 45 |
-
"""
|
| 46 |
chunks = []
|
| 47 |
for i in range(0, len(text), chunk_size - overlap):
|
| 48 |
chunks.append(text[i:i + chunk_size])
|
| 49 |
return chunks
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
st.info("Processing PDF document...")
|
|
|
|
|
|
|
| 53 |
text = load_pdf_text(file_path)
|
|
|
|
|
|
|
| 54 |
chunks = chunk_text(text)
|
| 55 |
|
|
|
|
| 56 |
embeddings = embedder.encode(chunks, show_progress_bar=True)
|
|
|
|
|
|
|
| 57 |
index.add(np.array(embeddings))
|
|
|
|
|
|
|
| 58 |
faiss.write_index(index, vectorstore_path)
|
| 59 |
-
|
|
|
|
| 60 |
|
| 61 |
-
# User interface
|
| 62 |
st.title("Atomic Habits RAG Application")
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
user_query = st.text_input("Enter your query:")
|
| 65 |
|
| 66 |
if user_query:
|
|
|
|
| 67 |
query_embedding = embedder.encode([user_query])
|
|
|
|
|
|
|
| 68 |
distances, indices = index.search(np.array(query_embedding), k=5)
|
|
|
|
|
|
|
| 69 |
retrieved_chunks = [chunks[idx] for idx in indices[0]]
|
| 70 |
|
|
|
|
| 71 |
st.subheader("Retrieved Chunks")
|
| 72 |
for chunk in retrieved_chunks:
|
| 73 |
st.write(chunk)
|
| 74 |
|
|
|
|
| 75 |
combined_input = " ".join(retrieved_chunks) + user_query
|
| 76 |
response = groq_client.generate(model="llama3-8b-8192", prompt=combined_input, max_tokens=200)
|
| 77 |
|
|
|
|
| 78 |
st.subheader("Generated Response")
|
| 79 |
st.write(response["text"])
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
import pdfplumber
|
| 4 |
from sentence_transformers import SentenceTransformer
|
|
|
|
| 5 |
import faiss
|
| 6 |
import numpy as np
|
| 7 |
+
from groq import Client
|
| 8 |
|
| 9 |
# Load Hugging Face Secrets
|
| 10 |
+
HUGGINGFACE_KEY = os.getenv("HUGGINGFACE_KEY")
|
| 11 |
if not HUGGINGFACE_KEY:
|
| 12 |
st.error("Hugging Face API token not found. Please set it in the Hugging Face Secrets.")
|
| 13 |
|
| 14 |
# Initialize Groq client
|
| 15 |
groq_client = Client(api_key=HUGGINGFACE_KEY)
|
| 16 |
|
| 17 |
+
# Load the SentenceTransformer model for embedding generation
|
| 18 |
embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
| 19 |
|
| 20 |
+
# Define file path and vector store folder
|
| 21 |
+
file_path = "Atomic habits ( PDFDrive ).pdf" # File directly in the root directory of the app
|
| 22 |
VECTORSTORE_FOLDER = "vectorstore"
|
| 23 |
|
| 24 |
+
# Ensure the vector store folder exists
|
| 25 |
if not os.path.exists(VECTORSTORE_FOLDER):
|
| 26 |
os.makedirs(VECTORSTORE_FOLDER)
|
| 27 |
|
| 28 |
+
# Define the vector store path
|
| 29 |
vectorstore_path = os.path.join(VECTORSTORE_FOLDER, "index.faiss")
|
| 30 |
+
|
| 31 |
+
# Load or create FAISS index
|
| 32 |
if os.path.exists(vectorstore_path):
|
| 33 |
index = faiss.read_index(vectorstore_path)
|
| 34 |
else:
|
| 35 |
index = faiss.IndexFlatL2(embedder.get_sentence_embedding_dimension())
|
| 36 |
|
| 37 |
+
# Function to load text from PDF
|
| 38 |
def load_pdf_text(file_path):
|
| 39 |
+
"""Extract text from the given PDF file."""
|
| 40 |
text = ""
|
| 41 |
with pdfplumber.open(file_path) as pdf:
|
| 42 |
for page in pdf.pages:
|
| 43 |
text += page.extract_text()
|
| 44 |
return text
|
| 45 |
|
| 46 |
+
# Function to chunk text into smaller pieces
|
| 47 |
def chunk_text(text, chunk_size=500, overlap=100):
|
| 48 |
+
"""Chunk the text into overlapping chunks."""
|
| 49 |
chunks = []
|
| 50 |
for i in range(0, len(text), chunk_size - overlap):
|
| 51 |
chunks.append(text[i:i + chunk_size])
|
| 52 |
return chunks
|
| 53 |
|
| 54 |
+
# Process the document and update vector store
|
| 55 |
+
def process_and_store_document(file_path):
|
| 56 |
+
"""Process the PDF document, chunk text, generate embeddings, and store them in FAISS."""
|
| 57 |
st.info("Processing PDF document...")
|
| 58 |
+
|
| 59 |
+
# Extract text from the PDF file
|
| 60 |
text = load_pdf_text(file_path)
|
| 61 |
+
|
| 62 |
+
# Chunk the text into smaller pieces
|
| 63 |
chunks = chunk_text(text)
|
| 64 |
|
| 65 |
+
# Generate embeddings for each chunk
|
| 66 |
embeddings = embedder.encode(chunks, show_progress_bar=True)
|
| 67 |
+
|
| 68 |
+
# Add the embeddings to the FAISS index
|
| 69 |
index.add(np.array(embeddings))
|
| 70 |
+
|
| 71 |
+
# Save the updated FAISS index
|
| 72 |
faiss.write_index(index, vectorstore_path)
|
| 73 |
+
|
| 74 |
+
st.success("Document processed and vector store updated!")
|
| 75 |
|
| 76 |
+
# User interface for Streamlit
|
| 77 |
st.title("Atomic Habits RAG Application")
|
| 78 |
|
| 79 |
+
# Button to trigger document processing
|
| 80 |
+
if st.button("Process PDF"):
|
| 81 |
+
process_and_store_document(file_path)
|
| 82 |
+
|
| 83 |
+
# Query input for the user
|
| 84 |
user_query = st.text_input("Enter your query:")
|
| 85 |
|
| 86 |
if user_query:
|
| 87 |
+
# Generate embedding for the user query
|
| 88 |
query_embedding = embedder.encode([user_query])
|
| 89 |
+
|
| 90 |
+
# Perform the search on the FAISS index
|
| 91 |
distances, indices = index.search(np.array(query_embedding), k=5)
|
| 92 |
+
|
| 93 |
+
# Retrieve the most relevant chunks based on the indices
|
| 94 |
retrieved_chunks = [chunks[idx] for idx in indices[0]]
|
| 95 |
|
| 96 |
+
# Display the retrieved chunks
|
| 97 |
st.subheader("Retrieved Chunks")
|
| 98 |
for chunk in retrieved_chunks:
|
| 99 |
st.write(chunk)
|
| 100 |
|
| 101 |
+
# Combine the retrieved chunks with the query and generate a response using Groq
|
| 102 |
combined_input = " ".join(retrieved_chunks) + user_query
|
| 103 |
response = groq_client.generate(model="llama3-8b-8192", prompt=combined_input, max_tokens=200)
|
| 104 |
|
| 105 |
+
# Display the generated response
|
| 106 |
st.subheader("Generated Response")
|
| 107 |
st.write(response["text"])
|