Wall06 commited on
Commit
73a473a
Β·
verified Β·
1 Parent(s): e4f6fc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -23
app.py CHANGED
@@ -1,36 +1,158 @@
1
  import gradio as gr
 
2
  from rag_engine import RAGEngine
3
 
 
4
  engine = RAGEngine()
5
 
6
- def upload_source(file=None, url=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  try:
8
- if file: msg = engine.load_pdf(file.name)
9
- elif url: msg = engine.load_url(url)
10
- else: return "❌ No source provided.", gr.update(interactive=False)
11
- return msg, gr.update(interactive=True, placeholder="Ask me anything!")
12
  except Exception as e:
13
- return f"❌ Error: {str(e)}", gr.update(interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- def chat(msg, history):
16
- ans, nlp = engine.answer_with_nlp(msg)
17
- history.append((msg, ans))
18
- return history, "", nlp
 
 
 
 
 
 
 
19
 
20
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
21
- gr.Markdown("# πŸ€– Your Pro RAG Chatbot")
22
  with gr.Row():
23
- with gr.Column(scale=1):
24
- file_in = gr.File(label="Step 1: Upload PDF")
25
- url_in = gr.Textbox(label="OR Paste URL")
26
- btn = gr.Button("πŸš€ Process Knowledge", variant="primary")
27
- status = gr.Label("Status: Waiting for data...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  with gr.Column(scale=2):
29
- chatbot = gr.Chatbot(height=400)
30
- msg_in = gr.Textbox(placeholder="Locked until data is processed...", interactive=False)
31
- nlp_out = gr.JSON(label="AI Analysis")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- btn.click(upload_source, [file_in, url_in], [status, msg_in])
34
- msg_in.submit(chat, [msg_in, chatbot], [chatbot, msg_in, nlp_out])
 
35
 
36
- demo.launch()
 
 
1
  import gradio as gr
2
+ import os
3
  from rag_engine import RAGEngine
4
 
5
+ # Initialize engine
6
  engine = RAGEngine()
7
 
8
+ # ── Helpers ──────────────────────────────────────────────────────────────────
9
+
10
+ def process_pdf(file):
11
+ if file is None:
12
+ return "⚠️ No file uploaded.", gr.update(interactive=False)
13
+ try:
14
+ msg = engine.load_pdf(file.name)
15
+ return msg, gr.update(interactive=True)
16
+ except Exception as e:
17
+ return f"❌ Error: {e}", gr.update(interactive=False)
18
+
19
+ def process_url(url):
20
+ if not url.strip():
21
+ return "⚠️ Please enter a URL.", gr.update(interactive=False)
22
+ try:
23
+ msg = engine.load_url(url.strip())
24
+ return msg, gr.update(interactive=True)
25
+ except Exception as e:
26
+ return f"❌ Error: {e}", gr.update(interactive=False)
27
+
28
+ def process_text(text):
29
+ if not text.strip():
30
+ return "⚠️ Please paste some text.", gr.update(interactive=False)
31
  try:
32
+ msg = engine.load_text(text.strip())
33
+ return msg, gr.update(interactive=True)
 
 
34
  except Exception as e:
35
+ return f"❌ Error: {e}", gr.update(interactive=False)
36
+
37
+ def chat(message, history):
38
+ if not message.strip():
39
+ return history, ""
40
+ answer = engine.answer(message)
41
+ history = history or []
42
+ history.append((message, answer))
43
+ return history, ""
44
+
45
+ def reset_all():
46
+ engine.reset()
47
+ return [], "", "πŸ”„ Knowledge base cleared. Load a new source to begin."
48
+
49
+ # ── UI ────────────────────────────────────────────────────────────────────────
50
+
51
+ DESCRIPTION = """
52
+ # πŸ€– RAG Chatbot β€” Chat with Your Data
53
+ Upload a **PDF**, paste a **website URL**, or drop in **raw text** β€” then ask anything.
54
+
55
+ Built with πŸ€— HuggingFace Β· FAISS Β· spaCy Β· Sentence-Transformers
56
+ """
57
 
58
+ with gr.Blocks(
59
+ title="RAG Chatbot",
60
+ theme=gr.themes.Soft(primary_hue="violet", secondary_hue="slate"),
61
+ css="""
62
+ #chatbot { min-height: 420px; }
63
+ .source-box { border: 1px solid #e2e8f0; border-radius: 12px; padding: 16px; background: #f8fafc; }
64
+ .status-bar { font-size: 13px; padding: 6px 12px; border-radius: 8px; }
65
+ footer { display: none !important; }
66
+ """,
67
+ ) as demo:
68
+ gr.Markdown(DESCRIPTION)
69
 
 
 
70
  with gr.Row():
71
+ # ── Left column: source loader ──────────────────────────────────────
72
+ with gr.Column(scale=1, elem_classes="source-box"):
73
+ gr.Markdown("### πŸ“‚ Load a Knowledge Source")
74
+
75
+ with gr.Tab("πŸ“„ PDF"):
76
+ pdf_input = gr.File(
77
+ label="Upload PDF",
78
+ file_types=[".pdf"],
79
+ type="filepath",
80
+ )
81
+ pdf_btn = gr.Button("Load PDF", variant="primary")
82
+
83
+ with gr.Tab("🌐 Website URL"):
84
+ url_input = gr.Textbox(
85
+ label="Website URL",
86
+ placeholder="https://example.com/page",
87
+ )
88
+ url_btn = gr.Button("Load URL", variant="primary")
89
+
90
+ with gr.Tab("πŸ“ Raw Text"):
91
+ text_input = gr.Textbox(
92
+ label="Paste your text",
93
+ lines=8,
94
+ placeholder="Paste any text here...",
95
+ )
96
+ text_btn = gr.Button("Load Text", variant="primary")
97
+
98
+ status = gr.Textbox(
99
+ label="Status",
100
+ value="⏳ Load a source to start chatting.",
101
+ interactive=False,
102
+ elem_classes="status-bar",
103
+ )
104
+
105
+ with gr.Accordion("ℹ️ NLP Insights", open=False):
106
+ nlp_output = gr.JSON(label="Last query analysis")
107
+
108
+ # ── Right column: chat ──────────────────────────────────���───────────
109
  with gr.Column(scale=2):
110
+ gr.Markdown("### πŸ’¬ Chat")
111
+ chatbot = gr.Chatbot(
112
+ elem_id="chatbot",
113
+ bubble_full_width=False,
114
+ avatar_images=(None, "https://huggingface.co/front/assets/huggingface_logo-noborder.svg"),
115
+ )
116
+
117
+ with gr.Row():
118
+ msg_box = gr.Textbox(
119
+ placeholder="Ask a question about your loaded content...",
120
+ show_label=False,
121
+ scale=4,
122
+ interactive=False,
123
+ )
124
+ send_btn = gr.Button("Send ➀", variant="primary", scale=1)
125
+
126
+ reset_btn = gr.Button("πŸ—‘οΈ Clear & Reset", variant="secondary")
127
+
128
+ # ── Example questions ────────────────────────────────────────────────────
129
+ gr.Examples(
130
+ examples=[
131
+ "What is the main topic of this document?",
132
+ "Summarise the key points in 3 bullet points.",
133
+ "What are the most important entities mentioned?",
134
+ "Give me a short conclusion based on the content.",
135
+ ],
136
+ inputs=msg_box,
137
+ label="πŸ’‘ Example questions",
138
+ )
139
+
140
+ # ── Wire events ──────────────────────────────────────────────────────────
141
+ def chat_with_nlp(message, history):
142
+ if not message.strip():
143
+ return history, "", {}
144
+ answer, nlp_info = engine.answer_with_nlp(message)
145
+ history = history or []
146
+ history.append((message, answer))
147
+ return history, "", nlp_info
148
+
149
+ pdf_btn.click(process_pdf, pdf_input, [status, msg_box])
150
+ url_btn.click(process_url, url_input, [status, msg_box])
151
+ text_btn.click(process_text, text_input, [status, msg_box])
152
 
153
+ send_btn.click(chat_with_nlp, [msg_box, chatbot], [chatbot, msg_box, nlp_output])
154
+ msg_box.submit(chat_with_nlp, [msg_box, chatbot], [chatbot, msg_box, nlp_output])
155
+ reset_btn.click(reset_all, outputs=[chatbot, msg_box, status])
156
 
157
+ if __name__ == "__main__":
158
+ demo.launch(share=False)