File size: 7,196 Bytes
5a5e72f
87b256d
 
5a5e72f
 
87b256d
 
5a5e72f
87b256d
5a5e72f
 
 
5e05c49
87b256d
5a5e72f
 
 
 
87b256d
 
5a5e72f
 
5e05c49
5a5e72f
5e05c49
 
5a5e72f
5e05c49
 
 
 
 
 
5a5e72f
 
5e05c49
 
87b256d
5a5e72f
 
 
 
 
 
 
87b256d
 
5a5e72f
87b256d
5e05c49
 
87b256d
5e05c49
 
 
87b256d
 
5a5e72f
 
 
87b256d
 
 
5e05c49
 
87b256d
5e05c49
 
 
87b256d
 
 
 
 
 
5a5e72f
 
 
5e05c49
87b256d
 
5a5e72f
87b256d
5a5e72f
 
 
87b256d
5a5e72f
 
 
 
 
 
 
 
 
 
87b256d
 
 
5e05c49
5a5e72f
87b256d
5a5e72f
5e05c49
 
5a5e72f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import os
import requests
import tempfile
import chromadb  
from langchain.document_loaders import PDFPlumberLoader
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_experimental.text_splitter import SemanticChunker
from langchain_chroma import Chroma
from langchain.chains import LLMChain, SequentialChain
from langchain.prompts import PromptTemplate
from langchain_groq import ChatGroq
from prompts import rag_prompt, relevancy_prompt, relevant_context_picker_prompt, response_synth

# ----------------- Streamlit UI Setup -----------------
st.set_page_config(page_title="Blah", layout="wide")
st.image("https://huggingface.co/front/assets/huggingface_logo-noborder.svg", width=150)  
st.title("Blah-1")


# ----------------- API Keys -----------------
os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")

# ----------------- Clear ChromaDB Cache -----------------
chromadb.api.client.SharedSystemClient.clear_system_cache()

# ----------------- Initialize Session State -----------------
if "pdf_loaded" not in st.session_state:
    st.session_state.pdf_loaded = False
if "chunked" not in st.session_state:
    st.session_state.chunked = False
if "vector_created" not in st.session_state:
    st.session_state.vector_created = False
if "processed_chunks" not in st.session_state:
    st.session_state.processed_chunks = None
if "vector_store" not in st.session_state:
    st.session_state.vector_store = None

# ----------------- Load Models -----------------
llm_judge = ChatGroq(model="deepseek-r1-distill-llama-70b")
rag_llm = ChatGroq(model="mixtral-8x7b-32768")

# ----------------- PDF Selection (Upload or URL) -----------------
st.sidebar.subheader("πŸ“‚ PDF Selection")
pdf_source = st.radio("Choose a PDF source:", ["Upload a PDF file", "Enter a PDF URL"], index=0, horizontal=True)

if pdf_source == "Upload a PDF file":
    uploaded_file = st.sidebar.file_uploader("Upload your PDF file", type=["pdf"])
    if uploaded_file:
        st.session_state.pdf_path = "temp.pdf"
        with open(st.session_state.pdf_path, "wb") as f:
            f.write(uploaded_file.getbuffer())
        st.session_state.pdf_loaded = False
        st.session_state.chunked = False
        st.session_state.vector_created = False

elif pdf_source == "Enter a PDF URL":
    pdf_url = st.sidebar.text_input("Enter PDF URL:")
    if pdf_url and not st.session_state.pdf_loaded:
        with st.spinner("πŸ”„ Downloading PDF..."):
            try:
                response = requests.get(pdf_url)
                if response.status_code == 200:
                    st.session_state.pdf_path = "temp.pdf"
                    with open(st.session_state.pdf_path, "wb") as f:
                        f.write(response.content)
                    st.session_state.pdf_loaded = False
                    st.session_state.chunked = False
                    st.session_state.vector_created = False
                    st.success("βœ… PDF Downloaded Successfully!")
                else:
                    st.error("❌ Failed to download PDF. Check the URL.")
            except Exception as e:
                st.error(f"Error downloading PDF: {e}")

# ----------------- Process PDF -----------------
if not st.session_state.pdf_loaded and "pdf_path" in st.session_state:
    with st.spinner("πŸ”„ Processing document... Please wait."):
        loader = PDFPlumberLoader(st.session_state.pdf_path)
        docs = loader.load()

        # Embedding Model
        model_name = "nomic-ai/modernbert-embed-base"
        embedding_model = HuggingFaceEmbeddings(model_name=model_name, model_kwargs={"device": "cpu"})

        # Split into Chunks
        text_splitter = SemanticChunker(embedding_model)
        document_chunks = text_splitter.split_documents(docs)

        # Store chunks in session state
        st.session_state.processed_chunks = document_chunks
        st.session_state.pdf_loaded = True
        st.success("βœ… Document processed and chunked successfully!")

# ----------------- Setup Vector Store  -----------------
if not st.session_state.vector_created and st.session_state.processed_chunks:
    with st.spinner("πŸ”„ Initializing Vector Store..."):
        vector_store = Chroma(
            collection_name="deepseek_collection",
            collection_metadata={"hnsw:space": "cosine"},
            embedding_function=embedding_model,
            persist_directory="./chroma_langchain_db"
        )
        vector_store.add_documents(st.session_state.processed_chunks)
        st.session_state.vector_store = vector_store
        st.session_state.vector_created = True
        st.success("βœ… Vector store initialized successfully!")

# ----------------- Query Input -----------------
query = st.text_input("πŸ” Ask a question about the document:")

if query:
    with st.spinner("πŸ”„ Retrieving relevant context..."):
        retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 5})
        retrieved_docs = retriever.invoke(query)
        context = [d.page_content for d in retrieved_docs]
        st.success("βœ… Context retrieved successfully!")

    # ----------------- Full SequentialChain Execution -----------------
    with st.spinner("πŸ”„ Running full pipeline..."):
        context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query", "context"], template=relevancy_prompt)
        relevant_prompt = PromptTemplate(input_variables=["relevancy_response"], template=relevant_context_picker_prompt)
        context_prompt = PromptTemplate(input_variables=["context_number", "context"], template=response_synth)
        final_prompt = PromptTemplate(input_variables=["query", "context"], template=rag_prompt)

        context_relevancy_chain = LLMChain(llm=llm_judge, prompt=context_relevancy_checker_prompt, output_key="relevancy_response")
        relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
        relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
        response_chain = LLMChain(llm=rag_llm, prompt=final_prompt, output_key="final_response")

        context_management_chain = SequentialChain(
            chains=[context_relevancy_chain, relevant_context_chain, relevant_contexts_chain, response_chain],
            input_variables=["context", "retriever_query", "query"],
            output_variables=["relevancy_response", "context_number", "relevant_contexts", "final_response"]
        )

        final_output = context_management_chain.invoke({"context": context, "retriever_query": query, "query": query})
        st.success("βœ… Full pipeline executed successfully!")

    # ----------------- Display All Outputs -----------------
    st.subheader("πŸŸ₯ Context Relevancy Evaluation")
    st.json(final_output["relevancy_response"])

    st.subheader("🟦 Picked Relevant Contexts")
    st.json(final_output["context_number"])

    st.subheader("πŸŸ₯ Extracted Relevant Contexts")
    st.json(final_output["relevant_contexts"])

    st.subheader("πŸŸ₯ RAG Final Response")
    st.write(final_output["final_response"])