RDAIS commited on
Commit
8b5dfd7
·
verified ·
1 Parent(s): f0f051a

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from typing import List
4
+
5
+ # In-memory document & vector store mock for Hugging Face Space Demo
6
+ documents_db = []
7
+
8
+ def ingest_document(file):
9
+ if file is None:
10
+ return "No file provided.", get_docs_summary()
11
+
12
+ file_name = os.path.basename(file.name)
13
+ try:
14
+ with open(file.name, "r", encoding="utf-8", errors="ignore") as f:
15
+ content = f.read()
16
+ except Exception as e:
17
+ return f"Error reading file: {str(e)}", get_docs_summary()
18
+
19
+ # Split into rough paragraphs/chunks
20
+ chunks = [p.strip() for p in content.split("\n\n") if p.strip()]
21
+ documents_db.append({
22
+ "name": file_name,
23
+ "chunks": chunks,
24
+ "raw": content
25
+ })
26
+
27
+ return f"Successfully ingested '{file_name}' ({len(chunks)} text chunks).", get_docs_summary()
28
+
29
+ def get_docs_summary():
30
+ if not documents_db:
31
+ return "No documents ingested yet."
32
+ summary = "### Ingested Documents:\n"
33
+ for idx, doc in enumerate(documents_db, 1):
34
+ summary += f"{idx}. **{doc['name']}** — {len(doc['chunks'])} chunks\n"
35
+ return summary
36
+
37
+ def answer_query(query: str, history: List):
38
+ if not query.strip():
39
+ return history, ""
40
+
41
+ if not documents_db:
42
+ bot_response = "⚠️ No documents ingested! Please upload a `.txt`, `.md`, or `.pdf` document first."
43
+ history.append((query, bot_response))
44
+ return history, ""
45
+
46
+ # Simple TF-IDF / keyword similarity score for space demo
47
+ query_terms = set(query.lower().split())
48
+ scored_chunks = []
49
+
50
+ for doc in documents_db:
51
+ for chunk in doc["chunks"]:
52
+ chunk_terms = set(chunk.lower().split())
53
+ overlap = len(query_terms.intersection(chunk_terms))
54
+ if overlap > 0:
55
+ scored_chunks.append((overlap, doc["name"], chunk))
56
+
57
+ scored_chunks.sort(key=lambda x: x[0], reverse=True)
58
+
59
+ if scored_chunks:
60
+ top_chunks = scored_chunks[:3]
61
+ context_str = "\n\n".join([f"From **{doc_name}**:\n\"{chunk}\"" for _, doc_name, chunk in top_chunks])
62
+ 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}'."
63
+ else:
64
+ bot_response = "I searched your ingested documents but couldn't find a direct keyword match. Try asking with different terms from your document."
65
+
66
+ history.append((query, bot_response))
67
+ return history, ""
68
+
69
+ def clear_db():
70
+ documents_db.clear()
71
+ return [], "Document store cleared.", "No documents ingested yet."
72
+
73
+ with gr.Blocks(title="RAGBot - Retrieval-Augmented Generation Demo", theme=gr.themes.Soft()) as demo:
74
+ gr.Markdown("# 🤖 RAGBot Interactive Demo")
75
+ gr.Markdown("Upload your `.txt` or `.md` documents, ingest them into the vector index, and ask questions with Retrieval-Augmented Generation (RAG).")
76
+
77
+ with gr.Row():
78
+ with gr.Column(scale=1):
79
+ gr.Markdown("### 📄 Document Ingestion")
80
+ file_input = gr.File(label="Upload Document (.txt, .md)")
81
+ ingest_btn = gr.Button("📥 Ingest Document", variant="primary")
82
+ ingest_status = gr.Textbox(label="Ingestion Status", interactive=False)
83
+ docs_summary = gr.Markdown(value=get_docs_summary())
84
+ clear_btn = gr.Button("🗑️ Clear Vector Database", variant="stop")
85
+
86
+ with gr.Column(scale=2):
87
+ gr.Markdown("### 💬 Chat & Context Retrieval")
88
+ chatbot = gr.Chatbot(label="RAG Conversation", height=450)
89
+ msg_input = gr.Textbox(label="Ask a question about your documents...", placeholder="e.g., What are the main features mentioned?", show_label=False)
90
+ send_btn = gr.Button("Send Question", variant="primary")
91
+
92
+ ingest_btn.click(ingest_document, inputs=[file_input], outputs=[ingest_status, docs_summary])
93
+ send_btn.click(answer_query, inputs=[msg_input, chatbot], outputs=[chatbot, msg_input])
94
+ msg_input.submit(answer_query, inputs=[msg_input, chatbot], outputs=[chatbot, msg_input])
95
+ clear_btn.click(clear_db, outputs=[chatbot, ingest_status, docs_summary])
96
+
97
+ if __name__ == "__main__":
98
+ demo.launch()