cuttle-pii 0.1.0__py3-none-any.whl
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.
- cuttle/__init__.py +1 -0
- cuttle/__main__.py +6 -0
- cuttle/adapters/__init__.py +1 -0
- cuttle/adapters/cli_adapter.py +658 -0
- cuttle/adapters/config_loader.py +114 -0
- cuttle/adapters/config_locator.py +69 -0
- cuttle/adapters/file_io.py +55 -0
- cuttle/adapters/format_settings.py +106 -0
- cuttle/adapters/formatters.py +247 -0
- cuttle/adapters/setup_models.py +167 -0
- cuttle/adapters/terminal.py +218 -0
- cuttle/cli/__init__.py +10 -0
- cuttle/cli/app.py +189 -0
- cuttle/cli/commands.py +358 -0
- cuttle/config/formats.json +91 -0
- cuttle/config/patterns.json +804 -0
- cuttle/config/values.json +467 -0
- cuttle/core/__init__.py +12 -0
- cuttle/core/anonymizer_engine.py +1177 -0
- cuttle/core/config_documents.py +53 -0
- cuttle/core/config_merge.py +109 -0
- cuttle/core/detection.py +126 -0
- cuttle/core/detection_modes.py +34 -0
- cuttle/core/entity_identity.py +133 -0
- cuttle/core/input_decoding.py +144 -0
- cuttle/core/nlp_models.py +39 -0
- cuttle/core/report.py +140 -0
- cuttle/core/value_identity.py +155 -0
- cuttle/core/values_generator.py +434 -0
- cuttle/core/values_picker.py +220 -0
- cuttle_pii-0.1.0.dist-info/METADATA +223 -0
- cuttle_pii-0.1.0.dist-info/RECORD +36 -0
- cuttle_pii-0.1.0.dist-info/WHEEL +5 -0
- cuttle_pii-0.1.0.dist-info/entry_points.txt +2 -0
- cuttle_pii-0.1.0.dist-info/licenses/LICENSE +674 -0
- cuttle_pii-0.1.0.dist-info/top_level.txt +1 -0
cuttle/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Cuttle package
|
cuttle/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Adapter layer for CLI integrations."""
|
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
logger = logging.getLogger(__name__)
|
|
7
|
+
|
|
8
|
+
# Checked without importing: pyperclip is loaded only when the user picks a
|
|
9
|
+
# clipboard action, so runs that never touch the clipboard do not pay for it.
|
|
10
|
+
CLIPBOARD_AVAILABLE = importlib.util.find_spec("pyperclip") is not None
|
|
11
|
+
|
|
12
|
+
from cuttle.adapters.file_io import UnsafeOutputPathError, read_input_file, write_text_no_symlink
|
|
13
|
+
from cuttle.adapters.format_settings import (
|
|
14
|
+
get_format_detail,
|
|
15
|
+
get_format_fields,
|
|
16
|
+
resolve_format_preference,
|
|
17
|
+
set_format_preference,
|
|
18
|
+
)
|
|
19
|
+
from cuttle.adapters.formatters import (
|
|
20
|
+
get_engine_status,
|
|
21
|
+
print_banner,
|
|
22
|
+
render_results_screen,
|
|
23
|
+
render_screen,
|
|
24
|
+
)
|
|
25
|
+
from cuttle.adapters.setup_models import run_wizard
|
|
26
|
+
from cuttle.adapters.terminal import Confirm, Prompt, console, sanitize
|
|
27
|
+
from cuttle.core.input_decoding import DecodedInput, InputDecodeError, decode_input
|
|
28
|
+
from cuttle.core.nlp_models import get_installed_models
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _disable_newline_translation(stream) -> None:
|
|
32
|
+
"""Make *stream* pass line endings through unchanged (``newline=""``).
|
|
33
|
+
|
|
34
|
+
Standard streams are opened with universal newlines, which turns CRLF into
|
|
35
|
+
LF on read and LF into ``os.linesep`` on write. That makes the output
|
|
36
|
+
platform-dependent and breaks diffs and checksums, so the payload streams
|
|
37
|
+
are switched to untranslated mode. Streams that cannot be reconfigured
|
|
38
|
+
(e.g. ``io.StringIO`` in tests) already do not translate and are left alone.
|
|
39
|
+
"""
|
|
40
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
41
|
+
if reconfigure is None:
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
reconfigure(newline="")
|
|
45
|
+
except (ValueError, OSError):
|
|
46
|
+
logger.debug("Could not disable newline translation on %r", stream, exc_info=True)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def read_stdin(encoding: str | None = None) -> DecodedInput:
|
|
50
|
+
"""Read all of stdin as bytes and decode it, preserving its line endings.
|
|
51
|
+
|
|
52
|
+
Reading the raw buffer avoids the console's locale codec, which would
|
|
53
|
+
corrupt UTF-16 or non-UTF-8 input before Cuttle could see it. Streams with
|
|
54
|
+
no byte buffer (e.g. ``io.StringIO`` in tests) are already text and are
|
|
55
|
+
returned as read.
|
|
56
|
+
|
|
57
|
+
:param encoding: codec from ``--encoding``, or ``None`` to auto-detect.
|
|
58
|
+
:raises InputDecodeError: on undecodable or binary input.
|
|
59
|
+
"""
|
|
60
|
+
buffer = getattr(sys.stdin, "buffer", None)
|
|
61
|
+
if buffer is not None:
|
|
62
|
+
return decode_input(buffer.read(), encoding)
|
|
63
|
+
_disable_newline_translation(sys.stdin)
|
|
64
|
+
return DecodedInput(text=sys.stdin.read(), encoding=encoding or "utf-8")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class UnencodableOutputError(ValueError):
|
|
68
|
+
"""Raised when the terminal's encoding cannot represent the sanitized text.
|
|
69
|
+
|
|
70
|
+
:ivar encoding: the terminal's encoding.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, encoding: str):
|
|
74
|
+
super().__init__(f"the terminal encoding ({encoding}) cannot display the output")
|
|
75
|
+
self.encoding = encoding
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _is_tty(stream) -> bool:
|
|
79
|
+
isatty = getattr(stream, "isatty", None)
|
|
80
|
+
try:
|
|
81
|
+
return bool(isatty and isatty())
|
|
82
|
+
except (ValueError, OSError):
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def write_stdout(text: str):
|
|
87
|
+
"""Write the sanitized *text* to stdout without altering a single character.
|
|
88
|
+
|
|
89
|
+
Redirected stdout uses the locale code page (cp1252 on Windows), which would
|
|
90
|
+
corrupt the payload, so a pipe or file receives UTF-8 bytes: the same bytes
|
|
91
|
+
``-o`` writes. A terminal is written as text, since raw UTF-8 would show as
|
|
92
|
+
mojibake on a non-UTF-8 console; if it cannot encode the text, nothing is
|
|
93
|
+
written. Line endings are kept as they are in *text*.
|
|
94
|
+
|
|
95
|
+
:raises UnencodableOutputError: when stdout is a terminal that cannot encode *text*.
|
|
96
|
+
"""
|
|
97
|
+
stdout = sys.stdout
|
|
98
|
+
buffer = getattr(stdout, "buffer", None)
|
|
99
|
+
if buffer is not None and not _is_tty(stdout):
|
|
100
|
+
stdout.flush()
|
|
101
|
+
buffer.write(text.encode("utf-8"))
|
|
102
|
+
buffer.flush()
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
_disable_newline_translation(stdout)
|
|
106
|
+
try:
|
|
107
|
+
# TextIOWrapper encodes the whole string before writing, so a failure writes nothing.
|
|
108
|
+
stdout.write(text)
|
|
109
|
+
except UnicodeEncodeError as e:
|
|
110
|
+
raise UnencodableOutputError(getattr(stdout, "encoding", None) or "unknown") from e
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _menu_entry(key, label: str) -> str:
|
|
114
|
+
return f" [{key}] {label}"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def check_and_setup_models(engine, prompt_for_install: bool = True):
|
|
118
|
+
"""Offer to install a language model when the engine is in pattern mode."""
|
|
119
|
+
if engine.detection_mode == "fast_mode" or engine.use_presidio or not prompt_for_install:
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
models = get_installed_models()
|
|
123
|
+
if not models:
|
|
124
|
+
render_screen(
|
|
125
|
+
console,
|
|
126
|
+
"Language Model Setup",
|
|
127
|
+
[
|
|
128
|
+
(
|
|
129
|
+
"Install a small language model to enable language-model-based detection.",
|
|
130
|
+
"warn",
|
|
131
|
+
),
|
|
132
|
+
(
|
|
133
|
+
"\nCuttle already protects IPs, emails, credentials, and other patterns with pattern detection.\n"
|
|
134
|
+
"To also catch personal names, organizations, and locations automatically,\n"
|
|
135
|
+
"you can install a small language model now.\n\n"
|
|
136
|
+
"Would you like to set it up now?",
|
|
137
|
+
None,
|
|
138
|
+
),
|
|
139
|
+
],
|
|
140
|
+
style="warn",
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
choice = Confirm.ask("Install language model now?", default=True)
|
|
144
|
+
if choice:
|
|
145
|
+
run_wizard(console)
|
|
146
|
+
engine.use_presidio = True
|
|
147
|
+
engine.init_engines()
|
|
148
|
+
if not engine.use_presidio:
|
|
149
|
+
console.print(
|
|
150
|
+
"Continuing in Fast mode - pattern detection remains active.\n", "warn"
|
|
151
|
+
)
|
|
152
|
+
else:
|
|
153
|
+
console.print(f"{engine.get_mode_name()} enabled. Detection is active.\n", "ok")
|
|
154
|
+
Prompt.ask("\nPress ENTER to continue")
|
|
155
|
+
else:
|
|
156
|
+
render_screen(
|
|
157
|
+
console,
|
|
158
|
+
"Fast Mode",
|
|
159
|
+
[
|
|
160
|
+
("Cuttle will use pattern detection.", "warn"),
|
|
161
|
+
("\nPress ENTER to continue.", None),
|
|
162
|
+
],
|
|
163
|
+
style="warn",
|
|
164
|
+
)
|
|
165
|
+
Prompt.ask("")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def run_format_configuration_wizard(engine):
|
|
169
|
+
"""Interactive wizard to configure regional format preferences.
|
|
170
|
+
|
|
171
|
+
Shows all configurable fields from formats.json, lets the user pick a
|
|
172
|
+
field, choose an available code, and persists the choice in config.json.
|
|
173
|
+
Choosing 'global' removes the explicit preference (implicit default).
|
|
174
|
+
"""
|
|
175
|
+
formats = engine.formats
|
|
176
|
+
config_path = engine.config_path
|
|
177
|
+
|
|
178
|
+
while True:
|
|
179
|
+
fields = get_format_fields(formats)
|
|
180
|
+
if not fields:
|
|
181
|
+
console.print("No configurable format fields found.", "error")
|
|
182
|
+
Prompt.ask("\nPress ENTER to return")
|
|
183
|
+
return
|
|
184
|
+
|
|
185
|
+
lines = ["Configure output formats:\n"]
|
|
186
|
+
for i, field in enumerate(fields, 1):
|
|
187
|
+
code = resolve_format_preference(engine.format_preferences, field)
|
|
188
|
+
detail = get_format_detail(formats, field, code)
|
|
189
|
+
fmt = detail.get("format", "N/A")
|
|
190
|
+
example = detail.get("example", "N/A")
|
|
191
|
+
lines.append(_menu_entry(i, f"{field:8s} -> {code} ({fmt} - e.g. {example})"))
|
|
192
|
+
back_idx = len(fields) + 1
|
|
193
|
+
lines.append(_menu_entry(back_idx, "<- Back"))
|
|
194
|
+
|
|
195
|
+
# Field names, codes and examples come from formats.json, which the user may override.
|
|
196
|
+
render_screen(console, "Format Configuration", sanitize("\n".join(lines)))
|
|
197
|
+
|
|
198
|
+
choices = [str(i) for i in range(1, back_idx + 1)]
|
|
199
|
+
choice = Prompt.ask("\nSelect field to configure", choices=choices, default=str(back_idx))
|
|
200
|
+
|
|
201
|
+
idx = int(choice)
|
|
202
|
+
if idx == back_idx:
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
field = fields[idx - 1]
|
|
206
|
+
|
|
207
|
+
# Show available codes for the selected field.
|
|
208
|
+
field_formats = formats.get(field, {})
|
|
209
|
+
if not isinstance(field_formats, dict) or not field_formats:
|
|
210
|
+
console.print(sanitize(f"No codes available for '{field}'."), "error")
|
|
211
|
+
Prompt.ask("\nPress ENTER to continue")
|
|
212
|
+
continue
|
|
213
|
+
|
|
214
|
+
current_code = resolve_format_preference(engine.format_preferences, field)
|
|
215
|
+
code_list = list(field_formats.keys())
|
|
216
|
+
|
|
217
|
+
while True:
|
|
218
|
+
lines = [f"Select format for {field}:\n"]
|
|
219
|
+
for i, code in enumerate(code_list, 1):
|
|
220
|
+
detail = field_formats[code]
|
|
221
|
+
fmt = detail.get("format", "")
|
|
222
|
+
example = detail.get("example", "")
|
|
223
|
+
countries = ", ".join(detail.get("countries", []))
|
|
224
|
+
marker = " <- current" if code == current_code else ""
|
|
225
|
+
lines.append(
|
|
226
|
+
_menu_entry(i, f"{code}{marker}")
|
|
227
|
+
+ f"\n Format: {fmt} | Example: {example} | Countries: {countries}"
|
|
228
|
+
)
|
|
229
|
+
back_idx2 = len(code_list) + 1
|
|
230
|
+
lines.append(_menu_entry(back_idx2, "<- Back"))
|
|
231
|
+
|
|
232
|
+
render_screen(
|
|
233
|
+
console, sanitize(f"{field.capitalize()} Formats"), sanitize("\n".join(lines))
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
choices2 = [str(i) for i in range(1, back_idx2 + 1)]
|
|
237
|
+
code_choice = Prompt.ask(
|
|
238
|
+
"\nSelect format code", choices=choices2, default=str(back_idx2)
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
code_idx = int(code_choice)
|
|
242
|
+
if code_idx == back_idx2:
|
|
243
|
+
break
|
|
244
|
+
|
|
245
|
+
code = code_list[code_idx - 1]
|
|
246
|
+
success, msg = set_format_preference(config_path, field, code, formats)
|
|
247
|
+
if success:
|
|
248
|
+
# Reload in-memory preferences so subsequent steps reflect the change.
|
|
249
|
+
engine.set_format_preferences(engine.config.get("format_preferences", {}))
|
|
250
|
+
current_code = code
|
|
251
|
+
console.print(f"\n{sanitize(msg)}", "ok")
|
|
252
|
+
else:
|
|
253
|
+
console.print(f"\nError: {sanitize(msg)}", "error")
|
|
254
|
+
|
|
255
|
+
Prompt.ask("\nPress ENTER to continue")
|
|
256
|
+
break # return to field list after selection
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def run_model_management_wizard(engine):
|
|
260
|
+
"""Interactive wizard to manage language models."""
|
|
261
|
+
while True:
|
|
262
|
+
models = get_installed_models()
|
|
263
|
+
lines: list[tuple[str, str | None]] = [("Language Model Management\n", "info")]
|
|
264
|
+
if models:
|
|
265
|
+
lines.append(("Installed Models:", "ok"))
|
|
266
|
+
for m in models:
|
|
267
|
+
lines.append((f" * {sanitize(m)} (Installed & Ready)", None))
|
|
268
|
+
else:
|
|
269
|
+
lines.append(("Warning: No language models installed.", "warn"))
|
|
270
|
+
lines.append(("Cuttle is running in Fast mode (pattern detection only).", None))
|
|
271
|
+
|
|
272
|
+
lines.append(("\nOptions:", None))
|
|
273
|
+
lines.append((_menu_entry(1, "Install / Download a language model"), None))
|
|
274
|
+
lines.append((_menu_entry(2, "<- Back"), None))
|
|
275
|
+
|
|
276
|
+
render_screen(console, "Language Models", lines)
|
|
277
|
+
|
|
278
|
+
choice = Prompt.ask("\nSelect option", choices=["1", "2"], default="2")
|
|
279
|
+
if choice == "1":
|
|
280
|
+
run_wizard(console)
|
|
281
|
+
# Re-initialize engine to detect new models
|
|
282
|
+
engine.use_presidio = True
|
|
283
|
+
engine.init_engines()
|
|
284
|
+
Prompt.ask("\nPress ENTER to continue")
|
|
285
|
+
elif choice == "2":
|
|
286
|
+
return
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def run_settings_menu(engine):
|
|
290
|
+
"""Interactive settings menu to configure formats or manage language models."""
|
|
291
|
+
while True:
|
|
292
|
+
lines = [
|
|
293
|
+
"Settings Menu:\n",
|
|
294
|
+
_menu_entry(1, "Configure output formats"),
|
|
295
|
+
_menu_entry(2, "Manage language models"),
|
|
296
|
+
_menu_entry(3, "<- Back"),
|
|
297
|
+
]
|
|
298
|
+
render_screen(console, "Settings", "\n".join(lines))
|
|
299
|
+
|
|
300
|
+
choice = Prompt.ask("\nSelect option", choices=["1", "2", "3"], default="3")
|
|
301
|
+
if choice == "1":
|
|
302
|
+
run_format_configuration_wizard(engine)
|
|
303
|
+
elif choice == "2":
|
|
304
|
+
run_model_management_wizard(engine)
|
|
305
|
+
elif choice == "3":
|
|
306
|
+
return
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
#: A line holding only this marker ends direct (pasted/typed) input in the wizard.
|
|
310
|
+
MANUAL_INPUT_TERMINATOR = "."
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def read_manual_input() -> list[str] | None:
|
|
314
|
+
"""Read pasted or typed lines until the terminator line or end of input.
|
|
315
|
+
|
|
316
|
+
Blank lines are part of the text: multi-paragraph pastes, stack traces and
|
|
317
|
+
logs with blank separators must be read whole, otherwise the rest of the
|
|
318
|
+
paste stays in stdin and is consumed by later prompts as answers. Input
|
|
319
|
+
ends on a line holding only ``MANUAL_INPUT_TERMINATOR`` or on EOF
|
|
320
|
+
(Ctrl-D on Unix, Ctrl-Z + ENTER on Windows).
|
|
321
|
+
|
|
322
|
+
:returns: the lines read, or ``None`` when input ended before any line was
|
|
323
|
+
entered (the user wants to go back).
|
|
324
|
+
"""
|
|
325
|
+
lines: list[str] = []
|
|
326
|
+
try:
|
|
327
|
+
while True:
|
|
328
|
+
line = input()
|
|
329
|
+
if line.strip() == MANUAL_INPUT_TERMINATOR:
|
|
330
|
+
break
|
|
331
|
+
lines.append(line)
|
|
332
|
+
except EOFError:
|
|
333
|
+
pass
|
|
334
|
+
return lines or None
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def run_interactive_wizard(
|
|
338
|
+
engine,
|
|
339
|
+
strategy: str | None = None,
|
|
340
|
+
prompt_for_install: bool = True,
|
|
341
|
+
encoding: str | None = None,
|
|
342
|
+
):
|
|
343
|
+
"""Run the interactive Cuttle wizard: input → review → output.
|
|
344
|
+
|
|
345
|
+
:param encoding: codec for files loaded in the wizard, or ``None`` to auto-detect.
|
|
346
|
+
"""
|
|
347
|
+
print_banner(console)
|
|
348
|
+
check_and_setup_models(engine, prompt_for_install=prompt_for_install)
|
|
349
|
+
|
|
350
|
+
state = "SELECT_INPUT"
|
|
351
|
+
raw_text = ""
|
|
352
|
+
source_filename = None
|
|
353
|
+
selected_strategy = None
|
|
354
|
+
clean_text = ""
|
|
355
|
+
changes = []
|
|
356
|
+
unchanged = 0
|
|
357
|
+
|
|
358
|
+
while True:
|
|
359
|
+
if state == "SELECT_INPUT":
|
|
360
|
+
step1_choices = [
|
|
361
|
+
"How would you like to provide the text?\n",
|
|
362
|
+
_menu_entry(1, "Paste or type text directly"),
|
|
363
|
+
_menu_entry(2, "Load from a file"),
|
|
364
|
+
]
|
|
365
|
+
if CLIPBOARD_AVAILABLE:
|
|
366
|
+
step1_choices.append(_menu_entry(3, "Use text from my clipboard"))
|
|
367
|
+
|
|
368
|
+
# Settings option (inserted before Exit).
|
|
369
|
+
if not CLIPBOARD_AVAILABLE:
|
|
370
|
+
settings_opt = 3
|
|
371
|
+
exit_opt = 4
|
|
372
|
+
else:
|
|
373
|
+
settings_opt = 4
|
|
374
|
+
exit_opt = 5
|
|
375
|
+
step1_choices.append(_menu_entry(settings_opt, "Settings"))
|
|
376
|
+
step1_choices.append(_menu_entry(exit_opt, "Exit Cuttle"))
|
|
377
|
+
|
|
378
|
+
render_screen(console, "Protection Status", get_engine_status(engine))
|
|
379
|
+
console.print("\n" + "\n".join(step1_choices))
|
|
380
|
+
|
|
381
|
+
base = ["1", "2"]
|
|
382
|
+
if CLIPBOARD_AVAILABLE:
|
|
383
|
+
base.append("3")
|
|
384
|
+
choices = [*base, str(settings_opt), str(exit_opt)]
|
|
385
|
+
input_choice = Prompt.ask("\nYour choice", choices=choices, default="1")
|
|
386
|
+
|
|
387
|
+
if input_choice == str(exit_opt):
|
|
388
|
+
console.print("\nExiting Cuttle.", "ok")
|
|
389
|
+
return
|
|
390
|
+
|
|
391
|
+
if input_choice == str(settings_opt):
|
|
392
|
+
run_settings_menu(engine)
|
|
393
|
+
continue
|
|
394
|
+
|
|
395
|
+
if input_choice == "1":
|
|
396
|
+
state = "INPUT_MANUAL"
|
|
397
|
+
elif input_choice == "2":
|
|
398
|
+
state = "INPUT_FILE"
|
|
399
|
+
elif input_choice == "3" and CLIPBOARD_AVAILABLE:
|
|
400
|
+
state = "INPUT_CLIPBOARD"
|
|
401
|
+
|
|
402
|
+
elif state == "INPUT_MANUAL":
|
|
403
|
+
render_screen(
|
|
404
|
+
console,
|
|
405
|
+
"Direct Input",
|
|
406
|
+
"Paste or type your text below (blank lines are kept).\n"
|
|
407
|
+
f"When you're done, type {MANUAL_INPUT_TERMINATOR} on a line of its own "
|
|
408
|
+
"and press ENTER\n"
|
|
409
|
+
"(or press Ctrl-D, or Ctrl-Z + ENTER on Windows).\n"
|
|
410
|
+
f"Type {MANUAL_INPUT_TERMINATOR} right away to go back.",
|
|
411
|
+
style="warn",
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
lines = read_manual_input()
|
|
415
|
+
if lines is None:
|
|
416
|
+
state = "SELECT_INPUT"
|
|
417
|
+
continue
|
|
418
|
+
|
|
419
|
+
raw_text = "\n".join(lines)
|
|
420
|
+
if not raw_text.strip():
|
|
421
|
+
render_screen(
|
|
422
|
+
console,
|
|
423
|
+
"Empty Input",
|
|
424
|
+
[
|
|
425
|
+
("Oops! No text was entered.", "error"),
|
|
426
|
+
("\nPress ENTER to try again.", None),
|
|
427
|
+
],
|
|
428
|
+
style="error",
|
|
429
|
+
)
|
|
430
|
+
Prompt.ask("")
|
|
431
|
+
raw_text = ""
|
|
432
|
+
continue
|
|
433
|
+
|
|
434
|
+
state = "SELECT_STRATEGY"
|
|
435
|
+
|
|
436
|
+
elif state == "INPUT_FILE":
|
|
437
|
+
error_msg = ""
|
|
438
|
+
while True:
|
|
439
|
+
body: list[tuple[str, str | None]] = []
|
|
440
|
+
if error_msg:
|
|
441
|
+
body.append((error_msg + "\n", "error"))
|
|
442
|
+
body.append(("Enter the path to the file you want to protect.", None))
|
|
443
|
+
|
|
444
|
+
render_screen(console, "Load from File", body, style="warn")
|
|
445
|
+
|
|
446
|
+
file_path = Prompt.ask("File path (or 'back' to go back)")
|
|
447
|
+
file_path = file_path.strip().strip("'\"")
|
|
448
|
+
if file_path.lower() in ["exit", "back", "b"]:
|
|
449
|
+
state = "SELECT_INPUT"
|
|
450
|
+
break
|
|
451
|
+
if not os.path.exists(file_path):
|
|
452
|
+
error_msg = (
|
|
453
|
+
f"Could not find '{sanitize(file_path)}'. Check the path and try again."
|
|
454
|
+
)
|
|
455
|
+
continue
|
|
456
|
+
try:
|
|
457
|
+
# Decoded from bytes: line endings are kept and undecodable
|
|
458
|
+
# or binary files are refused instead of silently trimmed.
|
|
459
|
+
raw_text = read_input_file(file_path, encoding).text
|
|
460
|
+
source_filename = os.path.basename(file_path)
|
|
461
|
+
state = "SELECT_STRATEGY"
|
|
462
|
+
break
|
|
463
|
+
except InputDecodeError as e:
|
|
464
|
+
error_msg = f"Cannot read '{sanitize(file_path)}': {sanitize(str(e))}"
|
|
465
|
+
continue
|
|
466
|
+
except Exception as e:
|
|
467
|
+
logger.debug("Failed to read file in interactive wizard", exc_info=True)
|
|
468
|
+
error_msg = f"Failed to read file: {sanitize(str(e))}"
|
|
469
|
+
continue
|
|
470
|
+
|
|
471
|
+
elif state == "INPUT_CLIPBOARD":
|
|
472
|
+
try:
|
|
473
|
+
import pyperclip
|
|
474
|
+
|
|
475
|
+
clipboard_text = pyperclip.paste()
|
|
476
|
+
if not clipboard_text.strip():
|
|
477
|
+
render_screen(
|
|
478
|
+
console,
|
|
479
|
+
"Clipboard Empty",
|
|
480
|
+
[
|
|
481
|
+
("Your clipboard is empty!", "error"),
|
|
482
|
+
(
|
|
483
|
+
"\nCopy some text to your clipboard first, then come back here.\n\n"
|
|
484
|
+
"Press ENTER to return.",
|
|
485
|
+
None,
|
|
486
|
+
),
|
|
487
|
+
],
|
|
488
|
+
style="error",
|
|
489
|
+
)
|
|
490
|
+
Prompt.ask("")
|
|
491
|
+
state = "SELECT_INPUT"
|
|
492
|
+
else:
|
|
493
|
+
render_screen(
|
|
494
|
+
console,
|
|
495
|
+
"Clipboard Loaded",
|
|
496
|
+
[
|
|
497
|
+
(f"Got {len(clipboard_text)} characters from your clipboard!", "ok"),
|
|
498
|
+
("\nContinue?", None),
|
|
499
|
+
],
|
|
500
|
+
style="ok",
|
|
501
|
+
)
|
|
502
|
+
proceed = Prompt.ask(
|
|
503
|
+
"Continue? (y/n/back)", choices=["y", "n", "back", "b"], default="y"
|
|
504
|
+
)
|
|
505
|
+
if proceed.lower() in ["n", "back", "b"]:
|
|
506
|
+
state = "SELECT_INPUT"
|
|
507
|
+
else:
|
|
508
|
+
raw_text = clipboard_text
|
|
509
|
+
state = "SELECT_STRATEGY"
|
|
510
|
+
except Exception as e:
|
|
511
|
+
logger.debug("Clipboard read failed in interactive wizard", exc_info=True)
|
|
512
|
+
render_screen(
|
|
513
|
+
console,
|
|
514
|
+
"Clipboard Error",
|
|
515
|
+
[
|
|
516
|
+
(f"Could not access clipboard: {sanitize(str(e))}", "error"),
|
|
517
|
+
("\nPress ENTER to return.", None),
|
|
518
|
+
],
|
|
519
|
+
style="error",
|
|
520
|
+
)
|
|
521
|
+
Prompt.ask("")
|
|
522
|
+
state = "SELECT_INPUT"
|
|
523
|
+
|
|
524
|
+
elif state == "SELECT_STRATEGY":
|
|
525
|
+
if strategy:
|
|
526
|
+
selected_strategy = strategy
|
|
527
|
+
state = "PROCESS"
|
|
528
|
+
continue
|
|
529
|
+
|
|
530
|
+
render_screen(
|
|
531
|
+
console,
|
|
532
|
+
"Choose Protection Style",
|
|
533
|
+
"How should Cuttle replace sensitive data?\n\n"
|
|
534
|
+
+ "\n".join(
|
|
535
|
+
[
|
|
536
|
+
_menu_entry(1, "Realistic Fakes - Replace with deterministic fake values"),
|
|
537
|
+
" Example: fake IPs, emails, and domains",
|
|
538
|
+
_menu_entry(2, "Labels - Replace with tags like <EMAIL_1>, <IP_ADDRESS_1>"),
|
|
539
|
+
" Useful for structured output or documentation",
|
|
540
|
+
_menu_entry(
|
|
541
|
+
3, "Defang - Keep real values, neutralize URLs, emails, IPs, domains"
|
|
542
|
+
),
|
|
543
|
+
" Example: evil[.]com; secrets and names stay visible",
|
|
544
|
+
_menu_entry(4, "Realistic Fakes + Defang - Fake values, neutralized"),
|
|
545
|
+
" Example: user_123@example[.]com; nothing real, nothing clickable",
|
|
546
|
+
_menu_entry(5, "<- Go back"),
|
|
547
|
+
]
|
|
548
|
+
),
|
|
549
|
+
)
|
|
550
|
+
strategy_choice = Prompt.ask(
|
|
551
|
+
"\nYour choice", choices=["1", "2", "3", "4", "5"], default="1"
|
|
552
|
+
)
|
|
553
|
+
if strategy_choice == "5":
|
|
554
|
+
state = "SELECT_INPUT"
|
|
555
|
+
raw_text = ""
|
|
556
|
+
continue
|
|
557
|
+
|
|
558
|
+
selected_strategy = {"1": "mask", "2": "tag", "3": "defang", "4": "mask+defang"}[
|
|
559
|
+
strategy_choice
|
|
560
|
+
]
|
|
561
|
+
state = "PROCESS"
|
|
562
|
+
|
|
563
|
+
elif state == "PROCESS":
|
|
564
|
+
render_screen(console, "Processing", [("Processing text locally.", "ok")], style="ok")
|
|
565
|
+
console.print("Working on it...", "dim")
|
|
566
|
+
|
|
567
|
+
assert selected_strategy is not None
|
|
568
|
+
clean_text, report = engine.anonymize(raw_text, strategy=selected_strategy)
|
|
569
|
+
changes = report.substitutions
|
|
570
|
+
unchanged = report.unchanged_count
|
|
571
|
+
|
|
572
|
+
state = "OUTPUT_DELIVERY"
|
|
573
|
+
|
|
574
|
+
elif state == "OUTPUT_DELIVERY":
|
|
575
|
+
# Shown once: the screen is never cleared, so the delivery steps below
|
|
576
|
+
# print only their own status instead of repeating the results.
|
|
577
|
+
render_results_screen(
|
|
578
|
+
console,
|
|
579
|
+
engine,
|
|
580
|
+
clean_text,
|
|
581
|
+
changes,
|
|
582
|
+
strategy=selected_strategy,
|
|
583
|
+
unchanged=unchanged,
|
|
584
|
+
)
|
|
585
|
+
if CLIPBOARD_AVAILABLE:
|
|
586
|
+
copy_to_clip = Prompt.ask(
|
|
587
|
+
"Copy to clipboard? (y/n/back)", choices=["y", "n", "back", "b"], default="y"
|
|
588
|
+
)
|
|
589
|
+
|
|
590
|
+
if copy_to_clip.lower() in ["back", "b"]:
|
|
591
|
+
state = "SELECT_INPUT" if strategy else "SELECT_STRATEGY"
|
|
592
|
+
continue
|
|
593
|
+
|
|
594
|
+
if copy_to_clip.lower() == "y":
|
|
595
|
+
try:
|
|
596
|
+
import pyperclip
|
|
597
|
+
|
|
598
|
+
pyperclip.copy(clean_text)
|
|
599
|
+
console.print("Copied to clipboard.", "ok")
|
|
600
|
+
except Exception as e:
|
|
601
|
+
logger.debug("Clipboard copy failed", exc_info=True)
|
|
602
|
+
console.print(f"Clipboard copy failed: {sanitize(str(e))}", "error")
|
|
603
|
+
else:
|
|
604
|
+
console.print("Clipboard copy skipped.", "dim")
|
|
605
|
+
|
|
606
|
+
save_to_file = Prompt.ask(
|
|
607
|
+
"Save to file? (y/n/back)", choices=["y", "n", "back", "b"], default="n"
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
if save_to_file.lower() in ["back", "b"]:
|
|
611
|
+
state = "SELECT_INPUT" if strategy else "SELECT_STRATEGY"
|
|
612
|
+
continue
|
|
613
|
+
|
|
614
|
+
if save_to_file.lower() == "y":
|
|
615
|
+
default_out = "cuttle_output.txt"
|
|
616
|
+
if source_filename:
|
|
617
|
+
base, ext = os.path.splitext(source_filename)
|
|
618
|
+
default_out = f"{base}_anonymized{ext}"
|
|
619
|
+
|
|
620
|
+
save_cancelled = False
|
|
621
|
+
while True:
|
|
622
|
+
out_path = Prompt.ask(
|
|
623
|
+
"Where should Cuttle save the file? (or 'back' to go back)",
|
|
624
|
+
default=default_out,
|
|
625
|
+
)
|
|
626
|
+
out_path = out_path.strip().strip("'\"")
|
|
627
|
+
|
|
628
|
+
if out_path.lower() == "back":
|
|
629
|
+
save_cancelled = True
|
|
630
|
+
break
|
|
631
|
+
|
|
632
|
+
try:
|
|
633
|
+
write_text_no_symlink(out_path, clean_text)
|
|
634
|
+
console.print(f"Saved to {sanitize(out_path)}.", "ok")
|
|
635
|
+
break
|
|
636
|
+
except UnsafeOutputPathError as e:
|
|
637
|
+
console.print(f"{sanitize(str(e))} Please try again.", "error")
|
|
638
|
+
except Exception as e:
|
|
639
|
+
logger.debug("File save failed in interactive wizard", exc_info=True)
|
|
640
|
+
console.print(
|
|
641
|
+
f"Failed to save file: {sanitize(str(e))}. Please try again.", "error"
|
|
642
|
+
)
|
|
643
|
+
|
|
644
|
+
if save_cancelled:
|
|
645
|
+
state = "SELECT_INPUT" if strategy else "SELECT_STRATEGY"
|
|
646
|
+
continue
|
|
647
|
+
else:
|
|
648
|
+
console.print("Saving to file skipped.", "dim")
|
|
649
|
+
|
|
650
|
+
console.print("\nAll done! Ready for another text.", "info")
|
|
651
|
+
|
|
652
|
+
another = Confirm.ask("\nProcess another text?", default=True)
|
|
653
|
+
if not another:
|
|
654
|
+
console.print("\nGoodbye.", "ok")
|
|
655
|
+
break
|
|
656
|
+
state = "SELECT_INPUT"
|
|
657
|
+
raw_text = ""
|
|
658
|
+
source_filename = None
|