string2string

repository·main·Indexed 20 days ago

https://github.com/stanfordnlp/string2string

A Python library for string-to-string algorithms in Natural Language Processing. It provides tools for sequence alignment (Needleman-Wunsch, Smith-Waterman), distance metrics (Levenshtein, Damerau-Levenshtein, Hamming, Jaccard), search (KMP), and similarity analysis using GloVe embeddings, BARTScore, and BERTScore. The library also includes NLP evaluation metrics like sacreBLEU and ROUGE, as well as utilities for tokenization and visualization of alignments and corpus embeddings.

Tokens
12.9K
Snippets
59
Records
70
Agent score
67%

What's inside string2string

  1. Overview of string2string capabilities

    main

    The string2string library provides algorithms and tools for various string-to-string problems, including:

    • Alignment: Pairwise local alignment (e.g., Smith-Waterman) and global alignment (e.g., Hirschberg).
    • Distance: Measuring differences between strings (e.g., Wagner-Fisher for edit distance).
    • Search: Lexical search (e.g., Knuth-Morris-Pratt) and semantic search (e.g., Faiss).
    • Similarity Analysis: Advanced neural approaches (e.g., BARTScore, BERTScore).
    • Metrics: Wrappers for established frameworks like sacreBLEU and ROUGE.

    The library is designed for applications in natural-language processing, bioinformatics, and computational social sciences.

  2. Access string2string tutorials

    main

    The library provides several interactive tutorials via Google Colab to learn about specific tasks:

    • Alignment Tasks and Algorithms
    • Distance Tasks and Algorithms
    • Search Tasks and Algorithms
    • Similarity Tasks and Algorithms
    • Semantic Search and Visualization of USPTO Patents (Hands-On)
    • Plagiarism Detection of Essays (Hands-On)
  3. Compute distance at the word level using Tokenizer

    main

    The distance module supports both strings and lists of strings. To compute distance at the word level, you can either pass lists of tokens directly to a distance class or use the Tokenizer class from string2string.misc to split text before computing the distance.

    from string2string.distance import LevenshteinEditDistance
    from string2string.misc import Tokenizer
    
    text1 = "The quick brown fox"
    text2 = "The kuack brown fox"
    
    # Option 1: Manual tokenization
    tokenizer = Tokenizer(word_delimiter=' ')
    tokens1 = tokenizer.tokenize(text1)
    tokens2 = tokenizer.tokenize(text2)
    
    edit_dist = LevenshteinEditDistance()
    word_level_score = edit_dist.compute(tokens1, tokens2)
    
    # Option 2: Passing lists directly
    # word_level_score = edit_dist.compute(['the', 'quick'], ['the', 'kuack'])
  4. Perform semantic search with FaissSearch

    main

    The FaissSearch class provides a wrapper around the Faiss library to perform semantic similarity searches using dense vectors. It uses transformer models (like BART) to generate embeddings.

    Workflow:

    1. Initialize: Provide model_name_or_path and tokenizer_name_or_path (e.g., 'facebook/bart-large').
    2. Initialize Corpus: Use initialize_corpus with a dataset (dictionary, pandas DataFrame, or HuggingFace dataset), specifying the section containing the text and the embedding_type (e.g., 'mean_pooling').
    3. Search: Use the .search() method with a query string and k (number of results).
    from string2string.search import FaissSearch
    
    # 1. Setup
    faiss_search = FaissSearch(
        model_name_or_path='facebook/bart-large',
        tokenizer_name_or_path='facebook/bart-large',
    )
    
    # 2. Prepare Corpus
    corpus = {'text': ['Sentence one', 'Sentence two', 'Sentence three']}
    faiss_search.initialize_corpus(
        corpus=corpus,
        section='text',
        embedding_type='mean_pooling',
    )
    
    # 3. Search
    query = 'I like running'
    top_k_results = faiss_search.search(query=query, k=5)
    
    # top_k_results is a dataframe/object containing 'text' and 'score'
    print(top_k_results)
  5. Detect plagiarism in essays with string2string

    main

    This tutorial demonstrates how to use string2string algorithms to detect plagiarism in essays by comparing text at both character and word levels.

    Key Metrics

    • Character-level edit distance: Measures the number of character-level changes required to transform one text into another.
    • Word-level edit distance: Measures the number of word-level changes required to transform one text into another.

    Example outputs from the tutorial:

    • Character-level edit distance: 3.0
    • Word-level edit distance: 2.0
    # Note: The provided segment contains the conceptual output of the tutorial rather than the implementation code.
    # Edit distance between these two texts at the character level is 3.0
    # Edit distance between these two texts at the word level is 2.0
  6. Compute BARTScore and BERTScore

    main

    The string2string.similarity module provides wrappers for advanced similarity metrics:

    • BARTScore(model_name_or_path=...): Computes BARTScore. Use compute(source_sentences, target_sentences, agg='mean', batch_size=4).
    • BERTScore(lang=...): Computes BERTScore. Use compute(source_sentences, target_sentences) to get precision, recall, and F1 scores.
    from string2string.similarity import BERTScore, BARTScore
    
    # BARTScore
    bart_scorer = BARTScore(model_name_or_path='facebook/bart-large-cnn')
    score_bart = bart_scorer.compute(source_sentences, target_sentences, agg="mean", batch_size=4)
    
    # BERTScore
    bert_scorer = BERTScore(lang="en")
    score_bert = bert_scorer.compute(source_sentences, target_sentences)
  7. Calculate Levenshtein Edit Distance

    main

    Use the string2string.distance.LevenshteinEditDistance class to calculate the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into another.

    from string2string.distance import LevenshteinEditDistance
    
    lev = LevenshteinEditDistance()
    # distance = lev.distance(str1, str2)
  8. Use Naive (Brute Force) Search

    main

    The string2string.search.NaiveSearch class implements a brute-force string matching algorithm. It checks for the pattern at every possible position in the text.

    from string2string.search import NaiveSearch
    
    # Usage depends on the specific implementation of __init__ and search methods
    searcher = NaiveSearch()
    # result = searcher.search(text, pattern)
  9. Use Faiss Semantic Search

    main

    The string2string.search.FaissSearch class provides semantic search capabilities using the Faiss library, allowing for similarity-based pattern matching rather than exact character matching.

    from string2string.search import FaissSearch
    
    # Usage depends on the specific implementation of __init__ and search methods
    searcher = FaissSearch()
    # result = searcher.search(text, pattern)