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
|
| 6 |
+
from sentence_transformers import SentenceTransformer, util
|
| 7 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 8 |
+
from tqdm.auto import tqdm
|
| 9 |
+
import textwrap
|
| 10 |
+
import re
|
| 11 |
+
import pandas as pd
|
| 12 |
+
|
| 13 |
+
# Configuration
|
| 14 |
+
MODEL_NAME = "all-mpnet-base-v2"
|
| 15 |
+
LLM_MODEL_ID = "google/gemma-2b-it"
|
| 16 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 17 |
+
NUM_RESULTS = 5
|
| 18 |
+
MIN_TOKEN_LENGTH = 30
|
| 19 |
+
|
| 20 |
+
# Initialize session state
|
| 21 |
+
if 'processed' not in st.session_state:
|
| 22 |
+
st.session_state.processed = False
|
| 23 |
+
if 'embeddings' not in st.session_state:
|
| 24 |
+
st.session_state.embeddings = None
|
| 25 |
+
if 'pages_and_chunks' not in st.session_state:
|
| 26 |
+
st.session_state.pages_and_chunks = []
|
| 27 |
+
|
| 28 |
+
# Helper functions
|
| 29 |
+
def text_formatter(text: str) -> str:
|
| 30 |
+
cleaned_text = text.replace("\n", " ").strip()
|
| 31 |
+
cleaned_text = re.sub(r'\s+', ' ', cleaned_text)
|
| 32 |
+
return cleaned_text
|
| 33 |
+
|
| 34 |
+
def split_list(input_list: list, slice_size: int = 10) -> list[list[str]]:
|
| 35 |
+
return [input_list[i:i + slice_size] for i in range(0, len(input_list), slice_size)]
|
| 36 |
+
|
| 37 |
+
def print_wrapped(text, wrap_length=80):
|
| 38 |
+
wrapped_text = textwrap.fill(text, wrap_length)
|
| 39 |
+
return wrapped_text
|
| 40 |
+
|
| 41 |
+
# PDF Processing
|
| 42 |
+
def process_pdf(uploaded_file):
|
| 43 |
+
doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
|
| 44 |
+
pages_and_texts = []
|
| 45 |
+
|
| 46 |
+
with st.spinner("Processing PDF..."):
|
| 47 |
+
for page_number, page in tqdm(enumerate(doc)):
|
| 48 |
+
text = page.get_text()
|
| 49 |
+
text = text_formatter(text)
|
| 50 |
+
pages_and_texts.append({
|
| 51 |
+
"page_number": page_number,
|
| 52 |
+
"text": text,
|
| 53 |
+
"char_count": len(text),
|
| 54 |
+
"word_count": len(text.split(" ")),
|
| 55 |
+
"token_count": len(text)/4
|
| 56 |
+
})
|
| 57 |
+
|
| 58 |
+
with st.spinner("Chunking text..."):
|
| 59 |
+
nlp = English()
|
| 60 |
+
nlp.add_pipe("sentencizer")
|
| 61 |
+
for item in tqdm(pages_and_texts):
|
| 62 |
+
item['sentences'] = [str(s) for s in nlp(item["text"]).sents]
|
| 63 |
+
item["sentence_chunks"] = split_list(item["sentences"])
|
| 64 |
+
|
| 65 |
+
pages_and_chunks = []
|
| 66 |
+
for item in tqdm(pages_and_texts):
|
| 67 |
+
for sentence_chunk in item["sentence_chunks"]:
|
| 68 |
+
chunk_dict = {
|
| 69 |
+
"page_number": item["page_number"],
|
| 70 |
+
"sentence_chunk": " ".join(sentence_chunk).replace(" ", " ").strip()
|
| 71 |
+
}
|
| 72 |
+
chunk_dict["chunk_token_count"] = len(chunk_dict["sentence_chunk"])/4
|
| 73 |
+
pages_and_chunks.append(chunk_dict)
|
| 74 |
+
|
| 75 |
+
return [c for c in pages_and_chunks if c["chunk_token_count"] > MIN_TOKEN_LENGTH]
|
| 76 |
+
|
| 77 |
+
# Model Loading
|
| 78 |
+
@st.cache_resource
|
| 79 |
+
def load_models():
|
| 80 |
+
embedding_model = SentenceTransformer(MODEL_NAME, device=DEVICE)
|
| 81 |
+
|
| 82 |
+
# LLM Model setup
|
| 83 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 84 |
+
tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID)
|
| 85 |
+
llm_model = AutoModelForCausalLM.from_pretrained(
|
| 86 |
+
LLM_MODEL_ID,
|
| 87 |
+
quantization_config=quantization_config,
|
| 88 |
+
device_map="auto"
|
| 89 |
+
)
|
| 90 |
+
return embedding_model, tokenizer, llm_model
|
| 91 |
+
|
| 92 |
+
# Streamlit UI
|
| 93 |
+
st.title("PDF Knowledge Assistant 📚")
|
| 94 |
+
st.markdown("Upload a PDF document and ask questions about its content")
|
| 95 |
+
|
| 96 |
+
# Sidebar for PDF Upload
|
| 97 |
+
with st.sidebar:
|
| 98 |
+
st.header("Document Setup")
|
| 99 |
+
uploaded_file = st.file_uploader("Upload PDF", type=["pdf"])
|
| 100 |
+
if uploaded_file:
|
| 101 |
+
if not st.session_state.processed:
|
| 102 |
+
st.session_state.pages_and_chunks = process_pdf(uploaded_file)
|
| 103 |
+
embedding_model, _, _ = load_models()
|
| 104 |
+
|
| 105 |
+
with st.spinner("Generating embeddings..."):
|
| 106 |
+
texts = [c["sentence_chunk"] for c in st.session_state.pages_and_chunks]
|
| 107 |
+
st.session_state.embeddings = torch.tensor(
|
| 108 |
+
embedding_model.encode(texts, convert_to_tensor=True),
|
| 109 |
+
device=DEVICE
|
| 110 |
+
)
|
| 111 |
+
st.session_state.processed = True
|
| 112 |
+
|
| 113 |
+
# Main Q&A Interface
|
| 114 |
+
if st.session_state.processed:
|
| 115 |
+
query = st.text_input("Enter your question about the document:")
|
| 116 |
+
|
| 117 |
+
if query:
|
| 118 |
+
embedding_model, tokenizer, llm_model = load_models()
|
| 119 |
+
|
| 120 |
+
# Retrieve relevant chunks
|
| 121 |
+
query_embedding = embedding_model.encode(query, convert_to_tensor=True)
|
| 122 |
+
scores = util.dot_score(query_embedding, st.session_state.embeddings)[0]
|
| 123 |
+
top_results = torch.topk(scores, k=NUM_RESULTS)
|
| 124 |
+
|
| 125 |
+
# Display relevant passages
|
| 126 |
+
st.subheader("Most Relevant Passages:")
|
| 127 |
+
for score, idx in zip(top_results[0], top_results[1]):
|
| 128 |
+
with st.expander(f"Relevance: {score:.2f}"):
|
| 129 |
+
st.write(st.session_state.pages_and_chunks[idx]["sentence_chunk"])
|
| 130 |
+
st.caption(f"Page: {st.session_state.pages_and_chunks[idx]['page_number']+1}")
|
| 131 |
+
|
| 132 |
+
# Generate answer
|
| 133 |
+
with st.spinner("Generating answer..."):
|
| 134 |
+
context = [st.session_state.pages_and_chunks[i] for i in top_results[1]]
|
| 135 |
+
prompt = f"""
|
| 136 |
+
Answer this question: {query}
|
| 137 |
+
Using information from these passages:
|
| 138 |
+
{" ".join([c['sentence_chunk'] for c in context])}
|
| 139 |
+
Keep answers technical and specific to the document content.
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 143 |
+
outputs = llm_model.generate(**inputs, max_new_tokens=500)
|
| 144 |
+
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 145 |
+
|
| 146 |
+
st.subheader("Generated Answer:")
|
| 147 |
+
st.write(print_wrapped(answer.split("Answer:")[-1].strip()))
|
| 148 |
+
else:
|
| 149 |
+
st.info("Please upload a PDF document to get started")
|