radlab-pii-classification 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.
- radlab_pii_classification-0.1.0/LICENSE +21 -0
- radlab_pii_classification-0.1.0/PKG-INFO +155 -0
- radlab_pii_classification-0.1.0/README.md +141 -0
- radlab_pii_classification-0.1.0/pii_classification/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/analysis/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/analysis/jsonl_generalise_labels.py +68 -0
- radlab_pii_classification-0.1.0/pii_classification/analysis/label_generalizer.py +31 -0
- radlab_pii_classification-0.1.0/pii_classification/analysis/labels_distribution_report.py +164 -0
- radlab_pii_classification-0.1.0/pii_classification/api/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/api/app.py +96 -0
- radlab_pii_classification-0.1.0/pii_classification/cli/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/cli/main.py +83 -0
- radlab_pii_classification-0.1.0/pii_classification/converters/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/converters/conll2jsonl.py +83 -0
- radlab_pii_classification-0.1.0/pii_classification/data/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/inference/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/inference/inference.py +298 -0
- radlab_pii_classification-0.1.0/pii_classification/trainer/__init__.py +0 -0
- radlab_pii_classification-0.1.0/pii_classification/trainer/data_processor.py +62 -0
- radlab_pii_classification-0.1.0/pii_classification/trainer/train.py +207 -0
- radlab_pii_classification-0.1.0/pii_classification/version.py +2 -0
- radlab_pii_classification-0.1.0/pyproject.toml +42 -0
- radlab_pii_classification-0.1.0/radlab_pii_classification.egg-info/PKG-INFO +155 -0
- radlab_pii_classification-0.1.0/radlab_pii_classification.egg-info/SOURCES.txt +32 -0
- radlab_pii_classification-0.1.0/radlab_pii_classification.egg-info/dependency_links.txt +1 -0
- radlab_pii_classification-0.1.0/radlab_pii_classification.egg-info/entry_points.txt +2 -0
- radlab_pii_classification-0.1.0/radlab_pii_classification.egg-info/requires.txt +6 -0
- radlab_pii_classification-0.1.0/radlab_pii_classification.egg-info/top_level.txt +6 -0
- radlab_pii_classification-0.1.0/setup.cfg +4 -0
- radlab_pii_classification-0.1.0/wandb/latest-run/files/code/pii_classification/trainer/train.py +208 -0
- radlab_pii_classification-0.1.0/wandb/run-20260425_024357-f07s2mx8/files/code/pii_classification/trainer/train.py +207 -0
- radlab_pii_classification-0.1.0/wandb/run-20260425_035015-2s30qj5h/files/code/pii_classification/trainer/train.py +208 -0
- radlab_pii_classification-0.1.0/wandb/run-20260425_042358-igdgn91g/files/code/pii_classification/trainer/train.py +208 -0
- radlab_pii_classification-0.1.0/wandb/run-20260425_052448-remt7qrp/files/code/pii_classification/trainer/train.py +208 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 radlab.dev
|
|
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,155 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: radlab-pii-classification
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Requires-Python: >=3.9
|
|
5
|
+
Description-Content-Type: text/markdown
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: pandas
|
|
8
|
+
Requires-Dist: xlsxwriter
|
|
9
|
+
Requires-Dist: seqeval
|
|
10
|
+
Requires-Dist: sacremoses
|
|
11
|
+
Requires-Dist: flask_cors
|
|
12
|
+
Requires-Dist: radlab-ml-utils>=1.0.0
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# PII Classification Model
|
|
16
|
+
|
|
17
|
+
This project provides a complete pipeline for Named Entity Recognition (NER) focused on identifying Personally
|
|
18
|
+
Identifiable Information (PII) in Polish text. It includes utilities for data conversion, label generalization, model
|
|
19
|
+
training using Hugging Face Transformers, and a deployment-ready Flask API with a simple web interface.
|
|
20
|
+
|
|
21
|
+
**Repository**:
|
|
22
|
+
[https://github.com/radlab-dev-group/anonymizer-model](https://github.com/radlab-dev-group/anonymizer-model)
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
|
|
26
|
+
- **Data Processing CLI**: Tools to convert CONLL/IOB formats to JSONL, generalize labels, and generate distribution
|
|
27
|
+
reports.
|
|
28
|
+
- **Training Pipeline**: A configurable trainer based on `AutoModelForTokenClassification` with Weights & Biases (W&B)
|
|
29
|
+
integration.
|
|
30
|
+
- **Advanced Inference**: A predictor that handles sub-token merging, punctuation cleaning, and gap preservation to
|
|
31
|
+
return human-readable entities.
|
|
32
|
+
- **REST API**: A Flask-based service to serve multiple model versions with optional dynamic quantization for faster
|
|
33
|
+
inference.
|
|
34
|
+
- **Web Tester**: A lightweight HTML/JS interface for real-time PII detection testing.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
Ensure you have Python $\ge$ 3.9 installed.
|
|
39
|
+
|
|
40
|
+
```textmate
|
|
41
|
+
git clone https://github.com/radlab-dev-group/anonymizer-model.git
|
|
42
|
+
cd anonymizer-model
|
|
43
|
+
pip install .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Data Preparation
|
|
47
|
+
|
|
48
|
+
The project is designed to work with datasets like `clarin-pl/kpwr-ner`.
|
|
49
|
+
|
|
50
|
+
1. **Download Dataset**: Store IOB files in `dataset/kpwr/raw/`.
|
|
51
|
+
2. **Convert to JSONL**:
|
|
52
|
+
|
|
53
|
+
```textmate
|
|
54
|
+
pii-classifier convert \
|
|
55
|
+
-i dataset/kpwr/raw/kpwr-ner-n82-train-tune.iob \
|
|
56
|
+
-o dataset/kpwr/converted/specific/kpwr-ner-n82-train-tune.jsonl
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
pii-classifier convert \
|
|
60
|
+
-i dataset/kpwr/raw/kpwr-ner-n82-test.iob \
|
|
61
|
+
-o dataset/kpwr/converted/specific/kpwr-ner-n82-test.jsonl
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
3. **Generalize Labels**:
|
|
65
|
+
Map fine-grained labels to general categories using a mapping file (e.g., `config/mappings/kpwr-ner.json`).
|
|
66
|
+
|
|
67
|
+
```textmate
|
|
68
|
+
pii-classifier generalise \
|
|
69
|
+
-i dataset/kpwr/converted/specific/kpwr-ner-n82-train-tune.jsonl \
|
|
70
|
+
dataset/kpwr/converted/specific/kpwr-ner-n82-test.jsonl \
|
|
71
|
+
-m config/mappings/kpwr-ner.json \
|
|
72
|
+
-o dataset/kpwr/converted/generalised/kpwr-ner-general-whole.jsonl
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
4. **Generate Report**:
|
|
76
|
+
Create an Excel report to analyze class distribution.
|
|
77
|
+
|
|
78
|
+
```textmate
|
|
79
|
+
pii-classifier report \
|
|
80
|
+
-i dataset/kpwr/converted/generalised/kpwr-ner-general-whole.jsonl \
|
|
81
|
+
-o dataset/kpwr/converted/generalised/kpwr-ner-general-whole-report.xlsx
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Training
|
|
85
|
+
|
|
86
|
+
Training is driven by a JSON configuration file located in `config/training/`.
|
|
87
|
+
|
|
88
|
+
To start training, run the training script:
|
|
89
|
+
|
|
90
|
+
```textmate
|
|
91
|
+
python pii_classification/trainer/train.py
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
**Key Training Features:**
|
|
95
|
+
|
|
96
|
+
- **Configurable**: Hyperparameters (learning rate, batch size, epochs) are managed via `kpwr-ner-config.json`.
|
|
97
|
+
- **W&B Integration**: Logs metrics and hyperparameters to Weights & Biases.
|
|
98
|
+
- **Automatic Export**: Saves the best model (based on `f1_macro`) into a `final_model` directory.
|
|
99
|
+
|
|
100
|
+
## Inference & API
|
|
101
|
+
|
|
102
|
+
### Running the API
|
|
103
|
+
|
|
104
|
+
The API allows you to load multiple model versions and perform predictions.
|
|
105
|
+
|
|
106
|
+
```textmate
|
|
107
|
+
python3 -m pii_classification.api.app
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**Endpoints:**
|
|
111
|
+
|
|
112
|
+
- `GET /models`: Returns a list of available models and the default model.
|
|
113
|
+
- `POST /predict`: Accepts JSON with `text` and optional `model` name. Returns a list of tokens and their predicted PII
|
|
114
|
+
labels.
|
|
115
|
+
|
|
116
|
+
### Web Interface (under development)
|
|
117
|
+
|
|
118
|
+
Open `pii_classification/ui/index.html` in a browser to interact with the API. The UI allows you to select a model,
|
|
119
|
+
input Polish text, and see highlighted PII entities.
|
|
120
|
+
|
|
121
|
+
Or simple python-like http server:
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
cd anonymizer-model/pii_classification/ui
|
|
125
|
+
python3 -m http.server
|
|
126
|
+
|
|
127
|
+
>> Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## CLI Reference
|
|
131
|
+
|
|
132
|
+
The `pii-classifier` command provides the following sub-commands:
|
|
133
|
+
|
|
134
|
+
| Command | Description | Required Arguments |
|
|
135
|
+
|:-------------|:-----------------------------------|:--------------------------------------------------|
|
|
136
|
+
| `convert` | Convert CONLL/IOB file to JSONL | `-i` (input), `-o` (output) |
|
|
137
|
+
| `generalise` | Map labels using a JSON map | `-i` (input files), `-m` (mapping), `-o` (output) |
|
|
138
|
+
| `report` | Generate Excel distribution report | `-i` (input files), `-o` (output) |
|
|
139
|
+
|
|
140
|
+
## Project Structure
|
|
141
|
+
|
|
142
|
+
```plain text
|
|
143
|
+
├── config/
|
|
144
|
+
│ ├── mappings/ # Label mapping JSONs
|
|
145
|
+
│ └── training/ # Training hyperparameter configs
|
|
146
|
+
├── pii_classification/
|
|
147
|
+
│ ├── analysis/ # Label generalization and reporting logic
|
|
148
|
+
│ ├── api/ # Flask API implementation
|
|
149
|
+
│ ├── cli/ # CLI entry point
|
|
150
|
+
│ ├── converters/ # Format conversion utilities
|
|
151
|
+
│ ├── inference/ # Model prediction and post-processing logic
|
|
152
|
+
│ ├── trainer/ # Training scripts and data processors
|
|
153
|
+
│ └── ui/ # Frontend tester (HTML/JS)
|
|
154
|
+
└── pyproject.toml # Project dependencies and metadata
|
|
155
|
+
```
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# PII Classification Model
|
|
2
|
+
|
|
3
|
+
This project provides a complete pipeline for Named Entity Recognition (NER) focused on identifying Personally
|
|
4
|
+
Identifiable Information (PII) in Polish text. It includes utilities for data conversion, label generalization, model
|
|
5
|
+
training using Hugging Face Transformers, and a deployment-ready Flask API with a simple web interface.
|
|
6
|
+
|
|
7
|
+
**Repository**:
|
|
8
|
+
[https://github.com/radlab-dev-group/anonymizer-model](https://github.com/radlab-dev-group/anonymizer-model)
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- **Data Processing CLI**: Tools to convert CONLL/IOB formats to JSONL, generalize labels, and generate distribution
|
|
13
|
+
reports.
|
|
14
|
+
- **Training Pipeline**: A configurable trainer based on `AutoModelForTokenClassification` with Weights & Biases (W&B)
|
|
15
|
+
integration.
|
|
16
|
+
- **Advanced Inference**: A predictor that handles sub-token merging, punctuation cleaning, and gap preservation to
|
|
17
|
+
return human-readable entities.
|
|
18
|
+
- **REST API**: A Flask-based service to serve multiple model versions with optional dynamic quantization for faster
|
|
19
|
+
inference.
|
|
20
|
+
- **Web Tester**: A lightweight HTML/JS interface for real-time PII detection testing.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
Ensure you have Python $\ge$ 3.9 installed.
|
|
25
|
+
|
|
26
|
+
```textmate
|
|
27
|
+
git clone https://github.com/radlab-dev-group/anonymizer-model.git
|
|
28
|
+
cd anonymizer-model
|
|
29
|
+
pip install .
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Data Preparation
|
|
33
|
+
|
|
34
|
+
The project is designed to work with datasets like `clarin-pl/kpwr-ner`.
|
|
35
|
+
|
|
36
|
+
1. **Download Dataset**: Store IOB files in `dataset/kpwr/raw/`.
|
|
37
|
+
2. **Convert to JSONL**:
|
|
38
|
+
|
|
39
|
+
```textmate
|
|
40
|
+
pii-classifier convert \
|
|
41
|
+
-i dataset/kpwr/raw/kpwr-ner-n82-train-tune.iob \
|
|
42
|
+
-o dataset/kpwr/converted/specific/kpwr-ner-n82-train-tune.jsonl
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
pii-classifier convert \
|
|
46
|
+
-i dataset/kpwr/raw/kpwr-ner-n82-test.iob \
|
|
47
|
+
-o dataset/kpwr/converted/specific/kpwr-ner-n82-test.jsonl
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
3. **Generalize Labels**:
|
|
51
|
+
Map fine-grained labels to general categories using a mapping file (e.g., `config/mappings/kpwr-ner.json`).
|
|
52
|
+
|
|
53
|
+
```textmate
|
|
54
|
+
pii-classifier generalise \
|
|
55
|
+
-i dataset/kpwr/converted/specific/kpwr-ner-n82-train-tune.jsonl \
|
|
56
|
+
dataset/kpwr/converted/specific/kpwr-ner-n82-test.jsonl \
|
|
57
|
+
-m config/mappings/kpwr-ner.json \
|
|
58
|
+
-o dataset/kpwr/converted/generalised/kpwr-ner-general-whole.jsonl
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
4. **Generate Report**:
|
|
62
|
+
Create an Excel report to analyze class distribution.
|
|
63
|
+
|
|
64
|
+
```textmate
|
|
65
|
+
pii-classifier report \
|
|
66
|
+
-i dataset/kpwr/converted/generalised/kpwr-ner-general-whole.jsonl \
|
|
67
|
+
-o dataset/kpwr/converted/generalised/kpwr-ner-general-whole-report.xlsx
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Training
|
|
71
|
+
|
|
72
|
+
Training is driven by a JSON configuration file located in `config/training/`.
|
|
73
|
+
|
|
74
|
+
To start training, run the training script:
|
|
75
|
+
|
|
76
|
+
```textmate
|
|
77
|
+
python pii_classification/trainer/train.py
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**Key Training Features:**
|
|
81
|
+
|
|
82
|
+
- **Configurable**: Hyperparameters (learning rate, batch size, epochs) are managed via `kpwr-ner-config.json`.
|
|
83
|
+
- **W&B Integration**: Logs metrics and hyperparameters to Weights & Biases.
|
|
84
|
+
- **Automatic Export**: Saves the best model (based on `f1_macro`) into a `final_model` directory.
|
|
85
|
+
|
|
86
|
+
## Inference & API
|
|
87
|
+
|
|
88
|
+
### Running the API
|
|
89
|
+
|
|
90
|
+
The API allows you to load multiple model versions and perform predictions.
|
|
91
|
+
|
|
92
|
+
```textmate
|
|
93
|
+
python3 -m pii_classification.api.app
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
**Endpoints:**
|
|
97
|
+
|
|
98
|
+
- `GET /models`: Returns a list of available models and the default model.
|
|
99
|
+
- `POST /predict`: Accepts JSON with `text` and optional `model` name. Returns a list of tokens and their predicted PII
|
|
100
|
+
labels.
|
|
101
|
+
|
|
102
|
+
### Web Interface (under development)
|
|
103
|
+
|
|
104
|
+
Open `pii_classification/ui/index.html` in a browser to interact with the API. The UI allows you to select a model,
|
|
105
|
+
input Polish text, and see highlighted PII entities.
|
|
106
|
+
|
|
107
|
+
Or simple python-like http server:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
cd anonymizer-model/pii_classification/ui
|
|
111
|
+
python3 -m http.server
|
|
112
|
+
|
|
113
|
+
>> Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## CLI Reference
|
|
117
|
+
|
|
118
|
+
The `pii-classifier` command provides the following sub-commands:
|
|
119
|
+
|
|
120
|
+
| Command | Description | Required Arguments |
|
|
121
|
+
|:-------------|:-----------------------------------|:--------------------------------------------------|
|
|
122
|
+
| `convert` | Convert CONLL/IOB file to JSONL | `-i` (input), `-o` (output) |
|
|
123
|
+
| `generalise` | Map labels using a JSON map | `-i` (input files), `-m` (mapping), `-o` (output) |
|
|
124
|
+
| `report` | Generate Excel distribution report | `-i` (input files), `-o` (output) |
|
|
125
|
+
|
|
126
|
+
## Project Structure
|
|
127
|
+
|
|
128
|
+
```plain text
|
|
129
|
+
├── config/
|
|
130
|
+
│ ├── mappings/ # Label mapping JSONs
|
|
131
|
+
│ └── training/ # Training hyperparameter configs
|
|
132
|
+
├── pii_classification/
|
|
133
|
+
│ ├── analysis/ # Label generalization and reporting logic
|
|
134
|
+
│ ├── api/ # Flask API implementation
|
|
135
|
+
│ ├── cli/ # CLI entry point
|
|
136
|
+
│ ├── converters/ # Format conversion utilities
|
|
137
|
+
│ ├── inference/ # Model prediction and post-processing logic
|
|
138
|
+
│ ├── trainer/ # Training scripts and data processors
|
|
139
|
+
│ └── ui/ # Frontend tester (HTML/JS)
|
|
140
|
+
└── pyproject.toml # Project dependencies and metadata
|
|
141
|
+
```
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import json
|
|
3
|
+
import argparse
|
|
4
|
+
|
|
5
|
+
from .label_generalizer import load_mapping, generalize_label
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def analyze_pii_distribution(input_files, mapping_path, output_path):
|
|
9
|
+
mapping = load_mapping(mapping_path)
|
|
10
|
+
all_labels = []
|
|
11
|
+
mapped_records = []
|
|
12
|
+
|
|
13
|
+
print(f"Loading files: {input_files}...")
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
for file_path in input_files:
|
|
17
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
18
|
+
for line in f:
|
|
19
|
+
if not line.strip():
|
|
20
|
+
continue
|
|
21
|
+
data = json.loads(line)
|
|
22
|
+
original_labels = data.get("labels", [])
|
|
23
|
+
all_labels.extend(original_labels)
|
|
24
|
+
|
|
25
|
+
mapped_labels = [
|
|
26
|
+
generalize_label(l, mapping) for l in original_labels
|
|
27
|
+
]
|
|
28
|
+
data["labels"] = mapped_labels
|
|
29
|
+
mapped_records.append(data)
|
|
30
|
+
|
|
31
|
+
if not all_labels:
|
|
32
|
+
print("Error: No labels found.")
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
total_tokens = len(all_labels)
|
|
36
|
+
print(f"Analysis complete. Found {total_tokens} tokens.")
|
|
37
|
+
|
|
38
|
+
# Write converted dataset
|
|
39
|
+
print(f"Saving converted dataset to: {output_path}")
|
|
40
|
+
with open(output_path, "w", encoding="utf-8") as out_f:
|
|
41
|
+
for record in mapped_records:
|
|
42
|
+
out_f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
43
|
+
|
|
44
|
+
print("Conversion and saving completed successfully.")
|
|
45
|
+
except Exception as e:
|
|
46
|
+
print(f"An error occurred: {e}")
|
|
47
|
+
sys.exit(1)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def main():
|
|
51
|
+
parser = argparse.ArgumentParser(
|
|
52
|
+
description="Generalize PII labels using a JSON map and output a converted JSONL file."
|
|
53
|
+
)
|
|
54
|
+
parser.add_argument(
|
|
55
|
+
"-i", "--input", nargs="+", required=True, help="Paths to JSONL files"
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"-m", "--mapping", required=True, help="Path to the mapping JSON file"
|
|
59
|
+
)
|
|
60
|
+
parser.add_argument(
|
|
61
|
+
"-o", "--output", required=True, help="Path to output converted .jsonl file"
|
|
62
|
+
)
|
|
63
|
+
args = parser.parse_args()
|
|
64
|
+
analyze_pii_distribution(args.input, args.mapping, args.output)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__":
|
|
68
|
+
main()
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def load_mapping(mapping_path: str | Path) -> dict:
|
|
9
|
+
"""Load a JSON mapping file."""
|
|
10
|
+
try:
|
|
11
|
+
with open(mapping_path, "r", encoding="utf-8") as f:
|
|
12
|
+
return json.load(f)
|
|
13
|
+
except Exception as e:
|
|
14
|
+
print(f"Error loading mapping file: {e}")
|
|
15
|
+
sys.exit(1)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def generalize_label(label: str, mapping: dict) -> str:
|
|
19
|
+
"""Map a BIO‑prefixed label to its high‑level category."""
|
|
20
|
+
if label == "O":
|
|
21
|
+
return "O"
|
|
22
|
+
base_label = re.sub(r"^[BI]-", "", label)
|
|
23
|
+
for prefix, category in mapping.items():
|
|
24
|
+
if base_label.startswith(prefix):
|
|
25
|
+
return category
|
|
26
|
+
return "MISC"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def strip_bio_prefix(label: str) -> str:
|
|
30
|
+
"""Remove the B‑/I‑ prefix; keep 'O' unchanged."""
|
|
31
|
+
return label if label == "O" else re.sub(r"^[BI]-", "", label)
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PII Class Distribution Analyzer
|
|
3
|
+
------------------------------
|
|
4
|
+
This script reads one or multiple JSONL files containing NER labels,
|
|
5
|
+
calculates the distribution of each class, and generates a formatted
|
|
6
|
+
Excel report. It provides both a detailed BIO-tag distribution and
|
|
7
|
+
a grouped class summary.
|
|
8
|
+
|
|
9
|
+
Example usage:
|
|
10
|
+
python analyzer.py -i train.jsonl val.jsonl -o report.xlsx
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import argparse
|
|
15
|
+
import pandas as pd
|
|
16
|
+
from collections import Counter
|
|
17
|
+
import sys
|
|
18
|
+
import re
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def strip_bio_prefix(label):
|
|
22
|
+
"""
|
|
23
|
+
Removes B- or I- prefix from NER labels to get the base class.
|
|
24
|
+
Example: 'B-nam_org_company' -> 'nam_org_company', 'O' -> 'O'
|
|
25
|
+
"""
|
|
26
|
+
if label == "O":
|
|
27
|
+
return "O"
|
|
28
|
+
return re.sub(r"^[BI]-", "", label)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def analyze_pii_distribution(input_files, output_excel):
|
|
32
|
+
"""
|
|
33
|
+
Reads JSONL files, counts NER labels, and generates a formatted
|
|
34
|
+
Excel report with two sheets: Full Distribution and Class Summary.
|
|
35
|
+
"""
|
|
36
|
+
all_labels = []
|
|
37
|
+
|
|
38
|
+
print(f"Loading files: {input_files}...")
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
for file_path in input_files:
|
|
42
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
43
|
+
for line in f:
|
|
44
|
+
if not line.strip():
|
|
45
|
+
continue
|
|
46
|
+
data = json.loads(line)
|
|
47
|
+
all_labels.extend(data.get("labels", []))
|
|
48
|
+
|
|
49
|
+
if not all_labels:
|
|
50
|
+
print("Error: No labels found in the provided files.")
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
# --- 1. Full Distribution (Exact labels) ---
|
|
54
|
+
full_counts = Counter(all_labels)
|
|
55
|
+
df_full = pd.DataFrame(full_counts.items(), columns=["Label", "Count"])
|
|
56
|
+
df_full = df_full.sort_values(by="Count", ascending=False).reset_index(
|
|
57
|
+
drop=True
|
|
58
|
+
)
|
|
59
|
+
total_tokens = df_full["Count"].sum()
|
|
60
|
+
df_full["Percentage"] = (df_full["Count"] / total_tokens * 100).round(
|
|
61
|
+
2
|
|
62
|
+
).astype(str) + "%"
|
|
63
|
+
|
|
64
|
+
# --- 2. Class Summary (Grouped B/I labels) ---
|
|
65
|
+
grouped_labels = [strip_bio_prefix(l) for l in all_labels]
|
|
66
|
+
group_counts = Counter(grouped_labels)
|
|
67
|
+
df_grouped = pd.DataFrame(group_counts.items(), columns=["Class", "Count"])
|
|
68
|
+
df_grouped = df_grouped.sort_values(by="Count", ascending=False).reset_index(
|
|
69
|
+
drop=True
|
|
70
|
+
)
|
|
71
|
+
df_grouped["Percentage"] = (df_grouped["Count"] / total_tokens * 100).round(
|
|
72
|
+
2
|
|
73
|
+
).astype(str) + "%"
|
|
74
|
+
|
|
75
|
+
print(f"Analysis complete. Found {total_tokens} tokens.")
|
|
76
|
+
|
|
77
|
+
# --- Excel Export ---
|
|
78
|
+
writer = pd.ExcelWriter(output_excel, engine="xlsxwriter")
|
|
79
|
+
|
|
80
|
+
df_full.to_excel(writer, sheet_name="Full Distribution", index=False)
|
|
81
|
+
df_grouped.to_excel(writer, sheet_name="Class Summary", index=False)
|
|
82
|
+
|
|
83
|
+
workbook = writer.book
|
|
84
|
+
|
|
85
|
+
header_format = workbook.add_format(
|
|
86
|
+
{
|
|
87
|
+
"bold": True,
|
|
88
|
+
"text_wrap": True,
|
|
89
|
+
"valign": "top",
|
|
90
|
+
"fg_color": "#D7E4BC",
|
|
91
|
+
"border": 1,
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
cell_format = workbook.add_format({"border": 1})
|
|
95
|
+
|
|
96
|
+
for sheet_name, df in [
|
|
97
|
+
("Full Distribution", df_full),
|
|
98
|
+
("Class Summary", df_grouped),
|
|
99
|
+
]:
|
|
100
|
+
worksheet = writer.sheets[sheet_name]
|
|
101
|
+
|
|
102
|
+
for col_num, value in enumerate(df.columns.values):
|
|
103
|
+
worksheet.write(0, col_num, value, header_format)
|
|
104
|
+
|
|
105
|
+
for row_num in range(1, len(df) + 1):
|
|
106
|
+
for col_num in range(len(df.columns)):
|
|
107
|
+
val = df.iloc[row_num - 1, col_num]
|
|
108
|
+
worksheet.write(row_num, col_num, val, cell_format)
|
|
109
|
+
|
|
110
|
+
# --- Chart Generation (Based on Class Summary, excluding 'O') ---
|
|
111
|
+
df_chart = df_grouped[df_grouped["Class"] != "O"].reset_index(drop=True)
|
|
112
|
+
chart_data_sheet_name = "ChartData"
|
|
113
|
+
df_chart.to_excel(writer, sheet_name=chart_data_sheet_name, index=False)
|
|
114
|
+
writer.sheets[chart_data_sheet_name].hide()
|
|
115
|
+
|
|
116
|
+
chart = workbook.add_chart({"type": "column"})
|
|
117
|
+
chart.add_series(
|
|
118
|
+
{
|
|
119
|
+
"name": "Occurrences",
|
|
120
|
+
"categories": [chart_data_sheet_name, 1, 0, len(df_chart), 0],
|
|
121
|
+
"values": [chart_data_sheet_name, 1, 1, len(df_chart), 1],
|
|
122
|
+
"fill": {"color": "#4F81BD"},
|
|
123
|
+
}
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
chart.set_title({"name": "PII Class Distribution (excluding Outside)"})
|
|
127
|
+
chart.set_x_axis({"name": "PII Class"})
|
|
128
|
+
chart.set_y_axis({"name": "Count"})
|
|
129
|
+
chart.set_style(11)
|
|
130
|
+
|
|
131
|
+
summary_sheet = writer.sheets["Class Summary"]
|
|
132
|
+
summary_sheet.insert_chart("E2", chart, {"x_scale": 1.5, "y_scale": 1.5})
|
|
133
|
+
|
|
134
|
+
writer.close()
|
|
135
|
+
print(f"Report successfully saved to: {output_excel}")
|
|
136
|
+
|
|
137
|
+
except FileNotFoundError as e:
|
|
138
|
+
print(f"Error: {e}")
|
|
139
|
+
sys.exit(1)
|
|
140
|
+
except json.JSONDecodeError:
|
|
141
|
+
print("Error: One of the files is not in a valid JSONL format.")
|
|
142
|
+
sys.exit(1)
|
|
143
|
+
except Exception as e:
|
|
144
|
+
print(f"An unexpected error occurred: {e}")
|
|
145
|
+
sys.exit(1)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def main():
|
|
149
|
+
parser = argparse.ArgumentParser(
|
|
150
|
+
description="Analyze class distribution from JSONL files and generate an Excel report."
|
|
151
|
+
)
|
|
152
|
+
parser.add_argument(
|
|
153
|
+
"-i", "--input", nargs="+", required=True, help="Paths to JSONL files"
|
|
154
|
+
)
|
|
155
|
+
parser.add_argument(
|
|
156
|
+
"-o", "--output", required=True, help="Path to the output .xlsx file"
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
args = parser.parse_args()
|
|
160
|
+
analyze_pii_distribution(args.input, args.output)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
if __name__ == "__main__":
|
|
164
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from flask_cors import CORS
|
|
4
|
+
from flask import Flask, request, jsonify
|
|
5
|
+
|
|
6
|
+
from pii_classification.inference.inference import AnonPredictor
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
ANON_API_PORT = int(os.getenv("ANON_API_PORT", 5001))
|
|
10
|
+
ANON_API_DEBUG = os.getenv("ANON_API_DEBUG", "false").lower() in ("1", "true", "yes")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
app = Flask(__name__)
|
|
14
|
+
CORS(app) # Enable CORS for UI interaction
|
|
15
|
+
|
|
16
|
+
# ----------------------------------------------------------------------
|
|
17
|
+
# Model registry
|
|
18
|
+
# ----------------------------------------------------------------------
|
|
19
|
+
MODEL_PATHS = {
|
|
20
|
+
"radlab/pii-pl-v1.0": "radlab/pii-pl-v1.0",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
USE_QUANTIZATION = True
|
|
24
|
+
|
|
25
|
+
# Load a predictor for every model at startup
|
|
26
|
+
PREDICTORS = {
|
|
27
|
+
name: AnonPredictor(model_path=path, use_quantized=USE_QUANTIZATION)
|
|
28
|
+
for name, path in MODEL_PATHS.items()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
# Choose a default model – the first one in the dict
|
|
32
|
+
DEFAULT_MODEL = next(iter(PREDICTORS))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ----------------------------------------------------------------------
|
|
36
|
+
# API: return the list of available model names
|
|
37
|
+
# ----------------------------------------------------------------------
|
|
38
|
+
@app.route("/models", methods=["GET"])
|
|
39
|
+
def list_models():
|
|
40
|
+
return jsonify({"models": list(PREDICTORS.keys()), "default": DEFAULT_MODEL})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ----------------------------------------------------------------------
|
|
44
|
+
# API: predict – optionally receive the model name to use
|
|
45
|
+
# ----------------------------------------------------------------------
|
|
46
|
+
@app.route("/predict", methods=["POST"])
|
|
47
|
+
def predict():
|
|
48
|
+
data = request.json or {}
|
|
49
|
+
text = data.get("text", "")
|
|
50
|
+
model_name = data.get("model", DEFAULT_MODEL)
|
|
51
|
+
|
|
52
|
+
if not text:
|
|
53
|
+
return jsonify({"error": "No text provided"}), 400
|
|
54
|
+
|
|
55
|
+
if model_name not in PREDICTORS:
|
|
56
|
+
return jsonify({"error": f"Model '{model_name}' not found"}), 400
|
|
57
|
+
|
|
58
|
+
predictor = PREDICTORS[model_name]
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
predictions = predictor.predict(
|
|
62
|
+
text=text, clean_punct=True, merge_entities=True, handle_gaps=True
|
|
63
|
+
)
|
|
64
|
+
return jsonify({"model": model_name, "predictions": predictions})
|
|
65
|
+
except Exception as e:
|
|
66
|
+
return jsonify({"error": str(e)}), 500
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ----------------------------------------------------------------------
|
|
70
|
+
# API: predict_and_anonymize – replace entities with tags
|
|
71
|
+
# ----------------------------------------------------------------------
|
|
72
|
+
@app.route("/predict_and_anonymize", methods=["POST"])
|
|
73
|
+
def predict_and_anonymize():
|
|
74
|
+
data = request.json or {}
|
|
75
|
+
text = data.get("text", "")
|
|
76
|
+
model_name = data.get("model", DEFAULT_MODEL)
|
|
77
|
+
labels = data.get("labels", [])
|
|
78
|
+
|
|
79
|
+
if not text:
|
|
80
|
+
return jsonify({"error": "No text provided"}), 400
|
|
81
|
+
|
|
82
|
+
if model_name not in PREDICTORS:
|
|
83
|
+
return jsonify({"error": f"Model '{model_name}' not found"}), 400
|
|
84
|
+
|
|
85
|
+
predictor = PREDICTORS[model_name]
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
result = predictor.predict_and_anonymize(text=text, labels=labels)
|
|
89
|
+
return jsonify({"model": model_name, **result})
|
|
90
|
+
except Exception as e:
|
|
91
|
+
return jsonify({"error": str(e)}), 500
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ----------------------------------------------------------------------
|
|
95
|
+
if __name__ == "__main__":
|
|
96
|
+
app.run(host="0.0.0.0", port=ANON_API_PORT, debug=ANON_API_DEBUG)
|
|
File without changes
|