Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces # must be first
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import faiss, PyPDF2, docx
|
| 6 |
+
from sentence_transformers import SentenceTransformer
|
| 7 |
+
from groq import Groq
|
| 8 |
+
|
| 9 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 10 |
+
MODELS = ["llama-3.3-70b-versatile", "llama-3.1-8b-instant"]
|
| 11 |
+
|
| 12 |
+
@spaces.GPU
|
| 13 |
+
def embed(texts):
|
| 14 |
+
return embedder.encode(texts)
|
| 15 |
+
|
| 16 |
+
def read_file(path):
|
| 17 |
+
if path.endswith(".pdf"):
|
| 18 |
+
return "".join(p.extract_text() or "" for p in PyPDF2.PdfReader(path).pages)
|
| 19 |
+
if path.endswith(".docx"):
|
| 20 |
+
return "\n".join(p.text for p in docx.Document(path).paragraphs)
|
| 21 |
+
return open(path, encoding="utf-8", errors="ignore").read()
|
| 22 |
+
|
| 23 |
+
def chunk_text(text, size=150, overlap=30):
|
| 24 |
+
words = text.split(); out = []
|
| 25 |
+
for i in range(0, len(words), size - overlap):
|
| 26 |
+
out.append(" ".join(words[i:i + size]))
|
| 27 |
+
if i + size >= len(words): break
|
| 28 |
+
return out
|
| 29 |
+
|
| 30 |
+
def build(files, size):
|
| 31 |
+
if not files:
|
| 32 |
+
return None, "Upload a file first."
|
| 33 |
+
paths = [f if isinstance(f, str) else f.name for f in files]
|
| 34 |
+
text = "\n".join(read_file(p) for p in paths)
|
| 35 |
+
chunks = chunk_text(text, int(size))
|
| 36 |
+
if not chunks:
|
| 37 |
+
return None, "No text found. If it is a scanned PDF, use a text-based file."
|
| 38 |
+
emb = embed(chunks)
|
| 39 |
+
emb = emb / np.linalg.norm(emb, axis=1, keepdims=True)
|
| 40 |
+
kb = {"chunks": chunks, "emb": emb.astype("float32")}
|
| 41 |
+
return kb, f"Indexed {len(chunks)} chunks from {len(paths)} file(s)."
|
| 42 |
+
|
| 43 |
+
def answer(question, kb, model, k):
|
| 44 |
+
key = os.environ.get("GROQ_API_KEY")
|
| 45 |
+
if not key:
|
| 46 |
+
return "Secret GROQ_API_KEY is missing in Space Settings.", ""
|
| 47 |
+
if not kb:
|
| 48 |
+
return "Upload a document and click 'Build knowledge base' first.", ""
|
| 49 |
+
if not question.strip():
|
| 50 |
+
return "Type a question first.", ""
|
| 51 |
+
idx = faiss.IndexFlatIP(kb["emb"].shape[1]); idx.add(kb["emb"])
|
| 52 |
+
q = embed([question]); q = q / np.linalg.norm(q, axis=1, keepdims=True)
|
| 53 |
+
scores, ids = idx.search(q.astype("float32"), int(k))
|
| 54 |
+
hits = [(kb["chunks"][i], float(s)) for s, i in zip(scores[0], ids[0]) if i >= 0]
|
| 55 |
+
context = "\n\n".join(d for d, _ in hits)
|
| 56 |
+
prompt = ("Answer using ONLY the context. If it is not there, say you "
|
| 57 |
+
f"don't know.\n\nContext:\n{context}\n\nQuestion: {question}\nAnswer:")
|
| 58 |
+
r = Groq(api_key=key).chat.completions.create(
|
| 59 |
+
model=model, messages=[{"role": "user", "content": prompt}])
|
| 60 |
+
sources = "\n\n".join(f"**Chunk {i}** · score {s:.2f}\n\n{d}"
|
| 61 |
+
for i, (d, s) in enumerate(hits, 1))
|
| 62 |
+
return r.choices[0].message.content, sources
|
| 63 |
+
|
| 64 |
+
with gr.Blocks(title="RAG App with Groq") as demo:
|
| 65 |
+
gr.Markdown("# 📚 Open-Source RAG App with Groq\nCS4106 — Foundations of Generative AI")
|
| 66 |
+
kb = gr.State(None)
|
| 67 |
+
files = gr.File(label="Upload PDF / DOCX / TXT", file_count="multiple",
|
| 68 |
+
file_types=[".pdf", ".docx", ".txt"])
|
| 69 |
+
with gr.Row():
|
| 70 |
+
size = gr.Slider(50, 300, value=150, step=10, label="Chunk size (words)")
|
| 71 |
+
k = gr.Slider(1, 5, value=3, step=1, label="Chunks to retrieve (k)")
|
| 72 |
+
model = gr.Dropdown(MODELS, value=MODELS[0], label="Model")
|
| 73 |
+
with gr.Row():
|
| 74 |
+
build_btn = gr.Button("Build knowledge base", variant="primary")
|
| 75 |
+
clear_btn = gr.Button("Clear knowledge base")
|
| 76 |
+
status = gr.Textbox(label="Status", interactive=False)
|
| 77 |
+
question = gr.Textbox(label="Ask a question about your documents")
|
| 78 |
+
ask_btn = gr.Button("Answer", variant="primary")
|
| 79 |
+
ans = gr.Markdown()
|
| 80 |
+
with gr.Accordion("Sources (retrieved chunks)", open=False):
|
| 81 |
+
src = gr.Markdown()
|
| 82 |
+
|
| 83 |
+
build_btn.click(build, [files, size], [kb, status])
|
| 84 |
+
clear_btn.click(lambda: (None, "Cleared.", None), None, [kb, status, files])
|
| 85 |
+
ask_btn.click(answer, [question, kb, model, k], [ans, src])
|
| 86 |
+
|
| 87 |
+
demo.launch()
|