Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "randfacts"
version = "0.24.0"
version = "0.24.1"
description = "Package to generate random facts"
readme = "README.md"
license = "MIT"
Expand Down
136 changes: 0 additions & 136 deletions src/randfacts/safe.txt

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/randfacts/unsafe.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ The most frequent season for most suicides to occur is in the spring. The winter
Teenage suicide is the second cause of death in the state of Wisconsin
Singer Billy Joel tried to commit suicide when he was 21 by drinking furniture polish
Back in 1919, the Russian transplant pioneer Serge Voronoff made headlines by grafting monkey testicles onto human males.
Nazi leader Adolf Hitler had only one testicle
About a third of all Jewish people alive at that time were murdered in the Holocaust.
A Muslim family that saved Jews during the Holocaust, was later saved by Israel during the genocide in Bosnia, and converted to Judaism.
In 1945, Eisenhower predicted that people would try to deny the holocaust, so he urged the press to come.
Expand All @@ -75,7 +74,6 @@ Steely Dan got their name from a sexual device depicted in the book 'The Naked L
60% of all people using the Internet, use it for pornography.
UK's Internet Porn Filter Architect was Arrested On Child Porn Offenses in 2014
A man will ejaculate approximately 18 quarts of semen in his lifetime.
Adolf Hitler was a vegetarian.
Hitler and Napoleon both had only one testicle
To "testify" was based on men in the Roman court swearing to a statement made by swearing on their testicles.
During WW1, a British soldier spared the life of a wounded German: Adolf Hitler
Expand Down Expand Up @@ -114,3 +112,5 @@ Vibrators were created in the 19th century to reduce "hysteria" in women.
Famous gangster, Al Capone, had undiagnosed syphillis until he went to prison.
According to a British law passed in 1845, attempting to commit suicide was a capital offense. Offenders could be hanged for trying.
There is a town named Dildo in the province of Newfoundland, Canada
The word "testify" is based on the Ancient Roman practice of making men swear on their testicles when making a statement in court.
Adolf Hitler was a vegetarian, and had only ONE testicle.
263 changes: 135 additions & 128 deletions tests/checkduplicates/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,127 +1,79 @@
//! A test for finding and managing duplicate facts across files.
//! Disclaimer: comments mostly generated by AI
use std::hash::{DefaultHasher, Hash, Hasher};

use clap::{command, Arg, ArgAction};
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use rayon::iter::ParallelIterator;
use rayon::prelude::*;
use structures::{DuplicateFactMatch, FactClass, SIMILARITY_THRESHOLD};

use crate::structures::Fact;

mod structures;
mod util;

/// Calculates the similarity ratio between two strings using a token sort approach.
///
/// This function implements a modified version of token sort ratio that:
/// 1. Performs early exit optimization for strings with significantly different lengths
/// 2. Filters out non-alphanumeric characters
/// 3. Converts all characters to lowercase for comparison
///
/// # Arguments
/// * `str1` - First string to compare
/// * `str2` - Second string to compare
///
/// # Returns
/// A float between 0 and 100 representing the similarity percentage,
/// with a -5 offset to reduce false positives
#[inline(always)]
fn token_sort_ratio(str1: &str, str2: &str) -> f64 {
let len1 = str1.len();
let len2 = str2.len();

// Early exit for obviously different strings
// if their lengths differ by more than half, they're most likely different enough
// this may lead to issues, but it lead to a ~23.33% performance improvement
if (len1 as f64 / len2 as f64) < 0.5 || (len2 as f64 / len1 as f64) < 0.5 {
return 0.0;
}

// Preallocate vectors with capacity
let mut vec1 = Vec::with_capacity(len1);
let mut vec2 = Vec::with_capacity(len2);

// Filter and collect bytes in one pass
vec1.extend(
str1.bytes()
.filter(|&b| b.is_ascii_alphanumeric())
.map(|b| b.to_ascii_lowercase()),
);

vec2.extend(
str2.bytes()
.filter(|&b| b.is_ascii_alphanumeric())
.map(|b| b.to_ascii_lowercase()),
);

// Calculate wagner fischer directly on character vectors
let dist = wagner_fischer_2row(&vec1, &vec2) as f64;
let maximum = vec1.len() + vec2.len();
struct SerializedFact {
original: Fact,
token_hashes: Vec<u64>,
}

if maximum == 0 {
return 0.0;
}
/// Removing common stop words seems to help with the false positives
///
/// See https://gist.github.com/sebleier/554280
#[rustfmt::skip]
const STOP_WORDS: &[&str] = &[
"i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself",
"yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself",
"they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that",
"these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had",
"having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as",
"until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through",
"during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off",
"over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how",
"all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not",
"only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should",
"now",
];

// Convert distance to similarity ratio and subtract 5 to reduce false positives
(1.0 - (dist / maximum as f64)) * 100.0 - 5.0
#[inline(always)]
fn hash<T: Hash>(t: &T) -> u64 {
let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}

/// Implements the Wagner-Fischer algorithm for calculating edit distance between two sequences,
/// optimized to use only two rows of memory.
/// This function takes in two slices of sorted token hashes and computes the Dice-Sorensen
/// coefficient.
///
/// # Arguments
/// * `s1` - First sequence of characters
/// * `s2` - Second sequence of characters
///
/// # Returns
/// The minimum number of single-character edits needed to transform one string into another
/// https://en.wikipedia.org/wiki/Dice-S%C3%B8rensen_coefficient#Formula
#[inline(always)]
fn wagner_fischer_2row(s1: &[u8], s2: &[u8]) -> usize {
// Ensure s1 is the shorter sequence for optimization
let (s1, s2) = if s1.len() < s2.len() {
(s1, s2)
} else {
(s2, s1)
};

let len1 = s1.len();
let len2 = s2.len();

// handle empty string cases
if len1 == 0 {
return len2;
}
if len2 == 0 {
return len1;
}

// Initialize two rows for the dynamic programming matrix
let mut prev_row = vec![0; len2 + 1];
let mut curr_row = vec![0; len2 + 1];

// Initialize first row with incremental values
(0..=len2).for_each(|i| {
prev_row[i] = i;
});

// Fill the matrix using only two rows
for (i, c1) in s1.iter().enumerate() {
curr_row[0] = i + 1;

for (j, c2) in s2.iter().enumerate() {
curr_row[j + 1] = if c1 == c2 {
// No edit needed
prev_row[j]
} else {
// Take minimum of three possible operations (insert, delete, substitute)
1 + prev_row[j].min(prev_row[j + 1]).min(curr_row[j])
};
fn dice_sorensen_sorted(set1: &[u64], set2: &[u64]) -> f64 {
let len1 = set1.len();
let len2 = set2.len();

let mut intersect = 0;
let mut i = 0;
let mut j = 0;

// calculate the intersection of the two sorted vecs of tokens:
// https://stackoverflow.com/questions/42538902/how-to-intersect-two-sorted-arrays-the-fastest-possible-way
while i < len1 && j < len2 {
let x = set1[i];
let y = set2[j];

if x == y {
intersect += 1;
i += 1;
j += 1;
} else if x < y {
i += 1;
} else {
j += 1;
}

// Swap rows using mem::swap for better performance
std::mem::swap(&mut prev_row, &mut curr_row);
}

prev_row[len2]
// DSC = (2|X intersect Y|)/(|X| + |Y|)
(2.0 * intersect as f64) / ((len1 + len2) as f64) * 100.0
}

/// Finds duplicate facts across safe and unsafe fact files using parallel processing.
Expand All @@ -137,17 +89,51 @@ fn wagner_fischer_2row(s1: &[u8], s2: &[u8]) -> usize {
fn find_duplicate_facts() -> Vec<DuplicateFactMatch> {
// read safe.txt and unsafe.txt into lists
let mut all_facts = util::load_fact_list("safe.txt", FactClass::Safe);

let mut unsafe_contents = util::load_fact_list("unsafe.txt", FactClass::Unsafe);

all_facts.append(&mut unsafe_contents);

// Calculate total number of possible combinations for progress bar
let total_facts = all_facts.len() as u64;
let total_combinations = num_integer::binomial(total_facts as u64, 2);
// serialize each fact by:
// tokenizing, filtering junk, hashing, and sorting
let mut facts: Vec<SerializedFact> = all_facts
.into_iter()
.map(|f| {
let mut hashes: Vec<u64> = f
.fact
.split_whitespace()
.filter_map(|tok| {
let normalized = tok
.chars()
.filter(char::is_ascii_alphanumeric)
.collect::<String>()
.to_ascii_lowercase();

if normalized.is_empty() || STOP_WORDS.contains(&normalized.as_str()) {
None
} else {
Some(hash(&normalized))
}
})
.collect();

// sort hashes so we can do a linear list intersect
hashes.sort_unstable();
// remove duplicates (dice sorensen expects a set)
hashes.dedup();

SerializedFact {
original: f,
token_hashes: hashes,
}
})
.collect();

// this will compare things that are of similar lengths first so that we can break out of the
// sliding window early once its mathematically impossible to be the same
facts.sort_unstable_by_key(|f| f.token_hashes.len());

// Initialize progress bar with custom style
let pb = ProgressBar::new(total_combinations);
let pb = ProgressBar::new(facts.len() as u64);
pb.set_style(
ProgressStyle::default_bar()
.template(
Expand All @@ -156,26 +142,46 @@ fn find_duplicate_facts() -> Vec<DuplicateFactMatch> {
.unwrap(),
);

// Generate all possible indices combinations
let indices: Vec<_> = (0..all_facts.len())
.flat_map(|i| ((i + 1)..all_facts.len()).map(move |j| (i, j)))
.collect();

// Process combinations in parallel
indices
.into_par_iter()
// when two things are different enough in length, they cannot be the same mathematically based
// on the similarity threshold.
//
// - DSC = (2 * X intersect Y)/(|X| + |Y|)
// - since the list is sorted, we know that len1 <= len2, so the maximum possible intersection
// between the two sets is len1
// - (2*len1)/(len1 + len2) >= threshold
// (2*len1) >= threshold*(len1 + len2)
// 2*len1 >= threshold*len1 + threshold*len2
// 2*len1 - threshold*len1 >= threshold*len2
// len1*(2 - threshold) >= threshold*len2
// len1*(2 - threshold)/threshold >= len2
let fractional_ratio = SIMILARITY_THRESHOLD / 100.0;
let length_diff_ratio = (2.0 - fractional_ratio) / fractional_ratio;

// Process facts in parallel
facts
.par_iter()
.enumerate()
.progress_with(pb)
.filter_map(|(i, j)| {
let facts = &all_facts;
let fact1 = &facts[i];
let fact2 = &facts[j];

let ratio = token_sort_ratio(&fact1.fact, &fact2.fact);
if ratio > SIMILARITY_THRESHOLD {
Some((fact1.clone(), fact2.clone(), ratio))
} else {
None
.flat_map(|(i, f1)| {
let mut matches = vec![];
let len1 = f1.token_hashes.len();

for f2 in &facts[i + 1..] {
let len2 = f2.token_hashes.len();

// if lengths are too different to possibly be the same, don't try any of the
// remaining facts
if (len2 as f64) > (len1 as f64) * length_diff_ratio {
break;
}

let ratio = dice_sorensen_sorted(&f1.token_hashes, &f2.token_hashes);
if ratio > SIMILARITY_THRESHOLD {
matches.push((f1.original.clone(), f2.original.clone(), ratio));
}
}

matches
})
.collect()
}
Expand Down Expand Up @@ -221,7 +227,8 @@ fn main() {
let mut unsafe_facts = util::load_fact_list("unsafe.txt", FactClass::Unsafe);

// sort removal indicies in reverse to maintain correct line numbers
indicies_to_remove.sort_unstable_by(|a, b| b.0.partial_cmp(&a.0).unwrap());
indicies_to_remove.sort_unstable_by(|a, b| b.0.cmp(&a.0));
indicies_to_remove.dedup();

// Remove duplicates from respective files
for (index, class) in indicies_to_remove {
Expand Down
4 changes: 2 additions & 2 deletions tests/checkduplicates/src/structures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::{fmt, sync::Arc};

/// Type used for when a fact match is found
pub type DuplicateFactMatch = (Fact, Fact, f64);
/// Wagner-Fishcer similarity threshold
pub const SIMILARITY_THRESHOLD: f64 = 82.3;
/// Sorensen-Dice similarity threshold
pub const SIMILARITY_THRESHOLD: f64 = 70.0;

/// The classification of a Fact, safe or unsafe
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down
9 changes: 7 additions & 2 deletions tests/checkduplicates/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,13 @@ pub fn load_fact_list(filename: &str, fact_class: FactClass) -> Vec<Fact> {
let buf = BufReader::new(file);
buf.lines()
.enumerate()
.map(|(line_number, line)| {
Fact::new(line.expect("Could not parse line"), fact_class, line_number)
.filter_map(|(line_number, line)| {
let strline = line.expect("Could not parse line");
if strline.trim().is_empty() {
return None;
}

Some(Fact::new(strline, fact_class, line_number))
})
.collect()
}