redactllm 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.
- redactllm/__init__.py +167 -0
- redactllm/__main__.py +5 -0
- redactllm/cli.py +92 -0
- redactllm/core/__init__.py +1 -0
- redactllm/core/config.py +138 -0
- redactllm/core/envfile.py +84 -0
- redactllm/core/normalize.py +31 -0
- redactllm/core/redactor.py +322 -0
- redactllm/core/vault.py +340 -0
- redactllm/detection/__init__.py +1 -0
- redactllm/detection/base.py +118 -0
- redactllm/detection/builtin.py +168 -0
- redactllm/detection/validators.py +136 -0
- redactllm/exceptions.py +16 -0
- redactllm/fakes.py +250 -0
- redactllm/http/__init__.py +1 -0
- redactllm/http/payloads.py +233 -0
- redactllm/http/sse.py +254 -0
- redactllm/http/transport.py +391 -0
- redactllm/integrations/__init__.py +12 -0
- redactllm/integrations/_common.py +140 -0
- redactllm/integrations/google_adk.py +251 -0
- redactllm/integrations/langchain.py +186 -0
- redactllm/integrations/litellm.py +268 -0
- redactllm/py.typed +0 -0
- redactllm/reveal.py +114 -0
- redactllm-0.1.0.dist-info/METADATA +506 -0
- redactllm-0.1.0.dist-info/RECORD +31 -0
- redactllm-0.1.0.dist-info/WHEEL +4 -0
- redactllm-0.1.0.dist-info/entry_points.txt +2 -0
- redactllm-0.1.0.dist-info/licenses/LICENSE +175 -0
redactllm/__init__.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""redactllm: keep personal data out of LLM APIs, and put it back in the answer.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
import redactllm
|
|
6
|
+
redactllm.install() # every OpenAI / Anthropic client created afterwards is protected
|
|
7
|
+
|
|
8
|
+
from openai import OpenAI
|
|
9
|
+
client = OpenAI() # unchanged
|
|
10
|
+
|
|
11
|
+
Or explicitly: ``redactllm.wrap(client)`` / ``OpenAI(http_client=redactllm.http_client())``.
|
|
12
|
+
Plain text: ``redactllm.redact("call 98450 12345").text`` -> ``"call <PHONE_1>"``.
|
|
13
|
+
|
|
14
|
+
No LLMs, no models, no network calls: detection is regex + checksums + context rules. Each LLM
|
|
15
|
+
request gets its own placeholder vault in your process memory, so users never see each other's data.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
import logging
|
|
23
|
+
from typing import Iterable, Mapping, Optional
|
|
24
|
+
|
|
25
|
+
from . import fakes, reveal
|
|
26
|
+
from .core.config import (
|
|
27
|
+
Config,
|
|
28
|
+
configure,
|
|
29
|
+
default_redactor,
|
|
30
|
+
effective_mode,
|
|
31
|
+
enabled,
|
|
32
|
+
get_config,
|
|
33
|
+
on_redact,
|
|
34
|
+
reset,
|
|
35
|
+
)
|
|
36
|
+
from .core.redactor import Entity, Redactor, RedactResult, context, session
|
|
37
|
+
from .core.vault import StreamRestorer, Vault
|
|
38
|
+
from .detection.base import Detector, PatternDetector, Span
|
|
39
|
+
from .exceptions import ConfigError, RedactionError, RedactLLMError
|
|
40
|
+
from .http.transport import async_http_client, http_client, install, installed, uninstall, unwrap, wrap
|
|
41
|
+
|
|
42
|
+
# A library must not configure logging; the app decides where redactllm's messages go.
|
|
43
|
+
logging.getLogger("redactllm").addHandler(logging.NullHandler())
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def redact(text: str, *, vault: Optional[Vault] = None) -> RedactResult:
|
|
47
|
+
"""Redact personal data in ``text`` using the default redactor.
|
|
48
|
+
Returns ``text`` unchanged when ``REDACTLLM_ENABLED=false``.
|
|
49
|
+
|
|
50
|
+
Restore with ``result.restore(answer)``: it puts back only this call's values. Without
|
|
51
|
+
``vault=`` or an active :func:`session`, the process-wide vault is used, which is shared by
|
|
52
|
+
every caller; don't pair it with module-level :func:`restore` on a multi-user server."""
|
|
53
|
+
if not enabled():
|
|
54
|
+
return RedactResult(text if isinstance(text, str) else "")
|
|
55
|
+
return default_redactor().redact(text, vault=vault)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def restore(text: str, *, vault: Optional[Vault] = None) -> str:
|
|
59
|
+
"""Put original values back in place of placeholders, from the active :func:`session` vault or
|
|
60
|
+
the process-wide one. On a multi-user server prefer ``RedactResult.restore()``."""
|
|
61
|
+
return default_redactor().restore(text, vault=vault)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def restore_partial(
|
|
65
|
+
text: str,
|
|
66
|
+
*,
|
|
67
|
+
rules: Optional[Mapping[str, object]] = None,
|
|
68
|
+
char: str = "*",
|
|
69
|
+
vault: Optional[Vault] = None,
|
|
70
|
+
) -> str:
|
|
71
|
+
"""Put original values back with part of each one hidden, chosen per label::
|
|
72
|
+
|
|
73
|
+
restore_partial("We'll call <PHONE_1>, <PERSON_1>") # "We'll call ******2345, Ravi"
|
|
74
|
+
|
|
75
|
+
Phone, Aadhaar, card, PAN... show their last 4 characters, emails and UPI IDs their first letter
|
|
76
|
+
and domain; names, addresses and your own labels come back in full. Override per label with a
|
|
77
|
+
function, an int (keep that many last characters), ``"show"`` or ``"hide"``:
|
|
78
|
+
``rules={"PHONE": 2, "PERSON": "hide", "EMPLOYEE_ID": redactllm.reveal.keep_first(3)}``."""
|
|
79
|
+
return default_redactor().restore_partial(text, rules=rules, char=char, vault=vault)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def detect(text: str) -> list:
|
|
83
|
+
"""Return detected spans without changing anything (none when ``REDACTLLM_ENABLED=false``)."""
|
|
84
|
+
if not enabled():
|
|
85
|
+
return []
|
|
86
|
+
return default_redactor().detect(text)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def add_pattern(label: str, pattern: str, **kwargs) -> None:
|
|
90
|
+
"""Add your own identifier format: ``add_pattern("EMPLOYEE_ID", r"\\bEMP-\\d{6}\\b")``."""
|
|
91
|
+
default_redactor().add_pattern(label, pattern, **kwargs)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def add_terms(label: str, terms: Iterable[str]) -> None:
|
|
95
|
+
"""Always redact these exact values (names, codenames, hostnames)."""
|
|
96
|
+
default_redactor().add_terms(label, terms)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def allow_terms(terms: Iterable[str]) -> None:
|
|
100
|
+
"""Never redact inside these values (your support email, company name...)."""
|
|
101
|
+
default_redactor().allow_terms(terms)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def add_detector(detector: Detector) -> None:
|
|
105
|
+
"""Plug in any detection logic (a :class:`Detector` subclass)."""
|
|
106
|
+
default_redactor().add_detector(detector)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def set_policy(policy: Optional[dict] = None, *, fake: Optional[bool] = None) -> None:
|
|
110
|
+
"""Per-label action: ``mask`` (default, reversible placeholder), ``fake`` (reversible realistic
|
|
111
|
+
fake value), ``hash``, ``drop`` or ``allow``::
|
|
112
|
+
|
|
113
|
+
set_policy({"PHONE": "fake", "EMAIL": "hash"})
|
|
114
|
+
set_policy(fake=True) # every masked label that can be faked gets a fake value
|
|
115
|
+
set_policy(fake=False) # back to placeholders (the default)
|
|
116
|
+
"""
|
|
117
|
+
default_redactor().set_policy(policy, fake=fake)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def set_faker(label: str, faker) -> None:
|
|
121
|
+
"""Fake values for your own label: ``set_faker("EMPLOYEE_ID", lambda v, rng: f"EMP-{rng.randint(0, 999999):06d}")``.
|
|
122
|
+
See :mod:`redactllm.fakes` for ready-made fakers."""
|
|
123
|
+
default_redactor().set_faker(label, faker)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
__all__ = [
|
|
127
|
+
"Config",
|
|
128
|
+
"ConfigError",
|
|
129
|
+
"Detector",
|
|
130
|
+
"Entity",
|
|
131
|
+
"PatternDetector",
|
|
132
|
+
"RedactLLMError",
|
|
133
|
+
"RedactResult",
|
|
134
|
+
"RedactionError",
|
|
135
|
+
"Redactor",
|
|
136
|
+
"Span",
|
|
137
|
+
"StreamRestorer",
|
|
138
|
+
"Vault",
|
|
139
|
+
"__version__",
|
|
140
|
+
"add_detector",
|
|
141
|
+
"add_pattern",
|
|
142
|
+
"add_terms",
|
|
143
|
+
"allow_terms",
|
|
144
|
+
"async_http_client",
|
|
145
|
+
"configure",
|
|
146
|
+
"context",
|
|
147
|
+
"detect",
|
|
148
|
+
"effective_mode",
|
|
149
|
+
"enabled",
|
|
150
|
+
"fakes",
|
|
151
|
+
"get_config",
|
|
152
|
+
"http_client",
|
|
153
|
+
"install",
|
|
154
|
+
"installed",
|
|
155
|
+
"on_redact",
|
|
156
|
+
"redact",
|
|
157
|
+
"reset",
|
|
158
|
+
"restore",
|
|
159
|
+
"restore_partial",
|
|
160
|
+
"reveal",
|
|
161
|
+
"session",
|
|
162
|
+
"set_faker",
|
|
163
|
+
"set_policy",
|
|
164
|
+
"uninstall",
|
|
165
|
+
"unwrap",
|
|
166
|
+
"wrap",
|
|
167
|
+
]
|
redactllm/__main__.py
ADDED
redactllm/cli.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Command line: try redaction on text or files.
|
|
2
|
+
|
|
3
|
+
echo "call me on 98450 12345" | redactllm
|
|
4
|
+
redactllm notes.txt --json
|
|
5
|
+
redactllm notes.txt --policy EMAIL=hash --policy IP_ADDRESS=allow
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Optional, Sequence
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from .core.redactor import Redactor
|
|
18
|
+
from .exceptions import ConfigError
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
22
|
+
p = argparse.ArgumentParser(
|
|
23
|
+
prog="redactllm", description="Redact personal data from text (no models, runs locally)."
|
|
24
|
+
)
|
|
25
|
+
p.add_argument("file", nargs="?", default="-", help="file to read, or - for stdin (default)")
|
|
26
|
+
p.add_argument("--json", action="store_true", help="print entities as JSON instead of text")
|
|
27
|
+
p.add_argument(
|
|
28
|
+
"--policy",
|
|
29
|
+
action="append",
|
|
30
|
+
default=[],
|
|
31
|
+
metavar="LABEL=ACTION",
|
|
32
|
+
help="mask (default), hash, drop or allow; repeatable",
|
|
33
|
+
)
|
|
34
|
+
p.add_argument("--version", action="version", version=f"redactllm {__version__}")
|
|
35
|
+
args = p.parse_args(argv)
|
|
36
|
+
|
|
37
|
+
policy = {}
|
|
38
|
+
for item in args.policy:
|
|
39
|
+
label, sep, action = item.partition("=")
|
|
40
|
+
if not sep or not label.strip() or not action.strip():
|
|
41
|
+
p.error(f"--policy expects LABEL=ACTION, got {item!r}")
|
|
42
|
+
policy[label.strip()] = action.strip()
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
redactor = Redactor(policy=policy)
|
|
46
|
+
except ConfigError as exc:
|
|
47
|
+
p.error(str(exc))
|
|
48
|
+
|
|
49
|
+
if args.file == "-":
|
|
50
|
+
text = sys.stdin.read()
|
|
51
|
+
else:
|
|
52
|
+
try:
|
|
53
|
+
text = Path(args.file).read_text(encoding="utf-8")
|
|
54
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
55
|
+
p.exit(2, f"redactllm: cannot read {args.file}: {exc}\n")
|
|
56
|
+
|
|
57
|
+
result = redactor.redact(text)
|
|
58
|
+
|
|
59
|
+
if args.json:
|
|
60
|
+
print( # noqa: T201 - CLI output
|
|
61
|
+
json.dumps(
|
|
62
|
+
{
|
|
63
|
+
"text": result.text,
|
|
64
|
+
"counts": result.counts,
|
|
65
|
+
"entities": [
|
|
66
|
+
{
|
|
67
|
+
"label": e.label,
|
|
68
|
+
"start": e.start,
|
|
69
|
+
"end": e.end,
|
|
70
|
+
"action": e.action,
|
|
71
|
+
"replacement": e.replacement,
|
|
72
|
+
"score": round(e.score, 2),
|
|
73
|
+
}
|
|
74
|
+
for e in result.entities
|
|
75
|
+
],
|
|
76
|
+
},
|
|
77
|
+
indent=2,
|
|
78
|
+
ensure_ascii=False,
|
|
79
|
+
)
|
|
80
|
+
)
|
|
81
|
+
else:
|
|
82
|
+
sys.stdout.write(result.text)
|
|
83
|
+
if result.text and not result.text.endswith("\n"):
|
|
84
|
+
sys.stdout.write("\n")
|
|
85
|
+
if result.entities:
|
|
86
|
+
summary = ", ".join(f"{k}: {v}" for k, v in result.counts.items())
|
|
87
|
+
print(f"\nredacted {len(result.entities)} item(s) ({summary})", file=sys.stderr) # noqa: T201
|
|
88
|
+
return 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__": # pragma: no cover
|
|
92
|
+
sys.exit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Redaction engine, global configuration, placeholder vault and restore rules."""
|
redactllm/core/config.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Global state: configuration, the REDACTLLM_ENABLED kill switch, audit hooks and the default redactor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import threading
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Callable, List, Mapping, Optional
|
|
9
|
+
|
|
10
|
+
from ..exceptions import ConfigError
|
|
11
|
+
from . import envfile
|
|
12
|
+
from .redactor import Redactor
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("redactllm")
|
|
15
|
+
|
|
16
|
+
MODES = ("redact", "detect", "off")
|
|
17
|
+
ON_ERROR = ("block", "passthrough")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Config:
|
|
22
|
+
mode: str = "redact" # redact | detect (dry run) | off
|
|
23
|
+
on_error: str = "block" # block | passthrough
|
|
24
|
+
log_counts: bool = True
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_config = Config()
|
|
28
|
+
_listeners: List[Callable[[dict], None]] = []
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def configure(
|
|
32
|
+
*,
|
|
33
|
+
mode: Optional[str] = None,
|
|
34
|
+
on_error: Optional[str] = None,
|
|
35
|
+
policy: Optional[Mapping[str, str]] = None,
|
|
36
|
+
min_score: Optional[float] = None,
|
|
37
|
+
hash_salt: Optional[str] = None,
|
|
38
|
+
log_counts: Optional[bool] = None,
|
|
39
|
+
fake: Optional[bool] = None,
|
|
40
|
+
) -> Config:
|
|
41
|
+
"""Change global behaviour. ``REDACTLLM_MODE`` (environment or ``.env``) always overrides ``mode``.
|
|
42
|
+
|
|
43
|
+
``fake=True`` sends realistic fake values instead of ``<PHONE_1>``-style placeholders (see
|
|
44
|
+
:func:`redactllm.set_policy`)."""
|
|
45
|
+
if mode is not None:
|
|
46
|
+
if mode not in MODES:
|
|
47
|
+
raise ConfigError(f"unknown mode {mode!r}; choose one of {MODES}")
|
|
48
|
+
_config.mode = mode
|
|
49
|
+
if on_error is not None:
|
|
50
|
+
if on_error not in ON_ERROR:
|
|
51
|
+
raise ConfigError(f"unknown on_error {on_error!r}; choose one of {ON_ERROR}")
|
|
52
|
+
_config.on_error = on_error
|
|
53
|
+
if policy is not None:
|
|
54
|
+
default_redactor().set_policy(policy)
|
|
55
|
+
if min_score is not None:
|
|
56
|
+
default_redactor().min_score = min_score
|
|
57
|
+
if hash_salt is not None:
|
|
58
|
+
default_redactor().hash_salt = hash_salt
|
|
59
|
+
if log_counts is not None:
|
|
60
|
+
_config.log_counts = log_counts
|
|
61
|
+
if fake is not None:
|
|
62
|
+
default_redactor().set_policy(fake=fake)
|
|
63
|
+
return _config
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_FALSE = ("0", "false", "no", "off", "disabled")
|
|
67
|
+
_TRUE = ("1", "true", "yes", "on", "enabled", "")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def enabled() -> bool:
|
|
71
|
+
"""``False`` when the kill switch ``REDACTLLM_ENABLED=false`` is set, in the environment or in
|
|
72
|
+
a ``.env`` file. Then redactllm does nothing at all: ``install()`` and ``wrap()`` patch nothing,
|
|
73
|
+
integrations pass requests through, and ``redact()`` returns text unchanged."""
|
|
74
|
+
raw = (envfile.get("REDACTLLM_ENABLED") or "").strip().lower()
|
|
75
|
+
if raw in _FALSE:
|
|
76
|
+
return False
|
|
77
|
+
if raw not in _TRUE:
|
|
78
|
+
logger.warning("redactllm: ignoring REDACTLLM_ENABLED=%r; use true or false", raw)
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def effective_mode() -> str:
|
|
83
|
+
"""The mode in force: ``off`` if disabled, else ``REDACTLLM_MODE`` (environment or ``.env``),
|
|
84
|
+
else the mode set with :func:`configure`."""
|
|
85
|
+
if not enabled():
|
|
86
|
+
return "off"
|
|
87
|
+
env = (envfile.get("REDACTLLM_MODE") or "").strip().lower()
|
|
88
|
+
return env if env in MODES else _config.mode
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def get_config() -> Config:
|
|
92
|
+
return _config
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def on_redact(fn: Callable[[dict], None]) -> Callable[[dict], None]:
|
|
96
|
+
"""Register an audit callback. It receives counts only, never the original values:
|
|
97
|
+
``{"direction": "request", "url": ..., "mode": "redact", "counts": {"PHONE": 1}}``."""
|
|
98
|
+
_listeners.append(fn)
|
|
99
|
+
return fn
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def clear_listeners() -> None:
|
|
103
|
+
_listeners.clear()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def emit_audit(event: dict) -> None:
|
|
107
|
+
if _config.log_counts and event.get("counts"):
|
|
108
|
+
logger.info("redactllm: %s %s %s", event.get("mode"), event.get("direction"), event["counts"])
|
|
109
|
+
for fn in _listeners:
|
|
110
|
+
try:
|
|
111
|
+
fn(event)
|
|
112
|
+
except Exception: # noqa: PERF203 - a broken audit hook must never break the app
|
|
113
|
+
logger.exception("redactllm: audit listener failed")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# --------------------------------------------------------------------------- default instance
|
|
117
|
+
|
|
118
|
+
_default: Optional[Redactor] = None
|
|
119
|
+
_default_lock = threading.Lock()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def default_redactor() -> Redactor:
|
|
123
|
+
global _default
|
|
124
|
+
if _default is None:
|
|
125
|
+
with _default_lock:
|
|
126
|
+
if _default is None:
|
|
127
|
+
_default = Redactor()
|
|
128
|
+
return _default
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def reset() -> None:
|
|
132
|
+
"""Restore the default configuration (mainly for tests)."""
|
|
133
|
+
global _default
|
|
134
|
+
with _default_lock:
|
|
135
|
+
_default = Redactor()
|
|
136
|
+
_config.mode, _config.on_error, _config.log_counts = "redact", "block", True
|
|
137
|
+
clear_listeners()
|
|
138
|
+
envfile.clear_cache()
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Read ``REDACTLLM_*`` settings from the process environment or a ``.env`` file.
|
|
2
|
+
|
|
3
|
+
No dependency on python-dotenv. The first ``.env`` found in the current directory or one of its
|
|
4
|
+
parents is read once, and only its ``REDACTLLM_*`` keys are used. A real environment variable always
|
|
5
|
+
wins over the file. Nothing is written to ``os.environ``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import threading
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Dict, Optional
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("redactllm")
|
|
17
|
+
|
|
18
|
+
PREFIX = "REDACTLLM_"
|
|
19
|
+
_cache: Optional[Dict[str, str]] = None
|
|
20
|
+
_lock = threading.Lock()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _find_env_file() -> Optional[Path]:
|
|
24
|
+
try:
|
|
25
|
+
here = Path.cwd()
|
|
26
|
+
except OSError:
|
|
27
|
+
return None
|
|
28
|
+
for folder in (here, *here.parents):
|
|
29
|
+
candidate = folder / ".env"
|
|
30
|
+
if candidate.is_file():
|
|
31
|
+
return candidate
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse(text: str) -> Dict[str, str]:
|
|
36
|
+
"""Parse ``KEY=VALUE`` lines: comments, blank lines, ``export`` and quotes are handled."""
|
|
37
|
+
out: Dict[str, str] = {}
|
|
38
|
+
for raw in text.splitlines():
|
|
39
|
+
line = raw.strip()
|
|
40
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
41
|
+
continue
|
|
42
|
+
if line.startswith("export "):
|
|
43
|
+
line = line[len("export ") :].lstrip()
|
|
44
|
+
key, _, value = line.partition("=")
|
|
45
|
+
key, value = key.strip(), value.strip()
|
|
46
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
|
47
|
+
value = value[1:-1]
|
|
48
|
+
elif " #" in value:
|
|
49
|
+
value = value.split(" #", 1)[0].rstrip()
|
|
50
|
+
if key:
|
|
51
|
+
out[key] = value
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _file_values() -> Dict[str, str]:
|
|
56
|
+
global _cache
|
|
57
|
+
if _cache is None:
|
|
58
|
+
with _lock:
|
|
59
|
+
if _cache is None:
|
|
60
|
+
values: Dict[str, str] = {}
|
|
61
|
+
path = _find_env_file()
|
|
62
|
+
if path is not None:
|
|
63
|
+
try:
|
|
64
|
+
parsed = parse(path.read_text(encoding="utf-8"))
|
|
65
|
+
values = {k: v for k, v in parsed.items() if k.startswith(PREFIX)}
|
|
66
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
67
|
+
logger.warning("redactllm: could not read %s: %s", path, exc)
|
|
68
|
+
_cache = values
|
|
69
|
+
return _cache
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def get(key: str) -> Optional[str]:
|
|
73
|
+
"""Value of ``key`` from the environment, else from ``.env``, else ``None``."""
|
|
74
|
+
value = os.environ.get(key)
|
|
75
|
+
if value is not None:
|
|
76
|
+
return value
|
|
77
|
+
return _file_values().get(key)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def clear_cache() -> None:
|
|
81
|
+
"""Forget the ``.env`` contents so the next lookup reads the file again."""
|
|
82
|
+
global _cache
|
|
83
|
+
with _lock:
|
|
84
|
+
_cache = None
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Text normalization that keeps character offsets stable.
|
|
2
|
+
|
|
3
|
+
Every Unicode decimal digit (Devanagari ०-९, Bengali ০-৯, Tamil, Gujarati, Odia, Arabic-Indic,
|
|
4
|
+
full-width, ...) is mapped to its ASCII digit. Each digit is a single code point on both sides, so
|
|
5
|
+
offsets found in the normalized text are valid in the original text.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import unicodedata
|
|
11
|
+
|
|
12
|
+
_TABLE: dict = {}
|
|
13
|
+
for cp in range(0x80, 0x1FC00): # every Unicode decimal-digit block lives in this range
|
|
14
|
+
ch = chr(cp)
|
|
15
|
+
if ch.isdigit() and not ("0" <= ch <= "9"):
|
|
16
|
+
try:
|
|
17
|
+
_TABLE[cp] = str(unicodedata.decimal(ch))
|
|
18
|
+
except (TypeError, ValueError):
|
|
19
|
+
continue
|
|
20
|
+
# NO-BREAK SPACE and friends behave like plain spaces inside numbers
|
|
21
|
+
for cp in (0x00A0, 0x2007, 0x202F):
|
|
22
|
+
_TABLE[cp] = " "
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize(text: str) -> str:
|
|
26
|
+
"""Same length as ``text``; non-ASCII digits become ASCII digits."""
|
|
27
|
+
return text.translate(_TABLE)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def digits_only(text: str) -> str:
|
|
31
|
+
return "".join(ch for ch in normalize(text) if ch.isdigit())
|