File size: 24,749 Bytes
23a973e 795e7d9 23a973e e5132e7 795e7d9 e5132e7 795e7d9 e5132e7 795e7d9 e5132e7 9436fbb e5132e7 795e7d9 e5132e7 795e7d9 0d33997 795e7d9 23a973e 795e7d9 0d33997 23a973e 24961bb 23a973e fd89df3 795e7d9 fd89df3 23a973e fd89df3 795e7d9 23a973e 795e7d9 23a973e 795e7d9 23a973e 795e7d9 11b2e61 795e7d9 e5132e7 23a973e 795e7d9 23a973e e5132e7 9fec855 795e7d9 23a973e 795e7d9 23a973e 795e7d9 23a973e 11b2e61 795e7d9 0d33997 795e7d9 0d33997 9fec855 ad66f04 795e7d9 ad66f04 795e7d9 9fec855 795e7d9 9fec855 795e7d9 9fec855 795e7d9 9fec855 795e7d9 9fec855 795e7d9 11b2e61 795e7d9 76ab94d 795e7d9 76ab94d 795e7d9 76ab94d 795e7d9 fd89df3 9fec855 795e7d9 9fec855 795e7d9 9fec855 795e7d9 9fec855 0d33997 795e7d9 9fec855 9436fbb 795e7d9 24961bb fd89df3 795e7d9 9fec855 795e7d9 0d33997 ad66f04 795e7d9 24961bb fd89df3 795e7d9 9124a44 795e7d9 9124a44 795e7d9 23a973e ad66f04 795e7d9 ad66f04 76ab94d e5132e7 76ab94d 9124a44 76ab94d 9124a44 76ab94d 9124a44 76ab94d 9124a44 795e7d9 76ab94d fd89df3 1f284e0 ad66f04 795e7d9 9fec855 795e7d9 9fec855 795e7d9 9fec855 795e7d9 9fec855 e5132e7 9fec855 9436fbb 9fec855 9436fbb 9fec855 9436fbb 9fec855 9436fbb 9fec855 9436fbb 9fec855 9436fbb 9fec855 9436fbb 24961bb 0200ef3 9fec855 0200ef3 24961bb 9fec855 24961bb 9fec855 24961bb 23a973e 795e7d9 a25099a 795e7d9 a25099a 9fec855 795e7d9 9fec855 795e7d9 23a973e 795e7d9 | 1 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 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | """
RAG Chat Interface for Hugging Face Space β Gradio UI layer.
All pure logic and backend HTTP lives in utils.py for testability.
"""
import gradio as gr
import os
import time
import threading
import requests
from typing import Generator, Tuple
from utils import (
BACKEND_URLS,
MAX_FILE_SIZE,
load_sample_data,
get_backend_url,
format_file_size,
extract_text_from_file,
resolve_file_path,
check_health,
fetch_indexed_docs,
upload_text_to_backend,
upload_pasted_text,
query_backend,
update_index_display,
load_index_state,
delete_document,
)
# ---------- Sample Data ----------
_SAMPLE_DATA = load_sample_data()
SAMPLE_LABELS: dict = _SAMPLE_DATA["labels"]
SAMPLE_DOCUMENTS: dict = {int(k): v for k, v in _SAMPLE_DATA["documents"].items()}
SAMPLE_QUESTIONS: list = _SAMPLE_DATA["sample_questions"]
# ---------- Sample-specific helpers ----------
def load_selected_samples(selected_labels: list) -> Tuple[bool, str, int, str]:
if not selected_labels:
return False, None, None, "β οΈ Please select at least one report."
years = sorted([SAMPLE_LABELS[lbl] for lbl in selected_labels])
parts = []
for year in years:
separator = "=" * 60
parts.append(f"{separator}\nANNUAL REPORT {year}\n{separator}\n{SAMPLE_DOCUMENTS[year]}")
combined = "\n\n".join(parts)
if len(years) == 1:
filename = f"annual_report_{years[0]}.txt"
else:
filename = f"annual_reports_{'_'.join(str(y) for y in years)}.txt"
return upload_text_to_backend(combined, filename)
def build_preview_text(selected_labels: list) -> str:
if not selected_labels:
return ""
years = sorted([SAMPLE_LABELS[lbl] for lbl in selected_labels])
parts = []
for year in years:
separator = "=" * 60
parts.append(f"{separator}\nANNUAL REPORT {year}\n{separator}\n{SAMPLE_DOCUMENTS[year]}")
return "\n\n".join(parts)
def warmup_with_status(start_time: float = None) -> Generator[Tuple[str, bool, str, float], None, None]:
if start_time is None:
start_time = time.time()
result = {"done": False, "success": False, "status_code": None, "error": None}
def do_request():
try:
resp = requests.get(get_backend_url("health"), timeout=None)
result["status_code"] = resp.status_code
result["success"] = resp.status_code == 200
except Exception as e:
result["error"] = str(e)
finally:
result["done"] = True
threading.Thread(target=do_request, daemon=True).start()
STEPS = [
(0, "β³ Initializing GPU model (Qwen 2.5 3B)..."),
(3, "β³ Initializing GPU model (Qwen 2.5 3B)...\nβ
Embedding model ready (BGE-small)"),
(6, "β³ Initializing GPU model (Qwen 2.5 3B)...\nβ
Embedding model ready (BGE-small)\nβ³ Loading index from volume..."),
(9, "β
GPU model loaded (Qwen 2.5 3B)\nβ
Embedding model ready (BGE-small)\nβ³ Loading index from volume..."),
]
while not result["done"]:
elapsed = time.time() - start_time
step_msg = STEPS[0][1]
for threshold, msg in STEPS:
if elapsed >= threshold:
step_msg = msg
yield f"{step_msg}\n\n*({elapsed:.1f}s elapsed)*", False, f"β³ Warming up... ({elapsed:.1f}s)", start_time
time.sleep(1)
elapsed = time.time() - start_time
if result["success"]:
final = (
"β
GPU model loaded (Qwen 2.5 3B)\n"
"β
Embedding model ready (BGE-small)\n"
"β
Index volume ready\n\n"
f"**β
Backend ready in {elapsed:.1f}s**"
)
yield final, True, f"β
Ready ({elapsed:.1f}s)", start_time
elif result["error"]:
yield f"β Cannot connect: {result['error']} ({elapsed:.1f}s)", False, f"β Failed ({elapsed:.1f}s)", start_time
else:
yield f"β Backend returned status {result['status_code']} ({elapsed:.1f}s)", False, f"β Failed ({elapsed:.1f}s)", start_time
# ---------- Main App ----------
def create_app() -> gr.Blocks:
with gr.Blocks() as demo:
page = gr.State("warmup")
document_indexed = gr.State(False)
indexed_docs = gr.State([])
active_docs = gr.State([]) # selected docs for query scope; [] = all
# ββ Warmup page ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(elem_id="warmup-page") as warmup_page:
gr.Markdown(
"""
<div style="text-align: center; margin-top: 15vh;">
<h1 style="font-size: 3em; margin-bottom: 0.5em;">π RAG Chat Interface</h1>
<p style="font-size: 1.2em; color: #666;">Powered by Qwen 2.5 & Modal</p>
<br>
<p style="color: #555;">Click the button below to warm up the backend and get started.</p>
</div>
"""
)
with gr.Row():
with gr.Column():
warmup_btn = gr.Button("π₯ Warm Up Backend", variant="primary", size="lg")
warmup_status = gr.Markdown("")
ready = gr.State(False)
start_time_state = gr.State(0.0)
warmup_btn.click(
fn=lambda: time.time(),
outputs=[start_time_state],
).then(
fn=warmup_with_status,
inputs=[start_time_state],
outputs=[warmup_status, ready, warmup_btn, start_time_state],
)
# ββ Chat page ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(elem_id="chat-page", visible=False) as chat_page:
gr.Markdown(
"""
<div style="text-align: center; margin-bottom: 1em;">
<h1>π RAG Chat Interface</h1>
</div>
"""
)
def respond(message, history, is_indexed, current_docs):
history = history or []
if not message or not message.strip():
yield history, message
return
user_msg = {"role": "user", "content": message}
if not is_indexed:
yield history + [user_msg, {"role": "assistant", "content": "β οΈ Please index a document first (see section 1)."}], ""
return
yield history + [user_msg, {"role": "assistant", "content": "π€ Thinking..."}], ""
final_answer = "π€ Thinking..."
# current_docs is a list (possibly empty = search all)
for chunk in query_backend(message, current_docs):
final_answer = chunk
yield history + [user_msg, {"role": "assistant", "content": final_answer}], ""
def _after_index(success, doc_id, char_count, source_text, error_msg=""):
"""
Shared post-index handler.
Returns: (indexed, docs, active_docs, index_status, preview_box, dropdown_update)
The freshly-uploaded doc is added to the active selection.
"""
if success:
docs = fetch_indexed_docs()
new_active = [doc_id] if doc_id in docs else docs[:]
display = update_index_display(docs)
preview = source_text or ""
return (
True,
docs,
new_active,
display,
preview,
gr.update(choices=docs, value=new_active),
)
else:
display = error_msg or "π *No document indexed yet*"
return False, gr.update(), gr.update(), display, "", gr.update()
# ββ Section 1: Select files to index ββ
with gr.Accordion("π₯ 1. Select files to index", open=True):
with gr.Tabs():
with gr.Tab("π Sample reports"):
sample_selector = gr.CheckboxGroup(
choices=list(SAMPLE_LABELS.keys()),
value=[],
label="Pick one or more sample annual reports",
interactive=True,
)
load_samples_btn = gr.Button("π Index Selected Reports", variant="primary")
samples_status = gr.Markdown("")
with gr.Tab("βοΈ Paste text"):
paste_input = gr.Textbox(
label="Paste text here",
lines=10,
max_lines=20,
placeholder="Paste any text content you want to ask questions aboutβ¦",
)
paste_filename = gr.Textbox(
label="Filename (optional)",
value="pasted.txt",
lines=1,
)
load_paste_btn = gr.Button("π Index Pasted Text", variant="primary")
paste_status = gr.Markdown("")
with gr.Tab("π Upload file"):
file_input = gr.File(
label="Upload .txt, .pdf, or .docx (one or many)",
file_types=[".txt", ".pdf", ".docx"],
file_count="multiple",
)
gr.Markdown(
"<small style='color:#888'>Drop one or more files at once. "
"PDF and DOCX are parsed locally; only the extracted text is sent. "
"Indexing starts automatically.</small>"
)
upload_status = gr.Markdown("")
# ββ Document Selector (multi-select for query scope) ββ
with gr.Row():
active_doc_dropdown = gr.Dropdown(
label="π Documents to query (also targets for Remove)",
choices=[],
value=[],
multiselect=True,
interactive=True,
scale=5,
info="Leave empty to search across ALL indexed documents.",
)
refresh_docs_btn = gr.Button("π Refresh", scale=1, min_width=80)
delete_doc_btn = gr.Button("ποΈ Remove selected", scale=1, min_width=120, variant="stop")
delete_status = gr.Markdown("")
# ββ Section 2: Preview indexed text ββ
with gr.Accordion("π 2. Preview indexed text", open=True):
index_status = gr.Markdown("π *No documents indexed yet*")
preview_box = gr.Textbox(
value="",
lines=18,
max_lines=18,
interactive=False,
label="Content",
placeholder="Index a document in section 1 to see its content here.",
)
# ββ Section 3: Chat ββ
with gr.Accordion("π¬ 3. Ask questions", open=True):
gr.Markdown("<small style='color:#888'>Quick questions:</small>")
with gr.Row():
q_btns = [gr.Button(q, size="sm") for q in SAMPLE_QUESTIONS]
chatbot = gr.Chatbot(height=420, show_label=False, value=[])
with gr.Row():
question_input = gr.Textbox(
placeholder="Type your question and press Enterβ¦",
lines=1,
scale=9,
show_label=False,
container=False,
)
send_btn = gr.Button("Send βΆ", scale=1, variant="primary")
INDEX_OUTPUTS = [
document_indexed,
indexed_docs,
active_docs,
index_status,
preview_box,
active_doc_dropdown,
]
SAMPLES_LABEL = "π Index Selected Reports"
PASTE_LABEL = "π Index Pasted Text"
def _busy(label):
return gr.update(value=label, interactive=False)
def _ready_btn(label):
return gr.update(value=label, interactive=True)
def _samples_action(selected_labels):
yield _busy("π Preparing reports..."), "π Preparing reportsβ¦", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
if not selected_labels:
result = _after_index(False, None, None, "", "β οΈ Please select at least one report.")
yield (_ready_btn(SAMPLES_LABEL), "β οΈ Please select at least one report.") + result
return
yield _busy("π€ Uploading & indexing..."), "π€ Uploading & indexingβ¦", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
success, doc_id, char_count, msg = load_selected_samples(selected_labels)
source_text = build_preview_text(selected_labels) if success else ""
result = _after_index(success, doc_id, char_count, source_text, msg)
final_status = "β
Done." if success else msg
yield (_ready_btn(SAMPLES_LABEL), final_status) + result
load_samples_btn.click(
fn=_samples_action,
inputs=[sample_selector],
outputs=[load_samples_btn, samples_status] + INDEX_OUTPUTS,
)
def _paste_action(text, filename):
yield _busy("π Preparing text..."), "π Preparing textβ¦", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
if not text or not text.strip():
result = _after_index(False, None, None, "", "β οΈ Please paste some text first.")
yield (_ready_btn(PASTE_LABEL), "β οΈ Please paste some text first.") + result
return
yield _busy("π€ Uploading & indexing..."), "π€ Uploading & indexingβ¦", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
success, doc_id, char_count, msg = upload_pasted_text(text, filename)
result = _after_index(success, doc_id, char_count, text if success else "", msg)
final_status = "β
Done." if success else msg
yield (_ready_btn(PASTE_LABEL), final_status) + result
load_paste_btn.click(
fn=_paste_action,
inputs=[paste_input, paste_filename],
outputs=[load_paste_btn, paste_status] + INDEX_OUTPUTS,
)
def _process_one_file(file_obj):
"""Parse + upload one file. Returns (ok, doc_id, char_count, text, msg)."""
path = resolve_file_path(file_obj)
base = os.path.basename(path) if path else "?"
if not path:
return False, None, None, "", f"β {base}: no file selected."
if not os.path.exists(path):
return False, None, None, "", f"β {base}: not found."
if os.path.getsize(path) > MAX_FILE_SIZE:
return False, None, None, "", f"β {base}: too large (max {format_file_size(MAX_FILE_SIZE)})."
text_content, err = extract_text_from_file(path)
if err or not text_content or not text_content.strip():
return False, None, None, "", err or f"β {base}: empty or unreadable."
stem, _ext = os.path.splitext(base)
filename = f"{stem}.txt"
success, doc_id, char_count, msg = upload_text_to_backend(text_content, filename)
if success:
return True, doc_id, char_count, text_content, f"β
{doc_id} ({char_count:,} chars)"
return False, None, None, "", f"β {filename}: {msg}"
def _upload_action(file_objs):
"""Handle one or many files. Yields progress then a final summary."""
# Normalise to a list β Gradio may pass a single file or a list.
if file_objs is None:
files = []
elif isinstance(file_objs, list):
files = file_objs
else:
files = [file_objs]
if not files:
yield ("β No files selected.",) + _after_index(
False, None, None, "", "β No files selected.",
)
return
total = len(files)
line_log: list = []
newly_indexed: list = [] # doc_ids of successful uploads
last_text = ""
for i, fobj in enumerate(files, start=1):
base = os.path.basename(resolve_file_path(fobj) or "?")
yield (
f"π [{i}/{total}] Parsing **{base}**β¦\n\n" + "\n".join(line_log),
gr.update(), gr.update(), gr.update(),
gr.update(), gr.update(), gr.update(),
)
ok, doc_id, _cc, text_content, msg = _process_one_file(fobj)
line_log.append(msg)
if ok:
newly_indexed.append(doc_id)
last_text = text_content
yield (
f"π€ [{i}/{total}] Done.\n\n" + "\n".join(line_log),
gr.update(), gr.update(), gr.update(),
gr.update(), gr.update(), gr.update(),
)
# Final state β select ALL successfully uploaded docs (not just the last).
ok_count = len(newly_indexed)
fail_count = total - ok_count
if ok_count:
all_docs = fetch_indexed_docs()
selected = [d for d in newly_indexed if d in all_docs]
if not selected:
selected = all_docs[:] # fallback
final_tuple = (
True,
all_docs,
selected,
update_index_display(all_docs),
last_text,
gr.update(choices=all_docs, value=selected),
)
else:
final_tuple = _after_index(False, None, None, "", "β All uploads failed.")
header = (
f"β
Indexed {ok_count}/{total} file{'s' if total != 1 else ''}."
if fail_count == 0
else f"β οΈ Indexed {ok_count}/{total} ({fail_count} failed)."
)
final_status = header + "\n\n" + "\n".join(line_log)
yield (final_status,) + final_tuple
file_input.upload(
fn=_upload_action,
inputs=[file_input],
outputs=[upload_status] + INDEX_OUTPUTS,
).then(
fn=lambda: gr.update(value=None),
outputs=[file_input],
)
active_doc_dropdown.change(
fn=lambda d: d or [],
inputs=[active_doc_dropdown],
outputs=[active_docs],
)
def _refresh_panel(current_active):
"""Re-fetch the doc list and keep selection where possible."""
docs = fetch_indexed_docs()
keep = [d for d in (current_active or []) if d in docs]
return gr.update(choices=docs, value=keep), keep
refresh_docs_btn.click(
fn=_refresh_panel,
inputs=[active_docs],
outputs=[active_doc_dropdown, active_docs],
)
def _delete_action(current_active):
"""Delete every doc currently selected. Empty selection = no-op."""
current_active = current_active or []
if not current_active:
yield (
gr.update(),
"β οΈ Select at least one document to remove.",
gr.update(), gr.update(), gr.update(),
gr.update(), gr.update(),
)
return
yield (
gr.update(),
f"ποΈ Removing {len(current_active)} document{'s' if len(current_active) != 1 else ''}...",
gr.update(), gr.update(), gr.update(),
gr.update(), gr.update(),
)
removed = []
failed = []
remaining: list = []
for name in current_active:
ok, remaining, _msg = delete_document(name)
(removed if ok else failed).append(name)
if removed and not failed:
msg = f"ποΈ Removed {len(removed)} document{'s' if len(removed) != 1 else ''}."
elif removed and failed:
msg = f"β οΈ Removed {len(removed)}, failed {len(failed)}."
else:
msg = f"β Failed to remove {len(failed)} document{'s' if len(failed) != 1 else ''}."
new_active = remaining[:] if remaining else []
yield (
gr.update(choices=remaining, value=new_active),
msg,
len(remaining) > 0,
remaining,
new_active,
update_index_display(remaining),
"" if not remaining else gr.update(),
)
delete_doc_btn.click(
fn=_delete_action,
inputs=[active_docs],
outputs=[
active_doc_dropdown,
delete_status,
document_indexed,
indexed_docs,
active_docs,
index_status,
preview_box,
],
)
for btn, q in zip(q_btns, SAMPLE_QUESTIONS):
btn.click(
fn=lambda x=q: x,
outputs=[question_input],
).then(
fn=respond,
inputs=[question_input, chatbot, document_indexed, active_docs],
outputs=[chatbot, question_input],
)
send_btn.click(
fn=respond,
inputs=[question_input, chatbot, document_indexed, active_docs],
outputs=[chatbot, question_input],
)
question_input.submit(
fn=respond,
inputs=[question_input, chatbot, document_indexed, active_docs],
outputs=[chatbot, question_input],
)
ready.change(
fn=lambda r: (gr.update(visible=not r), gr.update(visible=r), "chat" if r else "warmup"),
inputs=[ready],
outputs=[warmup_page, chat_page, page],
)
def _initial_load():
from utils import check_health
is_indexed, docs = check_health()
# Default: nothing selected β query searches across all documents.
return (
is_indexed,
docs,
[],
update_index_display(docs),
gr.update(choices=docs, value=[]),
)
demo.load(
fn=_initial_load,
outputs=[
document_indexed,
indexed_docs,
active_docs,
index_status,
active_doc_dropdown,
],
)
return demo
if __name__ == "__main__":
app = create_app()
app.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
|