Amna252003's picture
Update app.py
dd9c929 verified
Raw History Blame Contribute Delete
5.12 kB
import spaces # must be first
import os
import numpy as np
import gradio as gr
import faiss, PyPDF2, docx
from sentence_transformers import SentenceTransformer
from groq import Groq
embedder = SentenceTransformer("all-MiniLM-L6-v2")
PREFERRED = [
"llama-3.1-8b-instant",
"llama-3.3-70b-versatile",
"openai/gpt-oss-20b",
"openai/gpt-oss-120b",
"qwen/qwen3-32b",
"meta-llama/llama-4-scout-17b-16e-instruct",
]
SKIP = ("whisper", "guard", "tts", "orpheus", "compound", "embed", "playai")
@spaces.GPU
def embed(texts):
return embedder.encode(texts)
def pick_model(client, requested):
"""Return a chat model your key can really use."""
ids = [m.id for m in client.models.list().data]
if requested in ids:
return requested
for m in PREFERRED:
if m in ids:
return m
chat = [i for i in ids if not any(s in i.lower() for s in SKIP)]
if chat:
return chat[0]
raise RuntimeError("No chat model available for this API key.")
def read_file(path):
if path.endswith(".pdf"):
return "".join(p.extract_text() or "" for p in PyPDF2.PdfReader(path).pages)
if path.endswith(".docx"):
return "\n".join(p.text for p in docx.Document(path).paragraphs)
return open(path, encoding="utf-8", errors="ignore").read()
def chunk_text(text, size=150, overlap=30):
words = text.split(); out = []
for i in range(0, len(words), size - overlap):
out.append(" ".join(words[i:i + size]))
if i + size >= len(words): break
return out
def build(files, size):
try:
if not files:
return None, "❌ Upload a file first."
paths = [f if isinstance(f, str) else f.name for f in files]
text = "\n".join(read_file(p) for p in paths)
chunks = chunk_text(text, int(size))
if not chunks:
return None, "❌ No text found. If it is a scanned PDF, use a text-based file."
emb = np.array(embed(chunks))
emb = emb / np.linalg.norm(emb, axis=1, keepdims=True)
kb = {"chunks": chunks, "emb": emb.astype("float32")}
return kb, f"βœ… Indexed {len(chunks)} chunks from {len(paths)} file(s)."
except Exception as e:
return None, f"❌ Error: {type(e).__name__}: {e}"
def answer(question, kb, model, k):
try:
key = os.environ.get("GROQ_API_KEY")
if not key:
return "❌ Secret GROQ_API_KEY is missing in Space Settings.", ""
if not kb:
return "❌ Upload a document and click 'Build knowledge base' first.", ""
if not question or not question.strip():
return "❌ Type a question first.", ""
idx = faiss.IndexFlatIP(kb["emb"].shape[1]); idx.add(kb["emb"])
q = np.array(embed([question]))
q = q / np.linalg.norm(q, axis=1, keepdims=True)
scores, ids = idx.search(q.astype("float32"), int(k))
hits = [(kb["chunks"][i], float(s)) for s, i in zip(scores[0], ids[0]) if i >= 0]
context = "\n\n".join(d for d, _ in hits)
prompt = ("Answer using ONLY the context. If it is not there, say you "
f"don't know.\n\nContext:\n{context}\n\nQuestion: {question}\nAnswer:")
client = Groq(api_key=key.strip())
used = pick_model(client, model)
r = client.chat.completions.create(
model=used, messages=[{"role": "user", "content": prompt}])
sources = "\n\n".join(f"**Chunk {i}** Β· score {s:.2f}\n\n{d}"
for i, (d, s) in enumerate(hits, 1))
text = r.choices[0].message.content
return f"{text}\n\n*(model used: `{used}`)*", sources
except Exception as e:
return f"❌ Error: {type(e).__name__}: {e}", ""
with gr.Blocks(title="RAG App with Groq") as demo:
gr.Markdown("# πŸ“š Open-Source RAG App with Groq\nCS4106 β€” Foundations of Generative AI")
kb = gr.State(None)
files = gr.File(label="Upload PDF / DOCX / TXT", file_count="multiple",
file_types=[".pdf", ".docx", ".txt"])
with gr.Row():
size = gr.Slider(50, 300, value=150, step=10, label="Chunk size (words)")
k = gr.Slider(1, 5, value=3, step=1, label="Chunks to retrieve (k)")
model = gr.Dropdown(PREFERRED, value=PREFERRED[0], label="Model (auto-switches if unavailable)")
with gr.Row():
build_btn = gr.Button("Build knowledge base", variant="primary")
clear_btn = gr.Button("Clear knowledge base")
status = gr.Textbox(label="Status", interactive=False)
question = gr.Textbox(label="Ask a question about your documents")
ask_btn = gr.Button("Answer", variant="primary")
gr.Markdown("### Answer")
ans = gr.Markdown("*Your answer will appear here.*")
with gr.Accordion("Sources (retrieved chunks)", open=False):
src = gr.Markdown()
build_btn.click(build, [files, size], [kb, status])
clear_btn.click(lambda: (None, "Cleared.", None), None, [kb, status, files])
ask_btn.click(answer, [question, kb, model, k], [ans, src])
question.submit(answer, [question, kb, model, k], [ans, src])
demo.launch()