DrishtiSharma commited on
Commit
5ea6ce5
Β·
verified Β·
1 Parent(s): d00d31a

Create metadata_fixed.py

Browse files
Files changed (1) hide show
  1. lab/metadata_fixed.py +148 -0
lab/metadata_fixed.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import requests
4
+ import chromadb
5
+ import pdfplumber
6
+ from langchain.document_loaders import PDFPlumberLoader
7
+ from langchain_huggingface import HuggingFaceEmbeddings
8
+ from langchain_experimental.text_splitter import SemanticChunker
9
+ from langchain_chroma import Chroma
10
+ from langchain.chains import LLMChain
11
+ from langchain.prompts import PromptTemplate
12
+ from langchain_groq import ChatGroq
13
+ from prompts import rag_prompt, relevancy_prompt, relevant_context_picker_prompt, response_synth
14
+
15
+ # ----------------- Streamlit UI Setup -----------------
16
+ st.set_page_config(page_title="Blah", layout="centered")
17
+ st.title("Blah-1")
18
+
19
+ # ----------------- API Keys -----------------
20
+ os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
21
+ os.environ["HF_TOKEN"] = st.secrets.get("HF_TOKEN", "")
22
+
23
+ # ----------------- Clear ChromaDB Cache -----------------
24
+ chromadb.api.client.SharedSystemClient.clear_system_cache()
25
+
26
+ # ----------------- Initialize Session State -----------------
27
+ if "pdf_loaded" not in st.session_state:
28
+ st.session_state.pdf_loaded = False
29
+ if "chunked" not in st.session_state:
30
+ st.session_state.chunked = False
31
+ if "vector_created" not in st.session_state:
32
+ st.session_state.vector_created = False
33
+ if "processed_chunks" not in st.session_state:
34
+ st.session_state.processed_chunks = None
35
+ if "vector_store" not in st.session_state:
36
+ st.session_state.vector_store = None
37
+
38
+ # ----------------- Function to Extract PDF Title -----------------
39
+ def extract_pdf_title(pdf_path):
40
+ """Extract title from PDF metadata or first page."""
41
+ try:
42
+ with pdfplumber.open(pdf_path) as pdf:
43
+ first_page = pdf.pages[0]
44
+ text = first_page.extract_text()
45
+ return text.split("\n")[0] if text else "Untitled Document"
46
+ except Exception as e:
47
+ return "Untitled Document"
48
+
49
+ # ----------------- PDF Selection (Upload or URL) -----------------
50
+ st.subheader("πŸ“‚ PDF Selection")
51
+ pdf_source = st.radio("Choose a PDF source:", ["Upload a PDF file", "Enter a PDF URL"], index=0, horizontal=True)
52
+
53
+ if pdf_source == "Upload a PDF file":
54
+ uploaded_file = st.file_uploader("Upload your PDF file", type=["pdf"])
55
+ if uploaded_file:
56
+ st.session_state.pdf_path = "temp.pdf"
57
+ with open(st.session_state.pdf_path, "wb") as f:
58
+ f.write(uploaded_file.getbuffer())
59
+ st.session_state.pdf_loaded = False
60
+ st.session_state.chunked = False
61
+ st.session_state.vector_created = False
62
+
63
+ elif pdf_source == "Enter a PDF URL":
64
+ pdf_url = st.text_input("Enter PDF URL:")
65
+ if pdf_url and not st.session_state.pdf_loaded:
66
+ with st.spinner("πŸ”„ Downloading PDF..."):
67
+ try:
68
+ response = requests.get(pdf_url)
69
+ if response.status_code == 200:
70
+ st.session_state.pdf_path = "temp.pdf"
71
+ with open(st.session_state.pdf_path, "wb") as f:
72
+ f.write(response.content)
73
+ st.session_state.pdf_loaded = False
74
+ st.session_state.chunked = False
75
+ st.session_state.vector_created = False
76
+ st.success("βœ… PDF Downloaded Successfully!")
77
+ else:
78
+ st.error("❌ Failed to download PDF. Check the URL.")
79
+ except Exception as e:
80
+ st.error(f"Error downloading PDF: {e}")
81
+
82
+ # ----------------- Process PDF -----------------
83
+ if not st.session_state.pdf_loaded and "pdf_path" in st.session_state:
84
+ with st.spinner("πŸ”„ Processing document... Please wait."):
85
+ loader = PDFPlumberLoader(st.session_state.pdf_path)
86
+ docs = loader.load()
87
+
88
+ # Extract metadata
89
+ metadata = docs[0].metadata
90
+
91
+ # Try to get title from metadata, fallback to first page
92
+ title = metadata.get("Title", "").strip() if metadata.get("Title") else extract_pdf_title(st.session_state.pdf_path)
93
+
94
+ # Display Title
95
+ st.subheader(f"πŸ“„ Document Title: {title}")
96
+
97
+ # Debugging: Show metadata
98
+ st.json(metadata)
99
+
100
+ # Embedding Model (HF on CPU)
101
+ model_name = "nomic-ai/modernbert-embed-base"
102
+ embedding_model = HuggingFaceEmbeddings(model_name=model_name, model_kwargs={"device": "cpu"})
103
+
104
+ # Prevent unnecessary re-chunking
105
+ if not st.session_state.chunked:
106
+ text_splitter = SemanticChunker(embedding_model)
107
+ document_chunks = text_splitter.split_documents(docs)
108
+ st.session_state.processed_chunks = document_chunks
109
+ st.session_state.chunked = True
110
+
111
+ st.session_state.pdf_loaded = True
112
+ st.success("βœ… Document processed and chunked successfully!")
113
+
114
+ # ----------------- Setup Vector Store -----------------
115
+ if not st.session_state.vector_created and st.session_state.processed_chunks:
116
+ with st.spinner("πŸ”„ Initializing Vector Store..."):
117
+ st.session_state.vector_store = Chroma(
118
+ collection_name="deepseek_collection",
119
+ collection_metadata={"hnsw:space": "cosine"},
120
+ embedding_function=embedding_model
121
+ )
122
+ st.session_state.vector_store.add_documents(st.session_state.processed_chunks)
123
+ st.session_state.vector_created = True
124
+ st.success("βœ… Vector store initialized successfully!")
125
+
126
+ # ----------------- Query Input -----------------
127
+ query = st.text_input("πŸ” Ask a question about the document:")
128
+
129
+ if query:
130
+ with st.spinner("πŸ”„ Retrieving relevant context..."):
131
+ retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 5})
132
+ retrieved_docs = retriever.invoke(query)
133
+ context = [d.page_content for d in retrieved_docs]
134
+ st.success("βœ… Context retrieved successfully!")
135
+
136
+ # ----------------- Run Individual Chains Explicitly -----------------
137
+ context_relevancy_chain = LLMChain(llm=ChatGroq(model="deepseek-r1-distill-llama-70b"), prompt=PromptTemplate(input_variables=["retriever_query", "context"], template=relevancy_prompt), output_key="relevancy_response")
138
+ response_chain = LLMChain(llm=ChatGroq(model="mixtral-8x7b-32768"), prompt=PromptTemplate(input_variables=["query", "context"], template=rag_prompt), output_key="final_response")
139
+
140
+ response_crisis = context_relevancy_chain.invoke({"context": context, "retriever_query": query})
141
+ final_response = response_chain.invoke({"query": query, "context": context})
142
+
143
+ # ----------------- Display All Outputs -----------------
144
+ st.markdown("### 🟦 Picked Relevant Contexts")
145
+ st.json(response_crisis["relevancy_response"])
146
+
147
+ st.markdown("## πŸŸ₯ RAG Final Response")
148
+ st.write(final_response["final_response"])