Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,97 +1,104 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
from sentence_transformers import SentenceTransformer
|
| 6 |
import faiss
|
| 7 |
import numpy as np
|
|
|
|
| 8 |
from groq import Groq
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
return
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from PyPDF2 import PdfReader
|
| 4 |
+
from docx import Document
|
|
|
|
| 5 |
import faiss
|
| 6 |
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
from groq import Groq
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
|
| 11 |
+
# β
Ensure model uses CPU to avoid meta tensor issue on Hugging Face
|
| 12 |
+
torch.set_default_device("cpu")
|
| 13 |
+
|
| 14 |
+
# β
Load Groq API key from environment variable
|
| 15 |
+
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
|
| 16 |
+
|
| 17 |
+
# β
Load SentenceTransformer model safely
|
| 18 |
+
embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2", trust_remote_code=True)
|
| 19 |
+
|
| 20 |
+
# β
FAISS index and chunk store
|
| 21 |
+
INDEX = faiss.IndexFlatL2(384)
|
| 22 |
+
stored_chunks = []
|
| 23 |
+
|
| 24 |
+
# β
UI Styling for Streamlit
|
| 25 |
+
st.markdown("""
|
| 26 |
+
<style>
|
| 27 |
+
.main-title {
|
| 28 |
+
font-size: 40px;
|
| 29 |
+
color: #2E86C1;
|
| 30 |
+
font-weight: bold;
|
| 31 |
+
text-align: center;
|
| 32 |
+
margin-bottom: 30px;
|
| 33 |
+
}
|
| 34 |
+
.card {
|
| 35 |
+
background-color: #ffffff;
|
| 36 |
+
padding: 20px;
|
| 37 |
+
border-radius: 15px;
|
| 38 |
+
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
|
| 39 |
+
margin-top: 20px;
|
| 40 |
+
}
|
| 41 |
+
body {
|
| 42 |
+
background-color: #f8fbfd;
|
| 43 |
+
}
|
| 44 |
+
</style>
|
| 45 |
+
""", unsafe_allow_html=True)
|
| 46 |
+
|
| 47 |
+
st.markdown('<div class="main-title">π Smart RAG Document QA Assistant</div>', unsafe_allow_html=True)
|
| 48 |
+
|
| 49 |
+
# β
Extract text from files
|
| 50 |
+
def extract_text(file):
|
| 51 |
+
if file.type == "application/pdf":
|
| 52 |
+
reader = PdfReader(file)
|
| 53 |
+
return " ".join([page.extract_text() or "" for page in reader.pages])
|
| 54 |
+
elif file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
|
| 55 |
+
doc = Document(file)
|
| 56 |
+
return "\n".join([p.text for p in doc.paragraphs])
|
| 57 |
+
elif file.type.startswith("text"):
|
| 58 |
+
return file.read().decode("utf-8")
|
| 59 |
+
return ""
|
| 60 |
+
|
| 61 |
+
# β
Split long text into small chunks
|
| 62 |
+
def chunk_text(text, chunk_size=200):
|
| 63 |
+
words = text.split()
|
| 64 |
+
return [" ".join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)]
|
| 65 |
+
|
| 66 |
+
# β
Store chunks and their embeddings in FAISS
|
| 67 |
+
def store_embeddings(chunks):
|
| 68 |
+
vectors = embed_model.encode(chunks)
|
| 69 |
+
INDEX.add(np.array(vectors, dtype=np.float32))
|
| 70 |
+
stored_chunks.extend(chunks)
|
| 71 |
+
|
| 72 |
+
# β
Retrieve most relevant chunks for a given query
|
| 73 |
+
def retrieve_similar_chunks(query, top_k=3):
|
| 74 |
+
query_vector = embed_model.encode([query])
|
| 75 |
+
distances, indices = INDEX.search(np.array(query_vector, dtype=np.float32), top_k)
|
| 76 |
+
return [stored_chunks[i] for i in indices[0]]
|
| 77 |
+
|
| 78 |
+
# β
Ask Groq LLM to answer based on document context
|
| 79 |
+
def get_llm_answer(query, context):
|
| 80 |
+
prompt = f"Answer the question based on the following context:\n\n{context}\n\nQuestion: {query}"
|
| 81 |
+
chat_completion = client.chat.completions.create(
|
| 82 |
+
messages=[{"role": "user", "content": prompt}],
|
| 83 |
+
model="llama3-70b-8192"
|
| 84 |
+
)
|
| 85 |
+
return chat_completion.choices[0].message.content
|
| 86 |
+
|
| 87 |
+
# β
File upload and query UI
|
| 88 |
+
uploaded_file = st.file_uploader("π Upload your document", type=["pdf", "docx", "txt"])
|
| 89 |
+
query = st.text_input("π¬ Ask a question about your document")
|
| 90 |
+
|
| 91 |
+
if uploaded_file:
|
| 92 |
+
with st.spinner("Processing file..."):
|
| 93 |
+
text = extract_text(uploaded_file)
|
| 94 |
+
chunks = chunk_text(text)
|
| 95 |
+
store_embeddings(chunks)
|
| 96 |
+
st.success("β
Document uploaded and indexed!")
|
| 97 |
+
|
| 98 |
+
if st.button("π§ Get Answer") and query:
|
| 99 |
+
with st.spinner("Thinking..."):
|
| 100 |
+
context = "\n\n".join(retrieve_similar_chunks(query))
|
| 101 |
+
answer = get_llm_answer(query, context)
|
| 102 |
+
st.markdown(f'<div class="card"><b>Answer:</b><br>{answer}</div>', unsafe_allow_html=True)
|
| 103 |
+
|
| 104 |
+
st.markdown("<br><center style='color: grey;'>Built by Muqadas with β€οΈ using Streamlit + Groq + FAISS</center>", unsafe_allow_html=True)
|