Documentation
¶
Overview ¶
Package semblance provides deterministic, heuristic text-similarity sketching: shingling, MinHash, SimHash, and LSH indexing under one API. The name nods to Broder's "On the resemblance and containment of documents" (1997), which introduced shingle-based resemblance and minwise hashing.
This package is the convenience layer: two strings to a similarity score with sensible frozen defaults. The sub-packages (shingle, minhash, simhash, lsh) are each usable alone for anything more custom.
Everything is heuristic with known error bounds (see the sub-package docs) and deterministic: same input, same parameters, same seed → same signature, on every platform. Word tokenization shares the unicode-tables caveat documented in the shingle package.
Index ¶
- func Containment(a, b string) float64
- func Similarity(a, b string) float64
- type Config
- type Sketcher
- func (s *Sketcher) Config() Config
- func (s *Sketcher) Containment(a, b string) float64
- func (s *Sketcher) NewIndex() *lsh.Index
- func (s *Sketcher) NewStream() *Stream
- func (s *Sketcher) NewVerifiedIndex() *lsh.VerifiedIndex
- func (s *Sketcher) Similarity(a, b string) float64
- func (s *Sketcher) Sketch(text string) minhash.Signature
- func (s *Sketcher) SketchBytes(b []byte) minhash.Signature
- func (s *Sketcher) SketchInto(dst minhash.Signature, text string)
- func (s *Sketcher) SketchIntoBytes(dst minhash.Signature, b []byte)
- type Stream
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Containment ¶
Containment estimates the fraction of a's word shingles also present in b with the Defaults configuration — the asymmetric measure for quote and boilerplate detection ("how much of a is inside b"). Returns 0 if either text is too short to shingle.
func Similarity ¶
Similarity estimates the Jaccard similarity of the two texts' word shingle sets with the Defaults configuration, in [0, 1]. Standard error is about 0.044 at the default K=128. Returns 0 if either text is too short to shingle (fewer than 3 words).
Example ¶
The five-line path: two strings to a similarity score.
package main
import (
"fmt"
semblance "github.com/ophymx/semblance"
)
func main() {
sim := semblance.Similarity(
"the quick brown fox jumps over the lazy dog",
"the quick brown fox leaps over the lazy dog",
)
fmt.Printf("%.2f\n", sim)
}
Output: 0.42
Types ¶
type Config ¶
type Config struct {
// W is the word-shingle width.
W int
// K is the MinHash signature length. Standard error of similarity
// estimates is about 1/(2*sqrt(K)).
K int
// Seed selects the permutation family. Signatures are only comparable
// across equal (K, Seed).
Seed uint64
// Bands and Rows shape LSH indexes created by [Sketcher.NewIndex];
// Bands*Rows must equal K. Leave both zero if you never build an index.
Bands, Rows int
}
Config parameterizes a Sketcher. The zero value is not valid; start from Defaults.
func Defaults ¶
func Defaults() Config
Defaults returns the frozen default configuration: word shingles of width 3, signatures of length 128 with seed 0, and 16 bands of 8 rows (LSH candidate threshold ≈ 0.71). These values will not change within a major version; signatures sketched with Defaults today remain comparable with signatures sketched with Defaults in any future v1 release.
type Sketcher ¶
type Sketcher struct {
// contains filtered or unexported fields
}
Sketcher turns texts into MinHash signatures using a fixed configuration. It is immutable after creation and safe for concurrent use, provided concurrent SketchInto calls use distinct dst buffers.
Example ¶
package main
import (
"fmt"
semblance "github.com/ophymx/semblance"
)
func main() {
sk := semblance.NewSketcher(semblance.Defaults())
ix := sk.NewIndex()
ix.Add("doc1", sk.Sketch("the quick brown fox jumps over the lazy dog every single morning"))
ix.Add("doc2", sk.Sketch("an entirely unrelated document about locality sensitive hashing"))
candidates := ix.Query(sk.Sketch("the quick brown fox jumps over the lazy dog every single evening"))
fmt.Println(candidates)
}
Output: [doc1]
func NewSketcher ¶
NewSketcher returns a Sketcher for the configuration. Panics if W <= 0, K <= 0, or Bands/Rows are set (nonzero) but invalid or inconsistent with K.
func (*Sketcher) Containment ¶
Containment estimates the fraction of a's word shingles also present in b — the asymmetric counterpart of Sketcher.Similarity, in [0, 1]. A short text fully quoted inside a long one has low similarity but containment near 1, which is the right question for quote and boilerplate detection. Returns 0 if either text has no shingles.
func (*Sketcher) NewIndex ¶
NewIndex returns an empty LSH candidate index shaped by the configuration's Bands and Rows, for signatures produced by this Sketcher. Query returns unverified candidate ids; the caller verifies them. Panics if Bands/Rows were left zero.
func (*Sketcher) NewStream ¶
NewStream returns a Stream sketching with this Sketcher's configuration. The Stream reuses its buffers across Stream.Reset, so one Stream per worker amortizes all allocation.
Example ¶
Documents too large to hold in memory stream through an io.Writer; any chunking produces the same signature as sketching the whole text.
package main
import (
"fmt"
"io"
"strings"
semblance "github.com/ophymx/semblance"
)
func main() {
sk := semblance.NewSketcher(semblance.Defaults())
text := "the quick brown fox jumps over the lazy dog"
st := sk.NewStream()
io.Copy(st, strings.NewReader(text)) // e.g. an os.File in practice
fmt.Println(semblance.NewSketcher(semblance.Defaults()).Sketch(text)[0] == st.Signature()[0])
}
Output: true
func (*Sketcher) NewVerifiedIndex ¶
func (s *Sketcher) NewVerifiedIndex() *lsh.VerifiedIndex
NewVerifiedIndex returns an empty signature-storing LSH index shaped by the configuration's Bands and Rows. Its Query returns verified, ranked neighbors directly (see lsh.VerifiedIndex) — the convenient path for near-duplicate lookup, at the cost of retaining signatures. Panics if Bands/Rows were left zero.
func (*Sketcher) Similarity ¶
Similarity estimates the Jaccard similarity of the two texts' word shingle sets using this Sketcher's configuration, in [0, 1]. If either text has fewer than W words it has no shingles, and Similarity returns 0 — two degenerate texts do not count as identical.
func (*Sketcher) Sketch ¶
Sketch returns the MinHash signature of text's word shingles. Text with fewer than W words produces the empty-set signature (all math.MaxUint64); see Similarity for how the convenience layer treats those.
func (*Sketcher) SketchBytes ¶
SketchBytes is Sketcher.Sketch for a byte slice, without copying. The slice is not retained or mutated.
func (*Sketcher) SketchInto ¶
SketchInto sketches text into dst, overwriting it — the low-allocation path for bulk sketching. Panics if len(dst) != K.
func (*Sketcher) SketchIntoBytes ¶
SketchIntoBytes is Sketcher.SketchInto for a byte slice, without copying. The slice is not retained or mutated. Panics if len(dst) != K.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream sketches a document that arrives in chunks — an io.Writer for text too large to hold as one string. Any chunking, including splits inside tokens or multi-byte runes, produces exactly the signature of Sketcher.Sketch over the whole text.
Lifecycle: Write/WriteString the document, call Stream.Signature once to finalize, then Stream.Reset to start the next document. Writing after Signature (without Reset) panics. Not safe for concurrent use.
func (*Stream) Signature ¶
Signature finalizes the document (emitting any in-progress token) and returns its signature. The returned slice is a copy, valid after Reset. Idempotent: repeated calls return the same signature; Write between Signature and Reset panics, because the final token was already terminated.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cluster groups ids connected by pairwise matches — the final step of a dedup pipeline: sketch documents, index them, query for candidates, verify with minhash.JaccardMany, then Set.Union each verified pair and read back the connected components.
|
Package cluster groups ids connected by pairwise matches — the final step of a dedup pipeline: sketch documents, index them, query for candidates, verify with minhash.JaccardMany, then Set.Union each verified pair and read back the connected components. |
|
Package hll implements HyperLogLog cardinality sketches (Flajolet, Fusy, Gandouet & Meunier 2007): estimate the number of distinct 64-bit elements in a stream using 2^p one-byte registers.
|
Package hll implements HyperLogLog cardinality sketches (Flajolet, Fusy, Gandouet & Meunier 2007): estimate the number of distinct 64-bit elements in a stream using 2^p one-byte registers. |
|
internal
|
|
|
cpuinfo
Package cpuinfo detects CPU features for runtime kernel dispatch, without depending on anything outside the standard library.
|
Package cpuinfo detects CPU features for runtime kernel dispatch, without depending on anything outside the standard library. |
|
hashutil
Package hashutil provides the seeded parameter generation and hash mixing shared by the semblance packages.
|
Package hashutil provides the seeded parameter generation and hash mixing shared by the semblance packages. |
|
Package lsh provides in-memory locality-sensitive-hash indexes over the sketches produced by the minhash and simhash packages: a banding index for MinHash signatures and a Hamming-ball index for SimHash fingerprints.
|
Package lsh provides in-memory locality-sensitive-hash indexes over the sketches produced by the minhash and simhash packages: a banding index for MinHash signatures and a Hamming-ball index for SimHash fingerprints. |
|
Package minhash implements MinHash signatures (Broder 1997) for estimating the Jaccard similarity of sets from small fixed-size sketches.
|
Package minhash implements MinHash signatures (Broder 1997) for estimating the Jaccard similarity of sets from small fixed-size sketches. |
|
Package sample provides deterministic reservoir sampling (Vitter's Algorithm R): a uniform random sample of up to k items from a stream of unknown length, in fixed space.
|
Package sample provides deterministic reservoir sampling (Vitter's Algorithm R): a uniform random sample of up to k items from a stream of unknown length, in fixed space. |
|
Package shingle converts text into streams of shingle hashes: xxhash values of overlapping character k-grams or word w-grams, suitable for sketching with the minhash and simhash packages.
|
Package shingle converts text into streams of shingle hashes: xxhash values of overlapping character k-grams or word w-grams, suitable for sketching with the minhash and simhash packages. |
|
Package simhash implements 64-bit SimHash fingerprints (Charikar 2002) for estimating the cosine similarity of weighted feature sets from a single machine word.
|
Package simhash implements 64-bit SimHash fingerprints (Charikar 2002) for estimating the cosine similarity of weighted feature sets from a single machine word. |
|
Package topk implements the SpaceSaving frequent-items sketch (Metwally, Agrawal & El Abbadi 2005): track the heaviest items of a stream in fixed space, with per-item error bounds.
|
Package topk implements the SpaceSaving frequent-items sketch (Metwally, Agrawal & El Abbadi 2005): track the heaviest items of a stream in fixed space, with per-item error bounds. |
|
Package winnow implements winnowing document fingerprints (Schleimer, Wilkerson & Aiken, "Winnowing: Local Algorithms for Document Fingerprinting", 2003 — the MOSS algorithm): a position-aware selection of shingle hashes for locating where two documents overlap, not just how much.
|
Package winnow implements winnowing document fingerprints (Schleimer, Wilkerson & Aiken, "Winnowing: Local Algorithms for Document Fingerprinting", 2003 — the MOSS algorithm): a position-aware selection of shingle hashes for locating where two documents overlap, not just how much. |