Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,19 +5,24 @@ import faiss
|
|
| 5 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
import fitz # PyMuPDF for PDF extraction
|
|
|
|
| 8 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 9 |
|
|
|
|
| 10 |
# Configuration
|
|
|
|
| 11 |
MODEL_NAME = "ibm-granite/granite-3.1-1b-a400m-instruct"
|
| 12 |
EMBED_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
| 13 |
CHUNK_SIZE = 512
|
| 14 |
CHUNK_OVERLAP = 64
|
| 15 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
@st.cache_resource
|
| 18 |
def load_models():
|
| 19 |
try:
|
| 20 |
-
# Load tokenizer and generative model with trust_remote_code enabled
|
| 21 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 22 |
MODEL_NAME,
|
| 23 |
trust_remote_code=True,
|
|
@@ -25,25 +30,24 @@ def load_models():
|
|
| 25 |
)
|
| 26 |
model = AutoModelForCausalLM.from_pretrained(
|
| 27 |
MODEL_NAME,
|
| 28 |
-
device_map="auto" if DEVICE == "cuda" else None,
|
| 29 |
-
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
|
| 30 |
trust_remote_code=True,
|
| 31 |
revision="main",
|
|
|
|
|
|
|
| 32 |
low_cpu_mem_usage=True
|
| 33 |
).eval()
|
| 34 |
-
|
| 35 |
-
# Load embedding model for FAISS
|
| 36 |
embedder = SentenceTransformer(EMBED_MODEL, device=DEVICE)
|
| 37 |
return tokenizer, model, embedder
|
| 38 |
-
|
| 39 |
except Exception as e:
|
| 40 |
st.error(f"Model loading failed: {str(e)}")
|
| 41 |
st.stop()
|
| 42 |
|
| 43 |
tokenizer, model, embedder = load_models()
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
splitter = RecursiveCharacterTextSplitter(
|
| 48 |
chunk_size=CHUNK_SIZE,
|
| 49 |
chunk_overlap=CHUNK_OVERLAP,
|
|
@@ -51,61 +55,48 @@ def process_text(text):
|
|
| 51 |
)
|
| 52 |
return splitter.split_text(text)
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return ""
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
chunks = process_text(text)[:10] # Use first 10 chunks for summary
|
| 66 |
-
summaries = []
|
| 67 |
-
|
| 68 |
-
for chunk in chunks:
|
| 69 |
-
prompt = f"""<|user|>
|
| 70 |
-
Summarize this text section focusing on key themes, characters, and plot points:
|
| 71 |
-
{chunk[:2000]}
|
| 72 |
-
<|assistant|>
|
| 73 |
-
"""
|
| 74 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 75 |
-
outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.3)
|
| 76 |
-
summary_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 77 |
-
summaries.append(summary_text)
|
| 78 |
-
|
| 79 |
-
# Combine individual summaries into one comprehensive summary
|
| 80 |
-
combined = "\n".join(summaries)
|
| 81 |
-
final_prompt = f"""<|user|>
|
| 82 |
-
Combine these section summaries into a coherent book summary:
|
| 83 |
-
{combined}
|
| 84 |
-
<|assistant|>
|
| 85 |
-
The comprehensive summary is:"""
|
| 86 |
-
|
| 87 |
-
inputs = tokenizer(final_prompt, return_tensors="pt").to(DEVICE)
|
| 88 |
-
outputs = model.generate(**inputs, max_new_tokens=500, temperature=0.5)
|
| 89 |
-
full_summary = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 90 |
-
return full_summary.split(":")[-1].strip()
|
| 91 |
-
|
| 92 |
-
# Enhanced retrieval system using FAISS
|
| 93 |
-
def build_faiss_index(texts):
|
| 94 |
-
embeddings = embedder.encode(texts, show_progress_bar=True)
|
| 95 |
dimension = embeddings.shape[1]
|
| 96 |
index = faiss.IndexFlatIP(dimension)
|
| 97 |
faiss.normalize_L2(embeddings)
|
| 98 |
index.add(embeddings)
|
| 99 |
return index
|
| 100 |
|
| 101 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
def generate_answer(query, context):
|
| 103 |
-
prompt = f"
|
| 104 |
-
Using this context: {context}
|
| 105 |
-
Answer the question precisely and truthfully. If unsure, say "I don't know".
|
| 106 |
-
Question: {query}
|
| 107 |
-
<|assistant|>
|
| 108 |
-
"""
|
| 109 |
inputs = tokenizer(prompt, return_tensors="pt", max_length=1024, truncation=True).to(DEVICE)
|
| 110 |
outputs = model.generate(
|
| 111 |
**inputs,
|
|
@@ -115,52 +106,42 @@ Question: {query}
|
|
| 115 |
repetition_penalty=1.2,
|
| 116 |
do_sample=True
|
| 117 |
)
|
| 118 |
-
|
| 119 |
-
return
|
| 120 |
|
| 121 |
-
#
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
-
|
| 126 |
-
uploaded_file = st.file_uploader("Upload book (PDF or TXT)", type=["pdf", "txt"])
|
| 127 |
|
| 128 |
if uploaded_file:
|
| 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 |
-
faiss.normalize_L2(query_embed)
|
| 156 |
-
distances, indices = st.session_state.index.search(query_embed, k=3)
|
| 157 |
-
|
| 158 |
-
context = "\n".join([st.session_state.docs[i] for i in indices[0]])
|
| 159 |
-
answer = generate_answer(query, context)
|
| 160 |
-
|
| 161 |
-
st.subheader("Answer")
|
| 162 |
-
st.markdown(f"```\n{answer}\n```")
|
| 163 |
-
st.caption("Retrieved context confidence: {:.2f}".format(distances[0][0]))
|
| 164 |
-
|
| 165 |
-
except Exception as e:
|
| 166 |
-
st.error(f"Query failed: {str(e)}")
|
|
|
|
| 5 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 6 |
from sentence_transformers import SentenceTransformer
|
| 7 |
import fitz # PyMuPDF for PDF extraction
|
| 8 |
+
import docx2txt # For DOCX extraction
|
| 9 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 10 |
|
| 11 |
+
# ------------------------
|
| 12 |
# Configuration
|
| 13 |
+
# ------------------------
|
| 14 |
MODEL_NAME = "ibm-granite/granite-3.1-1b-a400m-instruct"
|
| 15 |
EMBED_MODEL = "sentence-transformers/all-mpnet-base-v2"
|
| 16 |
CHUNK_SIZE = 512
|
| 17 |
CHUNK_OVERLAP = 64
|
| 18 |
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 19 |
|
| 20 |
+
# ------------------------
|
| 21 |
+
# Model Loading with Caching
|
| 22 |
+
# ------------------------
|
| 23 |
@st.cache_resource
|
| 24 |
def load_models():
|
| 25 |
try:
|
|
|
|
| 26 |
tokenizer = AutoTokenizer.from_pretrained(
|
| 27 |
MODEL_NAME,
|
| 28 |
trust_remote_code=True,
|
|
|
|
| 30 |
)
|
| 31 |
model = AutoModelForCausalLM.from_pretrained(
|
| 32 |
MODEL_NAME,
|
|
|
|
|
|
|
| 33 |
trust_remote_code=True,
|
| 34 |
revision="main",
|
| 35 |
+
device_map="auto" if DEVICE == "cuda" else None,
|
| 36 |
+
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
|
| 37 |
low_cpu_mem_usage=True
|
| 38 |
).eval()
|
|
|
|
|
|
|
| 39 |
embedder = SentenceTransformer(EMBED_MODEL, device=DEVICE)
|
| 40 |
return tokenizer, model, embedder
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
st.error(f"Model loading failed: {str(e)}")
|
| 43 |
st.stop()
|
| 44 |
|
| 45 |
tokenizer, model, embedder = load_models()
|
| 46 |
|
| 47 |
+
# ------------------------
|
| 48 |
+
# Text Processing Functions
|
| 49 |
+
# ------------------------
|
| 50 |
+
def split_text(text):
|
| 51 |
splitter = RecursiveCharacterTextSplitter(
|
| 52 |
chunk_size=CHUNK_SIZE,
|
| 53 |
chunk_overlap=CHUNK_OVERLAP,
|
|
|
|
| 55 |
)
|
| 56 |
return splitter.split_text(text)
|
| 57 |
|
| 58 |
+
def extract_text(file):
|
| 59 |
+
file_type = file.type
|
| 60 |
+
if file_type == "application/pdf":
|
| 61 |
+
try:
|
| 62 |
+
doc = fitz.open(stream=file.read(), filetype="pdf")
|
| 63 |
+
return "\n".join([page.get_text() for page in doc])
|
| 64 |
+
except Exception as e:
|
| 65 |
+
st.error("Error processing PDF: " + str(e))
|
| 66 |
+
return ""
|
| 67 |
+
elif file_type == "text/plain":
|
| 68 |
+
return file.read().decode("utf-8")
|
| 69 |
+
elif file_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
|
| 70 |
+
try:
|
| 71 |
+
return docx2txt.process(file)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
st.error("Error processing DOCX: " + str(e))
|
| 74 |
+
return ""
|
| 75 |
+
else:
|
| 76 |
+
st.error("Unsupported file type: " + file_type)
|
| 77 |
return ""
|
| 78 |
|
| 79 |
+
def build_index(chunks):
|
| 80 |
+
embeddings = embedder.encode(chunks, show_progress_bar=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
dimension = embeddings.shape[1]
|
| 82 |
index = faiss.IndexFlatIP(dimension)
|
| 83 |
faiss.normalize_L2(embeddings)
|
| 84 |
index.add(embeddings)
|
| 85 |
return index
|
| 86 |
|
| 87 |
+
# ------------------------
|
| 88 |
+
# Summarization and Q&A Functions
|
| 89 |
+
# ------------------------
|
| 90 |
+
def generate_summary(text):
|
| 91 |
+
# Limit input text to avoid long sequences
|
| 92 |
+
prompt = f"<|user|>\nSummarize the following book in a concise and informative paragraph:\n\n{text[:4000]}\n<|assistant|>\n"
|
| 93 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 94 |
+
outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.5)
|
| 95 |
+
summary = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 96 |
+
return summary.split("<|assistant|>")[-1].strip() if "<|assistant|>" in summary else summary.strip()
|
| 97 |
+
|
| 98 |
def generate_answer(query, context):
|
| 99 |
+
prompt = f"<|user|>\nUsing the context below, answer the following question precisely. If unsure, say 'I don't know'.\n\nContext: {context}\n\nQuestion: {query}\n<|assistant|>\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
inputs = tokenizer(prompt, return_tensors="pt", max_length=1024, truncation=True).to(DEVICE)
|
| 101 |
outputs = model.generate(
|
| 102 |
**inputs,
|
|
|
|
| 106 |
repetition_penalty=1.2,
|
| 107 |
do_sample=True
|
| 108 |
)
|
| 109 |
+
answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 110 |
+
return answer.split("<|assistant|>")[-1].strip() if "<|assistant|>" in answer else answer.strip()
|
| 111 |
|
| 112 |
+
# ------------------------
|
| 113 |
+
# Streamlit UI
|
| 114 |
+
# ------------------------
|
| 115 |
+
st.set_page_config(page_title="RAG Book Analyzer", layout="wide")
|
| 116 |
+
st.title("RAG-Based Book Analyzer")
|
| 117 |
+
st.write("Upload a book (PDF, TXT, DOCX) to get a summary and ask questions about its content.")
|
| 118 |
|
| 119 |
+
uploaded_file = st.file_uploader("Upload File", type=["pdf", "txt", "docx"])
|
|
|
|
| 120 |
|
| 121 |
if uploaded_file:
|
| 122 |
+
text = extract_text(uploaded_file)
|
| 123 |
+
if text:
|
| 124 |
+
st.success("File successfully processed!")
|
| 125 |
+
st.write("Generating summary...")
|
| 126 |
+
summary = generate_summary(text)
|
| 127 |
+
st.markdown("### Book Summary")
|
| 128 |
+
st.write(summary)
|
| 129 |
+
|
| 130 |
+
# Process text into chunks and build FAISS index
|
| 131 |
+
chunks = split_text(text)
|
| 132 |
+
index = build_index(chunks)
|
| 133 |
+
st.session_state.chunks = chunks
|
| 134 |
+
st.session_state.index = index
|
| 135 |
+
|
| 136 |
+
st.markdown("### Ask a Question about the Book:")
|
| 137 |
+
query = st.text_input("Your Question:")
|
| 138 |
+
if query:
|
| 139 |
+
# Retrieve top 3 relevant chunks as context
|
| 140 |
+
query_embedding = embedder.encode([query])
|
| 141 |
+
faiss.normalize_L2(query_embedding)
|
| 142 |
+
distances, indices = index.search(query_embedding, k=3)
|
| 143 |
+
retrieved_chunks = [chunks[i] for i in indices[0] if i < len(chunks)]
|
| 144 |
+
context = "\n".join(retrieved_chunks)
|
| 145 |
+
answer = generate_answer(query, context)
|
| 146 |
+
st.markdown("### Answer")
|
| 147 |
+
st.write(answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|