Spaces:
Runtime error
Runtime error
File size: 7,601 Bytes
2072c53 b4fa060 2072c53 b4fa060 2072c53 b4fa060 2072c53 b4fa060 2072c53 b4fa060 2072c53 b4fa060 2072c53 b4fa060 2072c53 | 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 | import streamlit as st
from PyPDF2 import PdfReader
import os
# --- UPDATED IMPORTS (LANGCHAIN v1.1 COMPATIBLE) ---
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_huggingface import HuggingFaceEndpoint, HuggingFaceEndpointEmbeddings, ChatHuggingFace
# ... rest of your code ...
@st.cache_data
def get_pdf_text(pdf_docs):
"""
Extracts text from PDFs and creates Document objects with metadata.
Returns a list of Document objects, not a string.
"""
documents = []
for pdf in pdf_docs:
pdf_reader = PdfReader(pdf)
pdf_filename = pdf.name
for i, page in enumerate(pdf_reader.pages):
text = page.extract_text()
if text:
# Create a Document with metadata (page number starts at 1)
doc = Document(
page_content=text,
metadata={"page": i + 1, "source": pdf_filename}
)
documents.append(doc)
return documents
@st.cache_data
def get_text_chunks(documents):
"""
Splits Document objects into chunks while preserving metadata.
"""
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=2000, # 10k is often too big for precise page tracking; 2k is better
chunk_overlap=200
)
# split_documents ensures metadata (page num) is copied to new chunks
chunks = text_splitter.split_documents(documents)
return chunks
# --- Hugging Face Model Functions ---
@st.cache_resource
def get_hf_embeddings():
if "HF_API_TOKEN" not in st.secrets:
st.error("HF_API_TOKEN not found in secrets.toml.")
return None
return HuggingFaceEndpointEmbeddings(
model="BAAI/bge-small-en-v1.5",
huggingfacehub_api_token=st.secrets["HF_API_TOKEN"]
)
@st.cache_resource
def get_hf_llm():
if "HF_API_TOKEN" not in st.secrets:
return None
llm = HuggingFaceEndpoint(
huggingfacehub_api_token=st.secrets["HF_API_TOKEN"],
repo_id="mistralai/Mistral-7B-Instruct-v0.2",
# repo_id="meta-llama/Llama-3.2-3B-Instruct",
temperature=0.3,
max_new_tokens=512,
task="conversational"
)
return ChatHuggingFace(llm=llm)
# --- Vector Store Functions (UPDATED) ---
def get_vector_store(text_chunks):
"""Creates FAISS vector store from Document objects."""
if not text_chunks:
st.error("No text chunks found.")
return
embeddings = get_hf_embeddings()
if embeddings is None:
return
try:
# Use from_documents instead of from_texts to keep metadata
vector_store = FAISS.from_documents(documents=text_chunks, embedding=embeddings)
vector_store.save_local("faiss_index")
st.success("Vector store created and saved locally.")
except Exception as e:
st.error(f"Error creating vector store: {e}")
def load_faiss_index():
try:
embeddings = get_hf_embeddings()
if embeddings is None:
return None
db = FAISS.load_local(
"faiss_index",
embeddings,
allow_dangerous_deserialization=True
)
return db
except Exception as e:
# Silent fail on startup if index doesn't exist yet
return None
# --- Conversational Chain ---
def get_conversational_chain():
model = get_hf_llm()
if model is None:
return None
system_prompt = """
You are a helpful AI assistant answering questions based on PDF documents.
If the answer is not in the context, say you don't know and do not give any text about the question, just say "I don't know."
Context:
{context}
**Note:** please do not answer questions that are not related to the context provided. If the context does not contain the answer, respond with "I don't know."
"""
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt),
# The user's question will be passed here as the "human" message
("human", "Question: {input}")
])
# Create a simple chain using the pipe operator (|)
chain = prompt | model
return chain
# --- User Input Handler (UPDATED) ---
def user_input(user_question, db):
if db is None:
st.warning("Vector store is not loaded.")
return
try:
# 1. Get relevant documents
docs = db.similarity_search(user_question, k=4)
# 2. Get the response
chain = get_conversational_chain()
if chain is None:
st.error("Check API Key")
return
response = chain.invoke({
"context": docs,
"input": user_question
})
# 3. Display Response
st.markdown("### Reply:")
# Extract just the content text from the response
if hasattr(response, 'content'):
# Response is an AIMessage object
st.write(response.content)
elif isinstance(response, dict) and "answer" in response:
st.write(response["answer"])
elif isinstance(response, dict) and "content" in response:
st.write(response["content"])
else:
# Try to get string representation
st.write(str(response))
# # 4. Display Page Numbers (New Feature)
# st.markdown("---")
# st.markdown("#### 📄 Source Pages:")
# # Use a set to avoid duplicate page numbers
# unique_sources = set()
# for doc in docs:
# page_num = doc.metadata.get("page", "Unknown")
# file_name = doc.metadata.get("source", "Unknown")
# unique_sources.add(f"{file_name} (Page {page_num})")
# # Display sources cleanly
# for source in unique_sources:
# st.markdown(f"- {source}")
except Exception as e:
st.error(f"Error: {e}")
# --- Main App ---
def main():
st.set_page_config(page_title="Chat PDF (Hugging Face)")
st.header("Chat with PDF using mistralai/Mistral-7B-Instruct-v0.2")
if "faiss_db" not in st.session_state:
st.session_state.faiss_db = None
# Attempt to load index on launch
if st.session_state.faiss_db is None and os.path.exists("faiss_index"):
st.session_state.faiss_db = load_faiss_index()
with st.sidebar:
st.title("Menu:")
pdf_docs = st.file_uploader("Upload PDFs", accept_multiple_files=True)
if st.button("Process PDFs"):
if pdf_docs:
with st.spinner("Processing..."):
# 1. Get Documents (not string)
raw_documents = get_pdf_text(pdf_docs)
# 2. Split Documents (preserves metadata)
text_chunks = get_text_chunks(raw_documents)
# 3. Create Vector Store
get_vector_store(text_chunks)
st.session_state.faiss_db = load_faiss_index()
else:
st.warning("Upload a PDF first.")
user_question = st.text_input("Ask a Question")
if user_question:
if st.session_state.faiss_db:
user_input(user_question, st.session_state.faiss_db)
else:
st.warning("Process PDFs first.")
if __name__ == "__main__":
main() |