Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import faiss
|
3 |
+
import streamlit as st
|
4 |
+
from PyPDF2 import PdfReader
|
5 |
+
from sentence_transformers import SentenceTransformer
|
6 |
+
from groq import Groq
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
|
9 |
+
|
10 |
+
|
11 |
+
# Initialize Groq client
|
12 |
+
client = Groq(api_key="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")
|
13 |
+
|
14 |
+
# Load Sentence Transformer model
|
15 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
16 |
+
|
17 |
+
# Initialize FAISS
|
18 |
+
dimension = 384 # Embedding size for the Sentence Transformer model
|
19 |
+
index = faiss.IndexFlatL2(dimension)
|
20 |
+
|
21 |
+
# Function to process PDF and create embeddings
|
22 |
+
def process_pdf(pdf_file):
|
23 |
+
pdf_reader = PdfReader(pdf_file)
|
24 |
+
text = ""
|
25 |
+
for page in pdf_reader.pages:
|
26 |
+
text += page.extract_text()
|
27 |
+
chunks = [text[i:i + 500] for i in range(0, len(text), 500)] # Chunk into 500-char blocks
|
28 |
+
embeddings = model.encode(chunks)
|
29 |
+
index.add(embeddings)
|
30 |
+
return chunks, embeddings
|
31 |
+
|
32 |
+
# Function to query FAISS and generate a response
|
33 |
+
def query_model(query):
|
34 |
+
query_vector = model.encode([query])
|
35 |
+
_, indices = index.search(query_vector, k=3) # Top 3 similar chunks
|
36 |
+
response_chunks = [stored_chunks[idx] for idx in indices[0]]
|
37 |
+
context = " ".join(response_chunks)
|
38 |
+
|
39 |
+
# Groq API call
|
40 |
+
chat_completion = client.chat.completions.create(
|
41 |
+
messages=[
|
42 |
+
{
|
43 |
+
"role": "user",
|
44 |
+
"content": f"Context: {context}\n\nQuery: {query}",
|
45 |
+
}
|
46 |
+
],
|
47 |
+
model="llama3-8b-8192",
|
48 |
+
)
|
49 |
+
return chat_completion.choices[0].message.content
|
50 |
+
|
51 |
+
# Streamlit app
|
52 |
+
st.title("RAG-based PDF Question Answering")
|
53 |
+
st.write("Upload a PDF and ask questions based on its content.")
|
54 |
+
|
55 |
+
uploaded_file = st.file_uploader("Upload your PDF", type=["pdf"])
|
56 |
+
if uploaded_file:
|
57 |
+
stored_chunks, _ = process_pdf(uploaded_file)
|
58 |
+
st.success("PDF processed and embeddings created.")
|
59 |
+
|
60 |
+
query = st.text_input("Ask a question:")
|
61 |
+
if query:
|
62 |
+
answer = query_model(query)
|
63 |
+
st.write("### Answer:")
|
64 |
+
st.write(answer)
|