English | 한국어
newmean_pii
Detect and mask personal information in text on the device, in Flutter and Dart apps. A small multilingual
token-classification model (54 languages) runs in a C engine through dart:ffi; nothing is sent anywhere. Same models,
options and spans as the npm package @newmean-ai/pii.
dependencies:
newmean_pii: ^1.6.1
import 'package:newmean_pii/newmean_pii.dart';
final pii = await NewmeanPii.create(size: 'medium');
final r = await pii.redact('제 메일은 kim@example.com, 전화는 010-1234-5678입니다');
// r.text: "제 메일은 [EMAIL], 전화는 [PHONE]입니다"
Android (arm64-v8a, armeabi-v7a, x86_64), iOS (device and simulator), macOS, Linux and Windows. Needs Flutter 3.38 or Dart 3.10 or later: the package's build hook compiles the engine for each target with the platform's C compiler (Xcode, the Android NDK, clang or gcc, MSVC), so there is no prebuilt binary and no plugin setup. For the web, use the npm package.
Models
| size | file | notes |
|---|---|---|
nano |
2.6 MB | one shared layer applied 4 times, rank-32 embeddings |
small |
7.1 MB | 4 layers, rank-64 embeddings |
medium (default) |
11.3 MB | 6 layers, rank-192 embeddings |
large |
15.5 MB | 6 layers, full (pruned-vocabulary) embeddings |
Plus a 0.8 MB tokenizer shared by all sizes. Every file is checked against the size and SHA-256 pinned in the package before use, wherever it comes from:
-
Downloaded once (default) from Hugging Face (
newmean-ai/pii-<size>, tagv1.1.0) intocacheDir. The default is~/Library/Caches/newmean-piion iOS and macOS,~/.cache/newmean-piion Linux,%LOCALAPPDATA%\newmean-piion Windows and the app's temporary directory on Android; passcacheDir(for examplegetApplicationSupportDirectory()ofpath_provider) to keep the files elsewhere.modelUrlpoints at a self-hosted copy of the model folder. Android apps need theINTERNETpermission for the download. -
Bundled as Flutter assets, read with
readFile:flutter: assets: - assets/pii-nano/tokenizer.web.json - assets/pii-nano/onnx/model_q4.onnximport 'package:flutter/services.dart' show rootBundle; final pii = await NewmeanPii.create( size: 'nano', readFile: (path) async => (await rootBundle.load('assets/pii-nano/$path')).buffer.asUint8List(), ); -
A local folder with the Hugging Face layout (
modelDir), or bytes you already hold (NewmeanPii.fromBytes).
No model finds every piece of personal information. The technical report lists miss and over-masking rates per language and dataset; treat the output as a strong first pass, not a guarantee.
Labels
PERSON, EMAIL, PHONE, ADDRESS, ID_NUMBER, FINANCIAL, ORG, USERNAME, URL, DATE_OF_BIRTH, SECRET, and two
level 2 labels for indirect identifiers: PERSON_L2 (a surname with a title, a nickname, initials) and URL_L2 (public
profile or page URLs). Pass labels: level1Labels to leave level 2 visible. Names in labels that are not labels are
ignored, as in the npm package (the Python and Kotlin packages raise an error).
API
NewmeanPii.create({
String size = 'medium', // nano, small, medium, large
String? variant, // 'q4' or 'q4e'; default q4e for large/medium, q4 for small/nano
double sensitivity = 0, // > 0 masks more, < 0 masks less (about −1..1); NaN or ±infinity throws
Iterable<String>? labels, // labels to mask; default all (piiLabels)
bool regex = false, // also mask a few patterns (email, URL, card/account, phone, Korean resident number);
// default false (model only): almost no extra coverage, double the over-masking
bool keepEmoji = false, // true: the model also reads emoji (1.0 behaviour); default: never read or masked
bool wholeWords = true, // true: a span that ends inside a word covers the whole word
bool strictShortNames = false, // true: short texts (≤ 8 tokens) need stronger evidence to be read as names
Iterable<PiiAllowEntry>? allow, // values that are not PII in your data (see Lists); since 1.4.0
Iterable<PiiBlockEntry>? block, // values that are PII in your data (see Lists); since 1.4.0
String? listsId, // your name for the lists, shown in info.lists.id; since 1.4.0
String? modelDir, // local folder: tokenizer.web.json, onnx/model_<variant>.onnx
Future<Uint8List> Function(String path)? readFile, // e.g. Flutter assets
Uri? modelUrl, // self-hosted model folder (ending with "/"); default Hugging Face
String? cacheDir, // where downloads are kept
bool cache = true, // keep downloaded files
bool verify = true, // check size and SHA-256 of every file
void Function(PiiProgress)? onProgress,
}) → Future<NewmeanPii>
NewmeanPii.fromBytes(onnx: ..., tokenizer: ..., size: ..., variant: ..., allow: ..., block: ..., listsId: ...) → Future<NewmeanPii>
pii.detect(text) // → Future<List<PiiSpan>> {start, end, label, source}, sorted, non-overlapping
pii.redact(text, mode: RedactMode.tag) // tag → [EMAIL], mask → *****, blank → removed; or replace: (span, original) => ...
// → Future<PiiRedaction> {text, spans}
pii.detectSync(text), pii.redactSync(text) // the same on the calling isolate
pii.detectTable(text), pii.redactTable(text) // table mode (see Tables); detectTableSync, redactTableSync
pii.sensitivity = 0.3 // or setSensitivity(0.3); no reload
pii.info // packageVersion, modelVersion, size, variant, model and tokenizer pins, build, lists
pii.dispose()
regexSpans(text), applyRedaction(text, spans, mode: ...) // the pattern layer and the redaction modes on their own
modelFile(size, file) // published path, size and SHA-256 of 'q4', 'q4e' or 'tokenizer'
- Offsets are UTF-16 code units, the indices of Dart's
String:text.substring(span.start, span.end). Spans are widened to whole grapheme clusters, so an emoji, flag or combining sequence is masked whole or kept whole.sourceis"model","regex","model+regex","table"or"block".maskwrites one mask character per code point. - Emoji: by default emoji are taken out of the text the model reads, so the model does not read them as PII; offsets still refer to the
input, and an emoji inside a span splits it in two.
keepEmoji: truegives the model the text as given (1.0 behaviour). - Whole words: by default (since 1.3.0), a span that starts or ends inside a word is widened to the whole word ("R23" →
[ID_NUMBER], not[ID_NUMBER]23); letters of scripts written without spaces (Chinese, Japanese, Thai, Khmer, …) never extend a span, and a word ends where Hangul meets digits or Latin letters (「010-1234-5678입니다」 →[PHONE]입니다), and Korean particles after a Hangul span are left as they are (「홍길동님께」 →[PERSON]님께). It changes where a span ends, not what is masked: a short value the model misreads as a name, such as 「경기도」, becomes[PERSON]rather than[PERSON]기도;strictShortNamesleaves such values alone.wholeWords: falsegives the 1.2 spans. - Short values: with
strictShortNames: true, a text the model reads as at most 8 tokens (a survey answer, a table cell) needs stronger evidence to be read as a person's name: 「경기」, 「남성」 and 「네이버」 are left alone, while 「김민지」 and "Maria Lopez" are still found. With large, short survey items without personal information are masked 4.3% of the time instead of 7.9%, and 96.5% of lone names are found instead of 98.9%. Longer texts are unchanged. - Versions:
pii.versionis the model release (1.1.0);pii.info.packageVersion(=nativeVersion) is the package version. - Isolates:
detectandredactrun the model in a background isolate (Isolate.run), so the UI never blocks; the overhead is about 0.5 ms per call. One loaded model is shared by all calls and calls may overlap: severaldetectcalls at once run in parallel on different cores. Inside your own background isolate,detectSyncavoids the hop. - Memory: a loaded model takes about the size of its file plus the tokenizer;
dispose()frees it and the lists after running calls finish (otherwise they are freed when the object is garbage collected).
Lists
Since 1.4.0 you can tell the redactor what you already know about your data (create and fromBytes alike):
final pii = await NewmeanPii.create(
allow: [PiiAllowEntry('제주'), PiiAllowEntry('배민'), PiiAllowEntry('경기', label: 'PERSON')], // no label: any label
block: [PiiBlockEntry('박지훈', 'PERSON'), PiiBlockEntry('새솔고등학교', 'ORG')],
listsId: 'survey-2026-11 v3',
);
final r = await pii.redact('제주, 박지훈'); // NFC text
// r.text: "제주, [PERSON]" (without the lists, the medium model gives "[PERSON], [PERSON]")
block: every occurrence of an entry that starts and ends on a word boundary is masked with the entry's label (source"block"), also where the model finds nothing and whateverlabelsenables. A Hangul entry also matches before Korean particles (「박지훈님께」 → 「PERSON님께」); "Kim" does not match inside "Kimberly", nor in "Kim's" or "Kim-Lee" (apostrophes and hyphens join words, as inwholeWords); in scripts written without spaces any occurrence matches. A region with a block match takes the block label and is never allowed.allow: a span whose whole text is an entry is not masked; withlabel, only spans of that label family (PERSON covers PERSON_L2, URL covers URL_L2). The test is on the whole span, so it depends on where the model ends a span: a span 「제주도」 is not allowed by "제주"; list both forms when both occur.- Matching folds ASCII letters only (
KIM=kim); nothing else is normalized. Pass NFC text and entries: files exported on macOS or copied from PDFs may hold NFD Hangul, which never matches. Dart has no built-in normalization; normalize to NFC before calling, for example with the packageunorm_dart. - Exact forms only: 「박 지훈」 and 「박지훈」 are separate entries. A one-syllable entry such as 「김」 also masks every word that is 김 plus particles (「김은」, 「김도」).
- In table mode, block entries match inside each cell and do not vote; allowed spans leave before the column vote.
- Up to 10,000 entries per list, 1 to 64 code points each, no line breaks, no leading or trailing white space. Invalid lists
throw
PiiListException(list: "allow", "block" or "meta" forlistsId;index, null forlistsId;reason:bad_shape,too_long,bad_text,empty,edge_space,unknown_label,too_many,label_conflict,in_both,bad_lists_id) before any model file is read. The exception never holds an entry's text. info.lists(PiiListsInfo:allow,block,id) gives the entry counts after merging duplicates and yourlistsId, for audit records; nothing derived from the entries' text.
Tables
pii.detectTable(String text, {String delimiter = 'auto', bool header = true, bool vote = true,
String context = 'none'})
→ Future<List<PiiSpan>>
pii.redactTable(String text, {String delimiter = 'auto', bool header = true, bool vote = true, String context = 'none',
RedactMode mode = RedactMode.tag, String maskChar = '*', String Function(PiiSpan span, String original)? replace})
→ Future<PiiRedaction>
pii.detectTableSync(...), pii.redactTableSync(...) // the same on the calling isolate
Table mode reads a CSV, TSV, semicolon-separated or markdown pipe table as one text and clips every span to a cell value:
delimiters, quotes and line breaks are never masked, so the output is still a valid table. delimiter is 'auto'
(detected), ',', '\t', ';' or 'markdown' (anything else throws ArgumentError); quoted fields follow RFC 4180.
With vote, a column of short values is masked whole when the model finds names, emails, phone numbers or usernames in at
least 80% of its non-empty cells (and at least 4; columns with fewer than 5 non-empty cells do not vote); those spans have
source "table". Free-text columns (median value over 40 characters or 4 words) do not vote, placeholders (N/A, -,
none, null, 없음) are skipped, an email column needs @ and a phone column 6 or more digits. With header, the first
row is masked where the model finds PII but never voted on. With context: 'header' (default 'none'; anything else throws
ArgumentError) and a header row, each non-empty data cell of a column whose non-empty values are at least 80% distinct
is also read on its own as "
Libraries
- newmean_pii
- Detects and masks personal information (PII) in text on the device with the newmean-pii models: a port of the npm package @newmean-ai/pii over the shared native core (dart:ffi). Nothing is sent anywhere; model files are read locally or downloaded once from Hugging Face and checked against pinned SHA-256 values.