sunbal7 commited on
Commit
59f49c7
Β·
verified Β·
1 Parent(s): 4e52c88

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -94
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 PyPDF2
 
8
 
9
- # Model Setup
10
- device = "cuda" if torch.cuda.is_available() else "cpu"
11
- model_path = "ibm-granite/granite-3.1-1b-a400m-instruct"
12
- tokenizer = AutoTokenizer.from_pretrained(model_path)
 
 
13
 
14
- # Load the model with a conditional to avoid meta tensor issues on CPU vs GPU
15
- if device == "cpu":
16
- model = AutoModelForCausalLM.from_pretrained(model_path)
17
- else:
18
- model = AutoModelForCausalLM.from_pretrained(
19
- model_path,
20
- device_map="auto",
21
- low_cpu_mem_usage=True,
22
- torch_dtype=torch.float16,
23
- )
24
- model.eval()
25
 
26
- # Embedding Model for FAISS
27
- embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- # FAISS Index
30
- dimension = 384 # Embedding size for MiniLM
31
- index = faiss.IndexFlatL2(dimension)
32
- docs = [] # Store document texts
33
- summary = "" # Store book summary
34
 
35
- # Function to extract text from PDF
36
- def extract_text_from_pdf(uploaded_file):
37
- reader = PyPDF2.PdfReader(uploaded_file)
38
- text = "\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
39
- return text
 
 
 
40
 
41
- # Function to process uploaded documents and generate summary
42
- def process_documents(files):
43
- global docs, index, summary
44
- docs = []
 
 
 
 
 
 
 
 
 
45
 
46
- for file in files:
47
- if file.type == "application/pdf":
48
- text = extract_text_from_pdf(file)
49
- else:
50
- text = file.getvalue().decode("utf-8")
51
- docs.append(text)
 
 
 
 
52
 
53
- embeddings = embedding_model.encode(docs)
54
- index.add(np.array(embeddings))
 
 
 
 
 
55
 
56
- # Generate summary after processing documents
57
- summary = generate_summary("\n".join(docs))
 
58
 
59
- # Function to generate a book summary
60
- def generate_summary(text):
61
- chat = [
62
- {"role": "system", "content": "You are a helpful AI that summarizes books."},
63
- {"role": "user", "content": f"Summarize this book in a short paragraph:\n{text[:4000]}"} # Limiting input size for summarization
64
- ]
65
- chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
66
- input_tokens = tokenizer(chat, return_tensors="pt").to(device)
67
- output = model.generate(**input_tokens, max_new_tokens=300)
68
- return tokenizer.batch_decode(output, skip_special_tokens=True)[0]
69
 
70
- # Function to retrieve relevant context using FAISS
71
- def retrieve_context(query):
72
- if index.ntotal == 0:
73
- return "No documents available. Please upload files first."
 
 
 
 
74
 
75
- query_embedding = embedding_model.encode([query])
76
- distances, indices = index.search(np.array(query_embedding), k=1)
77
-
78
- if len(indices) == 0 or indices[0][0] >= len(docs):
79
- return "No relevant context found."
80
- return docs[indices[0][0]]
81
-
82
- # Function to generate response using IBM Granite model
83
- def generate_response(query, context):
84
- chat = [
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="πŸ“– AI Book Assistant", page_icon="πŸ“š")
95
- st.title("πŸ“– AI-Powered Book Assistant")
96
- st.subheader("Upload a book and get its summary or ask questions!")
97
 
98
- uploaded_file = st.file_uploader("Upload a book (PDF or TXT)", accept_multiple_files=False)
99
 
100
  if uploaded_file:
101
- with st.spinner("Processing book and generating summary..."):
102
- process_documents([uploaded_file])
103
- st.success("Book uploaded and processed!")
104
- st.markdown("### πŸ“š Book Summary:")
105
- st.write(summary)
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- query = st.text_input("Ask a question about the book:")
108
- if st.button("Get Answer"):
109
- if index.ntotal == 0:
110
- st.warning("Please upload a book first!")
111
- else:
112
- with st.spinner("Retrieving and generating response..."):
113
- context = retrieve_context(query)
114
- response = generate_response(query, context)
115
- st.markdown("### πŸ€– Answer:")
116
- st.write(response)
 
 
 
 
 
 
 
 
 
 
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)}")