Skip to content

About

A Python library for loading and working with CrypTool 2 language statistics files and dictionaries

Resources

Stars

2 stars

Watchers

3 watching

Forks

Repository files navigation

LanguageStatisticsLibPy

Fast statistical language models for cryptanalysis, originating from the CrypTool 2 language statistics library. Version 2 adds a Python corpus generator, arbitrary-order character/syllable/word models, and portable CTLS 2 / CTWM 1 formats while retaining the existing CTLS and specialized scoring APIs.

What is included

  • Existing CTLS 1 statistics loading and the original Unigrams through Hexagrams scoring classes.
  • CTLS 2: explicit Unicode token vocabularies, arbitrary n-gram order, dense or sparse scores, optional raw counts, training metadata and SHA-256 integrity.
  • CTWM 1: a separate word-model container using the same efficient numeric lookup representation, including <START> and <END> tokens.
  • Configurable boundary labels, optional punctuation tokens, and independent sentence-ending rules for character, syllable and word models (version 2.1).
  • English default boundary labels, documentation and demonstration corpora (version 2.2).
  • Corpus generation for characters, whitespace-separated syllables, optional greedy syllable segmentation, and Unicode words.
  • Direct dense array lookups, sparse integer-key lookups, prepared-key batch scoring, and an adapter to the unchanged old scoring methods.
  • Command-line training, inspection and conversion; reproducible examples, compatibility fixtures, tests and an actual performance report.

These are statistical n-gram scoring models. Training preserves observed raw counts and uses the CTLS log-frequency scoring convention. It does not implement conditional-probability smoothing or neural model training.

Installation

Requires Python 3.10 or newer and NumPy 1.24 or newer (below major version 3). From the unpacked project directory:

python -m pip install .

On Windows, py can be used instead of python. Both the lslp console command and python -m languagestatisticslibpy expose the same command-line interface. For development use python -m pip install -e ..

Train word models with sentence boundaries

python -m languagestatisticslibpy train --input examples/words_en.txt --output-dir word_models --unit word --language en --orders 1 2 3 --storage sparse
python -m languagestatisticslibpy inspect word_models/en-word-2gram.ctwm --top 10

The sentence I am a human. yields these word bigrams:

("<START>", "I")
("I", "am")
("am", "a")
("a", "human")
("human", "<END>")

Boundary markers each count as one token. Word CLI training includes them by default; the Python trainer enables them explicitly. For accurately segmented corpora, use --sentence-per-line; the built-in sentence splitter is a documented simple punctuation rule, without abbreviation or decimal-number recognition.

Define boundary markers and optional punctuation

<START> and <END> are the default labels of two reserved vocabulary entries. Each has its own token ID; the trainer inserts them automatically. Use start_token and end_token to choose different labels. Their IDs depend on the complete vocabulary; read them from model.token_to_id or metadata. Existing model files retain their stored labels and token IDs. See the migration notes when upgrading from 2.1.

Punctuation selection and sentence segmentation are separate settings:

from languagestatisticslibpy import NGramTrainer, save_model

trainer = NGramTrainer(
    orders=(1, 2, 3),
    unit="word",
    sentence_boundaries=True,
    start_token="<START>",
    end_token="<END>",
    punctuation=[".", ",", ";", ":", "!", "?"],
    sentence_endings=[".", "!", "?"],
)
trainer.add_text("Hello, world!")
model = trainer.build(storage="sparse")[2]
assert model.count_tokens(["Hello", ","]) == 1
assert model.count_tokens(["!", "<END>"]) == 1
save_model(model, "words-with-punctuation.ctwm", format="ctwm")

This counts ['<START>', 'Hello', ',', 'world', '!', '<END>'] as one sequence. A comma becomes a token without ending the sentence. Selected punctuation also works with syllable alphabets and automatically extends a fixed vocabulary. Use punctuation=True for the common preset, or retain the default None for the previous preprocessing behavior.

CLI equivalents are --start-token, --end-token, --include-punctuation, --punctuation, --punctuation-file, --sentence-endings and --sentence-endings-file. See boundary and punctuation configuration for exact defaults, examples, padding, quote/joiner handling and scoring usage.

Train syllable models, including orders above six

python -m languagestatisticslibpy train --input examples/syllables.txt --output-dir syllable_models --unit syllable --vocabulary examples/syllable_inventory.json --orders 1 2 3 7 --sentence-per-line --storage sparse

The inventory is an explicit JSON list such as ["La", "Le", "Li", "Lo", "Lu"]. The safe default input consists of whitespace-separated syllables. Add --syllable-mode greedy for deterministic longest-inventory-match segmentation of unsegmented input; its linguistic suitability depends on your inventory.

There is no fixed maximum order. Available corpus length, memory and runtime still constrain useful models. Sparse packed keys use arbitrary-precision Python integers, so they do not silently overflow at 64 bits. Flat dense tables do not require an n-dimensional NumPy array.

Python API

from languagestatisticslibpy import NGramTrainer, load_model, save_model

trainer = NGramTrainer(
    orders=(1, 2, 3), unit="word", language_code="en",
    sentence_boundaries=True,
)
trainer.add_tokens(["I", "am", "a", "human"])
trainer.add_tokens(["I", "am", "here"])
model = trainer.build(storage="sparse")[2]
save_model(model, "english-bigrams.ctwm", format="ctwm")

restored = load_model("english-bigrams.ctwm")
assert restored.count_tokens(["I", "am"]) == 2
ids = restored.encode_tokens(["<START>", "I", "am", "here", "<END>"])
score = restored.calculate_cost(ids)

Each add_tokens() call is an independent sequence. No word sequence is invented across sentence/document boundaries or across unknown-token breaks.

Cryptanalysis performance

Tokenize and map strings to IDs before entering a search loop:

model = load_model("examples/generated/demo-character-3gram.ctls2")
ids = model.encode_tokens(["A", "B", "R", "A"])

# Checked preparation; then the direct prepared-key lookup primitive.
key = model.encode_key(ids[:3])
lookup = model.lookup_key
one_score = lookup(key)

# Batch evaluation of a candidate; useful for longer sequences.
candidate_score = model.calculate_cost(ids)

# Dense orders 1..6: exactly the original specialized evaluation method.
legacy = model.as_legacy_grams()
original_style_score = legacy.calculate_cost(ids)

lookup_key expects a valid prepared key. It deliberately avoids validation in the hot path; use encode_key, lookup_ids or lookup_tokens at checked boundaries. For dense storage it is bound directly to NumPy array indexing. Sparse storage uses exact radix-V integer keys and a hash-table lookup.

The new batch scorer accumulates in float64; the old adapter retains the old floating-point accumulation and positional invalid-window behavior. The adapter shares its array by default. Use as_legacy_grams(copy=True) before mutating or calling the old normalize() method if the source model must be preserved.

A universal equal-speed promise across all vocabulary sizes and orders would be incorrect: long arbitrary-precision keys and large sparse working sets have real costs. Short candidate sequences also expose fixed vectorization overhead. The compatibility adapter gives eligible dense models the original method, and longer candidates can use the new vectorized path.

See measured results, the benchmark methodology and performance guidance. Results are synthetic workload measurements on the recorded machine, not a guarantee for every corpus.

Compatibility

Operation Support
New loader reads existing CTLS 1 Yes, with correct .NET length prefixes and UTF-8 handling
Old create_grams_by_size(1..6, ...) callers Retain their existing specialized classes
Standalone CTLS 2 is read by an untouched old reader No; use compatible-prefix mode or CTLS 1 export
CTLS 2 with legacy_compatible=True Old readers read its CTLS prefix; new readers also restore counts/metadata
Multi-character syllables/words through an untouched CTLS 1 reader Not representable in that format
CTLS 1 export Dense single-BMP-character statistics; sparse input can be expanded under an explicit budget
CTWM word-model files New loader required

Compatible-prefix mode requires a dense model, n <= 6, single BMP Unicode characters, and language/alphabet strings shorter than 128 UTF-8 bytes for the untouched original Python reader. It stores a full old-model prefix plus a validated CTLS2 extension, trading file/load size for interoperability. Both representations must agree. None of that extra processing runs during lookups.

python -m languagestatisticslibpy convert tests/fixtures/en-2gram-nocs.gz en-bigrams.ctls2 --format ctls2 --legacy-compatible
python -m languagestatisticslibpy convert en-bigrams.ctls2 en-2gram-nocs.gz --format ctls

Full format specifications and migration details are in docs/FORMATS.md and docs/MIGRATION.md.

Original APIs and dictionaries

The original APIs remain available:

from languagestatisticslibpy.LanguageStatistics import LanguageStatistics as LS

grams = LS.create_grams_by_size(2, "en", "tests/fixtures", False)
numbers = LS.map_text_into_number_space("HELLOWORLD", grams.alphabet)
print(grams.calculate_cost(numbers))

The predefined language configurations remain English, German, Spanish, French, Italian, Hungarian, Russian, Czech, Greek, Latin, Dutch, Swedish, Portuguese, Polish and Turkish. Full precomputed CT2 statistics and dictionaries are available separately from the CrypTool 2 repository. Three small original CT2 compatibility fixtures are included here.

Legacy WordTree decoding now handles multibyte UTF-8, counts entries once and requires an actual end-of-entry marker for a successful lookup. Consequently, a mere prefix is no longer reported as a complete dictionary entry.

Reproduce examples and validation

python examples/train_examples.py
python -m unittest discover -s tests -v
python benchmarks/benchmark_models.py --help

The eleven included demonstration models are reproducible from the tiny example corpora. They demonstrate functionality; they are not representative English or Rapanui language models. See examples/README.md.

docs/VALIDATION.md records the checks performed for this source release. The project remains under Apache-2.0.

About

A Python library for loading and working with CrypTool 2 language statistics files and dictionaries

Resources

Stars

2 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages