sunbal7 commited on
Commit
685e53c
Β·
verified Β·
1 Parent(s): bf18560

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -49
app.py CHANGED
@@ -4,24 +4,25 @@ 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
-
11
  # Configuration
12
  MODEL_NAME = "ibm-granite/granite-3.1-1b-a400m-instruct"
 
 
 
13
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
14
 
15
  @st.cache_resource
16
- def load_model():
17
  try:
18
- # Load with explicit configuration
19
  tokenizer = AutoTokenizer.from_pretrained(
20
  MODEL_NAME,
21
  trust_remote_code=True,
22
  revision="main"
23
  )
24
-
25
  model = AutoModelForCausalLM.from_pretrained(
26
  MODEL_NAME,
27
  device_map="auto" if DEVICE == "cuda" else None,
@@ -29,26 +30,9 @@ def load_model():
29
  trust_remote_code=True,
30
  revision="main",
31
  low_cpu_mem_usage=True
32
- )
33
- return model, tokenizer
34
- except Exception as e:
35
- st.error(f"Model loading failed: {str(e)}")
36
- st.stop()
37
-
38
- model, tokenizer = load_model()
39
-
40
-
41
- def load_models():
42
- try:
43
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
44
-
45
- model = AutoModelForCausalLM.from_pretrained(
46
- MODEL_NAME,
47
- device_map="auto" if DEVICE == "cuda" else None,
48
- torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
49
- low_cpu_mem_usage=True
50
  ).eval()
51
 
 
52
  embedder = SentenceTransformer(EMBED_MODEL, device=DEVICE)
53
  return tokenizer, model, embedder
54
 
@@ -58,7 +42,7 @@ def load_models():
58
 
59
  tokenizer, model, embedder = load_models()
60
 
61
- # Improved text processing
62
  def process_text(text):
63
  splitter = RecursiveCharacterTextSplitter(
64
  chunk_size=CHUNK_SIZE,
@@ -67,7 +51,7 @@ def process_text(text):
67
  )
68
  return splitter.split_text(text)
69
 
70
- # Enhanced PDF extraction
71
  def extract_pdf_text(uploaded_file):
72
  try:
73
  doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
@@ -83,28 +67,29 @@ def generate_summary(text):
83
 
84
  for chunk in chunks:
85
  prompt = f"""<|user|>
86
- Summarize this text section focusing on key themes, characters, and plot points:
87
- {chunk[:2000]}
88
- <|assistant|>
89
- """
90
-
91
  inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
92
  outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.3)
93
- summaries.append(tokenizer.decode(outputs[0], skip_special_tokens=True))
 
94
 
95
- # Combine summaries
96
  combined = "\n".join(summaries)
97
  final_prompt = f"""<|user|>
98
- Combine these section summaries into a coherent book summary:
99
- {combined}
100
- <|assistant|>
101
- The comprehensive summary is:"""
102
 
103
  inputs = tokenizer(final_prompt, return_tensors="pt").to(DEVICE)
104
  outputs = model.generate(**inputs, max_new_tokens=500, temperature=0.5)
105
- return tokenizer.decode(outputs[0], skip_special_tokens=True).split(":")[-1].strip()
 
106
 
107
- # Enhanced retrieval system
108
  def build_faiss_index(texts):
109
  embeddings = embedder.encode(texts, show_progress_bar=True)
110
  dimension = embeddings.shape[1]
@@ -113,15 +98,14 @@ def build_faiss_index(texts):
113
  index.add(embeddings)
114
  return index
115
 
116
- # Context-aware generation
117
  def generate_answer(query, context):
118
  prompt = f"""<|user|>
119
- Using this context: {context}
120
- Answer the question precisely and truthfully. If unsure, say "I don't know".
121
- Question: {query}
122
- <|assistant|>
123
- """
124
-
125
  inputs = tokenizer(prompt, return_tensors="pt", max_length=1024, truncation=True).to(DEVICE)
126
  outputs = model.generate(
127
  **inputs,
@@ -131,12 +115,14 @@ def generate_answer(query, context):
131
  repetition_penalty=1.2,
132
  do_sample=True
133
  )
134
- return tokenizer.decode(outputs[0], skip_special_tokens=True).split("<|assistant|>")[-1].strip()
 
135
 
136
- # Streamlit UI
137
  st.set_page_config(page_title="πŸ“š Smart Book Analyst", layout="wide")
138
  st.title("πŸ“š AI-Powered Book Analysis System")
139
 
 
140
  uploaded_file = st.file_uploader("Upload book (PDF or TXT)", type=["pdf", "txt"])
141
 
142
  if uploaded_file:
@@ -158,7 +144,8 @@ if uploaded_file:
158
  except Exception as e:
159
  st.error(f"Processing failed: {str(e)}")
160
 
161
- if st.session_state.index:
 
162
  query = st.text_input("Ask about the book:")
163
  if query:
164
  with st.spinner("πŸ” Searching for answers..."):
@@ -176,4 +163,4 @@ if st.session_state.index:
176
  st.caption("Retrieved context confidence: {:.2f}".format(distances[0][0]))
177
 
178
  except Exception as e:
179
- st.error(f"Query failed: {str(e)}")
 
4
  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,
24
  revision="main"
25
  )
 
26
  model = AutoModelForCausalLM.from_pretrained(
27
  MODEL_NAME,
28
  device_map="auto" if DEVICE == "cuda" else None,
 
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
 
 
42
 
43
  tokenizer, model, embedder = load_models()
44
 
45
+ # Improved text processing: splits text into chunks
46
  def process_text(text):
47
  splitter = RecursiveCharacterTextSplitter(
48
  chunk_size=CHUNK_SIZE,
 
51
  )
52
  return splitter.split_text(text)
53
 
54
+ # Enhanced PDF extraction using PyMuPDF
55
  def extract_pdf_text(uploaded_file):
56
  try:
57
  doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
 
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]
 
98
  index.add(embeddings)
99
  return index
100
 
101
+ # Context-aware answer generation
102
  def generate_answer(query, context):
103
  prompt = f"""<|user|>
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
  repetition_penalty=1.2,
116
  do_sample=True
117
  )
118
+ answer_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
119
+ return answer_text.split("<|assistant|>")[-1].strip()
120
 
121
+ # Streamlit UI setup
122
  st.set_page_config(page_title="πŸ“š Smart Book Analyst", layout="wide")
123
  st.title("πŸ“š AI-Powered Book Analysis System")
124
 
125
+ # File upload
126
  uploaded_file = st.file_uploader("Upload book (PDF or TXT)", type=["pdf", "txt"])
127
 
128
  if uploaded_file:
 
144
  except Exception as e:
145
  st.error(f"Processing failed: {str(e)}")
146
 
147
+ # Query interface
148
+ if "index" in st.session_state and st.session_state.index is not None:
149
  query = st.text_input("Ask about the book:")
150
  if query:
151
  with st.spinner("πŸ” Searching for answers..."):
 
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)}")