pdf-anonymizer-cli 0.30.0__tar.gz → 0.32.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pdf-anonymizer-cli
3
- Version: 0.30.0
3
+ Version: 0.32.0
4
4
  Summary: CLI for a tool to anonymize PDF, Markdown, plain text, CSV, Excel, and Word files using LLMs.
5
5
  Author-email: Leonid Ganeline <leo.gan.57@gmail.com>
6
6
  License: MIT
@@ -9,7 +9,7 @@ Requires-Python: >=3.10
9
9
  Description-Content-Type: text/markdown
10
10
  Requires-Dist: typer
11
11
  Requires-Dist: rich
12
- Requires-Dist: pdf-anonymizer-core>=0.30.0
12
+ Requires-Dist: pdf-anonymizer-core>=0.32.0
13
13
  Provides-Extra: excel
14
14
  Requires-Dist: pdf-anonymizer-core[excel]; extra == "excel"
15
15
  Provides-Extra: docx
@@ -25,7 +25,7 @@ A command-line interface for anonymizing PDF, Markdown, and plain text files usi
25
25
  - **Identity clues**: With `-p best-quality` or `--prompt-name detailed`, the tool also hides phrases that point to one person without writing their name (for example "the CEO of Tesla"). The default `best-speed` profile does not.
26
26
  - **Checksum labels**: After the fast number search, a real IBAN becomes `IBAN_1` and a mistyped one becomes `IBAN_LIKE_1`. Both are hidden. Same idea for cards, VINs, and a few national IDs.
27
27
  - **Operators, reports, and lists**: `--operator TYPE=mask|hash|generalize|shift|fake|encrypt`, leftover scan (`verify`), linkage-risk score (`report`), `--keep-list` / `--deny-list`, `--mapping-in`, optional locked maps, HIPAA coverage aid. See the [CLI History](https://leo-gan.github.io/anonymizer/project/cli-usage/#history).
28
- - **Large File Support**: Consistently anonymizes large files (tested up to 1GB).
28
+ - **File size**: Text and PDF are read into memory and then split into chunks. CSV, Excel, and Word are refused above 50 MiB. A measured 100 MB text run is in the [recipes](https://leo-gan.github.io/anonymizer/project/recipes/#processing-very-large-documents). There is no tested 1 GB path.
29
29
  - **Multi-Provider & Cost-Effective**: Free to use with local [Ollama](https://ollama.com/) models. It also supports major providers like [OpenAI](https://openai.com/), [Anthropic](https://www.anthropic.com/), [Google](https://ai.google.com/), [Hugging Face](https://huggingface.co/), and [OpenRouter](https://openrouter.ai/).
30
30
  - **Reversible**: Supports deanonymization to recover original data when needed.
31
31
  - **Multi-Format**: Works with PDF, Markdown, plain text, CSV, Excel, and Word (`.docx`) files.
@@ -65,7 +65,7 @@ The CLI will automatically load a `.env` file from the current directory or any
65
65
  - `ANTHROPIC_API_KEY`: Required when using Anthropic models.
66
66
  - `OLLAMA_HOST`: Optional, defaults to `http://localhost:11434` when using Ollama models.
67
67
  - `ANONYMIZER_MAPPING_KEY`: Optional. Same as `--mapping-passphrase` (writes `*.mapping.json.enc`).
68
- - `ANONYMIZER_FAKE_SECRET`: Optional. Seed for `--operator TYPE=fake`.
68
+ - `ANONYMIZER_FAKE_SECRET`: Required when `--operator` uses `fake`. There is no built-in seed.
69
69
  - `ANONYMIZER_ENCRYPT_SECRET`: Optional. Secret for `--operator TYPE=encrypt`.
70
70
 
71
71
  Example `.env` file:
@@ -115,7 +115,7 @@ pdf-anonymizer run FILE_PATH [FILE_PATH ...] \
115
115
  - `--mapping-passphrase TEXT`: Lock the mapping as `*.mapping.json.enc` (AES-256-GCM + Argon2id). Also `ANONYMIZER_MAPPING_KEY`. Default: plaintext JSON.
116
116
  - `--ephemeral-mapping`: Do not write `data/mappings/`. The vocabulary stays in this process only.
117
117
  - `--operator TYPE=op`: How to write a type (`replace`, `mask`, `hash`, `generalize`, `shift`, `fake`, `encrypt`). Repeatable. Default is `replace`.
118
- - `--fake-secret TEXT`: Seed for `fake`. Also `ANONYMIZER_FAKE_SECRET`.
118
+ - `--fake-secret TEXT`: Required seed for `fake`. Also `ANONYMIZER_FAKE_SECRET`.
119
119
  - `--encrypt-secret TEXT`: Secret for `encrypt`. Also `ANONYMIZER_ENCRYPT_SECRET`. Required when any type uses `encrypt`.
120
120
  - `--risk / --no-risk`: After masking, score identity-clue clumps (default: on). Writes `data/stats/<stem>.risk.json`.
121
121
 
@@ -6,7 +6,7 @@ A command-line interface for anonymizing PDF, Markdown, and plain text files usi
6
6
  - **Identity clues**: With `-p best-quality` or `--prompt-name detailed`, the tool also hides phrases that point to one person without writing their name (for example "the CEO of Tesla"). The default `best-speed` profile does not.
7
7
  - **Checksum labels**: After the fast number search, a real IBAN becomes `IBAN_1` and a mistyped one becomes `IBAN_LIKE_1`. Both are hidden. Same idea for cards, VINs, and a few national IDs.
8
8
  - **Operators, reports, and lists**: `--operator TYPE=mask|hash|generalize|shift|fake|encrypt`, leftover scan (`verify`), linkage-risk score (`report`), `--keep-list` / `--deny-list`, `--mapping-in`, optional locked maps, HIPAA coverage aid. See the [CLI History](https://leo-gan.github.io/anonymizer/project/cli-usage/#history).
9
- - **Large File Support**: Consistently anonymizes large files (tested up to 1GB).
9
+ - **File size**: Text and PDF are read into memory and then split into chunks. CSV, Excel, and Word are refused above 50 MiB. A measured 100 MB text run is in the [recipes](https://leo-gan.github.io/anonymizer/project/recipes/#processing-very-large-documents). There is no tested 1 GB path.
10
10
  - **Multi-Provider & Cost-Effective**: Free to use with local [Ollama](https://ollama.com/) models. It also supports major providers like [OpenAI](https://openai.com/), [Anthropic](https://www.anthropic.com/), [Google](https://ai.google.com/), [Hugging Face](https://huggingface.co/), and [OpenRouter](https://openrouter.ai/).
11
11
  - **Reversible**: Supports deanonymization to recover original data when needed.
12
12
  - **Multi-Format**: Works with PDF, Markdown, plain text, CSV, Excel, and Word (`.docx`) files.
@@ -46,7 +46,7 @@ The CLI will automatically load a `.env` file from the current directory or any
46
46
  - `ANTHROPIC_API_KEY`: Required when using Anthropic models.
47
47
  - `OLLAMA_HOST`: Optional, defaults to `http://localhost:11434` when using Ollama models.
48
48
  - `ANONYMIZER_MAPPING_KEY`: Optional. Same as `--mapping-passphrase` (writes `*.mapping.json.enc`).
49
- - `ANONYMIZER_FAKE_SECRET`: Optional. Seed for `--operator TYPE=fake`.
49
+ - `ANONYMIZER_FAKE_SECRET`: Required when `--operator` uses `fake`. There is no built-in seed.
50
50
  - `ANONYMIZER_ENCRYPT_SECRET`: Optional. Secret for `--operator TYPE=encrypt`.
51
51
 
52
52
  Example `.env` file:
@@ -96,7 +96,7 @@ pdf-anonymizer run FILE_PATH [FILE_PATH ...] \
96
96
  - `--mapping-passphrase TEXT`: Lock the mapping as `*.mapping.json.enc` (AES-256-GCM + Argon2id). Also `ANONYMIZER_MAPPING_KEY`. Default: plaintext JSON.
97
97
  - `--ephemeral-mapping`: Do not write `data/mappings/`. The vocabulary stays in this process only.
98
98
  - `--operator TYPE=op`: How to write a type (`replace`, `mask`, `hash`, `generalize`, `shift`, `fake`, `encrypt`). Repeatable. Default is `replace`.
99
- - `--fake-secret TEXT`: Seed for `fake`. Also `ANONYMIZER_FAKE_SECRET`.
99
+ - `--fake-secret TEXT`: Required seed for `fake`. Also `ANONYMIZER_FAKE_SECRET`.
100
100
  - `--encrypt-secret TEXT`: Secret for `encrypt`. Also `ANONYMIZER_ENCRYPT_SECRET`. Required when any type uses `encrypt`.
101
101
  - `--risk / --no-risk`: After masking, score identity-clue clumps (default: on). Writes `data/stats/<stem>.risk.json`.
102
102
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pdf-anonymizer-cli"
3
- version = "0.30.0"
3
+ version = "0.32.0"
4
4
  description = "CLI for a tool to anonymize PDF, Markdown, plain text, CSV, Excel, and Word files using LLMs."
5
5
  authors = [{ name = "Leonid Ganeline", email = "leo.gan.57@gmail.com" }]
6
6
  license = { text = "MIT" }
@@ -9,7 +9,7 @@ requires-python = ">=3.10"
9
9
  dependencies = [
10
10
  "typer",
11
11
  "rich",
12
- "pdf-anonymizer-core>=0.30.0",
12
+ "pdf-anonymizer-core>=0.32.0",
13
13
  ]
14
14
 
15
15
  [project.optional-dependencies]
@@ -24,7 +24,9 @@ from pdf_anonymizer_core.core import (
24
24
  )
25
25
  from pdf_anonymizer_core.span_ner import resolve_semantic_stages
26
26
  from pdf_anonymizer_core.gazetteers import load_phrase_list
27
+ from pdf_anonymizer_core.call_llm import LLMIdentificationError
27
28
  from pdf_anonymizer_core.llm_provider import configure_cache
29
+ from pdf_anonymizer_core.purge import purge_local_artifacts
28
30
  from pdf_anonymizer_core.mapping_crypto import resolve_mapping_passphrase
29
31
  from pdf_anonymizer_core.operators import parse_operator_specs
30
32
  from pdf_anonymizer_core.prompts import detailed, hipaa, simple
@@ -51,11 +53,32 @@ from pdf_anonymizer_core.apply_residuals import (
51
53
  from pdf_anonymizer_core.verify import verify_anonymized_text, write_residual_report
52
54
  from typing_extensions import Annotated
53
55
 
54
- # Setup logging using log file configured in conf.py
56
+ def _private_log_handler(path: str) -> logging.Handler:
57
+ """Append to the log with mode 0600.
58
+
59
+ The log names files and models. It must not be readable by every account
60
+ on the machine.
61
+ """
62
+ directory = os.path.dirname(path)
63
+ if directory:
64
+ os.makedirs(directory, mode=0o700, exist_ok=True)
65
+ descriptor = os.open(path, os.O_CREAT | os.O_APPEND | os.O_WRONLY, 0o600)
66
+ try:
67
+ os.fchmod(descriptor, 0o600)
68
+ except OSError:
69
+ pass
70
+ stream = os.fdopen(descriptor, "a", encoding="utf-8")
71
+ handler = logging.StreamHandler(stream)
72
+ handler.setFormatter(
73
+ logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
74
+ )
75
+ return handler
76
+
77
+
78
+ # The log is created at import so a crash before the first command is still recorded.
55
79
  logging.basicConfig(
56
80
  level=logging.INFO,
57
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
58
- handlers=[logging.FileHandler(DEFAULT_LOG_FILE), logging.StreamHandler()],
81
+ handlers=[_private_log_handler(DEFAULT_LOG_FILE), logging.StreamHandler()],
59
82
  )
60
83
 
61
84
  app = typer.Typer()
@@ -185,6 +208,17 @@ def run(
185
208
  ),
186
209
  ),
187
210
  ] = False,
211
+ cache: Annotated[
212
+ bool,
213
+ typer.Option(
214
+ "--cache/--no-cache",
215
+ help=(
216
+ "Store language-model replies on disk. Off by default. "
217
+ "A reply contains the chunk and the extracted values. "
218
+ "The file is mode 0600 and entries expire after 24 hours."
219
+ ),
220
+ ),
221
+ ] = False,
188
222
  mapping_passphrase: Annotated[
189
223
  Optional[str],
190
224
  typer.Option(
@@ -272,7 +306,7 @@ def run(
272
306
  "--fake-secret",
273
307
  help=(
274
308
  "Seed for --operator TYPE=fake. Also ANONYMIZER_FAKE_SECRET. "
275
- "Same person always gets the same fake. Default is a built-in constant."
309
+ "Required when fake is used. Same person always gets the same fake."
276
310
  ),
277
311
  ),
278
312
  ] = None,
@@ -354,6 +388,38 @@ def run(
354
388
  case_sensitive=False,
355
389
  ),
356
390
  ] = None,
391
+ k: Annotated[
392
+ Optional[int],
393
+ typer.Option(
394
+ "--k",
395
+ help=(
396
+ "CSV/Excel only. Generalize or suppress quasi-identifier "
397
+ "columns until each combination appears at least K times. "
398
+ "Does not rewrite PDFs. An aid, not a privacy certificate."
399
+ ),
400
+ min=2,
401
+ ),
402
+ ] = None,
403
+ quasi_columns: Annotated[
404
+ Optional[str],
405
+ typer.Option(
406
+ "--quasi-columns",
407
+ help=(
408
+ "Comma-separated quasi-identifier headers for --k. "
409
+ "Default: headers such as zip, gender, age, and birth date."
410
+ ),
411
+ ),
412
+ ] = None,
413
+ sensitive_column: Annotated[
414
+ Optional[str],
415
+ typer.Option(
416
+ "--sensitive-column",
417
+ help=(
418
+ "Column used only to report ℓ-diversity and t-closeness "
419
+ "with --k. It is not generalized."
420
+ ),
421
+ ),
422
+ ] = None,
357
423
  ) -> None:
358
424
  """
359
425
  Anonymize one or more files by replacing PII with anonymized placeholders.
@@ -421,14 +487,13 @@ def run(
421
487
  logging.warning("--verify-llm is ignored when the language model is off.")
422
488
  verify_llm = False
423
489
 
424
- if use_llm:
425
- # Configure LLM caching with values from configuration
426
- configure_cache(
427
- enabled=config.enable_cache,
428
- cache_dir=config.cache_dir,
429
- cache_file=config.cache_file,
430
- )
490
+ configure_cache(
491
+ enabled=bool(cache) and use_llm,
492
+ cache_dir=config.cache_dir,
493
+ cache_file=config.cache_file,
494
+ )
431
495
 
496
+ if use_llm:
432
497
  provider_name, _ = get_provider_and_model_name(config.model_name)
433
498
  if provider_name == "google":
434
499
  if "gemini" in config.model_name and not os.getenv("GOOGLE_API_KEY"):
@@ -492,6 +557,28 @@ def run(
492
557
  if deny_phrases:
493
558
  logging.info(" --deny-list: %s phrase(s)", len(deny_phrases))
494
559
 
560
+ table_privacy = None
561
+ if k is not None:
562
+ non_tables = [path for path in file_paths if not is_tabular_path(str(path))]
563
+ if non_tables:
564
+ logging.error(
565
+ "--k applies only to CSV and Excel. It does not rewrite %s.",
566
+ ", ".join(str(path) for path in non_tables),
567
+ )
568
+ sys.exit(1)
569
+ quasi = None
570
+ if quasi_columns:
571
+ quasi = [part.strip() for part in quasi_columns.split(",") if part.strip()]
572
+ table_privacy = {
573
+ "k": k,
574
+ "quasi_columns": quasi,
575
+ "sensitive_column": sensitive_column,
576
+ }
577
+ logging.info(
578
+ " --k: %s (table aid, not a certificate)",
579
+ k,
580
+ )
581
+
495
582
  logging.info(f"Found {len(file_paths)} file(s) to process.")
496
583
 
497
584
  seed_mapping = None
@@ -553,6 +640,11 @@ def run(
553
640
  use_llm=use_llm,
554
641
  use_ner=use_ner,
555
642
  min_confidence=min_confidence,
643
+ k=k,
644
+ quasi_columns=(
645
+ table_privacy["quasi_columns"] if table_privacy else None
646
+ ),
647
+ sensitive_column=sensitive_column,
556
648
  )
557
649
  )
558
650
  else:
@@ -578,7 +670,7 @@ def run(
578
670
  ocr=ocr,
579
671
  min_confidence=min_confidence,
580
672
  )
581
- except ValueError as exc:
673
+ except (ValueError, LLMIdentificationError) as exc:
582
674
  logging.error("%s", exc)
583
675
  sys.exit(1)
584
676
 
@@ -612,6 +704,7 @@ def run(
612
704
  ),
613
705
  output_pdf=want_pdf,
614
706
  redact=redact,
707
+ table_privacy=table_privacy,
615
708
  )
616
709
  logging.info(f"Anonymization for {file_path} complete!")
617
710
  logging.info(f"Anonymized text saved into '{anonymized_output_file}'")
@@ -1027,5 +1120,27 @@ def apply(
1027
1120
  logging.info(" hid %s", text)
1028
1121
 
1029
1122
 
1123
+ @app.command()
1124
+ def purge(
1125
+ root: Annotated[
1126
+ Path,
1127
+ typer.Option(
1128
+ "--root",
1129
+ help="Directory that contains data/ and app.log.",
1130
+ exists=True,
1131
+ file_okay=False,
1132
+ dir_okay=True,
1133
+ resolve_path=True,
1134
+ ),
1135
+ ] = Path("."),
1136
+ ) -> None:
1137
+ """Delete the local cache, mapping files, stats, and app.log.
1138
+
1139
+ Anonymized and deanonymized documents are left in place.
1140
+ """
1141
+ removed = purge_local_artifacts(root)
1142
+ logging.info("Removed %s local artifact(s).", len(removed))
1143
+
1144
+
1030
1145
  if __name__ == "__main__":
1031
1146
  app()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pdf-anonymizer-cli
3
- Version: 0.30.0
3
+ Version: 0.32.0
4
4
  Summary: CLI for a tool to anonymize PDF, Markdown, plain text, CSV, Excel, and Word files using LLMs.
5
5
  Author-email: Leonid Ganeline <leo.gan.57@gmail.com>
6
6
  License: MIT
@@ -9,7 +9,7 @@ Requires-Python: >=3.10
9
9
  Description-Content-Type: text/markdown
10
10
  Requires-Dist: typer
11
11
  Requires-Dist: rich
12
- Requires-Dist: pdf-anonymizer-core>=0.30.0
12
+ Requires-Dist: pdf-anonymizer-core>=0.32.0
13
13
  Provides-Extra: excel
14
14
  Requires-Dist: pdf-anonymizer-core[excel]; extra == "excel"
15
15
  Provides-Extra: docx
@@ -25,7 +25,7 @@ A command-line interface for anonymizing PDF, Markdown, and plain text files usi
25
25
  - **Identity clues**: With `-p best-quality` or `--prompt-name detailed`, the tool also hides phrases that point to one person without writing their name (for example "the CEO of Tesla"). The default `best-speed` profile does not.
26
26
  - **Checksum labels**: After the fast number search, a real IBAN becomes `IBAN_1` and a mistyped one becomes `IBAN_LIKE_1`. Both are hidden. Same idea for cards, VINs, and a few national IDs.
27
27
  - **Operators, reports, and lists**: `--operator TYPE=mask|hash|generalize|shift|fake|encrypt`, leftover scan (`verify`), linkage-risk score (`report`), `--keep-list` / `--deny-list`, `--mapping-in`, optional locked maps, HIPAA coverage aid. See the [CLI History](https://leo-gan.github.io/anonymizer/project/cli-usage/#history).
28
- - **Large File Support**: Consistently anonymizes large files (tested up to 1GB).
28
+ - **File size**: Text and PDF are read into memory and then split into chunks. CSV, Excel, and Word are refused above 50 MiB. A measured 100 MB text run is in the [recipes](https://leo-gan.github.io/anonymizer/project/recipes/#processing-very-large-documents). There is no tested 1 GB path.
29
29
  - **Multi-Provider & Cost-Effective**: Free to use with local [Ollama](https://ollama.com/) models. It also supports major providers like [OpenAI](https://openai.com/), [Anthropic](https://www.anthropic.com/), [Google](https://ai.google.com/), [Hugging Face](https://huggingface.co/), and [OpenRouter](https://openrouter.ai/).
30
30
  - **Reversible**: Supports deanonymization to recover original data when needed.
31
31
  - **Multi-Format**: Works with PDF, Markdown, plain text, CSV, Excel, and Word (`.docx`) files.
@@ -65,7 +65,7 @@ The CLI will automatically load a `.env` file from the current directory or any
65
65
  - `ANTHROPIC_API_KEY`: Required when using Anthropic models.
66
66
  - `OLLAMA_HOST`: Optional, defaults to `http://localhost:11434` when using Ollama models.
67
67
  - `ANONYMIZER_MAPPING_KEY`: Optional. Same as `--mapping-passphrase` (writes `*.mapping.json.enc`).
68
- - `ANONYMIZER_FAKE_SECRET`: Optional. Seed for `--operator TYPE=fake`.
68
+ - `ANONYMIZER_FAKE_SECRET`: Required when `--operator` uses `fake`. There is no built-in seed.
69
69
  - `ANONYMIZER_ENCRYPT_SECRET`: Optional. Secret for `--operator TYPE=encrypt`.
70
70
 
71
71
  Example `.env` file:
@@ -115,7 +115,7 @@ pdf-anonymizer run FILE_PATH [FILE_PATH ...] \
115
115
  - `--mapping-passphrase TEXT`: Lock the mapping as `*.mapping.json.enc` (AES-256-GCM + Argon2id). Also `ANONYMIZER_MAPPING_KEY`. Default: plaintext JSON.
116
116
  - `--ephemeral-mapping`: Do not write `data/mappings/`. The vocabulary stays in this process only.
117
117
  - `--operator TYPE=op`: How to write a type (`replace`, `mask`, `hash`, `generalize`, `shift`, `fake`, `encrypt`). Repeatable. Default is `replace`.
118
- - `--fake-secret TEXT`: Seed for `fake`. Also `ANONYMIZER_FAKE_SECRET`.
118
+ - `--fake-secret TEXT`: Required seed for `fake`. Also `ANONYMIZER_FAKE_SECRET`.
119
119
  - `--encrypt-secret TEXT`: Secret for `encrypt`. Also `ANONYMIZER_ENCRYPT_SECRET`. Required when any type uses `encrypt`.
120
120
  - `--risk / --no-risk`: After masking, score identity-clue clumps (default: on). Writes `data/stats/<stem>.risk.json`.
121
121
 
@@ -1,6 +1,6 @@
1
1
  typer
2
2
  rich
3
- pdf-anonymizer-core>=0.30.0
3
+ pdf-anonymizer-core>=0.32.0
4
4
 
5
5
  [docx]
6
6
  pdf-anonymizer-core[docx]