documentation-crawler-rag / ui /spaces_app.py
chintu4's picture
ok
7ef1828
Raw
History Blame Contribute Delete
3.29 kB
"""
Hugging Face Spaces Gradio app for RAG System
"""
import gradio as gr
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from src.app_hf import answer_question, add_urls
load_dotenv()
# Check if HF_TOKEN is set
hf_token = os.getenv("HF_TOKEN")
def _normalize_history(history):
if not history:
return []
normalized = []
for item in history:
if isinstance(item, dict) and item.get("role") in {"user", "assistant"}:
normalized.append(item)
elif isinstance(item, (list, tuple)) and len(item) == 2:
normalized.append({"role": "user", "content": item[0]})
normalized.append({"role": "assistant", "content": item[1]})
return normalized
def respond(message, chat_history, urls_text, progress=gr.Progress()):
try:
history = _normalize_history(chat_history)
# Parse URLs from text input
urls = None
if urls_text and urls_text.strip():
urls = [url.strip() for url in urls_text.split('\n') if url.strip()]
add_urls(urls)
reply = answer_question(message, urls=urls, progress=progress)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": reply})
return history, history
except Exception as e:
error_reply = f"❌ Error: {str(e)}"
history = _normalize_history(chat_history)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": error_reply})
return history, history
# Build the Gradio interface
with gr.Blocks(title="πŸ“š Documentation RAG Assistant") as demo:
gr.Markdown("# πŸ“š Documentation RAG Assistant")
gr.Markdown("Ask questions about your documentation with AI-powered retrieval")
gr.Markdown(f"**Status:** {'βœ… Ready' if hf_token else '❌ HF_TOKEN not set'}")
with gr.Row():
with gr.Column(scale=3):
chatbot = gr.Chatbot(label="Chat")
msg = gr.Textbox(
placeholder="Ask me anything...",
label="Your Question"
)
state = gr.State([])
with gr.Column(scale=1):
gr.Markdown("### πŸ“– Data Sources")
urls_input = gr.Textbox(
placeholder="https://docs.python.org\nhttps://realpython.com",
label="URLs to Search",
lines=5,
info="Paste URLs here (one per line)"
)
gr.Markdown("""
**Or** upload PDFs:
- Use the file upload below
- Supports PDF documents
""")
def submit_fn(user_message, history, urls):
history = history or []
new_history, _ = respond(user_message, history, urls)
return "", new_history, new_history
msg.submit(submit_fn, [msg, state, urls_input], [msg, chatbot, state])
send_btn = gr.Button("Send", variant="primary")
send_btn.click(submit_fn, [msg, state, urls_input], [msg, chatbot, state])
if __name__ == "__main__":
demo.queue()
demo.launch()