Punit1 commited on
Commit
994012d
·
verified ·
1 Parent(s): 3197da8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -77
app.py CHANGED
@@ -1,102 +1,146 @@
1
  import gradio as gr
2
  import torch
3
- import numpy as np
4
  import faiss
5
- import time
6
  import logging
 
7
  from transformers import AutoTokenizer, AutoModelForCausalLM
8
  from sentence_transformers import SentenceTransformer
9
  from pypdf import PdfReader
10
 
11
- # ==========================
12
- # Logging
13
- # ==========================
14
- logging.basicConfig(level=logging.INFO)
 
 
 
 
15
  logger = logging.getLogger(__name__)
16
 
17
- # ==========================
18
- # Load Embedding Model
19
- # ==========================
 
 
 
 
 
 
 
 
 
 
 
20
  embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
 
 
 
 
 
21
 
22
- # ==========================
23
- # Load Phi-3 Mini (CPU Optimized)
24
- # ==========================
25
- model_name = "microsoft/Phi-3-mini-4k-instruct"
26
 
27
- tokenizer = AutoTokenizer.from_pretrained(model_name)
 
28
 
 
29
  model = AutoModelForCausalLM.from_pretrained(
30
- model_name,
31
  torch_dtype=torch.float32,
32
  low_cpu_mem_usage=True
33
  )
34
 
35
- model.to("cpu")
36
  model.eval()
37
 
38
- # ==========================
39
- # Global Storage
40
- # ==========================
 
 
 
41
  chunks = []
42
- index = None
43
 
 
 
 
44
 
45
- # ==========================
46
- # Process PDF
47
- # ==========================
48
  def process_pdf(file):
49
- global chunks, index
 
 
50
 
51
  reader = PdfReader(file)
52
- text = ""
53
 
54
  for page in reader.pages:
55
- content = page.extract_text()
56
- if content:
57
- text += content
58
 
59
- chunk_size = 350
60
- chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- embeddings = embed_model.encode(chunks)
63
  dimension = embeddings.shape[1]
 
 
64
 
65
- index = faiss.IndexFlatL2(dimension)
66
- index.add(np.array(embeddings))
67
 
68
- return "✅ PDF processed successfully. You can now start chatting."
69
 
 
 
 
70
 
71
- # ==========================
72
- # Chat Function (RAG + Phi-3)
73
- # ==========================
74
- def chat_fn(message, history):
75
- global chunks, index
76
 
77
- if index is None:
78
  return "⚠ Please upload and process a PDF first."
79
 
 
 
80
  start_time = time.time()
81
 
82
- # Embed query
83
- query_embedding = embed_model.encode([message])
84
- D, I = index.search(np.array(query_embedding), k=2)
 
 
 
 
 
 
85
 
86
- context = "\n".join([chunks[i] for i in I[0]])
87
 
88
- # Proper Phi-3 Instruct Template
89
- prompt = f"""<|system|>
 
90
  You are a professional AI assistant.
91
- Answer clearly, concisely and intelligently.
92
- Use structured explanation if helpful.
93
- Avoid repeating the question.
94
- If answer not found in context, say so.
95
  <|end|>
96
 
97
  <|user|>
98
  Context:
99
- {context}
100
 
101
  Question:
102
  {message}
@@ -110,53 +154,62 @@ Question:
110
  with torch.no_grad():
111
  outputs = model.generate(
112
  **inputs,
113
- max_new_tokens=120,
114
- temperature=0.6,
115
  top_p=0.9,
 
116
  do_sample=True,
117
- repetition_penalty=1.15,
118
  use_cache=True
119
  )
120
 
121
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
122
  answer = response.split("<|assistant|>")[-1].strip()
123
 
124
- logger.info(f"Response time: {time.time() - start_time:.2f}s")
 
125
 
126
  return answer
127
 
 
 
 
128
 
129
- # ==========================
130
- # Beautiful Chat UI
131
- # ==========================
132
- with gr.Blocks(theme=gr.themes.Soft(), css="""
133
- #chatbot {height: 600px}
134
- """) as demo:
135
 
136
- gr.Markdown(
137
- """
138
- # 🤖 Smart RAG Assistant
139
- Powered by Phi-3 Mini + FAISS
140
- Upload a PDF and start chatting like ChatGPT.
141
- """
142
- )
143
 
144
  with gr.Row():
 
145
  with gr.Column(scale=1):
146
  pdf_file = gr.File(label="Upload PDF")
147
  upload_btn = gr.Button("Process PDF")
148
  status = gr.Markdown()
149
 
150
  with gr.Column(scale=3):
151
- chatbot = gr.ChatInterface(
152
- fn=chat_fn,
153
- chatbot=gr.Chatbot(elem_id="chatbot"),
154
- textbox=gr.Textbox(placeholder="Ask something about the document...", container=False),
155
- title="📘 Document Chat",
156
- retry_btn="🔄 Retry",
157
- clear_btn="🗑 Clear Chat"
158
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- upload_btn.click(process_pdf, inputs=pdf_file, outputs=status)
161
 
162
- demo.launch()
 
1
  import gradio as gr
2
  import torch
 
3
  import faiss
4
+ import numpy as np
5
  import logging
6
+ import time
7
  from transformers import AutoTokenizer, AutoModelForCausalLM
8
  from sentence_transformers import SentenceTransformer
9
  from pypdf import PdfReader
10
 
11
+ # =====================================================
12
+ # LOGGING CONFIGURATION
13
+ # =====================================================
14
+
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format="%(asctime)s - %(levelname)s - %(message)s"
18
+ )
19
  logger = logging.getLogger(__name__)
20
 
21
+ logger.info("Starting application...")
22
+
23
+ # =====================================================
24
+ # DEVICE CONFIG
25
+ # =====================================================
26
+
27
+ DEVICE = "cpu"
28
+ torch.set_num_threads(4)
29
+
30
+ # =====================================================
31
+ # LOAD EMBEDDING MODEL
32
+ # =====================================================
33
+
34
+ logger.info("Loading embedding model...")
35
  embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
36
+ logger.info("Embedding model loaded.")
37
+
38
+ # =====================================================
39
+ # LOAD PHI-3 MODEL
40
+ # =====================================================
41
 
42
+ MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
 
 
 
43
 
44
+ logger.info("Loading tokenizer...")
45
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
46
 
47
+ logger.info("Loading Phi-3 model (CPU optimized)...")
48
  model = AutoModelForCausalLM.from_pretrained(
49
+ MODEL_NAME,
50
  torch_dtype=torch.float32,
51
  low_cpu_mem_usage=True
52
  )
53
 
54
+ model.to(DEVICE)
55
  model.eval()
56
 
57
+ logger.info("Model loaded successfully.")
58
+
59
+ # =====================================================
60
+ # GLOBAL STORAGE
61
+ # =====================================================
62
+
63
  chunks = []
64
+ faiss_index = None
65
 
66
+ # =====================================================
67
+ # PDF PROCESSING
68
+ # =====================================================
69
 
 
 
 
70
  def process_pdf(file):
71
+ global chunks, faiss_index
72
+
73
+ logger.info("Processing PDF...")
74
 
75
  reader = PdfReader(file)
76
+ full_text = ""
77
 
78
  for page in reader.pages:
79
+ text = page.extract_text()
80
+ if text:
81
+ full_text += text + "\n"
82
 
83
+ if not full_text.strip():
84
+ return "❌ Could not extract text from PDF."
85
+
86
+ # Chunking
87
+ chunk_size = 400
88
+ chunks = [
89
+ full_text[i:i+chunk_size]
90
+ for i in range(0, len(full_text), chunk_size)
91
+ ]
92
+
93
+ logger.info(f"Created {len(chunks)} chunks.")
94
+
95
+ # Embeddings
96
+ embeddings = embed_model.encode(chunks, convert_to_numpy=True)
97
 
 
98
  dimension = embeddings.shape[1]
99
+ faiss_index = faiss.IndexFlatL2(dimension)
100
+ faiss_index.add(embeddings)
101
 
102
+ logger.info("FAISS index built successfully.")
 
103
 
104
+ return f"✅ PDF processed successfully ({len(chunks)} chunks created)."
105
 
106
+ # =====================================================
107
+ # CHAT FUNCTION
108
+ # =====================================================
109
 
110
+ def generate_answer(message, history):
111
+ global chunks, faiss_index
 
 
 
112
 
113
+ if faiss_index is None:
114
  return "⚠ Please upload and process a PDF first."
115
 
116
+ logger.info(f"Received question: {message}")
117
+
118
  start_time = time.time()
119
 
120
+ # Step 1: Embed Query
121
+ query_embedding = embed_model.encode([message], convert_to_numpy=True)
122
+
123
+ # Step 2: Retrieve top 2 chunks
124
+ distances, indices = faiss_index.search(query_embedding, k=2)
125
+
126
+ retrieved_context = "\n\n".join(
127
+ [chunks[i] for i in indices[0]]
128
+ )
129
 
130
+ logger.info("Retrieved relevant context.")
131
 
132
+ # Step 3: Create structured prompt
133
+ prompt = f"""
134
+ <|system|>
135
  You are a professional AI assistant.
136
+ Provide clear, structured, intelligent answers.
137
+ Keep answers concise but informative.
138
+ If information is missing in context, say so.
 
139
  <|end|>
140
 
141
  <|user|>
142
  Context:
143
+ {retrieved_context}
144
 
145
  Question:
146
  {message}
 
154
  with torch.no_grad():
155
  outputs = model.generate(
156
  **inputs,
157
+ max_new_tokens=150,
158
+ temperature=0.5,
159
  top_p=0.9,
160
+ repetition_penalty=1.1,
161
  do_sample=True,
 
162
  use_cache=True
163
  )
164
 
165
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
166
  answer = response.split("<|assistant|>")[-1].strip()
167
 
168
+ elapsed = time.time() - start_time
169
+ logger.info(f"Response generated in {elapsed:.2f} seconds.")
170
 
171
  return answer
172
 
173
+ # =====================================================
174
+ # GRADIO UI
175
+ # =====================================================
176
 
177
+ with gr.Blocks() as demo:
 
 
 
 
 
178
 
179
+ gr.Markdown("# 🤖 Smart RAG Assistant")
180
+ gr.Markdown("Upload a PDF and chat intelligently using Phi-3 Mini.")
 
 
 
 
 
181
 
182
  with gr.Row():
183
+
184
  with gr.Column(scale=1):
185
  pdf_file = gr.File(label="Upload PDF")
186
  upload_btn = gr.Button("Process PDF")
187
  status = gr.Markdown()
188
 
189
  with gr.Column(scale=3):
190
+ chatbot = gr.Chatbot(height=600)
191
+ msg = gr.Textbox(
192
+ placeholder="Ask something about the document..."
 
 
 
 
193
  )
194
+ clear = gr.Button("Clear Chat")
195
+
196
+ upload_btn.click(
197
+ process_pdf,
198
+ inputs=pdf_file,
199
+ outputs=status
200
+ )
201
+
202
+ def respond(message, chat_history):
203
+ answer = generate_answer(message, chat_history)
204
+ chat_history.append((message, answer))
205
+ return "", chat_history
206
+
207
+ msg.submit(
208
+ respond,
209
+ inputs=[msg, chatbot],
210
+ outputs=[msg, chatbot]
211
+ )
212
 
213
+ clear.click(lambda: [], None, chatbot)
214
 
215
+ demo.launch(theme=gr.themes.Soft())