Spaces:
Sleeping
Sleeping
Update lib/comparison.py
Browse files- lib/comparison.py +48 -94
lib/comparison.py
CHANGED
|
@@ -1,94 +1,48 @@
|
|
| 1 |
-
from transformers import BertTokenizer,
|
| 2 |
-
import torch
|
| 3 |
-
from sklearn.
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
# Load
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
# Word embedding on summary text using BERT
|
| 50 |
-
def get_bert_embeddings(texts):
|
| 51 |
-
"""Obtain BERT embeddings for a list of texts."""
|
| 52 |
-
embeddings = []
|
| 53 |
-
with torch.no_grad():
|
| 54 |
-
for text in texts:
|
| 55 |
-
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)
|
| 56 |
-
outputs = model(**inputs)
|
| 57 |
-
# Take the mean of token embeddings as the sentence embedding
|
| 58 |
-
embedding = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
|
| 59 |
-
embeddings.append(embedding)
|
| 60 |
-
return np.array(embeddings)
|
| 61 |
-
|
| 62 |
-
# Compute similirity matrices over embeddings
|
| 63 |
-
def compute_similarity(embeddings1, embeddings2):
|
| 64 |
-
"""Compute pairwise cosine similarity between two sets of embeddings."""
|
| 65 |
-
return cosine_similarity(embeddings1, embeddings2)
|
| 66 |
-
|
| 67 |
-
# For each paragraphs summed up, get the most close summary from other year and compare contents
|
| 68 |
-
def compare_summaries(results1, results2):
|
| 69 |
-
"""Compare summaries from two documents and return similarity scores."""
|
| 70 |
-
# Get embeddings for each set of summaries
|
| 71 |
-
summaries1 = [result['summary'] for result in results1]
|
| 72 |
-
summaries2 = [result['summary'] for result in results2]
|
| 73 |
-
sentiment1 = [result['sentiment'] for result in results1]
|
| 74 |
-
sentiment2 = [result['sentiment'] for result in results2]
|
| 75 |
-
embeddings1 = get_bert_embeddings(summaries1)
|
| 76 |
-
embeddings2 = get_bert_embeddings(summaries2)
|
| 77 |
-
|
| 78 |
-
# Compute similarity
|
| 79 |
-
similarity_matrix = compute_similarity(embeddings1, embeddings2)
|
| 80 |
-
|
| 81 |
-
# Analyze matches
|
| 82 |
-
matches = []
|
| 83 |
-
for i, row in enumerate(similarity_matrix):
|
| 84 |
-
most_similar_index = np.argmax(row)
|
| 85 |
-
similarity_score = row[most_similar_index]
|
| 86 |
-
matches.append({
|
| 87 |
-
'summary_doc1': summaries1[i],
|
| 88 |
-
'summary_doc2': summaries2[most_similar_index],
|
| 89 |
-
'sentiment_doc1': sentiment1[i],
|
| 90 |
-
'sentiment_doc2': sentiment2[most_similar_index],
|
| 91 |
-
'similarity_score': similarity_score
|
| 92 |
-
})
|
| 93 |
-
|
| 94 |
-
return matches
|
|
|
|
| 1 |
+
from transformers import BertTokenizer, BertModel
|
| 2 |
+
import torch
|
| 3 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# Load BERT tokenizer and model
|
| 7 |
+
bert_model_name = "bert-base-uncased"
|
| 8 |
+
tokenizer = BertTokenizer.from_pretrained(bert_model_name)
|
| 9 |
+
model = BertModel.from_pretrained(bert_model_name)
|
| 10 |
+
model.eval() # Set to evaluation mode
|
| 11 |
+
|
| 12 |
+
# Function to obtain BERT embeddings
|
| 13 |
+
def get_bert_embeddings(texts):
|
| 14 |
+
"""Obtain BERT embeddings for a list of texts."""
|
| 15 |
+
embeddings = []
|
| 16 |
+
with torch.no_grad():
|
| 17 |
+
for text in texts:
|
| 18 |
+
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True)
|
| 19 |
+
outputs = model(**inputs)
|
| 20 |
+
# Take the mean of token embeddings as the sentence embedding
|
| 21 |
+
embedding = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
|
| 22 |
+
embeddings.append(embedding)
|
| 23 |
+
return np.array(embeddings)
|
| 24 |
+
|
| 25 |
+
# Compute similarity matrices over embeddings
|
| 26 |
+
def compute_similarity(embeddings1, embeddings2):
|
| 27 |
+
"""Compute pairwise cosine similarity between two sets of embeddings."""
|
| 28 |
+
return cosine_similarity(embeddings1, embeddings2)
|
| 29 |
+
|
| 30 |
+
# Compare a paragraph with a list of other paragraphs
|
| 31 |
+
def compare_summaries(paragraph, paragraphs):
|
| 32 |
+
"""
|
| 33 |
+
Compare a single paragraph with a list of summaries,
|
| 34 |
+
and return the most similar summary along with the similarity score.
|
| 35 |
+
"""
|
| 36 |
+
# Get embeddings for the paragraph and the list of summaries
|
| 37 |
+
paragraph_embedding = get_bert_embeddings([paragraph])[0] # Single paragraph embedding
|
| 38 |
+
summaries_embeddings = get_bert_embeddings(paragraphs) # Embeddings for list of paragraphs
|
| 39 |
+
|
| 40 |
+
# Compute similarity between the paragraph and each summary
|
| 41 |
+
similarities = compute_similarity([paragraph_embedding], summaries_embeddings)[0]
|
| 42 |
+
|
| 43 |
+
# Find the most similar summary
|
| 44 |
+
most_similar_index = np.argmax(similarities) # Get index of most similar summary
|
| 45 |
+
most_similar_summary = summaries[most_similar_index] # Corresponding summary
|
| 46 |
+
similarity_score = similarities[most_similar_index] # Similarity score
|
| 47 |
+
|
| 48 |
+
return most_similar_summary, similarity_score
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|