ajoy0071998 commited on
Commit
26a2907
Β·
verified Β·
1 Parent(s): d1a45c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -247
app.py CHANGED
@@ -1,249 +1,78 @@
1
  import streamlit as st
2
- import nltk
3
- import fitz
4
- import spacy
5
- import json
6
- import subprocess
7
- import re
8
- import numpy as np
9
- from summa import keywords
10
- from nltk.tokenize import sent_tokenize, word_tokenize
11
  from sentence_transformers import SentenceTransformer, util
12
- import time
13
- import os
14
-
15
- # Download required NLTK data
16
- nltk.download('punkt_tab', quiet=True)
17
- nltk.download('stopwords', quiet=True)
18
-
19
- # Load SpaCy model with a check to download if missing
20
- def load_spacy_model():
21
- model_name = "en_core_web_sm"
22
- try:
23
- return spacy.load(model_name)
24
- except OSError:
25
- st.warning(f"Model '{model_name}' not found. Downloading now...")
26
- subprocess.run(["python", "-m", "spacy", "download", model_name], check=True)
27
- return spacy.load(model_name)
28
-
29
- nlp = load_spacy_model()
30
- sbert_model = SentenceTransformer("paraphrase-MiniLM-L6-v2")
31
-
32
- CHARS_TO_REMOVE = "(){},;-'\":β€˜β€™β€œβ€"
33
-
34
- # Text processing functions (unchanged)
35
- def clean_text(text):
36
- text = "".join(char if char not in CHARS_TO_REMOVE else " " for char in text)
37
- text = re.sub(r'\s+', ' ', text).strip()
38
- return text
39
-
40
- def extract_text_from_pdf(pdf_file):
41
- try:
42
- doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
43
- text = "\n".join(page.get_text("text") for page in doc)
44
- return text.strip()
45
- except Exception as e:
46
- st.error(f"Error reading PDF: {e}")
47
- return ""
48
-
49
- def custom_sent_tokenize(text):
50
- sentence_endings = re.compile(r'(?<!\b[A-Z])(?<!\b[A-Z]\.)(?<!\b[A-Z]\.[A-Z])(?<=\.)\s+')
51
- sentences = sentence_endings.split(text)
52
- return [s.strip() for s in sentences if s.strip()]
53
-
54
- def chunk_text(text, chunk_size=15, max_words=150, overlap=10):
55
- sentences = custom_sent_tokenize(text)
56
- chunks = []
57
- i = 0
58
- while i < len(sentences):
59
- chunk = sentences[i:i + chunk_size]
60
- chunk_text = " ".join(chunk)
61
- words = word_tokenize(chunk_text)
62
- if len(words) > max_words:
63
- chunk.pop()
64
- chunk_text = " ".join(chunk)
65
- if chunks:
66
- prev_words = word_tokenize(chunks[-1])[-overlap:]
67
- chunk_text = " ".join(prev_words) + " " + chunk_text
68
- chunks.append(chunk_text)
69
- i += chunk_size
70
- return chunks
71
-
72
- # Keyword extraction functions (unchanged)
73
- def normalize_text(text):
74
- return text.lower().strip()
75
-
76
- def lemmatize_keywords(keywords_list):
77
- doc = nlp(" ".join(keywords_list))
78
- return {token.lemma_ for token in doc if token.is_alpha}
79
-
80
- def extract_keywords(chunk):
81
- doc = nlp(chunk)
82
- ner_keywords = {normalize_text(ent.text) for ent in doc.ents}
83
- singlerank_keywords = {normalize_text(kw) for kw in keywords.keywords(chunk, scores=False).split("\n")}
84
- all_tokens = {normalize_text(token.text) for token in doc if token.is_alpha}
85
- all_keywords = ner_keywords | singlerank_keywords | all_tokens
86
- return lemmatize_keywords(all_keywords)
87
-
88
- # Embedding generation (unchanged)
89
- def get_chunk_embeddings(chunks):
90
- return [sbert_model.encode(chunk, convert_to_tensor=True) for chunk in chunks]
91
-
92
- # Levenshtein distance and keyword correction (unchanged)
93
- def levenshtein_distance(s1, s2):
94
- if len(s1) < len(s2):
95
- return levenshtein_distance(s2, s1)
96
- if len(s2) == 0:
97
- return len(s1)
98
- previous_row = range(len(s2) + 1)
99
- for i, c1 in enumerate(s1):
100
- current_row = [i + 1]
101
- for j, c2 in enumerate(s2):
102
- insertions = previous_row[j + 1] + 1
103
- deletions = current_row[j] + 1
104
- substitutions = previous_row[j] + (c1 != c2)
105
- current_row.append(min(insertions, deletions, substitutions))
106
- previous_row = current_row
107
- return previous_row[-1]
108
-
109
- def correct_keywords(query_keywords, stored_keywords, threshold=2):
110
- corrected_keywords = set()
111
- for qk in query_keywords:
112
- if qk in stored_keywords:
113
- corrected_keywords.add(qk)
114
- else:
115
- min_dist = float('inf')
116
- best_match = qk
117
- for sk in stored_keywords:
118
- dist = levenshtein_distance(qk, sk)
119
- if dist < min_dist:
120
- min_dist = dist
121
- best_match = sk
122
- if min_dist <= threshold:
123
- corrected_keywords.add(best_match)
124
- else:
125
- corrected_keywords.add(qk)
126
- return corrected_keywords
127
-
128
- # Bit Vector-based search and retrieval (unchanged)
129
- def process_pdf(pdf_file):
130
- text = extract_text_from_pdf(pdf_file)
131
- text = clean_text(text)
132
- chunks = chunk_text(text)
133
- n_chunks = len(chunks)
134
-
135
- keyword_bitmaps = {}
136
- chunk_keywords = []
137
- for i, chunk in enumerate(chunks):
138
- keywords = extract_keywords(chunk)
139
- chunk_keywords.append(keywords)
140
- for kw in keywords:
141
- if kw not in keyword_bitmaps:
142
- keyword_bitmaps[kw] = np.zeros(n_chunks, dtype=bool)
143
- keyword_bitmaps[kw][i] = 1
144
-
145
- chunk_embeddings = get_chunk_embeddings(chunks)
146
- all_keywords = set().union(*chunk_keywords)
147
- return chunks, chunk_embeddings, keyword_bitmaps, chunk_keywords, all_keywords
148
-
149
- def search_relevant_chunks(query, chunks, chunk_embeddings, keyword_bitmaps, chunk_keywords, all_keywords, top_k=5):
150
- query_keywords = extract_keywords(query)
151
- corrected_query_keywords = correct_keywords(query_keywords, all_keywords)
152
-
153
- matched_bitmap = np.zeros(len(chunks), dtype=bool)
154
- for keyword in corrected_query_keywords:
155
- if keyword in keyword_bitmaps:
156
- matched_bitmap |= keyword_bitmaps[keyword]
157
-
158
- matched_chunk_indices = set(np.where(matched_bitmap)[0])
159
- chunk_scores = {idx: len(corrected_query_keywords & chunk_keywords[idx]) for idx in matched_chunk_indices}
160
- matched_chunks = [(chunks[idx], idx) for idx in sorted(chunk_scores, key=chunk_scores.get, reverse=True)]
161
-
162
- if len(matched_chunks) >= top_k:
163
- return [chunk for chunk, _ in matched_chunks[:top_k]]
164
-
165
- remaining_slots = top_k - len(matched_chunks)
166
- unmatched_indices = [i for i in range(len(chunks)) if i not in matched_chunk_indices]
167
- query_embedding = sbert_model.encode(query, convert_to_tensor=True)
168
- similarities = [util.pytorch_cos_sim(query_embedding, chunk_emb).item() for chunk_emb in chunk_embeddings]
169
- top_indices = sorted(unmatched_indices, key=lambda i: similarities[i], reverse=True)[:remaining_slots]
170
- similar_chunks = [chunks[i] for i in top_indices]
171
- return [chunk for chunk, _ in matched_chunks] + similar_chunks[:top_k]
172
-
173
- # Mistral API query (unchanged)
174
- def query_mistral(prompt, MISTRAL_API_KEY):
175
- payload = {"model": "mistral-large-latest", "messages": [{"role": "user", "content": prompt}]}
176
- curl_command = [
177
- "curl", "--location", "https://api.mistral.ai/v1/chat/completions",
178
- "--header", "Content-Type: application/json",
179
- "--header", "Accept: application/json",
180
- "--header", f"Authorization: Bearer {MISTRAL_API_KEY}",
181
- "--data", json.dumps(payload)
182
- ]
183
- response = subprocess.run(curl_command, capture_output=True, text=True)
184
- if response.returncode == 0:
185
- try:
186
- response_json = json.loads(response.stdout)
187
- return response_json['choices'][0]['message']['content']
188
- except (KeyError, json.JSONDecodeError):
189
- return "Error parsing the LLM response."
190
- return f"Error: {response.stderr}"
191
-
192
- # Streamlit app
193
- st.title("PDF Query System")
194
- st.write("Upload PDFs and ask questions about their content.")
195
-
196
- # File uploader for multiple PDFs
197
- uploaded_files = st.file_uploader("Upload PDF files", type="pdf", accept_multiple_files=True)
198
-
199
- # Store processed PDFs in session state
200
- if 'processed_pdfs' not in st.session_state:
201
- st.session_state.processed_pdfs = {}
202
-
203
- # Process uploaded PDFs
204
- if uploaded_files:
205
- for pdf_file in uploaded_files:
206
- if pdf_file.name not in st.session_state.processed_pdfs:
207
- with st.spinner(f"Processing {pdf_file.name}..."):
208
- start_time = time.time()
209
- chunks, chunk_embeddings, keyword_bitmaps, chunk_keywords, all_keywords = process_pdf(pdf_file)
210
- st.session_state.processed_pdfs[pdf_file.name] = {
211
- "chunks": chunks,
212
- "chunk_embeddings": chunk_embeddings,
213
- "keyword_bitmaps": keyword_bitmaps,
214
- "chunk_keywords": chunk_keywords,
215
- "all_keywords": all_keywords
216
- }
217
- end_time = time.time()
218
- st.success(f"Processed {pdf_file.name} in {end_time - start_time:.4f} seconds")
219
-
220
- # Query input
221
- query = st.text_input("Enter your query:")
222
-
223
- # Mistral API key from environment variable (recommended for security)
224
- MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "S3vzsvK7rP5in24joHgL55dVCjqYSi1F") # Fallback for local testing
225
-
226
- if st.button("Search") and query and st.session_state.processed_pdfs:
227
- with st.spinner("Searching..."):
228
- all_relevant_chunks = []
229
- for pdf_name, data in st.session_state.processed_pdfs.items():
230
- start_search = time.time()
231
- relevant_chunks = search_relevant_chunks(
232
- query, data["chunks"], data["chunk_embeddings"],
233
- data["keyword_bitmaps"], data["chunk_keywords"], data["all_keywords"]
234
- )
235
- end_search = time.time()
236
- all_relevant_chunks.extend(relevant_chunks)
237
- st.write(f"Search time for {pdf_name}: {end_search - start_search:.4f} seconds")
238
-
239
- context = "\n".join(all_relevant_chunks)
240
- start_response_time = time.time()
241
- llm_prompt = f"Only Based on the following context, answer the query:\n{context}\n\nQuery: {query}"
242
- response = query_mistral(llm_prompt, MISTRAL_API_KEY)
243
- end_response_time = time.time()
244
-
245
- st.subheader("Response:")
246
- st.write(response)
247
- st.write(f"Response time: {end_response_time - start_response_time:.4f} seconds")
248
- elif st.button("Search") and not st.session_state.processed_pdfs:
249
- st.warning("Please upload at least one PDF before searching.")
 
1
  import streamlit as st
2
+ import pdfplumber
 
 
 
 
 
 
 
 
3
  from sentence_transformers import SentenceTransformer, util
4
+ import torch
5
+ from typing import List
6
+ from difflib import ndiff
7
+
8
+ # Load SBERT model
9
+ model = SentenceTransformer('paraphrase-mpnet-base-v2')
10
+
11
+ st.set_page_config(page_title="PDF Difference Viewer", layout="wide")
12
+ st.title("πŸ“„ PDF Semantic Difference Viewer")
13
+
14
+ # Function to extract text from PDF
15
+ def extract_text(pdf_file) -> List[str]:
16
+ with pdfplumber.open(pdf_file) as pdf:
17
+ text = ""
18
+ for page in pdf.pages:
19
+ text += page.extract_text() + "\n"
20
+ return [para.strip() for para in text.split("\n") if para.strip()]
21
+
22
+ # Function to compare text semantically
23
+ def compare_texts(text_a: List[str], text_b: List[str], threshold_mod=0.85, threshold_add_del=0.6):
24
+ results = []
25
+ emb_a = model.encode(text_a, convert_to_tensor=True)
26
+ emb_b = model.encode(text_b, convert_to_tensor=True)
27
+
28
+ matched_b = set()
29
+ add_count = del_count = mod_count = 0
30
+
31
+ for idx_a, a_vec in enumerate(emb_a):
32
+ scores = util.cos_sim(a_vec, emb_b)[0]
33
+ best_match_idx = torch.argmax(scores).item()
34
+ best_score = scores[best_match_idx].item()
35
+
36
+ if best_score >= threshold_mod:
37
+ results.append(("modified", text_a[idx_a], text_b[best_match_idx]))
38
+ matched_b.add(best_match_idx)
39
+ mod_count += 1
40
+ elif best_score < threshold_add_del:
41
+ results.append(("removed", text_a[idx_a], ""))
42
+ del_count += 1
43
+
44
+ # Find additions
45
+ for idx_b, para_b in enumerate(text_b):
46
+ if idx_b not in matched_b:
47
+ results.append(("added", "", para_b))
48
+ add_count += 1
49
+
50
+ return results, add_count, del_count, mod_count
51
+
52
+ # Streamlit file uploader
53
+ col1, col2 = st.columns(2)
54
+ with col1:
55
+ pdf1 = st.file_uploader("Upload First PDF", type="pdf")
56
+ with col2:
57
+ pdf2 = st.file_uploader("Upload Second PDF", type="pdf")
58
+
59
+ if pdf1 and pdf2:
60
+ text_a = extract_text(pdf1)
61
+ text_b = extract_text(pdf2)
62
+
63
+ st.success("PDFs uploaded and processed. Comparing...")
64
+ results, add_count, del_count, mod_count = compare_texts(text_a, text_b)
65
+
66
+ st.subheader("πŸ“Š Summary Report")
67
+ st.markdown(f"- βœ… **Added**: {add_count}\n- ❌ **Removed**: {del_count}\n- ✏️ **Modified**: {mod_count}")
68
+
69
+ st.subheader("πŸ“ Detailed Comparison")
70
+ for tag, old, new in results:
71
+ if tag == "added":
72
+ st.markdown(f"<div style='background-color:#d4edda;padding:10px;border-radius:5px;'>βœ… <b>Added:</b> {new}</div>", unsafe_allow_html=True)
73
+ elif tag == "removed":
74
+ st.markdown(f"<div style='background-color:#f8d7da;padding:10px;border-radius:5px;'>❌ <b>Removed:</b> {old}</div>", unsafe_allow_html=True)
75
+ elif tag == "modified":
76
+ st.markdown(f"<div style='background-color:#fff3cd;padding:10px;border-radius:5px;'>✏️ <b>Modified:</b><br><i>Old:</i> {old}<br><i>New:</i> {new}</div>", unsafe_allow_html=True)
77
+ else:
78
+ st.info("Please upload two PDF files to begin comparison.")