Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,116 +1,163 @@
|
|
1 |
import streamlit as st
|
2 |
import torch
|
3 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
-
import faiss
|
5 |
import numpy as np
|
|
|
|
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
-
import
|
|
|
8 |
|
9 |
-
#
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
13 |
|
14 |
-
#
|
15 |
-
if
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
model_path,
|
20 |
-
device_map="auto",
|
21 |
-
low_cpu_mem_usage=True,
|
22 |
-
torch_dtype=torch.float16,
|
23 |
-
)
|
24 |
-
model.eval()
|
25 |
|
26 |
-
#
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
-
|
30 |
-
dimension = 384 # Embedding size for MiniLM
|
31 |
-
index = faiss.IndexFlatL2(dimension)
|
32 |
-
docs = [] # Store document texts
|
33 |
-
summary = "" # Store book summary
|
34 |
|
35 |
-
#
|
36 |
-
def
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
40 |
|
41 |
-
#
|
42 |
-
def
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
-
for
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
|
|
|
|
|
|
|
|
52 |
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
57 |
-
|
|
|
58 |
|
59 |
-
#
|
60 |
-
def
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
output = model.generate(**input_tokens, max_new_tokens=300)
|
68 |
-
return tokenizer.batch_decode(output, skip_special_tokens=True)[0]
|
69 |
|
70 |
-
#
|
71 |
-
def
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
{"role": "system", "content": "You are a helpful assistant using retrieved knowledge."},
|
86 |
-
{"role": "user", "content": f"Context: {context}\nQuestion: {query}\nAnswer based on context:"},
|
87 |
-
]
|
88 |
-
chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
89 |
-
input_tokens = tokenizer(chat, return_tensors="pt").to(device)
|
90 |
-
output = model.generate(**input_tokens, max_new_tokens=200)
|
91 |
-
return tokenizer.batch_decode(output, skip_special_tokens=True)[0]
|
92 |
|
93 |
# Streamlit UI
|
94 |
-
st.set_page_config(page_title="
|
95 |
-
st.title("
|
96 |
-
st.subheader("Upload a book and get its summary or ask questions!")
|
97 |
|
98 |
-
uploaded_file = st.file_uploader("Upload
|
99 |
|
100 |
if uploaded_file:
|
101 |
-
with st.spinner("
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
if
|
110 |
-
st.
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import torch
|
|
|
|
|
3 |
import numpy as np
|
4 |
+
import faiss
|
5 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
from sentence_transformers import SentenceTransformer
|
7 |
+
import fitz # PyMuPDF for better 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 |
+
# Initialize session state
|
18 |
+
if "docs" not in st.session_state:
|
19 |
+
st.session_state.docs = []
|
20 |
+
if "index" not in st.session_state:
|
21 |
+
st.session_state.index = None
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
# Model loading with better error handling
|
24 |
+
@st.cache_resource
|
25 |
+
def load_models():
|
26 |
+
try:
|
27 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
28 |
+
|
29 |
+
model = AutoModelForCausalLM.from_pretrained(
|
30 |
+
MODEL_NAME,
|
31 |
+
device_map="auto" if DEVICE == "cuda" else None,
|
32 |
+
torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
|
33 |
+
low_cpu_mem_usage=True
|
34 |
+
).eval()
|
35 |
+
|
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 |
+
# Improved text processing
|
46 |
+
def process_text(text):
|
47 |
+
splitter = RecursiveCharacterTextSplitter(
|
48 |
+
chunk_size=CHUNK_SIZE,
|
49 |
+
chunk_overlap=CHUNK_OVERLAP,
|
50 |
+
length_function=len
|
51 |
+
)
|
52 |
+
return splitter.split_text(text)
|
53 |
|
54 |
+
# Enhanced PDF extraction
|
55 |
+
def extract_pdf_text(uploaded_file):
|
56 |
+
try:
|
57 |
+
doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
|
58 |
+
return "\n".join([page.get_text() for page in doc])
|
59 |
+
except Exception as e:
|
60 |
+
st.error(f"PDF extraction error: {str(e)}")
|
61 |
+
return ""
|
62 |
+
|
63 |
+
# Multi-step summarization
|
64 |
+
def generate_summary(text):
|
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 |
+
|
75 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
76 |
+
outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.3)
|
77 |
+
summaries.append(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
78 |
|
79 |
+
# Combine summaries
|
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 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True).split(":")[-1].strip()
|
90 |
|
91 |
+
# Enhanced retrieval system
|
92 |
+
def build_faiss_index(texts):
|
93 |
+
embeddings = embedder.encode(texts, show_progress_bar=True)
|
94 |
+
dimension = embeddings.shape[1]
|
95 |
+
index = faiss.IndexFlatIP(dimension)
|
96 |
+
faiss.normalize_L2(embeddings)
|
97 |
+
index.add(embeddings)
|
98 |
+
return index
|
|
|
|
|
99 |
|
100 |
+
# Context-aware generation
|
101 |
+
def generate_answer(query, context):
|
102 |
+
prompt = f"""<|user|>
|
103 |
+
Using this context: {context}
|
104 |
+
Answer the question precisely and truthfully. If unsure, say "I don't know".
|
105 |
+
Question: {query}
|
106 |
+
<|assistant|>
|
107 |
+
"""
|
108 |
|
109 |
+
inputs = tokenizer(prompt, return_tensors="pt", max_length=1024, truncation=True).to(DEVICE)
|
110 |
+
outputs = model.generate(
|
111 |
+
**inputs,
|
112 |
+
max_new_tokens=300,
|
113 |
+
temperature=0.4,
|
114 |
+
top_p=0.9,
|
115 |
+
repetition_penalty=1.2,
|
116 |
+
do_sample=True
|
117 |
+
)
|
118 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True).split("<|assistant|>")[-1].strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
# Streamlit UI
|
121 |
+
st.set_page_config(page_title="π Smart Book Analyst", layout="wide")
|
122 |
+
st.title("π AI-Powered Book Analysis System")
|
|
|
123 |
|
124 |
+
uploaded_file = st.file_uploader("Upload book (PDF or TXT)", type=["pdf", "txt"])
|
125 |
|
126 |
if uploaded_file:
|
127 |
+
with st.spinner("π Analyzing book content..."):
|
128 |
+
try:
|
129 |
+
if uploaded_file.type == "application/pdf":
|
130 |
+
text = extract_pdf_text(uploaded_file)
|
131 |
+
else:
|
132 |
+
text = uploaded_file.read().decode()
|
133 |
+
|
134 |
+
chunks = process_text(text)
|
135 |
+
st.session_state.docs = chunks
|
136 |
+
st.session_state.index = build_faiss_index(chunks)
|
137 |
+
|
138 |
+
with st.expander("π Book Summary", expanded=True):
|
139 |
+
summary = generate_summary(text)
|
140 |
+
st.write(summary)
|
141 |
+
|
142 |
+
except Exception as e:
|
143 |
+
st.error(f"Processing failed: {str(e)}")
|
144 |
|
145 |
+
if st.session_state.index:
|
146 |
+
query = st.text_input("Ask about the book:")
|
147 |
+
if query:
|
148 |
+
with st.spinner("π Searching for answers..."):
|
149 |
+
try:
|
150 |
+
# Retrieve top 3 relevant chunks
|
151 |
+
query_embed = embedder.encode([query])
|
152 |
+
faiss.normalize_L2(query_embed)
|
153 |
+
distances, indices = st.session_state.index.search(query_embed, k=3)
|
154 |
+
|
155 |
+
context = "\n".join([st.session_state.docs[i] for i in indices[0]])
|
156 |
+
answer = generate_answer(query, context)
|
157 |
+
|
158 |
+
st.subheader("Answer")
|
159 |
+
st.markdown(f"```\n{answer}\n```")
|
160 |
+
st.caption("Retrieved context confidence: {:.2f}".format(distances[0][0]))
|
161 |
+
|
162 |
+
except Exception as e:
|
163 |
+
st.error(f"Query failed: {str(e)}")
|