# Pii Pattern Redactor (`eichan/pii-pattern-redactor`) Actor

- **URL**: https://apify.com/eichan/pii-pattern-redactor.md
- **Developed by:** [Eichan Jolly](https://apify.com/eichan) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$0.01 / actor start

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## PII Pattern Redactor

**Actor slug:** `pii-pattern-redactor`\
**Store category:** `AI`\
**Runtime:** Python 3.12 standard library only; no Apify SDK, login, external LLM, or third-party AI service.

### What it does

Take **one user-supplied text string** and replace detected patterns with **`[EMAIL]`, `[PHONE]`, or `[CARD]`**. Emit **one Dataset item** with redacted text and counts only; the `findings` array never contains matched values.

### Who it is for

Developers who want a quick local, deterministic **first-pass** filter for logs, support content, prompts, or sample data before further handling. **Do not use this as a standalone privacy/security control.**

### Method

- **EMAIL:** a conservative, ASCII-oriented email-address regular expression.
- **CARD:** 13–19 ASCII digits, either contiguous or separated by single spaces or hyphens. **Only** candidates that pass the **Luhn checksum** are replaced. Unsuccessful card candidates are excluded from partial phone matches.
- **PHONE:** plausible phone-like groupings (7–15 digits including optional country code, punctuation and spaces), plus unformatted 10–12-digit sequences. Fixed-group formatted phone boundaries are checked first so two phone numbers separated by a space are not accidentally treated as one number or a rejected card candidate. Pattern shape and digit length are checked; no country-specific telephone validation occurs.
- Match priority is **EMAIL → CARD → PHONE**, then matching spans are replaced left-to-right without overlaps. Every run is deterministic.
- `findings` counts are ordered `EMAIL`, `PHONE`, `CARD`, and only nonzero categories are present. No raw values, offsets, or snippets are placed in findings or terminal logs.

### Input

Required `text` (string): 1–100,000 Unicode code points; whitespace-only strings are rejected. The **prefilled** Actor input schema contains the working sample below.

### Output fields

`redactedText` (string or null on error), `findings` (list of `{ "type": "EMAIL|PHONE|CARD", "count": integer }` objects, never raw values), `totalRedactions` (integer), `status` (`success` or `error`), and `error` (null or readable message). No matches is a successful item with the original text, `findings: []`, and `totalRedactions: 0`.

### Limits, false positives and safety warning

**This is pattern matching. It can miss real personal data and can flag look-alikes. It is NOT a compliance, privacy, or safety guarantee.** Do not assume the result is anonymized, de-identified, GDPR/CCPA/HIPAA-compliant, PCI-safe, or safe to publish.

- Does not recognize names, addresses, IDs, free-form disclosures, many international/local phone formats, non-ASCII emails, or obfuscated values.
- Luhn is a checksum, **not** proof that a number is an issued card. Conversely, an incorrectly entered card number fails Luhn and is not labeled as CARD.
- Phone-like sequences can be mistaken for order numbers. Unformatted telephone patterns have conservative size limits; numbers outside them may remain.
- If no pattern matches, input text is returned unchanged, even if it still contains sensitive information. Manually review outputs before sharing.
- There is no content fetching or external AI API. On Apify, input/output do traverse **Apify platform storage** via its native REST API; this Actor does not send content to a separate service.
- Invalid input yields one `status: "error"` Dataset item and a nonzero exit after saving it.

### Working input example (also the exact schema prefill)

```json
{
  "text": "Email me at sam@example.org or call +1 415-555-2671. Test card: 4111 1111 1111 1111."
}
```

### Actual output example (from script-mode smoke run)

```json
{
  "redactedText": "Email me at [EMAIL] or call [PHONE]. Test card: [CARD].",
  "findings": [
    {
      "type": "EMAIL",
      "count": 1
    },
    {
      "type": "PHONE",
      "count": 1
    },
    {
      "type": "CARD",
      "count": 1
    }
  ],
  "totalRedactions": 3,
  "status": "success",
  "error": null
}
```

### How to run locally

From this Actor folder with Python 3.12+:

```bash
## Bash/macOS/Linux: reuse the proven sample input.
ACTOR_INPUT_JSON="$(cat tests/sample_input.json)" python src/main.py
```

Or create `storage/key_value_stores/default/INPUT.json` containing the input JSON, then run `python src/main.py`. Local Dataset items appear in `storage/datasets/default/000000001.json` (with increasing sequence numbers). You can override the storage root with `APIFY_LOCAL_STORAGE_DIR`.

### Apify platform behavior (no SDK)

The Actor selects input in this order:

1. `ACTOR_INPUT_JSON` (when set, even if it contains invalid JSON; invalid input is reported instead of silently falling through).
2. When `APIFY_DEFAULT_KEY_VALUE_STORE_ID` exists: `GET https://api.apify.com/v2/key-value-stores/{id}/records/INPUT` with `Authorization: Bearer {APIFY_TOKEN}`.
3. Otherwise: local `./storage/key_value_stores/default/INPUT.json` (or the `APIFY_LOCAL_STORAGE_DIR` equivalent).

On the platform, one result is appended to `POST https://api.apify.com/v2/datasets/{APIFY_DEFAULT_DATASET_ID}/items` using the runtime token. The Actor does **not** require customers to provide an API key or log in to a third-party service. Both storage requests have a 20-second timeout; network, HTTP, and TLS certificate problems return readable errors without tracebacks. No custom API base URL validation is imposed.

### Reproducible verification

- `python -m unittest discover -s tests -v` runs included automated tests, including direct subprocess script mode and local REST mocks.
- `python tests/run_smoke.py` re-runs the **actual** `python src/main.py` with the schema prefill, saves a local Dataset record, and regenerates `tests/smoke_evidence.md`, `tests/smoke_stdout.txt`, and `tests/smoke_dataset_item.json`.
- `python tests/run_regression_smoke.py` runs the corrected two-phone case and the mixed-text case via real subprocess execution and saves their Dataset records and terminal outputs under `tests/regression_smoke/`.
- `tests/unittest_terminal.txt`, `tests/smoke_evidence.md`, and `tests/regression_smoke/evidence.md` contain captured outputs from the delivery verification. Live Docker builds and Apify-platform deployment were **not** executed.

### Store category and suggested pricing

Category: **AI** (data preparation utility). Suggested pricing: **USD $0.005 per completed run**; *suggestion only*. It is recorded in `store_metadata.json`. **No publishing or billing setup was performed.**

# Actor input Schema

## `text` (type: `string`):

Text to process locally; maximum 100,000 Unicode code points.

## Actor input object example

```json
{
  "text": "Email me at sam@example.org or call +1 415-555-2671. Test card: 4111 1111 1111 1111."
}
```

# Actor output Schema

## `dataset` (type: `string`):

Dataset containing the Actor's result items

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "text": "Email me at sam@example.org or call +1 415-555-2671. Test card: 4111 1111 1111 1111."
};

// Run the Actor and wait for it to finish
const run = await client.actor("eichan/pii-pattern-redactor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "text": "Email me at sam@example.org or call +1 415-555-2671. Test card: 4111 1111 1111 1111." }

# Run the Actor and wait for it to finish
run = client.actor("eichan/pii-pattern-redactor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "text": "Email me at sam@example.org or call +1 415-555-2671. Test card: 4111 1111 1111 1111."
}' |
apify call eichan/pii-pattern-redactor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,eichan/pii-pattern-redactor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/6pP5yqpMPdO0I8BHL/builds/7pEpjMAnLsNtd5Kdq/openapi.json
