simran40 commited on
Commit
a74d897
Β·
verified Β·
1 Parent(s): fcd815e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -43
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import gradio as gr
2
- import fitz
3
  import re
4
  import faiss
5
  import numpy as np
@@ -9,17 +9,17 @@ from transformers import pipeline
9
 
10
 
11
  # =================================================
12
- # MODELS
13
  # =================================================
14
 
15
- # Embedding model (for retrieval)
16
  embedding_model = SentenceTransformer("multi-qa-MiniLM-L6-cos-v1")
17
 
18
- # BART summarization model (used as answer generator)
19
- bart = pipeline(
20
- "summarization",
21
- model="facebook/bart-large-cnn",
22
- tokenizer="facebook/bart-large-cnn"
23
  )
24
 
25
 
@@ -42,7 +42,7 @@ def clean_text(text):
42
  return text.strip()
43
 
44
 
45
- def chunk_text(text, chunk_size=400, overlap=80):
46
  chunks = []
47
  start = 0
48
  while start < len(text):
@@ -53,57 +53,63 @@ def chunk_text(text, chunk_size=400, overlap=80):
53
 
54
 
55
  # =================================================
56
- # VECTOR SEARCH
57
  # =================================================
58
 
59
  def build_faiss_index(chunks):
60
  embeddings = embedding_model.encode(chunks)
61
  embeddings = np.array(embeddings).astype("float32")
 
62
  index = faiss.IndexFlatL2(embeddings.shape[1])
63
  index.add(embeddings)
 
64
  return index, chunks
65
 
66
 
67
- def retrieve_chunks(question, index, chunks, top_k=3):
68
- q_emb = embedding_model.encode([question]).astype("float32")
69
- _, indices = index.search(q_emb, top_k)
70
- return [chunks[i] for i in indices[0]]
 
 
 
 
 
 
 
71
 
72
 
73
  # =================================================
74
- # QUESTION–ANSWER USING BART
75
  # =================================================
76
 
77
  def generate_answer(question, context_chunks):
78
- context = " ".join(context_chunks)
79
-
80
- prompt = f"""
81
- Answer the following question using ONLY the given context.
82
 
83
- Context:
84
- {context}
 
 
 
85
 
86
- Question:
87
- {question}
88
- """
89
 
90
- result = bart(
91
- prompt,
92
- max_length=120,
93
- min_length=30,
94
- do_sample=False
95
- )[0]["summary_text"]
96
 
97
- return result
98
 
99
 
100
  # =================================================
101
  # MAIN PIPELINE
102
  # =================================================
103
 
104
- def pdf_qa(pdf_file, question):
105
  if pdf_file is None or question.strip() == "":
106
- return "Please upload a PDF and ask a question."
107
 
108
  text = extract_text_from_pdf(pdf_file.name)
109
  text = clean_text(text)
@@ -111,7 +117,7 @@ def pdf_qa(pdf_file, question):
111
  chunks = chunk_text(text)
112
  index, chunks = build_faiss_index(chunks)
113
 
114
- relevant_chunks = retrieve_chunks(question, index, chunks)
115
  answer = generate_answer(question, relevant_chunks)
116
 
117
  return answer
@@ -124,27 +130,41 @@ def pdf_qa(pdf_file, question):
124
  with gr.Blocks() as demo:
125
 
126
  gr.Markdown("""
127
- # πŸ“„ PDF Question Answering System (BART Based)
 
 
 
 
128
 
129
- Upload a **PDF** and ask a **specific question**.
130
- The system retrieves relevant content and generates a **focused answer**,
131
- not a full summary.
132
  """)
133
 
134
  with gr.Row():
135
  with gr.Column(scale=1):
136
- pdf_input = gr.File(label="πŸ“€ Upload PDF", file_types=[".pdf"])
 
 
 
 
137
  question_input = gr.Textbox(
138
  label="❓ Ask your question",
139
- placeholder="e.g. What is the objective of the project?",
140
  lines=2
141
  )
142
- btn = gr.Button("πŸ” Get Answer")
 
143
 
144
  with gr.Column(scale=2):
145
- output = gr.Textbox(label="πŸ“Œ Answer", lines=8)
 
 
 
146
 
147
- btn.click(pdf_qa, [pdf_input, question_input], output)
 
 
 
 
148
 
149
  gr.Markdown("""
150
  ---
 
1
  import gradio as gr
2
+ import fitz # PyMuPDF
3
  import re
4
  import faiss
5
  import numpy as np
 
9
 
10
 
11
  # =================================================
12
+ # MODEL LOADING (ONCE)
13
  # =================================================
14
 
15
+ # Embedding model for semantic search
16
  embedding_model = SentenceTransformer("multi-qa-MiniLM-L6-cos-v1")
17
 
18
+ # Extractive Question Answering model (HIGH ACCURACY)
19
+ qa_pipeline = pipeline(
20
+ "question-answering",
21
+ model="deepset/roberta-base-squad2",
22
+ tokenizer="deepset/roberta-base-squad2"
23
  )
24
 
25
 
 
42
  return text.strip()
43
 
44
 
45
+ def chunk_text(text, chunk_size=350, overlap=80):
46
  chunks = []
47
  start = 0
48
  while start < len(text):
 
53
 
54
 
55
  # =================================================
56
+ # VECTOR DATABASE (FAISS)
57
  # =================================================
58
 
59
  def build_faiss_index(chunks):
60
  embeddings = embedding_model.encode(chunks)
61
  embeddings = np.array(embeddings).astype("float32")
62
+
63
  index = faiss.IndexFlatL2(embeddings.shape[1])
64
  index.add(embeddings)
65
+
66
  return index, chunks
67
 
68
 
69
+ def retrieve_relevant_chunks(question, index, chunks, top_k=5):
70
+ query_embedding = embedding_model.encode([question]).astype("float32")
71
+ distances, indices = index.search(query_embedding, top_k)
72
+
73
+ results = []
74
+ for i, idx in enumerate(indices[0]):
75
+ results.append((chunks[idx], distances[0][i]))
76
+
77
+ # sort by relevance
78
+ results.sort(key=lambda x: x[1])
79
+ return [r[0] for r in results]
80
 
81
 
82
  # =================================================
83
+ # ANSWER GENERATION (ACCURATE)
84
  # =================================================
85
 
86
  def generate_answer(question, context_chunks):
87
+ best_answer = ""
88
+ best_score = 0.0
 
 
89
 
90
+ for chunk in context_chunks:
91
+ result = qa_pipeline(
92
+ question=question,
93
+ context=chunk
94
+ )
95
 
96
+ if result["score"] > best_score:
97
+ best_score = result["score"]
98
+ best_answer = result["answer"]
99
 
100
+ if best_score < 0.3 or best_answer.strip() == "":
101
+ return "Information not found in the document."
 
 
 
 
102
 
103
+ return best_answer
104
 
105
 
106
  # =================================================
107
  # MAIN PIPELINE
108
  # =================================================
109
 
110
+ def pdf_qa_chat(pdf_file, question):
111
  if pdf_file is None or question.strip() == "":
112
+ return "Please upload a PDF and enter a valid question."
113
 
114
  text = extract_text_from_pdf(pdf_file.name)
115
  text = clean_text(text)
 
117
  chunks = chunk_text(text)
118
  index, chunks = build_faiss_index(chunks)
119
 
120
+ relevant_chunks = retrieve_relevant_chunks(question, index, chunks)
121
  answer = generate_answer(question, relevant_chunks)
122
 
123
  return answer
 
130
  with gr.Blocks() as demo:
131
 
132
  gr.Markdown("""
133
+ # πŸ“„ PDF Question Answering System (High Accuracy)
134
+
135
+ Upload a **PDF document** and ask a **specific question**.
136
+ The system uses **semantic retrieval + extractive AI**, ensuring
137
+ **accurate answers directly from the document** (no hallucination).
138
 
139
+ ---
 
 
140
  """)
141
 
142
  with gr.Row():
143
  with gr.Column(scale=1):
144
+ pdf_input = gr.File(
145
+ label="πŸ“€ Upload PDF",
146
+ file_types=[".pdf"]
147
+ )
148
+
149
  question_input = gr.Textbox(
150
  label="❓ Ask your question",
151
+ placeholder="e.g. Whose report is this?",
152
  lines=2
153
  )
154
+
155
+ submit_btn = gr.Button("πŸ” Get Answer")
156
 
157
  with gr.Column(scale=2):
158
+ answer_output = gr.Textbox(
159
+ label="πŸ“Œ Answer",
160
+ lines=6
161
+ )
162
 
163
+ submit_btn.click(
164
+ fn=pdf_qa_chat,
165
+ inputs=[pdf_input, question_input],
166
+ outputs=answer_output
167
+ )
168
 
169
  gr.Markdown("""
170
  ---