Skip to content

Backend

Masking engines that PrivacyComponent can use.

PrivacyBackend

Bases: Protocol

Create an isolated PrivacySession for each invocation.

A backend may hold resources that are safe to share, such as an analyzer or an HTTP client. It must not share mappings between the sessions it opens.

open_session()

Open a session with an empty mapping.

Returns:

Name Type Description
PrivacySession PrivacySession

A new session that shares no mapping with any other session.

PrivacySession

Bases: Protocol

Mask and restore text within one mapping scope.

A session owns the mapping between original values and their placeholders. Every text masked by the same session uses the same placeholder for the same original value, and restore_text restores only placeholders that this session created. A session is used by one invocation at a time, so it does not need to be safe for concurrent use.

mask_text(text) async

Replace the PII in a text with placeholders and record the mapping.

Parameters:

Name Type Description Default
text str

The text to mask. May be empty.

required

Returns:

Name Type Description
str str

The masked text.

restore_text(text) async

Replace the placeholders this session created with their original values.

Parameters:

Name Type Description Default
text str

The text to restore. Text without known placeholders is returned unchanged.

required

Returns:

Name Type Description
str str

The restored text.

TextAnonymizerBackend(text_analyzer, entities=None, language='id')

Open sessions that detect PII with a shared analyzer and keep their own mapping.

Every session gets a new TextAnonymizer, which owns the mutable mapping. The analyzer and the Presidio AnonymizerEngine are shared between sessions, because they hold no per-call state.

Example
backend = TextAnonymizerBackend(text_analyzer=TextAnalyzer(), entities=["PERSON", "EMAIL_ADDRESS"])
session = backend.open_session()
masked = await session.mask_text("Email budi@example.com")
assert await session.restore_text(masked) == "Email budi@example.com"

Initialize the backend.

Parameters:

Name Type Description Default
text_analyzer BaseTextAnalyzer

The analyzer that detects PII. Sessions call it from worker threads.

required
entities Sequence[str] | None

The entity types to mask. Defaults to None, which masks every entity type the analyzer supports.

None
language str

The language of the masked text. Defaults to "id".

'id'

open_session()

Open a session with a new, empty mapping.

Returns:

Name Type Description
PrivacySession PrivacySession

A session backed by its own TextAnonymizer.