Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import fitz # PyMuPDF
|
| 4 |
+
import faiss
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pickle
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import tiktoken
|
| 9 |
+
from groq import Groq
|
| 10 |
+
|
| 11 |
+
# Initialize embedding model
|
| 12 |
+
embed_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
| 13 |
+
|
| 14 |
+
# Function to extract text from PDF
|
| 15 |
+
def extract_text_from_pdf(pdf_file):
|
| 16 |
+
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
|
| 17 |
+
text = "\n".join([page.get_text("text") for page in doc])
|
| 18 |
+
return text
|
| 19 |
+
|
| 20 |
+
# Function to split text into chunks
|
| 21 |
+
def chunk_text(text, chunk_size=512):
|
| 22 |
+
tokenizer = tiktoken.get_encoding("cl100k_base")
|
| 23 |
+
tokens = tokenizer.encode(text)
|
| 24 |
+
chunks = [tokens[i:i+chunk_size] for i in range(0, len(tokens), chunk_size)]
|
| 25 |
+
return ["".join(tokenizer.decode(chunk)) for chunk in chunks]
|
| 26 |
+
|
| 27 |
+
# Function to generate embeddings
|
| 28 |
+
def generate_embeddings(chunks):
|
| 29 |
+
return embed_model.encode(chunks, convert_to_numpy=True)
|
| 30 |
+
|
| 31 |
+
# Function to store embeddings in FAISS
|
| 32 |
+
def store_in_faiss(embeddings, chunks):
|
| 33 |
+
dimension = embeddings.shape[1]
|
| 34 |
+
index = faiss.IndexFlatL2(dimension)
|
| 35 |
+
index.add(embeddings)
|
| 36 |
+
with open("faiss_index.pkl", "wb") as f:
|
| 37 |
+
pickle.dump((index, chunks), f)
|
| 38 |
+
return index
|
| 39 |
+
|
| 40 |
+
# Function to load FAISS index
|
| 41 |
+
def load_faiss():
|
| 42 |
+
with open("faiss_index.pkl", "rb") as f:
|
| 43 |
+
index, chunks = pickle.load(f)
|
| 44 |
+
return index, chunks
|
| 45 |
+
|
| 46 |
+
# Function to search FAISS
|
| 47 |
+
def search_faiss(query, top_k=3):
|
| 48 |
+
query_embedding = embed_model.encode([query])
|
| 49 |
+
index, chunks = load_faiss()
|
| 50 |
+
_, indices = index.search(query_embedding, top_k)
|
| 51 |
+
results = [chunks[i] for i in indices[0]]
|
| 52 |
+
return results
|
| 53 |
+
|
| 54 |
+
# Function to interact with Groq API
|
| 55 |
+
def query_groq(query):
|
| 56 |
+
client = Groq(api_key=os.getenv("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"))
|
| 57 |
+
response = client.chat.completions.create(
|
| 58 |
+
messages=[{"role": "user", "content": query}],
|
| 59 |
+
model="llama-3.3-70b-versatile"
|
| 60 |
+
)
|
| 61 |
+
return response.choices[0].message.content
|
| 62 |
+
|
| 63 |
+
# Streamlit UI
|
| 64 |
+
st.title("RAG-based PDF Q&A App")
|
| 65 |
+
|
| 66 |
+
uploaded_file = st.file_uploader("Upload a PDF", type="pdf")
|
| 67 |
+
if uploaded_file:
|
| 68 |
+
st.write("Processing PDF...")
|
| 69 |
+
text = extract_text_from_pdf(uploaded_file)
|
| 70 |
+
chunks = chunk_text(text)
|
| 71 |
+
embeddings = generate_embeddings(chunks)
|
| 72 |
+
store_in_faiss(embeddings, chunks)
|
| 73 |
+
st.success("PDF processed and indexed!")
|
| 74 |
+
|
| 75 |
+
query = st.text_input("Ask a question:")
|
| 76 |
+
if query:
|
| 77 |
+
retrieved_chunks = search_faiss(query)
|
| 78 |
+
context = " ".join(retrieved_chunks)
|
| 79 |
+
response = query_groq(f"Context: {context} \n Question: {query}")
|
| 80 |
+
st.write("### Answer:")
|
| 81 |
+
st.write(response)
|