Added API Key (#1)
Browse files- Added API Key (8d382e3decedde1a4d8c33346a9910c78b67a164)
app.py
CHANGED
|
@@ -1,70 +1,157 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
for
|
| 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 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
import PyPDF2
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import numpy as np
|
| 9 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 10 |
+
|
| 11 |
+
from groq import Groq
|
| 12 |
+
|
| 13 |
+
# -----------------------------
|
| 14 |
+
# Configuration
|
| 15 |
+
# -----------------------------
|
| 16 |
+
GROQ_API_KEY = os.getenv("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")
|
| 17 |
+
MODEL_NAME = "llama3-8b-8192"
|
| 18 |
+
|
| 19 |
+
client = Groq(api_key=GROQ_API_KEY)
|
| 20 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 21 |
+
|
| 22 |
+
# -----------------------------
|
| 23 |
+
# PDF Processing
|
| 24 |
+
# -----------------------------
|
| 25 |
+
def extract_text_from_pdfs(files: List[tempfile.NamedTemporaryFile]):
|
| 26 |
+
documents = []
|
| 27 |
+
for file in files:
|
| 28 |
+
reader = PyPDF2.PdfReader(file)
|
| 29 |
+
for page_num, page in enumerate(reader.pages):
|
| 30 |
+
text = page.extract_text()
|
| 31 |
+
if text:
|
| 32 |
+
documents.append({
|
| 33 |
+
"text": text,
|
| 34 |
+
"source": f"{os.path.basename(file.name)} - page {page_num + 1}"
|
| 35 |
+
})
|
| 36 |
+
return documents
|
| 37 |
+
|
| 38 |
+
# -----------------------------
|
| 39 |
+
# Chunking
|
| 40 |
+
# -----------------------------
|
| 41 |
+
def chunk_text(documents, chunk_size=500, overlap=50):
|
| 42 |
+
chunks = []
|
| 43 |
+
for doc in documents:
|
| 44 |
+
text = doc["text"]
|
| 45 |
+
words = text.split()
|
| 46 |
+
start = 0
|
| 47 |
+
while start < len(words):
|
| 48 |
+
chunk_words = words[start:start + chunk_size]
|
| 49 |
+
chunk_text = " ".join(chunk_words)
|
| 50 |
+
chunks.append({
|
| 51 |
+
"text": chunk_text,
|
| 52 |
+
"source": doc["source"]
|
| 53 |
+
})
|
| 54 |
+
start += chunk_size - overlap
|
| 55 |
+
return chunks
|
| 56 |
+
|
| 57 |
+
# -----------------------------
|
| 58 |
+
# Embeddings & Retrieval
|
| 59 |
+
# -----------------------------
|
| 60 |
+
def embed_chunks(chunks):
|
| 61 |
+
texts = [c["text"] for c in chunks]
|
| 62 |
+
embeddings = embedder.encode(texts)
|
| 63 |
+
return embeddings
|
| 64 |
+
|
| 65 |
+
def retrieve_relevant_chunks(query, chunks, embeddings, top_k=3):
|
| 66 |
+
query_embedding = embedder.encode([query])
|
| 67 |
+
similarities = cosine_similarity(query_embedding, embeddings)[0]
|
| 68 |
+
top_indices = np.argsort(similarities)[-top_k:][::-1]
|
| 69 |
+
|
| 70 |
+
results = []
|
| 71 |
+
for idx in top_indices:
|
| 72 |
+
results.append(chunks[idx])
|
| 73 |
+
return results
|
| 74 |
+
|
| 75 |
+
# -----------------------------
|
| 76 |
+
# LLM Call
|
| 77 |
+
# -----------------------------
|
| 78 |
+
def ask_llm(question, context, history):
|
| 79 |
+
messages = history.copy()
|
| 80 |
+
|
| 81 |
+
system_prompt = (
|
| 82 |
+
"You are a helpful assistant. Answer the question strictly using the provided context. "
|
| 83 |
+
"If the answer is not in the context, say so."
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
messages.insert(0, {"role": "system", "content": system_prompt})
|
| 87 |
+
messages.append({
|
| 88 |
+
"role": "user",
|
| 89 |
+
"content": f"Context:\n{context}\n\nQuestion:\n{question}"
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
response = client.chat.completions.create(
|
| 93 |
+
model=MODEL_NAME,
|
| 94 |
+
messages=messages,
|
| 95 |
+
temperature=0.3
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
return response.choices[0].message.content
|
| 99 |
+
|
| 100 |
+
# -----------------------------
|
| 101 |
+
# Main Chat Logic
|
| 102 |
+
# -----------------------------
|
| 103 |
+
def chat(files, question, chat_history):
|
| 104 |
+
if not files:
|
| 105 |
+
return chat_history, "Please upload PDF files first."
|
| 106 |
+
|
| 107 |
+
documents = extract_text_from_pdfs(files)
|
| 108 |
+
chunks = chunk_text(documents)
|
| 109 |
+
embeddings = embed_chunks(chunks)
|
| 110 |
+
|
| 111 |
+
relevant_chunks = retrieve_relevant_chunks(question, chunks, embeddings)
|
| 112 |
+
|
| 113 |
+
context = ""
|
| 114 |
+
sources = []
|
| 115 |
+
for c in relevant_chunks:
|
| 116 |
+
context += c["text"] + "\n\n"
|
| 117 |
+
sources.append(c["source"])
|
| 118 |
+
|
| 119 |
+
answer = ask_llm(question, context, chat_history)
|
| 120 |
+
|
| 121 |
+
answer_with_sources = (
|
| 122 |
+
f"{answer}\n\n"
|
| 123 |
+
f"Sources:\n" + "\n".join(set(sources))
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
chat_history.append({"role": "user", "content": question})
|
| 127 |
+
chat_history.append({"role": "assistant", "content": answer_with_sources})
|
| 128 |
+
|
| 129 |
+
return chat_history, answer_with_sources
|
| 130 |
+
|
| 131 |
+
# -----------------------------
|
| 132 |
+
# Gradio UI
|
| 133 |
+
# -----------------------------
|
| 134 |
+
with gr.Blocks(title="Enhanced RAG Chatbot") as demo:
|
| 135 |
+
gr.Markdown("## 📚 Enhanced RAG-Based Chatbot (PDF QA)")
|
| 136 |
+
gr.Markdown("Upload multiple PDFs and ask questions based on their content.")
|
| 137 |
+
|
| 138 |
+
with gr.Row():
|
| 139 |
+
pdf_files = gr.File(
|
| 140 |
+
label="Upload PDF Files",
|
| 141 |
+
file_types=[".pdf"],
|
| 142 |
+
file_count="multiple"
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
chatbot = gr.Chatbot()
|
| 146 |
+
question = gr.Textbox(label="Ask a question")
|
| 147 |
+
state = gr.State([])
|
| 148 |
+
|
| 149 |
+
submit = gr.Button("Ask")
|
| 150 |
+
|
| 151 |
+
submit.click(
|
| 152 |
+
fn=chat,
|
| 153 |
+
inputs=[pdf_files, question, state],
|
| 154 |
+
outputs=[chatbot, chatbot]
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
demo.launch()
|