ragbot-demo / app.py
RDAIS's picture
Upload app.py with huggingface_hub
8b5dfd7 verified
Raw History Blame Contribute Delete
4.24 kB
import gradio as gr
import os
from typing import List
# In-memory document & vector store mock for Hugging Face Space Demo
documents_db = []
def ingest_document(file):
if file is None:
return "No file provided.", get_docs_summary()
file_name = os.path.basename(file.name)
try:
with open(file.name, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
except Exception as e:
return f"Error reading file: {str(e)}", get_docs_summary()
# Split into rough paragraphs/chunks
chunks = [p.strip() for p in content.split("\n\n") if p.strip()]
documents_db.append({
"name": file_name,
"chunks": chunks,
"raw": content
})
return f"Successfully ingested '{file_name}' ({len(chunks)} text chunks).", get_docs_summary()
def get_docs_summary():
if not documents_db:
return "No documents ingested yet."
summary = "### Ingested Documents:\n"
for idx, doc in enumerate(documents_db, 1):
summary += f"{idx}. **{doc['name']}** — {len(doc['chunks'])} chunks\n"
return summary
def answer_query(query: str, history: List):
if not query.strip():
return history, ""
if not documents_db:
bot_response = "⚠️ No documents ingested! Please upload a `.txt`, `.md`, or `.pdf` document first."
history.append((query, bot_response))
return history, ""
# Simple TF-IDF / keyword similarity score for space demo
query_terms = set(query.lower().split())
scored_chunks = []
for doc in documents_db:
for chunk in doc["chunks"]:
chunk_terms = set(chunk.lower().split())
overlap = len(query_terms.intersection(chunk_terms))
if overlap > 0:
scored_chunks.append((overlap, doc["name"], chunk))
scored_chunks.sort(key=lambda x: x[0], reverse=True)
if scored_chunks:
top_chunks = scored_chunks[:3]
context_str = "\n\n".join([f"From **{doc_name}**:\n\"{chunk}\"" for _, doc_name, chunk in top_chunks])
bot_response = f"**Relevant Context Retrieved:**\n\n{context_str}\n\n---\n**RAG Answer:**\nBased on your documents, here is the retrieved information addressing '{query}'."
else:
bot_response = "I searched your ingested documents but couldn't find a direct keyword match. Try asking with different terms from your document."
history.append((query, bot_response))
return history, ""
def clear_db():
documents_db.clear()
return [], "Document store cleared.", "No documents ingested yet."
with gr.Blocks(title="RAGBot - Retrieval-Augmented Generation Demo", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🤖 RAGBot Interactive Demo")
gr.Markdown("Upload your `.txt` or `.md` documents, ingest them into the vector index, and ask questions with Retrieval-Augmented Generation (RAG).")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📄 Document Ingestion")
file_input = gr.File(label="Upload Document (.txt, .md)")
ingest_btn = gr.Button("📥 Ingest Document", variant="primary")
ingest_status = gr.Textbox(label="Ingestion Status", interactive=False)
docs_summary = gr.Markdown(value=get_docs_summary())
clear_btn = gr.Button("🗑️ Clear Vector Database", variant="stop")
with gr.Column(scale=2):
gr.Markdown("### 💬 Chat & Context Retrieval")
chatbot = gr.Chatbot(label="RAG Conversation", height=450)
msg_input = gr.Textbox(label="Ask a question about your documents...", placeholder="e.g., What are the main features mentioned?", show_label=False)
send_btn = gr.Button("Send Question", variant="primary")
ingest_btn.click(ingest_document, inputs=[file_input], outputs=[ingest_status, docs_summary])
send_btn.click(answer_query, inputs=[msg_input, chatbot], outputs=[chatbot, msg_input])
msg_input.submit(answer_query, inputs=[msg_input, chatbot], outputs=[chatbot, msg_input])
clear_btn.click(clear_db, outputs=[chatbot, ingest_status, docs_summary])
if __name__ == "__main__":
demo.launch()