datahub-ai-classifier 0.1.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.
- datahub_ai_classifier-0.1.0/LICENSE +21 -0
- datahub_ai_classifier-0.1.0/PKG-INFO +76 -0
- datahub_ai_classifier-0.1.0/README.md +62 -0
- datahub_ai_classifier-0.1.0/pyproject.toml +24 -0
- datahub_ai_classifier-0.1.0/setup.cfg +4 -0
- datahub_ai_classifier-0.1.0/src/datahub_ai_classifier.egg-info/PKG-INFO +76 -0
- datahub_ai_classifier-0.1.0/src/datahub_ai_classifier.egg-info/SOURCES.txt +20 -0
- datahub_ai_classifier-0.1.0/src/datahub_ai_classifier.egg-info/dependency_links.txt +1 -0
- datahub_ai_classifier-0.1.0/src/datahub_ai_classifier.egg-info/entry_points.txt +2 -0
- datahub_ai_classifier-0.1.0/src/datahub_ai_classifier.egg-info/requires.txt +5 -0
- datahub_ai_classifier-0.1.0/src/datahub_ai_classifier.egg-info/top_level.txt +1 -0
- datahub_ai_classifier-0.1.0/src/datahub_classifier/__init__.py +5 -0
- datahub_ai_classifier-0.1.0/src/datahub_classifier/classifier.py +240 -0
- datahub_ai_classifier-0.1.0/src/datahub_classifier/llm_client.py +93 -0
- datahub_ai_classifier-0.1.0/src/datahub_classifier/tagger.py +152 -0
- datahub_ai_classifier-0.1.0/src/datahub_classifier/taxonomy.py +73 -0
- datahub_ai_classifier-0.1.0/tests/test_classifier.py +322 -0
- datahub_ai_classifier-0.1.0/tests/test_classifier_llm_client.py +138 -0
- datahub_ai_classifier-0.1.0/tests/test_datahub_classification.py +155 -0
- datahub_ai_classifier-0.1.0/tests/test_plugin_names.py +7 -0
- datahub_ai_classifier-0.1.0/tests/test_tagger.py +227 -0
- datahub_ai_classifier-0.1.0/tests/test_taxonomy.py +63 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DataHub Classifier contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datahub-ai-classifier
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Customer-taxonomy LLM classification and tagging for DataHub
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: acryl-datahub[datahub-rest]>=1.7.0
|
|
10
|
+
Requires-Dist: openai>=1.40.0
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest; extra == "dev"
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# DataHub Classifier
|
|
16
|
+
|
|
17
|
+
Classify DataHub fields against a customer-provided tag list using an
|
|
18
|
+
OpenAI-compatible LLM, then apply those tags.
|
|
19
|
+
|
|
20
|
+
Install:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install datahub-ai-classifier
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Example recipe: `datahub_classifier.example.yml`.
|
|
27
|
+
|
|
28
|
+
Both plugins must be in the same recipe, with the same `taxonomy` map.
|
|
29
|
+
|
|
30
|
+
```yaml
|
|
31
|
+
source:
|
|
32
|
+
type: postgres
|
|
33
|
+
config:
|
|
34
|
+
classification:
|
|
35
|
+
enabled: true
|
|
36
|
+
sample_size: 10
|
|
37
|
+
max_workers: 1
|
|
38
|
+
classifiers:
|
|
39
|
+
- type: datahub_classifier.classifier:AIPIIClassifier
|
|
40
|
+
config:
|
|
41
|
+
llm_model: gpt-4.1-mini
|
|
42
|
+
llm_base_url: https://api.openai.com/v1
|
|
43
|
+
llm_api_key: "<your-api-key>"
|
|
44
|
+
llm_timeout_seconds: 60
|
|
45
|
+
llm_max_retries: 0
|
|
46
|
+
confidence_threshold: 0.6
|
|
47
|
+
max_samples: 8
|
|
48
|
+
taxonomy: &taxonomy
|
|
49
|
+
C1: >
|
|
50
|
+
Restricted identifiers. Use for national IDs and tax numbers
|
|
51
|
+
such as SSN values like 123-45-6789 stored in columns named
|
|
52
|
+
ssn.
|
|
53
|
+
C2: >
|
|
54
|
+
Confidential personal and payment data. Use for a person's
|
|
55
|
+
full_name, email, phone, home_address, and date_of_birth, and
|
|
56
|
+
for order_total money amounts.
|
|
57
|
+
C3: >
|
|
58
|
+
Internal operational data. Use for customer_id, order_id,
|
|
59
|
+
loyalty_tier, currency, order status, shipped_at, and
|
|
60
|
+
created_at timestamps.
|
|
61
|
+
|
|
62
|
+
transformers:
|
|
63
|
+
- type: datahub-classifier
|
|
64
|
+
config:
|
|
65
|
+
taxonomy: *taxonomy
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Missing tags are created. Existing tags are not overwritten.
|
|
69
|
+
Classifier alone leaves glossary terms and does not create tags.
|
|
70
|
+
|
|
71
|
+
## Development
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install -e '.[dev]'
|
|
75
|
+
pytest
|
|
76
|
+
```
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# DataHub Classifier
|
|
2
|
+
|
|
3
|
+
Classify DataHub fields against a customer-provided tag list using an
|
|
4
|
+
OpenAI-compatible LLM, then apply those tags.
|
|
5
|
+
|
|
6
|
+
Install:
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install datahub-ai-classifier
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Example recipe: `datahub_classifier.example.yml`.
|
|
13
|
+
|
|
14
|
+
Both plugins must be in the same recipe, with the same `taxonomy` map.
|
|
15
|
+
|
|
16
|
+
```yaml
|
|
17
|
+
source:
|
|
18
|
+
type: postgres
|
|
19
|
+
config:
|
|
20
|
+
classification:
|
|
21
|
+
enabled: true
|
|
22
|
+
sample_size: 10
|
|
23
|
+
max_workers: 1
|
|
24
|
+
classifiers:
|
|
25
|
+
- type: datahub_classifier.classifier:AIPIIClassifier
|
|
26
|
+
config:
|
|
27
|
+
llm_model: gpt-4.1-mini
|
|
28
|
+
llm_base_url: https://api.openai.com/v1
|
|
29
|
+
llm_api_key: "<your-api-key>"
|
|
30
|
+
llm_timeout_seconds: 60
|
|
31
|
+
llm_max_retries: 0
|
|
32
|
+
confidence_threshold: 0.6
|
|
33
|
+
max_samples: 8
|
|
34
|
+
taxonomy: &taxonomy
|
|
35
|
+
C1: >
|
|
36
|
+
Restricted identifiers. Use for national IDs and tax numbers
|
|
37
|
+
such as SSN values like 123-45-6789 stored in columns named
|
|
38
|
+
ssn.
|
|
39
|
+
C2: >
|
|
40
|
+
Confidential personal and payment data. Use for a person's
|
|
41
|
+
full_name, email, phone, home_address, and date_of_birth, and
|
|
42
|
+
for order_total money amounts.
|
|
43
|
+
C3: >
|
|
44
|
+
Internal operational data. Use for customer_id, order_id,
|
|
45
|
+
loyalty_tier, currency, order status, shipped_at, and
|
|
46
|
+
created_at timestamps.
|
|
47
|
+
|
|
48
|
+
transformers:
|
|
49
|
+
- type: datahub-classifier
|
|
50
|
+
config:
|
|
51
|
+
taxonomy: *taxonomy
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Missing tags are created. Existing tags are not overwritten.
|
|
55
|
+
Classifier alone leaves glossary terms and does not create tags.
|
|
56
|
+
|
|
57
|
+
## Development
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install -e '.[dev]'
|
|
61
|
+
pytest
|
|
62
|
+
```
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "datahub-ai-classifier"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Customer-taxonomy LLM classification and tagging for DataHub"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"acryl-datahub[datahub-rest]>=1.7.0",
|
|
14
|
+
"openai>=1.40.0",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.entry-points."datahub.ingestion.transformer.plugins"]
|
|
18
|
+
datahub-classifier = "datahub_classifier.tagger:PIITagTransformer"
|
|
19
|
+
|
|
20
|
+
[project.optional-dependencies]
|
|
21
|
+
dev = ["pytest"]
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.packages.find]
|
|
24
|
+
where = ["src"]
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datahub-ai-classifier
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Customer-taxonomy LLM classification and tagging for DataHub
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: acryl-datahub[datahub-rest]>=1.7.0
|
|
10
|
+
Requires-Dist: openai>=1.40.0
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest; extra == "dev"
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# DataHub Classifier
|
|
16
|
+
|
|
17
|
+
Classify DataHub fields against a customer-provided tag list using an
|
|
18
|
+
OpenAI-compatible LLM, then apply those tags.
|
|
19
|
+
|
|
20
|
+
Install:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install datahub-ai-classifier
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Example recipe: `datahub_classifier.example.yml`.
|
|
27
|
+
|
|
28
|
+
Both plugins must be in the same recipe, with the same `taxonomy` map.
|
|
29
|
+
|
|
30
|
+
```yaml
|
|
31
|
+
source:
|
|
32
|
+
type: postgres
|
|
33
|
+
config:
|
|
34
|
+
classification:
|
|
35
|
+
enabled: true
|
|
36
|
+
sample_size: 10
|
|
37
|
+
max_workers: 1
|
|
38
|
+
classifiers:
|
|
39
|
+
- type: datahub_classifier.classifier:AIPIIClassifier
|
|
40
|
+
config:
|
|
41
|
+
llm_model: gpt-4.1-mini
|
|
42
|
+
llm_base_url: https://api.openai.com/v1
|
|
43
|
+
llm_api_key: "<your-api-key>"
|
|
44
|
+
llm_timeout_seconds: 60
|
|
45
|
+
llm_max_retries: 0
|
|
46
|
+
confidence_threshold: 0.6
|
|
47
|
+
max_samples: 8
|
|
48
|
+
taxonomy: &taxonomy
|
|
49
|
+
C1: >
|
|
50
|
+
Restricted identifiers. Use for national IDs and tax numbers
|
|
51
|
+
such as SSN values like 123-45-6789 stored in columns named
|
|
52
|
+
ssn.
|
|
53
|
+
C2: >
|
|
54
|
+
Confidential personal and payment data. Use for a person's
|
|
55
|
+
full_name, email, phone, home_address, and date_of_birth, and
|
|
56
|
+
for order_total money amounts.
|
|
57
|
+
C3: >
|
|
58
|
+
Internal operational data. Use for customer_id, order_id,
|
|
59
|
+
loyalty_tier, currency, order status, shipped_at, and
|
|
60
|
+
created_at timestamps.
|
|
61
|
+
|
|
62
|
+
transformers:
|
|
63
|
+
- type: datahub-classifier
|
|
64
|
+
config:
|
|
65
|
+
taxonomy: *taxonomy
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Missing tags are created. Existing tags are not overwritten.
|
|
69
|
+
Classifier alone leaves glossary terms and does not create tags.
|
|
70
|
+
|
|
71
|
+
## Development
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install -e '.[dev]'
|
|
75
|
+
pytest
|
|
76
|
+
```
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/datahub_ai_classifier.egg-info/PKG-INFO
|
|
5
|
+
src/datahub_ai_classifier.egg-info/SOURCES.txt
|
|
6
|
+
src/datahub_ai_classifier.egg-info/dependency_links.txt
|
|
7
|
+
src/datahub_ai_classifier.egg-info/entry_points.txt
|
|
8
|
+
src/datahub_ai_classifier.egg-info/requires.txt
|
|
9
|
+
src/datahub_ai_classifier.egg-info/top_level.txt
|
|
10
|
+
src/datahub_classifier/__init__.py
|
|
11
|
+
src/datahub_classifier/classifier.py
|
|
12
|
+
src/datahub_classifier/llm_client.py
|
|
13
|
+
src/datahub_classifier/tagger.py
|
|
14
|
+
src/datahub_classifier/taxonomy.py
|
|
15
|
+
tests/test_classifier.py
|
|
16
|
+
tests/test_classifier_llm_client.py
|
|
17
|
+
tests/test_datahub_classification.py
|
|
18
|
+
tests/test_plugin_names.py
|
|
19
|
+
tests/test_tagger.py
|
|
20
|
+
tests/test_taxonomy.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
datahub_classifier
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import math
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from datahub.ingestion.glossary.classification_types import (
|
|
8
|
+
ColumnInfo,
|
|
9
|
+
DebugInfo,
|
|
10
|
+
InfotypeProposal,
|
|
11
|
+
)
|
|
12
|
+
from datahub.ingestion.glossary.classifier import Classifier
|
|
13
|
+
|
|
14
|
+
from datahub_classifier.llm_client import chat_json, get_llm_client
|
|
15
|
+
from datahub_classifier.taxonomy import parse_taxonomy
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
SYSTEM_PROMPT = """You classify database columns against a customer-provided taxonomy.
|
|
20
|
+
Return JSON only:
|
|
21
|
+
{
|
|
22
|
+
"columns": [
|
|
23
|
+
{
|
|
24
|
+
"name": "<column name>",
|
|
25
|
+
"infotype": "<one of the allowed type ids>",
|
|
26
|
+
"confidence": 0.0-1.0
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
Rules:
|
|
31
|
+
- Use only allowed type ids.
|
|
32
|
+
- Prefer None when evidence is weak.
|
|
33
|
+
- Use the type description to decide.
|
|
34
|
+
- Broad ids such as C1 are valid if they are in the list.
|
|
35
|
+
- Use column name, datatype, and sample values.
|
|
36
|
+
- Do not invent sample values.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _require_str(config: Dict[str, Any], key: str, *, allow_blank: bool = False) -> str:
|
|
41
|
+
value = config.get(key)
|
|
42
|
+
if not isinstance(value, str):
|
|
43
|
+
raise ValueError(f"{key} is required")
|
|
44
|
+
if not allow_blank and not value.strip():
|
|
45
|
+
raise ValueError(f"{key} is required")
|
|
46
|
+
return value
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AIPIIClassifier(Classifier):
|
|
50
|
+
"""DataHub classifier that proposes taxonomy matches via an LLM."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, config: Dict[str, Any]) -> None:
|
|
53
|
+
self.config = config or {}
|
|
54
|
+
self.llm_model = _require_str(self.config, "llm_model")
|
|
55
|
+
self.llm_api_key = _require_str(self.config, "llm_api_key", allow_blank=True)
|
|
56
|
+
self.llm_base_url = _require_str(self.config, "llm_base_url")
|
|
57
|
+
raw_timeout = self.config.get("llm_timeout_seconds", 60)
|
|
58
|
+
raw_retries = self.config.get("llm_max_retries", 0)
|
|
59
|
+
if isinstance(raw_timeout, bool):
|
|
60
|
+
raise ValueError("llm_timeout_seconds must be a number greater than 0")
|
|
61
|
+
if isinstance(raw_retries, bool) or not isinstance(raw_retries, int):
|
|
62
|
+
raise ValueError("llm_max_retries must be a non-negative integer")
|
|
63
|
+
try:
|
|
64
|
+
self.llm_timeout_seconds = float(raw_timeout)
|
|
65
|
+
except (TypeError, ValueError) as exc:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
"llm_timeout_seconds must be a number greater than 0"
|
|
68
|
+
) from exc
|
|
69
|
+
if not math.isfinite(self.llm_timeout_seconds) or self.llm_timeout_seconds <= 0:
|
|
70
|
+
raise ValueError("llm_timeout_seconds must be a number greater than 0")
|
|
71
|
+
if raw_retries < 0:
|
|
72
|
+
raise ValueError("llm_max_retries must be a non-negative integer")
|
|
73
|
+
self.llm_max_retries = raw_retries
|
|
74
|
+
self.taxonomy = parse_taxonomy(self.config.get("taxonomy"))
|
|
75
|
+
self.allowed_infotypes = tuple(
|
|
76
|
+
[entry.id for entry in self.taxonomy] + ["None"]
|
|
77
|
+
)
|
|
78
|
+
raw_threshold = self.config.get("confidence_threshold", 0.6)
|
|
79
|
+
raw_max_samples = self.config.get("max_samples", 8)
|
|
80
|
+
if isinstance(raw_threshold, bool):
|
|
81
|
+
raise ValueError("confidence_threshold must be a number between 0 and 1")
|
|
82
|
+
if isinstance(raw_max_samples, bool) or not isinstance(raw_max_samples, int):
|
|
83
|
+
raise ValueError("max_samples must be a non-negative integer")
|
|
84
|
+
try:
|
|
85
|
+
self.confidence_threshold = float(raw_threshold)
|
|
86
|
+
except (TypeError, ValueError) as exc:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
"confidence_threshold must be a number between 0 and 1"
|
|
89
|
+
) from exc
|
|
90
|
+
self.max_samples = raw_max_samples
|
|
91
|
+
if not math.isfinite(self.confidence_threshold) or not (
|
|
92
|
+
0 <= self.confidence_threshold <= 1
|
|
93
|
+
):
|
|
94
|
+
raise ValueError("confidence_threshold must be a number between 0 and 1")
|
|
95
|
+
if self.max_samples < 0:
|
|
96
|
+
raise ValueError("max_samples must be a non-negative integer")
|
|
97
|
+
self._client = None
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def create(cls, config_dict: Dict[str, Any]) -> "AIPIIClassifier":
|
|
101
|
+
return cls(config_dict or {})
|
|
102
|
+
|
|
103
|
+
def _client_or_create(self):
|
|
104
|
+
if self._client is None:
|
|
105
|
+
self._client = get_llm_client(
|
|
106
|
+
self.llm_api_key,
|
|
107
|
+
self.llm_base_url,
|
|
108
|
+
timeout=self.llm_timeout_seconds,
|
|
109
|
+
max_retries=self.llm_max_retries,
|
|
110
|
+
)
|
|
111
|
+
return self._client
|
|
112
|
+
|
|
113
|
+
def classify(self, columns: List[ColumnInfo]) -> List[ColumnInfo]:
|
|
114
|
+
if not columns:
|
|
115
|
+
return columns
|
|
116
|
+
|
|
117
|
+
payload = []
|
|
118
|
+
for col in columns:
|
|
119
|
+
samples = [str(v) for v in (col.values or [])[: self.max_samples]]
|
|
120
|
+
# DataHub mixin historically populates "DataType"; Metadata reads "Datatype".
|
|
121
|
+
datatype = col.metadata.datatype or (col.metadata.meta_info or {}).get(
|
|
122
|
+
"DataType"
|
|
123
|
+
)
|
|
124
|
+
payload.append(
|
|
125
|
+
{
|
|
126
|
+
"name": col.metadata.name,
|
|
127
|
+
"datatype": datatype,
|
|
128
|
+
"description": col.metadata.description,
|
|
129
|
+
"dataset": col.metadata.dataset_name,
|
|
130
|
+
"samples": samples,
|
|
131
|
+
}
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
catalog = [
|
|
135
|
+
{"id": entry.id, "description": entry.description}
|
|
136
|
+
for entry in self.taxonomy
|
|
137
|
+
]
|
|
138
|
+
user_prompt = (
|
|
139
|
+
"Allowed type ids: "
|
|
140
|
+
+ ", ".join(self.allowed_infotypes)
|
|
141
|
+
+ "\n\nTaxonomy:\n"
|
|
142
|
+
+ str(catalog)
|
|
143
|
+
+ "\n\nClassify these columns:\n"
|
|
144
|
+
+ str(payload)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
result = chat_json(
|
|
148
|
+
self._client_or_create(),
|
|
149
|
+
system=SYSTEM_PROMPT,
|
|
150
|
+
user=user_prompt,
|
|
151
|
+
model=self.llm_model,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
if not isinstance(result, dict) or not isinstance(result.get("columns"), list):
|
|
155
|
+
raise ValueError("LLM PII response must contain a columns list")
|
|
156
|
+
|
|
157
|
+
known_names = {
|
|
158
|
+
col.metadata.name for col in columns if col.metadata.name is not None
|
|
159
|
+
}
|
|
160
|
+
by_name = {}
|
|
161
|
+
duplicate_names = set()
|
|
162
|
+
for item in result["columns"]:
|
|
163
|
+
if not isinstance(item, dict):
|
|
164
|
+
logger.warning("Ignoring malformed LLM PII prediction: not an object")
|
|
165
|
+
continue
|
|
166
|
+
|
|
167
|
+
name = item.get("name")
|
|
168
|
+
infotype = item.get("infotype")
|
|
169
|
+
confidence = item.get("confidence")
|
|
170
|
+
|
|
171
|
+
if not isinstance(name, str) or name not in known_names:
|
|
172
|
+
logger.warning(
|
|
173
|
+
"Ignoring LLM PII prediction for unknown column %r", name
|
|
174
|
+
)
|
|
175
|
+
continue
|
|
176
|
+
if not isinstance(infotype, str) or infotype not in self.allowed_infotypes:
|
|
177
|
+
logger.warning(
|
|
178
|
+
"Ignoring LLM PII prediction for %s: invalid infotype %r",
|
|
179
|
+
name,
|
|
180
|
+
infotype,
|
|
181
|
+
)
|
|
182
|
+
continue
|
|
183
|
+
if (
|
|
184
|
+
isinstance(confidence, bool)
|
|
185
|
+
or not isinstance(confidence, (int, float))
|
|
186
|
+
or not math.isfinite(float(confidence))
|
|
187
|
+
or not 0 <= float(confidence) <= 1
|
|
188
|
+
):
|
|
189
|
+
logger.warning(
|
|
190
|
+
"Ignoring LLM PII prediction for %s: invalid confidence %r",
|
|
191
|
+
name,
|
|
192
|
+
confidence,
|
|
193
|
+
)
|
|
194
|
+
continue
|
|
195
|
+
if name in by_name or name in duplicate_names:
|
|
196
|
+
logger.warning(
|
|
197
|
+
"Ignoring duplicate LLM PII predictions for column %s", name
|
|
198
|
+
)
|
|
199
|
+
by_name.pop(name, None)
|
|
200
|
+
duplicate_names.add(name)
|
|
201
|
+
continue
|
|
202
|
+
|
|
203
|
+
by_name[name] = (infotype, float(confidence))
|
|
204
|
+
|
|
205
|
+
for col in columns:
|
|
206
|
+
name = col.metadata.name
|
|
207
|
+
item = by_name.get(name) if name else None
|
|
208
|
+
if not item:
|
|
209
|
+
continue
|
|
210
|
+
|
|
211
|
+
infotype, confidence = item
|
|
212
|
+
|
|
213
|
+
if infotype == "None":
|
|
214
|
+
continue
|
|
215
|
+
if confidence < self.confidence_threshold:
|
|
216
|
+
logger.debug(
|
|
217
|
+
"Skipping %s.%s: confidence %.2f < %.2f",
|
|
218
|
+
col.metadata.dataset_name,
|
|
219
|
+
name,
|
|
220
|
+
confidence,
|
|
221
|
+
self.confidence_threshold,
|
|
222
|
+
)
|
|
223
|
+
continue
|
|
224
|
+
|
|
225
|
+
col.infotype_proposals = [
|
|
226
|
+
InfotypeProposal(
|
|
227
|
+
infotype=infotype,
|
|
228
|
+
confidence_level=confidence,
|
|
229
|
+
debug_info=DebugInfo(values=confidence, name=confidence),
|
|
230
|
+
)
|
|
231
|
+
]
|
|
232
|
+
logger.info(
|
|
233
|
+
"PII proposal %s.%s -> %s (%.2f)",
|
|
234
|
+
col.metadata.dataset_name,
|
|
235
|
+
name,
|
|
236
|
+
infotype,
|
|
237
|
+
confidence,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
return columns
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Dict, Optional
|
|
7
|
+
|
|
8
|
+
from openai import OpenAI
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _json_object(content: str) -> Dict[str, Any]:
|
|
14
|
+
parsed = json.loads(content)
|
|
15
|
+
if not isinstance(parsed, dict):
|
|
16
|
+
raise ValueError("LLM response must be a JSON object")
|
|
17
|
+
return parsed
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_llm_client(
|
|
21
|
+
api_key: str,
|
|
22
|
+
base_url: str,
|
|
23
|
+
*,
|
|
24
|
+
timeout: float,
|
|
25
|
+
max_retries: int,
|
|
26
|
+
) -> OpenAI:
|
|
27
|
+
return OpenAI(
|
|
28
|
+
api_key=api_key or "not-required",
|
|
29
|
+
base_url=base_url,
|
|
30
|
+
timeout=timeout,
|
|
31
|
+
max_retries=max_retries,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def chat_json(
|
|
36
|
+
client: OpenAI,
|
|
37
|
+
*,
|
|
38
|
+
system: str,
|
|
39
|
+
user: str,
|
|
40
|
+
model: str,
|
|
41
|
+
temperature: Optional[float] = 0.1,
|
|
42
|
+
) -> Dict[str, Any]:
|
|
43
|
+
messages = [
|
|
44
|
+
{"role": "system", "content": system},
|
|
45
|
+
{"role": "user", "content": user},
|
|
46
|
+
]
|
|
47
|
+
kwargs: Dict[str, Any] = {
|
|
48
|
+
"model": model,
|
|
49
|
+
"response_format": {"type": "json_object"},
|
|
50
|
+
"messages": messages,
|
|
51
|
+
}
|
|
52
|
+
if temperature is not None:
|
|
53
|
+
kwargs["temperature"] = temperature
|
|
54
|
+
|
|
55
|
+
while True:
|
|
56
|
+
try:
|
|
57
|
+
response = client.chat.completions.create(**kwargs)
|
|
58
|
+
break
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
message = str(exc).lower()
|
|
61
|
+
if "temperature" in kwargs and "temperature" in message:
|
|
62
|
+
logger.warning(
|
|
63
|
+
"Model %s rejected temperature=%s; retrying without it",
|
|
64
|
+
model,
|
|
65
|
+
kwargs["temperature"],
|
|
66
|
+
)
|
|
67
|
+
kwargs.pop("temperature")
|
|
68
|
+
continue
|
|
69
|
+
if "response_format" in kwargs and (
|
|
70
|
+
"response_format" in message
|
|
71
|
+
or "response format" in message
|
|
72
|
+
or "json_object" in message
|
|
73
|
+
):
|
|
74
|
+
logger.warning(
|
|
75
|
+
"Model %s rejected JSON response format; retrying without it",
|
|
76
|
+
model,
|
|
77
|
+
)
|
|
78
|
+
kwargs.pop("response_format")
|
|
79
|
+
continue
|
|
80
|
+
raise
|
|
81
|
+
|
|
82
|
+
content = response.choices[0].message.content or "{}"
|
|
83
|
+
try:
|
|
84
|
+
return _json_object(content)
|
|
85
|
+
except json.JSONDecodeError:
|
|
86
|
+
match = re.search(r"\{.*\}", content, re.DOTALL)
|
|
87
|
+
if not match:
|
|
88
|
+
logger.warning(
|
|
89
|
+
"Failed to parse LLM JSON response: %s",
|
|
90
|
+
content[:500],
|
|
91
|
+
)
|
|
92
|
+
return {}
|
|
93
|
+
return _json_object(match.group(0))
|