Spaces:
Sleeping
Sleeping
Download app.py from Nvrhustle/RAG-Document-Assistant: direct link, hf CLI and curl.
- Browser
- Download file 4.16 kB
-
https://huggingface.co/spaces/Nvrhustle/RAG-Document-Assistant/resolve/main/app.py
- Command line
-
hf download hf://spaces/Nvrhustle/RAG-Document-Assistant/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Nvrhustle/RAG-Document-Assistant/resolve/main/app.py
4.16 kB
| import os | |
| import gradio as gr | |
| from langchain_community.document_loaders import PyPDFLoader | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from langchain_chroma import Chroma | |
| from langchain_community.embeddings import SentenceTransformerEmbeddings | |
| from langchain_core.documents import Document | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from langchain_huggingface import ( | |
| HuggingFaceEndpoint, | |
| ChatHuggingFace | |
| ) | |
| # ====================== | |
| # CONFIGURATION | |
| # ====================== | |
| DB_PATH = "/data/chroma_db" # ✅ Persistent on HF Spaces | |
| rag_state = { | |
| "vector_db": None, | |
| "llm": None, | |
| } | |
| # ====================== | |
| # INITIALIZATION | |
| # ====================== | |
| def initialize_rag(file_obj, hf_token): | |
| if not hf_token: | |
| return "⚠️ Please provide a Hugging Face token." | |
| if not file_obj: | |
| return "⚠️ Please upload a PDF file." | |
| try: | |
| # 1️⃣ Load PDF | |
| loader = PyPDFLoader(file_obj.name) | |
| docs = loader.load() | |
| # 2️⃣ Split | |
| splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=500, | |
| chunk_overlap=50 | |
| ) | |
| chunks = splitter.split_documents(docs) | |
| # 3️⃣ Embed + Store | |
| embedding_fn = SentenceTransformerEmbeddings( | |
| model_name="all-MiniLM-L6-v2" | |
| ) | |
| rag_state["vector_db"] = Chroma.from_documents( | |
| documents=chunks, | |
| embedding=embedding_fn, | |
| persist_directory=DB_PATH | |
| ) | |
| # 4️⃣ Base HF LLM | |
| base_llm = HuggingFaceEndpoint( | |
| repo_id="HuggingFaceH4/zephyr-7b-beta", | |
| huggingfacehub_api_token=hf_token, | |
| temperature=0.1, | |
| max_new_tokens=512, | |
| ) | |
| # 5️⃣ Chat Wrapper | |
| rag_state["llm"] = ChatHuggingFace(llm=base_llm) | |
| return f"✅ Indexed {len(chunks)} chunks. You can now chat." | |
| except Exception as e: | |
| return f"❌ Error: {str(e)}" | |
| # ====================== | |
| # CHAT LOGIC | |
| # ====================== | |
| def chat_logic(message, history): | |
| if not rag_state["vector_db"] or not rag_state["llm"]: | |
| return "⚠️ Please initialize the system first." | |
| try: | |
| # 1️⃣ Retrieve | |
| retriever = rag_state["vector_db"].as_retriever( | |
| search_kwargs={"k": 3} | |
| ) | |
| docs = retriever.invoke(message) | |
| context = "\n\n".join(d.page_content for d in docs) | |
| # 2️⃣ Chat Prompt | |
| prompt = ChatPromptTemplate.from_messages([ | |
| ( | |
| "system", | |
| "Answer ONLY using the provided context. " | |
| "If the answer is not in the context, say 'I don't know'." | |
| ), | |
| ( | |
| "human", | |
| "CONTEXT:\n{context}\n\nQUESTION:\n{question}" | |
| ) | |
| ]) | |
| chain = prompt | rag_state["llm"] | |
| # 3️⃣ Generate | |
| response = chain.invoke({ | |
| "context": context, | |
| "question": message | |
| }) | |
| return response.content.strip() | |
| except Exception as e: | |
| return f"❌ Error: {str(e)}" | |
| # ====================== | |
| # UI | |
| # ====================== | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 📄 RAG Document Assistant") | |
| gr.Markdown("Upload a PDF and chat with it using Retrieval-Augmented Generation.") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| hf_token_input = gr.Textbox( | |
| label="Hugging Face Token", | |
| type="password", | |
| placeholder="hf_..." | |
| ) | |
| file_input = gr.File( | |
| label="Upload PDF", | |
| file_types=[".pdf"] | |
| ) | |
| init_btn = gr.Button("Initialize System", variant="primary") | |
| status_output = gr.Textbox( | |
| label="Status", | |
| interactive=False | |
| ) | |
| with gr.Column(scale=2): | |
| chatbot = gr.ChatInterface( | |
| fn=chat_logic | |
| ) | |
| init_btn.click( | |
| initialize_rag, | |
| inputs=[file_input, hf_token_input], | |
| outputs=status_output | |
| ) | |
| demo.launch() | |