|
import gradio as gr |
|
from datasets import load_dataset |
|
import numpy as np |
|
from model2vec import StaticModel |
|
from reach import Reach |
|
from difflib import ndiff |
|
import tqdm |
|
from contextlib import contextmanager |
|
|
|
|
|
model = StaticModel.from_pretrained("minishlab/M2V_base_output") |
|
|
|
|
|
default_dataset1_name = "sst2" |
|
default_dataset1_split = "train" |
|
default_dataset2_name = "sst2" |
|
default_dataset2_split = "validation" |
|
default_text_column = "sentence" |
|
default_threshold = 0.9 |
|
|
|
|
|
ds_default1 = load_dataset(default_dataset1_name, split=default_dataset1_split) |
|
ds_default2 = load_dataset(default_dataset2_name, split=default_dataset2_split) |
|
|
|
def batch_iterable(iterable, batch_size): |
|
"""Helper function to create batches from an iterable.""" |
|
for i in range(0, len(iterable), batch_size): |
|
yield iterable[i:i + batch_size] |
|
|
|
@contextmanager |
|
def tqdm_redirect(progress): |
|
original_tqdm = tqdm.tqdm |
|
try: |
|
tqdm.tqdm = progress.tqdm |
|
yield |
|
finally: |
|
tqdm.tqdm = original_tqdm |
|
|
|
def compute_embeddings(texts, batch_size, progress, desc="Computing embeddings"): |
|
with tqdm_redirect(progress): |
|
embeddings = model.encode(texts, show_progressbar=True, batch_size=batch_size) |
|
return embeddings |
|
|
|
def deduplicate( |
|
embedding_matrix: np.ndarray, |
|
threshold: float, |
|
batch_size: int = 1024, |
|
progress=None |
|
) -> tuple[np.ndarray, dict[int, int]]: |
|
|
|
|
|
progress(0, desc="Building search index...") |
|
reach = Reach( |
|
vectors=embedding_matrix, items=[str(i) for i in range(len(embedding_matrix))] |
|
) |
|
|
|
deduplicated_indices = set(range(len(embedding_matrix))) |
|
duplicate_to_original_mapping = {} |
|
|
|
|
|
progress(0, desc="Finding nearest neighbors...") |
|
results = reach.nearest_neighbor_threshold( |
|
embedding_matrix, |
|
threshold=threshold, |
|
batch_size=batch_size, |
|
show_progressbar=False, |
|
) |
|
|
|
|
|
total_items = len(embedding_matrix) |
|
for i, similar_items in enumerate( |
|
progress.tqdm(results, desc="Processing duplicates", total=total_items) |
|
): |
|
if i not in deduplicated_indices: |
|
continue |
|
|
|
similar_indices = [int(item[0]) for item in similar_items if int(item[0]) != i] |
|
|
|
for sim_idx in similar_indices: |
|
if sim_idx in deduplicated_indices: |
|
deduplicated_indices.remove(sim_idx) |
|
duplicate_to_original_mapping[sim_idx] = i |
|
|
|
return np.array(list(deduplicated_indices)), duplicate_to_original_mapping |
|
|
|
def display_word_differences(x: str, y: str) -> str: |
|
diff = ndiff(x.split(), y.split()) |
|
return " ".join([word for word in diff if word.startswith(("+", "-"))]) |
|
|
|
def perform_deduplication( |
|
deduplication_type, |
|
dataset1_name, |
|
dataset1_split, |
|
dataset1_text_column, |
|
dataset2_name="", |
|
dataset2_split="", |
|
dataset2_text_column="", |
|
threshold=default_threshold, |
|
progress=gr.Progress(track_tqdm=True), |
|
): |
|
try: |
|
|
|
threshold = float(threshold) |
|
|
|
|
|
status = "" |
|
|
|
if deduplication_type == "Single dataset": |
|
|
|
status = "Loading Dataset 1..." |
|
yield status, "" |
|
if ( |
|
dataset1_name == default_dataset1_name |
|
and dataset1_split == default_dataset1_split |
|
): |
|
ds = ds_default1 |
|
else: |
|
ds = load_dataset(dataset1_name, split=dataset1_split) |
|
|
|
|
|
status = "Extracting texts from Dataset 1..." |
|
yield status, "" |
|
texts = [example[dataset1_text_column] for example in ds] |
|
|
|
|
|
status = "Computing embeddings for Dataset 1..." |
|
yield status, "" |
|
embedding_matrix = compute_embeddings( |
|
texts, |
|
batch_size=64, |
|
progress=progress, |
|
desc="Computing embeddings for Dataset 1", |
|
) |
|
|
|
|
|
status = "Deduplicating embeddings..." |
|
yield status, "" |
|
deduplicated_indices, duplicate_to_original_mapping = deduplicate( |
|
embedding_matrix, threshold, progress=progress |
|
) |
|
|
|
|
|
num_duplicates = len(duplicate_to_original_mapping) |
|
num_total = len(texts) |
|
num_deduplicated = len(deduplicated_indices) |
|
|
|
result_text = f"**Total documents:** {num_total}\n" |
|
result_text += f"**Number of duplicates found:** {num_duplicates}\n" |
|
result_text += ( |
|
f"**Number of unique documents after deduplication:** {num_deduplicated}\n\n" |
|
) |
|
|
|
|
|
if num_duplicates > 0: |
|
result_text += "**Examples of duplicates found:**\n\n" |
|
num_examples = min(5, num_duplicates) |
|
for duplicate_idx, original_idx in list(duplicate_to_original_mapping.items())[:num_examples]: |
|
original_text = texts[original_idx] |
|
duplicate_text = texts[duplicate_idx] |
|
differences = display_word_differences(original_text, duplicate_text) |
|
result_text += f"**Original text:**\n{original_text}\n\n" |
|
result_text += f"**Duplicate text:**\n{duplicate_text}\n\n" |
|
result_text += f"**Differences:**\n{differences}\n" |
|
result_text += "-" * 50 + "\n\n" |
|
else: |
|
result_text += "No duplicates found." |
|
|
|
|
|
status = "Deduplication completed." |
|
yield status, result_text |
|
|
|
elif deduplication_type == "Cross-dataset": |
|
|
|
|
|
pass |
|
|
|
except Exception as e: |
|
yield f"An error occurred: {e}", "" |
|
raise e |
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("# Semantic Deduplication") |
|
|
|
deduplication_type = gr.Radio( |
|
choices=["Single dataset", "Cross-dataset"], |
|
label="Deduplication Type", |
|
value="Single dataset", |
|
) |
|
|
|
with gr.Row(): |
|
dataset1_name = gr.Textbox(value=default_dataset1_name, label="Dataset 1 Name") |
|
dataset1_split = gr.Textbox(value=default_dataset1_split, label="Dataset 1 Split") |
|
dataset1_text_column = gr.Textbox(value=default_text_column, label="Text Column Name") |
|
|
|
dataset2_inputs = gr.Column(visible=False) |
|
with dataset2_inputs: |
|
gr.Markdown("### Dataset 2") |
|
with gr.Row(): |
|
dataset2_name = gr.Textbox(value=default_dataset2_name, label="Dataset 2 Name") |
|
dataset2_split = gr.Textbox(value=default_dataset2_split, label="Dataset 2 Split") |
|
dataset2_text_column = gr.Textbox(value=default_text_column, label="Text Column Name") |
|
|
|
threshold = gr.Slider( |
|
minimum=0.0, maximum=1.0, value=default_threshold, label="Similarity Threshold" |
|
) |
|
|
|
compute_button = gr.Button("Compute") |
|
|
|
status_output = gr.Markdown() |
|
result_output = gr.Markdown() |
|
|
|
|
|
def update_visibility(deduplication_type_value): |
|
if deduplication_type_value == "Cross-dataset": |
|
return gr.update(visible=True) |
|
else: |
|
return gr.update(visible=False) |
|
|
|
deduplication_type.change( |
|
update_visibility, inputs=deduplication_type, outputs=dataset2_inputs |
|
) |
|
|
|
compute_button.click( |
|
fn=perform_deduplication, |
|
inputs=[ |
|
deduplication_type, |
|
dataset1_name, |
|
dataset1_split, |
|
dataset1_text_column, |
|
dataset2_name, |
|
dataset2_split, |
|
dataset2_text_column, |
|
threshold, |
|
], |
|
outputs=[status_output, result_output], |
|
) |
|
|
|
demo.launch() |
|
|