Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
from sentence_transformers import SentenceTransformer, util
|
4 |
+
import PyPDF2
|
5 |
+
from docx import Document
|
6 |
+
from nltk.corpus import wordnet as wn
|
7 |
+
import nltk
|
8 |
+
import pandas as pd
|
9 |
+
|
10 |
+
# Ensure required resources are downloaded
|
11 |
+
nltk.download('wordnet')
|
12 |
+
nltk.download('omw-1.4')
|
13 |
+
|
14 |
+
# Load the tokenizer and model for sentence embeddings
|
15 |
+
@st.cache_resource
|
16 |
+
def load_model():
|
17 |
+
try:
|
18 |
+
tokenizer = AutoTokenizer.from_pretrained("rakeshkiriyath/gpt2Medium_text_to_sql")
|
19 |
+
model = AutoModelForCausalLM.from_pretrained("rakeshkiriyath/gpt2Medium_text_to_sql")
|
20 |
+
sentence_model = SentenceTransformer('all-MiniLM-L6-v2') # Smaller, faster sentence embeddings model
|
21 |
+
st.success("Model loaded successfully!")
|
22 |
+
return tokenizer, model, sentence_model
|
23 |
+
except Exception as e:
|
24 |
+
st.error(f"Error loading models: {e}")
|
25 |
+
return None, None, None
|
26 |
+
|
27 |
+
# Extract text from a PDF file
|
28 |
+
def extract_text_from_pdf(pdf_file):
|
29 |
+
try:
|
30 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
31 |
+
text = ""
|
32 |
+
for page in pdf_reader.pages:
|
33 |
+
text += page.extract_text()
|
34 |
+
return text
|
35 |
+
except Exception as e:
|
36 |
+
st.error(f"Error reading PDF: {e}")
|
37 |
+
return ""
|
38 |
+
|
39 |
+
# Extract text from a Word document
|
40 |
+
def extract_text_from_word(docx_file):
|
41 |
+
try:
|
42 |
+
doc = Document(docx_file)
|
43 |
+
text = ""
|
44 |
+
for paragraph in doc.paragraphs:
|
45 |
+
text += paragraph.text + "\n"
|
46 |
+
return text
|
47 |
+
except Exception as e:
|
48 |
+
st.error(f"Error reading Word document: {e}")
|
49 |
+
return ""
|
50 |
+
|
51 |
+
# Optimized comparison using embeddings and matrix operations
|
52 |
+
def compare_sentences(doc1_sentences, doc2_sentences, sentence_model):
|
53 |
+
# Encode all sentences in batches to get embeddings
|
54 |
+
doc1_embeddings = sentence_model.encode(doc1_sentences, convert_to_tensor=True, batch_size=16)
|
55 |
+
doc2_embeddings = sentence_model.encode(doc2_sentences, convert_to_tensor=True, batch_size=16)
|
56 |
+
|
57 |
+
# Compute cosine similarity matrix between all pairs
|
58 |
+
similarity_matrix = util.pytorch_cos_sim(doc1_embeddings, doc2_embeddings)
|
59 |
+
|
60 |
+
# Extract pairs with similarity > threshold
|
61 |
+
threshold = 0.6 # Adjust this for stricter or looser matching
|
62 |
+
similar_sentences = []
|
63 |
+
|
64 |
+
for i, row in enumerate(similarity_matrix):
|
65 |
+
for j, score in enumerate(row):
|
66 |
+
if score >= threshold:
|
67 |
+
similar_sentences.append((i, j, score.item(), doc1_sentences[i], doc2_sentences[j]))
|
68 |
+
|
69 |
+
return similar_sentences
|
70 |
+
|
71 |
+
# Find similar words or synonyms between two sentences
|
72 |
+
def find_similar_words(sentence1, sentence2):
|
73 |
+
words1 = set(sentence1.split())
|
74 |
+
words2 = set(sentence2.split())
|
75 |
+
similar_words = []
|
76 |
+
|
77 |
+
for word1 in words1:
|
78 |
+
for word2 in words2:
|
79 |
+
if word1 == word2 or is_synonym(word1, word2):
|
80 |
+
similar_words.append((word1, word2))
|
81 |
+
|
82 |
+
return similar_words
|
83 |
+
|
84 |
+
# Check if two words are synonyms using WordNet
|
85 |
+
def is_synonym(word1, word2):
|
86 |
+
synonyms_word1 = set(lemma.name() for synset in wn.synsets(word1) for lemma in synset.lemmas())
|
87 |
+
synonyms_word2 = set(lemma.name() for synset in wn.synsets(word2) for lemma in synset.lemmas())
|
88 |
+
return len(synonyms_word1.intersection(synonyms_word2)) > 0
|
89 |
+
|
90 |
+
# Streamlit UI
|
91 |
+
def main():
|
92 |
+
st.title("Enhanced Comparative Analysis of Two Documents")
|
93 |
+
st.sidebar.header("Upload Files")
|
94 |
+
|
95 |
+
# Upload files
|
96 |
+
uploaded_file1 = st.sidebar.file_uploader("Upload the First Document (PDF/Word)", type=["pdf", "docx"])
|
97 |
+
uploaded_file2 = st.sidebar.file_uploader("Upload the Second Document (PDF/Word)", type=["pdf", "docx"])
|
98 |
+
|
99 |
+
if uploaded_file1 and uploaded_file2:
|
100 |
+
# Extract text from the uploaded documents
|
101 |
+
if uploaded_file1.name.endswith(".pdf"):
|
102 |
+
text1 = extract_text_from_pdf(uploaded_file1)
|
103 |
+
else:
|
104 |
+
text1 = extract_text_from_word(uploaded_file1)
|
105 |
+
|
106 |
+
if uploaded_file2.name.endswith(".pdf"):
|
107 |
+
text2 = extract_text_from_pdf(uploaded_file2)
|
108 |
+
else:
|
109 |
+
text2 = extract_text_from_word(uploaded_file2)
|
110 |
+
|
111 |
+
if not text1.strip():
|
112 |
+
st.error("The first document is empty or could not be read.")
|
113 |
+
return
|
114 |
+
if not text2.strip():
|
115 |
+
st.error("The second document is empty or could not be read.")
|
116 |
+
return
|
117 |
+
|
118 |
+
st.write("### Preview of Document 1:")
|
119 |
+
st.text(text1[:500]) # Display a preview of Document 1
|
120 |
+
st.write("### Preview of Document 2:")
|
121 |
+
st.text(text2[:500]) # Display a preview of Document 2
|
122 |
+
|
123 |
+
# Split text into sentences
|
124 |
+
doc1_sentences = text1.split('. ')
|
125 |
+
doc2_sentences = text2.split('. ')
|
126 |
+
|
127 |
+
# Limit sentences for testing purposes (optional)
|
128 |
+
doc1_sentences = doc1_sentences[:50] # Remove this line for full processing
|
129 |
+
doc2_sentences = doc2_sentences[:50] # Remove this line for full processing
|
130 |
+
|
131 |
+
# Load models
|
132 |
+
tokenizer, model, sentence_model = load_model()
|
133 |
+
if not sentence_model:
|
134 |
+
st.error("Failed to load the sentence embedding model.")
|
135 |
+
return
|
136 |
+
|
137 |
+
# Perform sentence comparison
|
138 |
+
st.info("Comparing sentences, this may take a moment...")
|
139 |
+
similar_sentences = compare_sentences(doc1_sentences, doc2_sentences, sentence_model)
|
140 |
+
|
141 |
+
# Display results
|
142 |
+
st.header("Comparative Analysis Results")
|
143 |
+
st.write(f"Number of sentences in Document 1: {len(doc1_sentences)}")
|
144 |
+
st.write(f"Number of sentences in Document 2: {len(doc2_sentences)}")
|
145 |
+
|
146 |
+
if similar_sentences:
|
147 |
+
st.success(f"Found {len(similar_sentences)} similar sentences!")
|
148 |
+
|
149 |
+
# Prepare table for similar words
|
150 |
+
table_data = []
|
151 |
+
for match in similar_sentences:
|
152 |
+
doc1_index, doc2_index, score, sent1, sent2 = match
|
153 |
+
similar_words = find_similar_words(sent1, sent2)
|
154 |
+
similar_words_str = ", ".join([f"({w1}, {w2})" for w1, w2 in similar_words])
|
155 |
+
table_data.append([f"Sentence {doc1_index + 1}", f"Sentence {doc2_index + 1}", score, similar_words_str])
|
156 |
+
|
157 |
+
# Create a DataFrame for display
|
158 |
+
comparison_df = pd.DataFrame(table_data, columns=["Document 1 Sentence", "Document 2 Sentence", "Similarity Score", "Similar Words/Synonyms"])
|
159 |
+
st.table(comparison_df)
|
160 |
+
else:
|
161 |
+
st.info("No significantly similar sentences found.")
|
162 |
+
else:
|
163 |
+
st.warning("Please upload two documents to compare.")
|
164 |
+
|
165 |
+
if __name__ == "__main__":
|
166 |
+
main()
|