Skip to main content

TypeSeg

Fine-grained, character-level content-type segmentation for textual inputs.

License PyPI Python Live demo

typeseg labels every character position of a text with one of 35 content types (html, css, javascript_typescript, python, powershell, encoding_base64, …), recovering the internal structure of mixed, malformed, or convention-breaking inputs. pip install typeseg provides local CPU inference with bundled model weights. It needs no API key, separate model download at first use, or training framework. Use fast() (U-Net) for lower latency, or precise() (Mamba) for long-context segmentation. Both include a separate security profile.

Correct model output on a heavily mangled HTML input with a hidden shell payload

Model output on a heavily mangled input (stress-test): the script/style tags are missing and a reverse shell targeting an LLM is hidden inside an HTML comment, yet the embedded shell region is recovered correctly. Color saturation reflects per-character confidence.

pip install typeseg

The standard install is ready for CPU inference. For NVIDIA GPU acceleration, follow the CUDA setup guide to enable both model families with the same API and model weights.

On Intel Macs, use Python 3.9–3.13 to match the available ONNX Runtime wheels.

import typeseg

text = "<div>hi</div>\n.btn { color: red; }\nalert('x');"

result = typeseg.precise(text)   # Mamba: highest quality, long-context  (recommended)
# result = typeseg.fast(text)    # U-Net: faster, when throughput matters more than quality

for seg in result.segments:
    print(f"{seg.start:>4}-{seg.end:<4} {seg.label:<22} {seg.confidence:.2f}")

#    0-14   html                   0.86
#   14-35   css                    0.91
#   35-46   javascript_typescript  0.87

Security models

General remains the default. For mixed scripts and encoded payloads, select the security specialist explicitly:

typeseg.fast(text, model_set="security")     # U-Net-Sec
typeseg.precise(text, model_set="security")  # Mamba-Sec

The CLI accepts --model-set security; the browser has a visible model selector. Security can be less accurate on ordinary languages. Use Options.security(...) to customize its confidence/whitespace/minimum-run decoder.

Installing the package also gives you a typeseg command (alias segcat) that renders a file — tinted by content type, with a legend and a per-segment confidence table — straight in the terminal, no Python REPL needed:

typeseg file.html              # segment a file with Mamba (precise)
typeseg --model fast file.html # use the faster U-Net instead
cat foo.txt | typeseg          # read from stdin
typeseg --demo                 # built-in mixed / prompt-injection sample
python -m typeseg --demo       # equivalent module form

typeseg segmenting a mixed CSS/JS/HTML/SQL/shell input in the terminal

A Segmentation exposes:

  • segments — merged runs as Segment(start, end, label, confidence, text),
  • char_labels — per-character label (length len(text)),
  • char_confidence — per-character confidence in [0, 1],
  • char_probs — the full per-character probability distribution, a float32 array of shape (len(text), len(labels)) whose rows sum to ~1. This is the raw model output (before post-processing relabelling); columns follow labels. The open-set other class is not a column — it is derived by confidence gating, so a character routed to other still keeps its distribution over the known classes here.
  • labels — the class names, in char_probs column order.
r = typeseg.precise("SELECT 1")
r.char_probs.shape            # (8, 35)
r.char_distribution(0)        # {'sql': 0.99, 'text': 0.001, ...} for char 0

When printed to a terminal, a Segment renders as a colour-tinted chip of its text (matching the interactive viewer). Colour is auto-detected: it is emitted only to a TTY and honours NO_COLOR; force it with TYPESEG_COLOR=always or disable with TYPESEG_COLOR=never.

Content types

The models classify each character into one of 35 content types, plus the open-set other. The 35 names below are exactly the char_probs columns (see typeseg.precise("").labels for the live column order); other (index 35) is the virtual class with no column, assigned by confidence gating to below-threshold / unknown characters.

category classes
Programming languages (17) python, javascript_typescript, java, c_family (C / C++ / Obj-C), csharp (C#), go, rust, ruby, php, swift, kotlin, scala, dart, visual_basic, shell (sh / bash), powershell, sql
Markup & docs (7) html, xml, svg, css, markdown, restructuredtext, tex (TeX / LaTeX)
Data & config (6) json, yaml, csv, text (plain natural language), dockerfile, gettext_catalog (gettext .po)
Binary-to-text encodings (5) encoding_hex, encoding_base64, encoding_base32, encoding_base58, encoding_base85 (Ascii85)
Open-set other — below-threshold / unrecognised; not a char_probs column

Use cases

Representative use cases for granular content-type segmentation

Content-aware routing and LLM-agent guardrails, span-level scanning of mixed/encoded payloads, structure recovery in malformed or convention-breaking inputs, and dataset triage — moving the decision from the whole file down to individual character spans. See the project README for details.

Backends

pip install typeseg installs the CPU runtime for both models at arbitrary input length. The GPU setup below enables CUDA backends with the same API and model weights. A pure-numpy fallback still ships in the box and runs whenever onnxruntime is unavailable or TYPESEG_BACKEND=numpy is set. Inspect the active backend:

import typeseg
typeseg.backend_info(model="precise")
# CPU wheel example:
# {'backend': 'onnx', 'gpu': False, 'precise_scan': 'native-avx512', ...}

typeseg --diagnose prints the selected model's runtime as JSON without reading a file or stdin. Add --model fast or --model-set security to inspect another model. It initializes only the selected model's backend. precise_scan reports native-avx512, native-sse2, or native-scalar when the compiled scan is active, and onnx-scan when the original, slower ONNX scan is used. cupy-cuda and numpy identify the other Mamba paths.

Providers identify the backend active for each loaded model, including CPU fallback when CUDA dependencies are unavailable.

Platform wheels contain the Mamba CPU extension, built ahead of time so users do not need a compiler. Source builds need a C++17 compiler for that extension; if it is unavailable, the original ONNX scan remains functional but Mamba can be substantially slower. A pure-NumPy fallback also ships.

On CPU, Mamba's compiled scan keeps each channel's 16 state values together while processing the sequence. Both directions use the same model weights and inference windows. ONNX handles the surrounding projections and convolutions. The compiled scan uses FP32 arithmetic with a polynomial exponential, so floating-point rounding can differ slightly from the original ONNX graph. CPUs with AVX-512 process all 16 states together after runtime CPU/OS feature checks. Other x86-64 CPUs use SSE2, and other architectures use the scalar kernel.

Per-model device (auto). The two models reach the GPU by different routes:

  • fast() (U-Net) uses ONNX CUDA. A bounded cache replays CUDA graphs for repeated window shapes, with stable device buffers and serialized access to each graph. Larger shapes and unsupported captures use ordinary ONNX execution.
  • precise() (Mamba) uses a CuPy CUDA scan kernel. For the shipped 16-state models, 16 threads cooperate on each channel and retain the original FMA accumulation order. Short sequences and other state dimensions use the original CUDA kernel. The ONNX Mamba path handles CPU inference when CuPy/GPU is unavailable.

Select the backend with the TYPESEG_BACKEND environment variable:

TYPESEG_BACKEND behaviour
(unset) / onnx auto: U-Net on CUDA (onnxruntime) when it loads, Mamba on CuPy CUDA when present; otherwise CPU/numpy
cpu use ONNX CPU for both models; skip CUDA device and kernel checks
numpy force the pure-numpy backend
gpu / cuda require CUDA for both models — no CPU fallback; raise immediately if it cannot initialise

For deployments that require CUDA, set TYPESEG_BACKEND=gpu or cuda to report setup errors immediately. The GPU configuration uses typeseg[gpu] (onnxruntime-gpu for U-Net, CuPy for Mamba), CUDA 12.8 or newer within the CUDA 12 series, and cuDNN 9.x on the library path.

Running on GPU

CUDA accelerates both U-Net and Mamba and is especially useful for repeated scans and larger inputs. Loaded models and compiled kernels are reused across calls. The setup below is tested on Linux/WSL2 with an NVIDIA GPU. Native Windows CUDA has not yet been validated; macOS uses the CPU backend.

The GPU extra keeps ONNX Runtime 1.20–1.26 and CuPy on a shared CUDA 12 stack. Newer default ONNX Runtime GPU builds on PyPI use CUDA 13. Install the GPU runtime last as shown below so its CUDA provider takes precedence over the CPU package's shared Python module.

The following setup installs CUDA 12.x and cuDNN 9.x libraries as pip wheels for an NVIDIA GPU.

# 1. The GPU extra: onnxruntime-gpu (U-Net) + cupy-cuda12x (Mamba scan)
pip install "typeseg[gpu]"
pip install --force-reinstall --no-deps "onnxruntime-gpu>=1.20,<1.27"

# 2. CUDA 12 + cuDNN 9 libraries that onnxruntime-gpu needs (CuPy bundles its own).
#    Skip any you already have system-wide.
pip install nvidia-cudnn-cu12 nvidia-cublas-cu12 nvidia-cuda-runtime-cu12 \
            nvidia-cufft-cu12 nvidia-curand-cu12

# 3. Put those wheels' libs on the loader path (one-off per shell; not needed if
#    CUDA/cuDNN are already installed system-wide):
export LD_LIBRARY_PATH="$(python - <<'PY'
import os, nvidia, glob
root = os.path.dirname(nvidia.__file__)
print(":".join(glob.glob(os.path.join(root, "*", "lib"))))
PY
):$LD_LIBRARY_PATH"

Verify both models are on the GPU:

import typeseg
typeseg.backend_info()
# {'backend': 'onnx', 'gpu': True, 'precise_gpu': True,
#  'fast_providers': ['CUDAExecutionProvider', 'CPUExecutionProvider'],
#  'precise_providers': ['CuPyCUDA:NVIDIA GeForce RTX 5070 Laptop GPU']}

text = "<div>hi</div>\n.btn { color: red; }\nalert('x');"
typeseg.fast(text)      # U-Net on onnxruntime-gpu  (~140k chars/s)
typeseg.precise(text)   # Mamba on the CuPy scan    (~58k tokens/s raw forward)

To make GPU mandatory (raise instead of silently using CPU), set TYPESEG_BACKEND=gpu. Notes:

  • The first CUDA call compiles kernels — a one-time warmup of seconds (longer on brand-new GPU architectures, e.g. Blackwell sm_120). Keep the process warm.
  • backend_info() reflects what each model actually loaded; if it shows CPUExecutionProvider for fast_providers, a CUDA/cuDNN library failed to load — re-check step 2/3 (a common miss is libcurand.so.10 → nvidia-curand-cu12).
  • On Windows, the tested CUDA route uses WSL2.

Post-processing mirrors the interactive viewer via an Options object; every step can be tuned or disabled:

from typeseg import precise, Options

result = precise(text, Options(other_threshold=0.30, min_run_chars=3))
result = precise(text, Options(paired_delimiter_fill=False))   # disable one step

Building from source

The model weights (typeseg/data/*.npz, *.onnx) are generated from the released checkpoints and are not checked in. From the repository root:

python scripts/export_typeseg_weights.py   # checkpoints -> data/*.npz + manifest.json
python scripts/export_typeseg_onnx.py      # data/*.npz   -> data/*.onnx
python scripts/export_security_models.py  # frozen security checkpoints -> package + browser assets
python -m build packages/typeseg   # or: uv build packages/typeseg

See the project repository and the accompanying MSc thesis for methodology, models, and benchmarks. Licensed under Apache-2.0.

Post-processing methods

The raw model gives a probability vector per character. Post-processing applies a few cheap local passes (each O(n), no parsing) before segments are exposed. They run in the order below; toggle each via Options. Implementation: typeseg/_postprocess.py (the interactive viewer in viewers/core.py has a few additional heuristics).

step Options flag what it does
1. Whitespace relabeling whitespace_relabel Whitespace carries no real prediction, so each space/tab/newline copies the label of its nearest non-whitespace neighbour (ties go left). Keeps segments from fragmenting on indentation. (Thesis step 1.)
2. Confidence gating confidence_gating, other_threshold A character whose top class probability is below other_threshold (default 0.30) is routed to a virtual open-set other label. (Thesis step 2.)
3. Boundary snapping boundary_snap, boundary_snap_max_shift A boundary between two runs may shift by ≤ boundary_snap_max_shift (default 2) onto a nearby delimiter symbol (< > " ' \ ( ) [ ] { } / \ , ; : =`) or whitespace, so cuts land on natural seams. A shift is rejected if a moved non-delimiter position's destination-label probability is materially lower than the model's. (Thesis step 3.)
4. Minimum-run normalization min_run_normalize, min_run_chars Interior runs shorter than min_run_chars (default 3) are absorbed into the better-supported neighbour (AABBAA → AAAAAA); short edge runs are kept. Removes single-character noise. (Thesis step 4.)
5. Paired-delimiter fill paired_delimiter_fill, paired_delimiter_max_shift For a run wrapped by the same host on both sides (A B A), nudge both edges (≤ shift, default 2) so the inner run sits inside a matching delimiter pair — " ", ' ', ` `, ( ), [ ], { } — pushing the delimiters out to the host. Example: in onclick="alert(…)" the =" is ejected to html and only alert(…) stays javascript. Not part of the thesis four steps; matches the deployment viewer.

Steps 1–4 are the four steps documented in the thesis (off by default for the thesis benchmark numbers; on by default here for deployment-style output). Step 5 is an extra the interactive viewer also applies. The viewer has further heuristics (markdown_structure_fill, local_host_fill, newline_snap) not ported here — see viewers/core.py for those.

These passes are cheap, but on long inputs they run on the CPU and can outweigh the model's own forward pass — so the highest throughput is with post-processing off, exposing the raw per-character argmax:

raw = Options(whitespace_relabel=False, confidence_gating=False, boundary_snap=False,
              min_run_normalize=False, paired_delimiter_fill=False)
result = precise(text, raw)

The trade-off is noisier segments (single-character runs, frayed boundaries); the default keeps post-processing on for cleaner, deployment-style output.

Acknowledgments

This work was carried out with extensive technical feedback from and many informative discussions with Dr. Yanick Fratantonio and Dr. Luca Invernizzi from Google Security Research (authors of Magika), who also provided generous access to Google Cloud compute resources. Gemini models were used to create and refine the dense segment annotations and to act as the active-learning oracle. Thanks also go to Univ.-Prof. Stefan Rass (JKU Secure Systems Group) for his guidance, especially regarding parsing and classical computer-science approaches. I am especially grateful for his detailed feedback on the accompanying master's thesis and for him supporting this academic collaboration.

Metadata

Release files for typeseg 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typeseg 0.3.1
File Size Uploaded Provenance Actions
typeseg-0.3.1.tar.gz 43.0 MB Without provenance Details for typeseg-0.3.1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for typeseg 0.3.1
File Actions
typeseg-0.3.1-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details for typeseg-0.3.1-cp39-abi3-win_amd64.whl
typeseg-0.3.1-cp39-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.9 abi3 Linux glibc 2.27+ x86-64, Linux glibc 2.28+ x86-64 Details for typeseg-0.3.1-cp39-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
typeseg-0.3.1-cp39-abi3-macosx_11_0_x86_64.whl CPython 3.9 abi3 macOS 11.0+ x86-64 Details for typeseg-0.3.1-cp39-abi3-macosx_11_0_x86_64.whl
typeseg-0.3.1-cp39-abi3-macosx_11_0_arm64.whl CPython 3.9 abi3 macOS 11.0+ ARM64 Details for typeseg-0.3.1-cp39-abi3-macosx_11_0_arm64.whl

Total release size: 215.0 MB

Release files / typeseg-0.3.1.tar.gz

Download URL typeseg-0.3.1.tar.gz
Size 43.0 MB
Tags Source
SHA-256 checksum
How to use checksums
86e8fea3325a82b238a1ee9897baf32e25e38d0f4263f46e3ca042b4dccb84c8
BLAKE2b-256 checksum
How to use checksums
3bc03228a77978d50a42ae42e36db050a9090912f280048927229ccab5b5bc5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.21 {"installer":{"name":"uv","version":"0.12.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / typeseg-0.3.1-cp39-abi3-win_amd64.whl

Download URL typeseg-0.3.1-cp39-abi3-win_amd64.whl
Size 43.1 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
7522bd1c95497518d1066870a6efef2d9cd20e2da6d04fb7147f472b64400d78
BLAKE2b-256 checksum
How to use checksums
50d36dd9d0d5d770725fdbed35e514f5d790020cc9a62e35f1afd328a95761c7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.21 {"installer":{"name":"uv","version":"0.12.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / typeseg-0.3.1-cp39-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL typeseg-0.3.1-cp39-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 43.1 MB
Tags CPython 3.9 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64 abi3
SHA-256 checksum
How to use checksums
92d70342f6e9424648eaa0c1db0c7450e52ecfcb09a7a5eb717066ac40fbccf5
BLAKE2b-256 checksum
How to use checksums
b2b478b121677743a9abbe9c1893bbcba335226a13887da27534a4642dc99a93
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.21 {"installer":{"name":"uv","version":"0.12.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / typeseg-0.3.1-cp39-abi3-macosx_11_0_x86_64.whl

Download URL typeseg-0.3.1-cp39-abi3-macosx_11_0_x86_64.whl
Size 42.9 MB
Tags CPython 3.9 abi3 macOS 11.0+ x86-64
SHA-256 checksum
How to use checksums
636068afed10d80d6709e98083d5838e33da36a07e00ec3e5163032ff311bbe4
BLAKE2b-256 checksum
How to use checksums
7eea6fa893347f5a4a59af7cf42a1576d33af5500877550fc581e0e4f9d6849f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.21 {"installer":{"name":"uv","version":"0.12.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / typeseg-0.3.1-cp39-abi3-macosx_11_0_arm64.whl

Download URL typeseg-0.3.1-cp39-abi3-macosx_11_0_arm64.whl
Size 42.9 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
ad9c8967542c5bb35ebf760beea37346c32ab0a85dbe72e925917564e7e7c3e0
BLAKE2b-256 checksum
How to use checksums
b9d6e9b7b4dec3448e678c8cef59031b2ec6aff4a9211363777fe6f347b8bc35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.21 {"installer":{"name":"uv","version":"0.12.21","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for typeseg 0.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page