Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 9 min read

Redact before you prompt: a fail-closed pre-processor for call transcripts in Python

This article was created with the help of AI and the code was run and tested before publishing (Python 3.13, standard library only). Sending call transcripts to an LLM for QA scoring, summaries or theme analysis is now

This article was created with the help of AI and the code was run and tested before publishing (Python 3.13, standard library only).

Sending call transcripts to an LLM for QA scoring, summaries or theme analysis is now routine. The transcript is also where everything the customer said ends up: email addresses, callback numbers, and on payment calls, card numbers and security codes read out loud.

Two pieces of official guidance frame the problem:

  • The PCI Security Standards Council's FAQ 1210 says storing card security codes in an audio recording after authorization violates PCI DSS Requirement 3.3.1 "even if the data is encrypted", and that suppression or redaction during data entry should be enabled where it exists. A transcript or prompt log containing the code is, at minimum, something you want to avoid creating; check the details with your assessor.
  • Canada's privacy regulator (OPC guidance, updated Oct 8, 2026) notes recordings collect "incidental personal information offered by the caller not relevant to the call", and asks for narrow purposes and limited retention.

Managed redaction exists (for example Amazon Transcribe and the open-source Presidio), but both are explicit that it's not perfect. Amazon's docs: it "may not identify and remove all instances of sensitive data." Presidio: "no guarantee that Presidio will find all sensitive information… additional systems and protections should be employed."

So this tutorial builds a small, deterministic pre-processor that sits between your transcript store and your model, designed around one rule: if it isn't sure, it doesn't send. It complements a real PII detector rather than replacing one.

Design

  1. Normalise spoken digits. "Four one one one" becomes 4111, so number rules can see it.
  2. Excise payment segments. When a turn mentions a card number, security code or expiry, drop that turn and the following ones until the payment is confirmed (capped at 6 turns). Removing whole turns is more robust than blanking digits.
  3. Redact remaining identifiers with typed placeholders: email, Luhn-valid card numbers, phone numbers, other long numbers.
  4. Allowlist metadata by purpose. qa_scoring keeps call ID, date, queue, agent and duration. Caller number, name and account number never leave.
  5. Residual scan, fail closed. If any turn still contains 7+ digits, the call is marked QUARANTINE_FOR_REVIEW and should not be sent.
  6. Retention tag. Attach a delete_after date based on a per-purpose policy, and an audit record with counts only, never raw values.

The code

redact_for_ai.py (standard library only):

"""Minimise and redact a call transcript before it is sent to an AI model.

Illustrative tutorial code, not a compliance tool. Pattern-based redaction
misses things; treat the residual check and human review as part of the design.

Pipeline:
  1. normalise spoken digits ("four one one one" -> "4111") so they can be detected
  2. excise payment segments entirely (prefer removing over spot-redacting)
  3. redact remaining identifiers with typed placeholders
  4. keep only the metadata fields the stated purpose needs
  5. residual scan: if anything still looks like a long number, quarantine
  6. attach a delete_after date from a per-purpose retention policy
"""
from __future__ import annotations

import json
import re
import sys
from collections import Counter
from datetime import date, timedelta

DIGIT_WORDS = {"zero": "0", "oh": "0", "one": "1", "two": "2", "three": "3",
               "four": "4", "five": "5", "six": "6", "seven": "7",
               "eight": "8", "nine": "9"}
_TOKEN = r"(?:\d+|" + "|".join(DIGIT_WORDS) + r")"
# three or more digit-ish tokens in a row, separated by spaces/commas/dashes/dots
SPOKEN_RUN = re.compile(rf"\b{_TOKEN}(?:[\s,.\-]+{_TOKEN}){{2,}}\b", re.IGNORECASE)

PAYMENT_OPEN = re.compile(r"card number|security code|\bcvv\b|\bcvc\b|expir|"
                          r"back of the card|long number on", re.IGNORECASE)
PAYMENT_CLOSE = re.compile(r"\bapproved\b|went through|\bprocessed\b|payment is complete",
                           re.IGNORECASE)
MAX_PAYMENT_TURNS = 6

EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")
PHONE = re.compile(r"(?<!\d)(?:\+?1[\s.-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}(?!\d)")
LONG_NUMBER = re.compile(r"(?<!\d)(?:\d[\s-]?){12,18}\d(?!\d)")
ANY_DIGITS_7 = re.compile(r"(?:\d[\s-]?){6,}\d")

# Illustrative retention periods only; set real values with your legal/privacy owner.
RETENTION_DAYS = {"qa_scoring": 90, "coaching": 90, "trend_reporting": 30}
# Metadata each purpose may keep. Everything else is dropped before the AI sees it.
METADATA_ALLOWLIST = {
    "qa_scoring": {"call_id", "call_date", "queue", "agent_id", "duration_s"},
    "coaching": {"call_id", "call_date", "agent_id"},
    "trend_reporting": {"call_id", "call_date", "queue"},
}


def luhn_ok(digits: str) -> bool:
    total, parity = 0, len(digits) % 2
    for i, ch in enumerate(digits):
        d = int(ch)
        if i % 2 == parity:
            d *= 2
            if d > 9:
                d -= 9
        total += d
    return total % 10 == 0


def normalise_spoken_digits(text: str) -> str:
    def join(m: re.Match) -> str:
        parts = re.split(r"[\s,.\-]+", m.group(0))
        return "".join(DIGIT_WORDS.get(p.lower(), p) for p in parts)
    return SPOKEN_RUN.sub(join, text)


def redact_text(text: str, counts: Counter) -> str:
    text = normalise_spoken_digits(text)

    def sub(pattern, label, value_check=None):
        nonlocal text
        def repl(m):
            if value_check and not value_check(m.group(0)):
                return m.group(0)
            counts[label] += 1
            return f"[{label}]"
        text = pattern.sub(repl, text)

    sub(EMAIL, "EMAIL")
    sub(LONG_NUMBER, "CARD_NUMBER", lambda s: luhn_ok(re.sub(r"\D", "", s)))
    sub(PHONE, "PHONE")
    sub(LONG_NUMBER, "LONG_NUMBER")  # long numbers that failed the Luhn check
    return text


def excise_payment_segments(turns: list[dict], counts: Counter) -> list[dict]:
    out, i = [], 0
    while i < len(turns):
        if PAYMENT_OPEN.search(normalise_spoken_digits(turns[i]["text"])):
            j = i
            while j < len(turns) and j - i < MAX_PAYMENT_TURNS:
                if PAYMENT_CLOSE.search(turns[j]["text"]):
                    break
                j += 1
            end = min(j, len(turns) - 1)
            n = end - i + 1
            counts["PAYMENT_TURNS_REMOVED"] += n
            out.append({"speaker": "system",
                        "text": f"[payment segment removed: {n} turns]"})
            i = end + 1
        else:
            out.append(turns[i])
            i += 1
    return out


def prepare(call: dict, purpose: str) -> dict:
    if purpose not in METADATA_ALLOWLIST:
        raise ValueError(f"unknown purpose {purpose!r}: define it before processing calls")
    counts: Counter = Counter()
    turns = excise_payment_segments(call["turns"], counts)
    turns = [{"speaker": t["speaker"], "text": redact_text(t["text"], counts)}
             for t in turns]

    meta = {k: v for k, v in call["metadata"].items() if k in METADATA_ALLOWLIST[purpose]}
    dropped = sorted(set(call["metadata"]) - set(meta))

    residual = [idx for idx, t in enumerate(turns) if ANY_DIGITS_7.search(t["text"])]
    status = "QUARANTINE_FOR_REVIEW" if residual else "READY_FOR_AI"

    delete_after = (date.fromisoformat(call["metadata"]["call_date"])
                    + timedelta(days=RETENTION_DAYS[purpose])).isoformat()
    return {
        "status": status,
        "purpose": purpose,
        "delete_after": delete_after,
        "metadata": meta,
        "turns": turns,
        # audit record: counts and field names only, never the raw values
        "audit": {"redactions": dict(sorted(counts.items())),
                  "metadata_dropped": dropped,
                  "residual_turns": residual},
    }


if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "sample_call.json"
    purpose = sys.argv[2] if len(sys.argv) > 2 else "qa_scoring"
    with open(path) as f:
        result = prepare(json.load(f), purpose)
    print(json.dumps(result, indent=2))
    sys.exit(0 if result["status"] == "READY_FOR_AI" else 1)

A few details worth calling out:

  • Allowlists, not blocklists. An unknown purpose raises ValueError, and metadata fields not on the purpose's list are dropped. New fields added upstream fail safe.
  • Luhn first, then phone, then "anything long". A 16-digit number that passes the Luhn check is labelled CARD_NUMBER; long numbers that fail it are still removed as LONG_NUMBER.
  • The audit record is safe to log. It contains counts and dropped field names, which is what you need to monitor redaction rates without creating another copy of the data.

Running it on a hypothetical call

sample_call.json is an invented billing call: the customer confirms an email, reads out the standard 4111… test card number and a security code, then leaves a callback number. Running python3 redact_for_ai.py sample_call.json qa_scoring prints (exit code 0):

{
  "status": "READY_FOR_AI",
  "purpose": "qa_scoring",
  "delete_after": "2027-02-11",
  "metadata": {
    "call_id": "demo-0001",
    "call_date": "2026-11-13",
    "queue": "billing",
    "agent_id": "a-17",
    "duration_s": 412
  },
  "turns": [
    {
      "speaker": "agent",
      "text": "Thanks for calling billing. Can I confirm the email on the account?"
    },
    {
      "speaker": "customer",
      "text": "Sure, it's [EMAIL]. I was charged twice for October."
    },
    {
      "speaker": "system",
      "text": "[payment segment removed: 5 turns]"
    },
    {
      "speaker": "customer",
      "text": "Great. If anything else comes up, call me on [PHONE]."
    },
    {
      "speaker": "agent",
      "text": "Will do. You'll get a confirmation email within the hour."
    }
  ],
  "audit": {
    "redactions": {
      "EMAIL": 1,
      "PAYMENT_TURNS_REMOVED": 5,
      "PHONE": 1
    },
    "metadata_dropped": [
      "account_number",
      "caller_number",
      "customer_name"
    ],
    "residual_turns": []
  }
}

The five payment turns (from the agent's request for the card number to the payment confirmation) collapse into one line. Notice the cost: the agent's refund explanation sat inside that window and was removed too. That's the over-redaction trade-off. If your QA scorecard needs that content, fix it upstream (take payment in a separate step, or pause recording only for the digits) rather than loosening the redaction.

If we append a turn like "my member number is 44-17-22-90", nothing matches a specific rule, but the residual scan catches eight digits and the status flips to QUARANTINE_FOR_REVIEW with residual_turns: [5]. That is the behaviour you want: a person looks at it before any model does.

Tests

test_redact_for_ai.py pins both the guarantees and the known gaps:

test_card_vs_other_long_number (test_redact_for_ai.TestHelpers.test_card_vs_other_long_number) ... ok
test_email_and_phone (test_redact_for_ai.TestHelpers.test_email_and_phone) ... ok
test_luhn (test_redact_for_ai.TestHelpers.test_luhn) ... ok
test_spoken_digits (test_redact_for_ai.TestHelpers.test_spoken_digits) ... ok
test_cvv_outside_payment_window_is_a_known_gap (test_redact_for_ai.TestPrepare.test_cvv_outside_payment_window_is_a_known_gap) ... ok
test_labels_are_best_effort (test_redact_for_ai.TestPrepare.test_labels_are_best_effort) ... ok
test_metadata_allowlist (test_redact_for_ai.TestPrepare.test_metadata_allowlist) ... ok
test_payment_segment_removed (test_redact_for_ai.TestPrepare.test_payment_segment_removed) ... ok
test_purpose_changes_fields (test_redact_for_ai.TestPrepare.test_purpose_changes_fields) ... ok
test_ready_and_no_raw_values (test_redact_for_ai.TestPrepare.test_ready_and_no_raw_values) ... ok
test_residual_number_quarantines (test_redact_for_ai.TestPrepare.test_residual_number_quarantines) ... ok
test_retention_date (test_redact_for_ai.TestPrepare.test_retention_date) ... ok
test_unknown_purpose_rejected (test_redact_for_ai.TestPrepare.test_unknown_purpose_rejected) ... ok

----------------------------------------------------------------------
Ran 13 tests in 0.002s

OK

Two tests are deliberately about limitations:

  • test_cvv_outside_payment_window_is_a_known_gap: a bare "it's 123" outside a detected payment segment is not redacted. Three-digit numbers are everywhere (prices, order counts), so pattern rules can't safely remove them without context.
  • test_labels_are_best_effort: a 10-digit member ID is removed, but labelled PHONE. Don't build reporting on placeholder types.

Limitations (read before using)

  • English-only keyword triggers. Payment detection relies on phrases like "card number" and "security code". Other languages, other phrasings and ASR errors will slip through, which is why the residual scan exists.
  • No names or addresses. Free-text names and street addresses need an NER-based detector (Presidio, a managed service, or similar). Put this pre-processor after it as a backstop.
  • Upstream controls matter more. The best outcome is that card data is never recorded: pause or suppress recording during payment capture, per the PCI SSC guidance. This code is for what gets through anyway.
  • Retention values are placeholders. The 30/90-day numbers are illustrative. Real periods come from your legal and privacy owners, and the delete_after tag only helps if something actually deletes.
  • Evidence trade-off. If you only keep redacted transcripts, the original recording may become your only complete record (Amazon's docs make this point). Decide deliberately what you need for disputes.

Wrap-up

The pattern generalises beyond calls to tickets, chats and emails: normalise, remove whole sensitive segments, redact, allowlist, and fail closed on anything left over. It's a few dozen lines of code, and it means the question "did the model ever see that card number?" has a testable answer.

Not legal advice. Check payment-security and privacy obligations for your own jurisdiction and contracts.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.